@interopio/bridge 1.1.0 → 1.1.1

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/changelog.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  # Change Log
4
4
 
5
+ ## 1.1.1 (2026-03-20)
6
+ ### Fixed
7
+ - fix: regression port/host config is not applied
8
+
5
9
  ## 1.1.0 (2026-03-19)
6
10
  ### Added
7
11
  - write bound address port to a file
package/dist/main.js CHANGED
@@ -57,18 +57,17 @@ function gatewayDiscoveryPipeServer({ logger, info, pipeNameProps }) {
57
57
  function onGatewayStarted(log, env = process.env) {
58
58
  return (gateway2) => {
59
59
  const info = JSON.stringify({ ...gateway2.info(), pid: process.pid });
60
- if (isRunningInConnectDesktop()) {
60
+ if (isRunningInConnectDesktop(env)) {
61
61
  const startingContext = parseStartingContext(env);
62
62
  const environment = startingContext.env ?? env.IO_CD_ENV ?? env["GLUE-ENV"] ?? "DEMO";
63
63
  const region = startingContext.region ?? env.IO_CD_REGION ?? env["GLUE-REGION"] ?? "INTEROP.IO";
64
64
  const user = env.USERNAME ?? env.USER;
65
- let discoveryServer;
66
65
  const options = {
67
66
  logger: log,
68
67
  info,
69
68
  pipeNameProps: { environment, region, user }
70
69
  };
71
- discoveryServer = gatewayDiscoveryPipeServer(options);
70
+ gatewayDiscoveryPipeServer(options);
72
71
  } else {
73
72
  log.info(`gateway started: ${info}`);
74
73
  }
@@ -88,7 +87,7 @@ async function serverGatewayConfig(gateway2, bridge, env = process.env) {
88
87
  const gatewayConfig = applicationConfig?.customProperties;
89
88
  port = gatewayConfig?.port ?? 8385;
90
89
  host = gatewayConfig?.ip ?? "127.0.0.1";
91
- route = gatewayConfig?.route;
90
+ route = gatewayConfig?.route ?? "/";
92
91
  }
93
92
  if (enabled) {
94
93
  const environment = startingContext.env ?? env.IO_CD_ENV ?? env["GLUE-ENV"] ?? "DEMO";
@@ -108,16 +107,11 @@ async function serverGatewayConfig(gateway2, bridge, env = process.env) {
108
107
  }
109
108
  }
110
109
  if (enabled) {
111
- return {
112
- host,
113
- port,
114
- management,
110
+ const result = {
115
111
  gateway: {
116
112
  clients: {
117
113
  inactive_seconds: 0
118
114
  },
119
- route,
120
- ping: bridge.wsPingInterval ?? void 0,
121
115
  mesh: {
122
116
  auth: { user: null },
123
117
  node: bridge.uuid,
@@ -152,6 +146,22 @@ async function serverGatewayConfig(gateway2, bridge, env = process.env) {
152
146
  }
153
147
  }
154
148
  };
149
+ if (host !== void 0) {
150
+ result.host = host;
151
+ }
152
+ if (port !== void 0) {
153
+ result.port = port;
154
+ }
155
+ if (route !== void 0) {
156
+ result.gateway.route = route;
157
+ }
158
+ if (bridge.wsPingInterval !== void 0) {
159
+ result.gateway.ping = bridge.wsPingInterval;
160
+ }
161
+ if (management !== void 0) {
162
+ result.management = management;
163
+ }
164
+ return result;
155
165
  }
156
166
  }
157
167
 
@@ -1120,7 +1130,7 @@ var InternalRelays = class {
1120
1130
  // package.json
1121
1131
  var package_default = {
1122
1132
  name: "@interopio/bridge",
1123
- version: "1.1.0",
1133
+ version: "1.1.1",
1124
1134
  license: "see license in license.md",
1125
1135
  author: "interop.io",
1126
1136
  homepage: "https://docs.interop.io/bridge",
package/dist/main.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/instance/BridgeNode.ts", "../../bridge-gateway/src/desktop.ts", "../../bridge-gateway/src/index.ts", "../../bridge-gateway/src/pipes/common.ts", "../../bridge-gateway/src/pipes/discovery.ts", "../../bridge-mesh/src/mesh/rest-directory/routes.ts", "../../bridge-mesh/src/mesh/ws/relays/core.ts", "../../bridge-mesh/src/mesh/ws/cluster/core.ts", "../../bridge-mesh/src/index.ts", "../../bridge-mesh/src/mesh/gateway/mesh.ts", "../../bridge-mesh/src/mesh/connections.ts", "../../bridge-mesh/src/mesh/lamport.ts", "../../bridge-mesh/src/mesh/relays.ts", "../package.json", "../src/version/MemberVersion.ts", "../src/utils/network.ts", "../src/utils/internal/IpAddressUtil.ts", "../src/cluster/Address.ts", "../src/config/Properties.ts", "../src/config/NamedDiscoveryConfig.ts", "../src/config/KubernetesConfig.ts", "../src/config/DiscoveryConfig.ts", "../src/config/Config.ts", "../src/kubernetes/KubernetesDiscoveryStrategyFactory.ts", "../src/kubernetes/KubernetesEndpointResolver.ts", "../src/kubernetes/KubernetesConfig.ts", "../src/discovery/settings.ts", "../src/kubernetes/KubernetesProperties.ts", "../src/discovery/SimpleDiscoveryNode.ts", "../src/kubernetes/DnsEndpointResolver.ts", "../src/kubernetes/KubernetesApiProvider.ts", "../src/kubernetes/KubernetesClient.ts", "../src/logging.ts", "../src/kubernetes/KubernetesApiEndpointResolver.ts", "../src/kubernetes/KubernetesDiscoveryStrategy.ts", "../src/discovery/multicast/MulticastDiscoveryStrategy.ts", "../src/discovery/multicast/MulticastProperties.ts", "../src/discovery/multicast/MulticastDiscoveryStrategyFactory.ts", "../src/discovery/index.ts", "../src/internal/config/NamedDiscoveryConfigUtils.ts", "../src/license/types.ts", "../src/license/LicenseValidator.ts", "../src/license/BridgeLicenseValidator.ts", "../src/utils/uuid.ts", "../src/instance/AddressPicker.ts", "../src/main.mts"],
4
- "sourcesContent": ["import gatewayServer, { GatewayServer } from '@interopio/gateway-server';\nimport type { ServerConfig } from '@interopio/gateway-server/config';\nimport { userInfo } from 'node:os';\nimport { onGatewayStarted, serverGatewayConfig } from '../../../bridge-gateway/src/index.ts';\nimport { BridgeMeshChannel, mesh } from '../../../bridge-mesh/src/index.ts';\nimport Connections from '../../../bridge-mesh/src/mesh/connections.ts';\nimport { InternalRelays } from '../../../bridge-mesh/src/mesh/relays.ts';\nimport info from '../../package.json' with { type: 'json' };\nimport { type Member } from '../cluster/Member.ts';\nimport { Config, JoinConfig } from '../config/Config.ts';\nimport { type DiscoveryConfig, type DiscoveryStrategyConfig } from '../config/DiscoveryConfig.ts';\nimport {\n DefaultDiscoveryService,\n DefaultDiscoveryServiceFactory,\n type DiscoveryService,\n type DiscoveryServiceSettings\n} from '../discovery/index.ts';\nimport { SimpleDiscoveryNode } from '../discovery/SimpleDiscoveryNode.ts';\nimport { createDiscoveryStrategyConfigs } from '../internal/config/NamedDiscoveryConfigUtils.ts';\nimport { BridgeLicenseValidator } from \"../license/BridgeLicenseValidator.ts\";\nimport { type LicenseValidator } from \"../license/LicenseValidator.ts\";\nimport getLogger, { type Logger } from '../logging.ts';\nimport { newUUID } from '../utils/uuid.ts';\nimport { type MemberVersion, parseVersion } from '../version/MemberVersion.ts';\nimport { type AddressPicker, DefaultAddressPicker } from './AddressPicker.ts';\n\nfunction logStartingInfo(logger: Logger) {\n logger.info(`Starting io.Bridge v${info.version} using Node.js ${process.version} with PID ${process.pid} (started by ${userInfo().username} in ${process.cwd()})`);\n}\n\nfunction createJoiner(logger: Logger, config: JoinConfig) {\n\n}\n\nfunction createDiscoveryService(logger: Logger,\n conf: DiscoveryConfig,\n isAutoDetectionEnabled: boolean,\n localMember: Promise<Member>): DiscoveryService {\n const factory = new DefaultDiscoveryServiceFactory();\n\n const node = localMember.then(member => new SimpleDiscoveryNode(member.address)) ;\n\n const settings: DiscoveryServiceSettings = {\n mode: 'member',\n node: node,\n conf: conf,\n auto: isAutoDetectionEnabled,\n logger: logger,\n };\n return factory.newDiscoveryService(settings);\n}\n\nfunction createAddressPicker(node: BridgeNode): AddressPicker {\n const config = node.config;\n const logger = node.getLogger('AddressPicker');\n return new DefaultAddressPicker(config, logger);\n}\n\nfunction isAnyNamedConfigEnabled(join: JoinConfig) {\n return createDiscoveryStrategyConfigs(join).length > 0;\n}\n\nexport class BridgeNode {\n readonly config: Config;\n #uuid: string;\n readonly #discoveryService: DiscoveryService;\n private readonly meshChannel: BridgeMeshChannel;\n private readonly version: MemberVersion;\n private server?: GatewayServer.Server;\n private readonly licenseValidator: LicenseValidator;\n #licenseCheckIntervalId: ReturnType<typeof setInterval> | undefined;\n\n constructor(config: Config) {\n this.config = config;\n\n this.licenseValidator = BridgeLicenseValidator(this.getLogger('license'));\n this.licenseValidator.validate(config.license);\n\n this.uuid = newUUID();\n this.version = parseVersion(info.version);\n const addressPicker = createAddressPicker(this);\n\n\n const localMemberPromise: Promise<Member> = addressPicker.pickAddress()\n .then(() => addressPicker.getPublicAddressFor('member'))\n .then((publicAddress) => {\n return {\n local: true,\n address: publicAddress,\n uuid: this.uuid,\n version: this.version,\n };\n }).finally(() => {\n addressPicker.close();\n });\n\n const joinConfig = config.network.join;\n\n const discoveryConfig: DiscoveryConfig = {\n discoveryServiceFactory: joinConfig.discovery.discoveryServiceFactory,\n discoveryStrategyConfigs: joinConfig.discovery.discoveryStrategyConfigs.concat(createDiscoveryStrategyConfigs(joinConfig)),\n };\n\n const strategyConfigs = createDiscoveryStrategyConfigs(joinConfig);\n\n const isAutoDetectionEnabled = joinConfig.autoDetectionEnabled;\n\n this.#discoveryService = createDiscoveryService(getLogger(\"discovery\"), discoveryConfig, isAutoDetectionEnabled, localMemberPromise);\n\n const relays = new InternalRelays(this.getLogger('relays'));\n\n const connections = new Connections(this.getLogger('nodes'), this.uuid, this.config.mesh.timeout ?? 60000);\n\n this.meshChannel = new BridgeMeshChannel(relays, connections, this.getLogger(\"channel\"));\n }\n\n getLogger(name: string) {\n return getLogger(name);\n }\n /**\n * Get the address on which the server is bound\n * @returns The server address info, undefined if not started, or null if stopped\n */\n\n get address() {\n return this.server?.address;\n }\n\n private scheduleLicenseCheck() {\n const task = async () => {\n try {\n this.licenseValidator.validate(this.config.license, {\n logSuccessMessages: false,\n });\n }\n catch (error) {\n // this.logger.error(error);\n await this.stop();\n }\n };\n\n const licenseCheckInterval = 1000 * 60 * 60 * 24; // 1 day\n return setInterval(task, licenseCheckInterval);\n }\n\n get uuid() {\n return this.#uuid;\n }\n\n set uuid(uuid: string) {\n this.#uuid = uuid;\n }\n\n async start() {\n await this.meshChannel.init();\n const config: ServerConfig = {\n port: this.config.server.port,\n host: this.config.server.host,\n ssl: this.config.server.ssl.enabled ? {\n requestCert: this.config.server.auth.type === 'x509',\n ...(this.config.server.ssl)\n } : undefined,\n auth: { type: 'none', ...(this.config.server.auth) },\n cors: this.config.server.cors.disabled ? false : this.config.server.cors,\n app: async (configurer, config) => {\n await mesh({\n logger: this.getLogger('mesh'),\n enabled: true,\n relays: this.meshChannel.relays,\n connections: this.meshChannel.connections,\n socket: {\n ping: this.config.server.wsPingInterval ?? 30000, // 30 seconds\n }\n }, configurer, config);\n },\n ...(await serverGatewayConfig(this.config.gateway, {\n meshChannel: this.meshChannel,\n wsPingInterval: this.config.server.wsPingInterval,\n uuid: this.uuid\n }))\n };\n\n logStartingInfo(this.getLogger('node'));\n\n const join = this.config.network.join;\n if (isAnyNamedConfigEnabled(join) || (join.autoDetectionEnabled && !this.#isEmptyDiscoveryStrategies())) {\n await this.#discoveryService.start();\n }\n\n this.server = await gatewayServer(config);\n if (config.gateway !== undefined) {\n onGatewayStarted(this.getLogger('gw'))(this.server.gateway);\n }\n this.#licenseCheckIntervalId = this.scheduleLicenseCheck();\n this.join();\n }\n\n join() {\n\n }\n\n async stop() {\n if (this.server)\n {\n await this.server.close()\n }\n try {\n await this.#discoveryService.close();\n }\n catch (e) {\n // ignore\n }\n\n await this.meshChannel.close();\n if (this.#licenseCheckIntervalId !== undefined) {\n clearInterval(this.#licenseCheckIntervalId);\n this.#licenseCheckIntervalId = undefined;\n }\n }\n\n #isEmptyDiscoveryStrategies() {\n return this.#discoveryService instanceof DefaultDiscoveryService && this.#discoveryService.strategies.length === 0;\n }\n}\n", "import type { GatewayConfig } from '@interopio/gateway-server/gateway-ent'\nexport function isRunningInConnectDesktop(env = process.env): boolean {\n return env._GD_STARTING_CONTEXT_ !== undefined;\n}\n\nexport type ApplicationConfig = {\n name: string;\n customProperties?: {\n gatewayApp?: boolean\n [key: string]: unknown\n } | GatewayConfig,\n [key: string]: unknown\n}\n\nexport type StartingContext = {\n instanceId: string\n env: string\n region: string\n applicationConfig?: ApplicationConfig\n [key: string]: unknown\n}\n\nexport function parseStartingContext(env = process.env): StartingContext {\n if (!isRunningInConnectDesktop(env)) {\n throw new Error(\"Not running in io.Connect Desktop\");\n }\n return JSON.parse(env._GD_STARTING_CONTEXT_);\n}\n", "import type { MeshChannel } from '@interopio/gateway/mesh/api';\nimport { isRunningInConnectDesktop, parseStartingContext } from './desktop.ts';\nimport type { Logger } from '@interopio/gateway/logging/api';\nimport type { Server } from 'node:net';\nimport { IOGateway } from '@interopio/gateway';\nimport type { ServerConfig } from '@interopio/gateway-server/config';\nimport { gatewayDiscoveryPipeServer } from './pipes/discovery.ts';\nimport { getPipeFileName } from './pipes/common.ts';\nimport type { GatewayConfig } from \"@interopio/gateway-server/gateway-ent\";\n\nexport function onGatewayStarted(log: Logger, env = process.env): (gateway: IOGateway.Gateway) => void {\n return (gateway) => {\n const info = JSON.stringify({...gateway.info(), pid: process.pid});\n if (isRunningInConnectDesktop()) {\n const startingContext = parseStartingContext(env);\n const environment = startingContext.env ?? env.IO_CD_ENV ?? env[\"GLUE-ENV\"] ?? 'DEMO';\n const region = startingContext.region ?? env.IO_CD_REGION ?? env[\"GLUE-REGION\"] ?? 'INTEROP.IO';\n const user = env.USERNAME ?? env.USER;\n let discoveryServer: Server;\n const options = {\n logger: log,\n info,\n pipeNameProps: {environment, region, user}\n } as const;\n discoveryServer = gatewayDiscoveryPipeServer(options);\n }\n else {\n log.info(`gateway started: ${info}`);\n }\n }\n}\n\nexport async function serverGatewayConfig(gateway: {\n enabled?: boolean,\n contexts: {\n lifetime?: 'ref-counted' | 'ownership' | 'retained'\n }\n },\n bridge: {\n meshChannel: MeshChannel,\n wsPingInterval?: number,\n uuid?: string,\n management?: ServerConfig['management']\n }, env = process.env): Promise<Pick<ServerConfig, 'gateway' | 'management' | 'port' | 'host'> | undefined> {\n let enabled = gateway.enabled;\n let management = bridge.management;\n let port: number | string | undefined;\n let host: string | undefined;\n let route: string | undefined;\n\n if (isRunningInConnectDesktop(env)) {\n const startingContext = parseStartingContext(env);\n if (enabled === undefined) {\n const applicationConfig = startingContext.applicationConfig;\n enabled = applicationConfig?.customProperties?.gatewayApp === true || applicationConfig?.name === 'io-connect-gateway';\n const gatewayConfig = applicationConfig?.customProperties as GatewayConfig | undefined;\n port = gatewayConfig?.port ?? 8385;\n host = gatewayConfig?.ip ?? '127.0.0.1';\n route = gatewayConfig?.route;\n }\n if (enabled) {\n const environment = startingContext.env ?? env.IO_CD_ENV ?? env[\"GLUE-ENV\"] ?? 'DEMO';\n const region = startingContext.region ?? env.IO_CD_REGION ?? env[\"GLUE-REGION\"] ?? 'INTEROP.IO';\n const user = env.USERNAME ?? env.USER;\n\n management ??= {server: {}};\n management.server.path ??= getPipeFileName(`glue42-gateway-${environment}-${region}-${user}`);\n management.commands ??= {};\n management.commands.shutdown ??= {};\n management.commands.shutdown.enabled ??= true;\n }\n\n }\n let contextsLifetime = gateway.contexts.lifetime;\n if (contextsLifetime === undefined) {\n if (isRunningInConnectDesktop(env)) {\n contextsLifetime = 'retained';\n }\n }\n if (enabled) {\n return {\n host,\n port,\n management,\n gateway: {\n clients: {\n inactive_seconds: 0,\n },\n route,\n ping: bridge.wsPingInterval ?? undefined,\n mesh: {\n auth: { user: null },\n node: bridge.uuid,\n channel: bridge.meshChannel\n },\n contexts: {\n lifetime: contextsLifetime,\n visibility: [\n { context: /___channel___.+/, restrictions: 'cluster' },\n { context: '__insights_pi_storage__', restrictions: 'cluster' },\n { context: /T42\\..*/, restrictions: 'local' },\n { context: \"___platform_prefs___\", restrictions: 'local' },\n { context: /___workspace___.+/, restrictions: 'local' },\n { context: /___window-hibernation___.+/, restrictions: 'local' },\n { context: /___instance___.+/, restrictions: 'local' },\n { context: /___window___.+/, restrictions: 'local' },\n { restrictions: 'cluster' }\n ]\n },\n methods: {\n visibility: [\n { method: /T42\\..*/, restrictions: 'local' },\n { restrictions: 'cluster' }\n ]\n },\n peers: {\n visibility: [\n { domain: 'context', restrictions: 'cluster' },\n { domain: 'interop', restrictions: 'cluster' },\n { domain: 'bus', restrictions: 'local' }\n ]\n }\n }\n };\n }\n}\n", "import { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { rmSync } from \"node:fs\";\n\nfunction isWinOS() {\n return process.platform === \"win32\";\n}\nexport function getPipeFileName(pipe: string, removeExisting = false) {\n const fileName = isWinOS() ? `\\\\\\\\.\\\\pipe\\\\${pipe}` : join(tmpdir(), `${pipe}.sock`);\n if (!isWinOS() && removeExisting) {\n try {\n rmSync(fileName);\n }\n catch (e) {\n // Ignore error if file does not exist or cannot be removed\n }\n }\n return fileName;\n}\n", "import { getPipeFileName } from './common.ts';\nimport type { PipeNameProperties, PipeServerOptions } from './types.ts';\nimport { createServer } from 'node:net';\n\nfunction getDiscoveryPipeFileName({ environment, region, user }: PipeNameProperties) {\n return getPipeFileName(`glue42-${environment}-${region}-${user}`, true);\n}\n\nexport function gatewayDiscoveryPipeServer({ logger, info, pipeNameProps }: PipeServerOptions) {\n const pipeName = getDiscoveryPipeFileName(pipeNameProps);\n logger.info(`gateway started: ${info}, opening ${pipeName}`);\n const server = createServer((stream) => {\n logger.info(`stream connected, sending info...`);\n stream.write(info);\n stream.end(() => {\n server.close();\n });\n });\n server.listen(pipeName);\n return server;\n}\n", "import type { Node, NodeAnnouncement, NodeConnections } from '../types.ts';\nimport type {\n ServerConfigurer,\n ServerConfigurerHandlerSpec,\n ServerHttpRequest\n} from '@interopio/gateway-server/web/server';\nimport type {AuthorizationRule} from '@interopio/gateway-server/auth/api';\n\nfunction buildCanonicalBaseURL(request: ServerHttpRequest): URL {\n const requestURL = request.URL;\n const protocol = requestURL.protocol === 'https:' ? 'wss://' : 'ws://';\n return new URL(protocol + requestURL.host);\n}\n\nfunction toCanonicalEndpoint(endpoint: string, request: ServerHttpRequest): string {\n\n const canonicalBaseURL = buildCanonicalBaseURL(request);\n\n const endpointURL = new URL(endpoint, canonicalBaseURL);\n if (endpointURL.protocol == canonicalBaseURL.protocol && endpointURL.host === canonicalBaseURL.host) {\n return endpointURL.pathname + endpointURL.search + endpointURL.hash;\n }\n else {\n return endpointURL.href;\n }\n}\n\nfunction fromCanonicalEndpoint(endpoint: string, request: ServerHttpRequest): string {\n const canonicalBaseURL = buildCanonicalBaseURL(request);\n const endpointURL = new URL(endpoint, canonicalBaseURL);\n return endpointURL.href;\n}\n\nfunction fromRequestNode(node: NodeAnnouncement, request: ServerHttpRequest): NodeAnnouncement {\n const endpoint = toCanonicalEndpoint(node.endpoint ?? `/cluster?node=${node.node}`, request);\n if (endpoint !== node.endpoint) {\n return { ...node, endpoint };\n }\n return node;\n}\nfunction toRequestNode(node: Node, request: ServerHttpRequest): Node {\n const endpoint = fromCanonicalEndpoint(node.endpoint, request);\n if (endpoint !== node.endpoint) {\n return { ...node, endpoint };\n }\n return node;\n}\n\nfunction routes(config: { connections: NodeConnections, authorize?: AuthorizationRule }, {handle}: ServerConfigurer) {\n const {connections, authorize} = config;\n handle(\n {\n request: {method: 'POST', path: '/api/nodes'}, options: {cors: true, authorize},\n handler: async ({request, response}) => {\n const json = await request.json();\n if (!Array.isArray(json)) {\n response.setRawStatusCode(400 /*Bad Request*/);\n await response.end();\n }\n else {\n const nodes = (json as NodeAnnouncement[]).map((node) => {\n return fromRequestNode(node, request);\n });\n const result = connections.announce(nodes).map((connection) => {\n const connect = connection.connect?.map((node) => {\n return toRequestNode(node, request);\n });\n return { ...connection, connect: connect }\n });\n const buffer = Buffer.from(JSON.stringify(result), 'utf8');\n response.setRawStatusCode(200 /*OK*/);\n response.headers.set('Content-Type', 'application/json; charset=utf8');\n await response.body(buffer);\n }\n }\n },\n {\n request: {method: 'GET', path: /^\\/api\\/nodes\\/(?<nodeId>.+)$/}, options: {cors: true, authorize},\n handler: async ({request, response}, {nodeId}) => {\n const result = connections.find(nodeId)?.map((node) => toRequestNode(node, request));\n if (result !== undefined) {\n const buffer = Buffer.from(JSON.stringify(result), 'utf8');\n response.setRawStatusCode(200 /* OK */);\n response.headers.set('Content-Type', 'application/json; charset=utf8');\n await response.body(buffer);\n } else {\n response.setRawStatusCode(404 /* Not Found */);\n await response.end();\n }\n },\n } as ServerConfigurerHandlerSpec<'nodeId'>,\n {\n request: {method: 'DELETE', path: /^\\/api\\/nodes\\/(?<nodeId>.*)$/}, options: {cors: true, authorize},\n handler: async ({response}, {nodeId}) => {\n\n const removed = connections.remove(nodeId);\n if (removed) {\n response.setRawStatusCode(200 /* OK */);\n } else {\n response.setRawStatusCode(404 /* Not Found */);\n }\n await response.end();\n }\n } as ServerConfigurerHandlerSpec<'nodeId'>,\n );\n}\n\nexport default routes;\n", "import type { Relays } from '../../types.ts';\n\nimport type {ServerWebSocketHandler} from '@interopio/gateway-server/web/server';\nimport {IOGateway} from '@interopio/gateway';\n\nlet handlerId = 0;\nasync function create(log: IOGateway.Logging.Logger,\n internal: Relays,\n env: { endpoint: string }): Promise<ServerWebSocketHandler> {\n\n const id = ++handlerId;\n log.info(`relays-${id} server is listening on ${env.endpoint}`);\n let keyId = 0;\n return async ({socket, handshake}) => {\n const logPrefix = handshake.logPrefix ?? '';\n const query = handshake.url.searchParams;\n const key = `r.${id}.${++keyId}`\n log.info(`${logPrefix}connected on /relays with ${query} and assigned key ${key}`);\n internal.add(key, (msg: string, c, cb) => {\n if (log.enabledFor('trace')) {\n log.debug(`${logPrefix}sending with key ${key}: ${msg}`);\n }\n socket.send(msg, {binary: false}, (err?: Error) => {\n cb(key, err);\n });\n });\n //onOpen(connectedNodes, key);\n socket.on('error', (err: Error) => {\n log.error(`${logPrefix}websocket error: ${err.message}`, err);\n });\n socket.on('message', (data, _isBinary) => {\n if (Array.isArray(data)) {\n data = Buffer.concat(data);\n }\n try {\n internal.receive(key, data as unknown as string);\n } catch (e) {\n log.warn(`${logPrefix}error processing received data '${data}'`, e);\n }\n });\n socket.on('close', (code, reason) => {\n internal.remove(key);\n\n log.info(`${logPrefix}disconnected from relays (code: ${code}, reason: '${reason.toString('utf8')}')`);\n });\n };\n}\n\nexport const meshRelays = ({logger, relays}: { logger: IOGateway.Logging.Logger, relays: Relays }) => {\n return async (env: { endpoint: string }) => {\n return await create(logger, relays, env);\n }\n}\n", "import type { WebSocket } from 'ws';\nimport type { Relays } from '../../types.ts';\nimport type { ServerWebSocketHandler } from '@interopio/gateway-server/web/server';\nimport { IOGateway } from '@interopio/gateway';\n\nfunction onMessage(relays: Relays,\n log: IOGateway.Logging.Logger,\n key: string,\n node: string,\n socketsByNodeId: Map<string, Map<string, WebSocket>>,\n msg: string) {\n try {\n relays.send(key, node, msg, (k, err?: Error) => {\n if (err) {\n log.warn(`${k} error writing msg ${msg}: ${err}`);\n return;\n }\n if (log.enabledFor('trace')) {\n log.debug(`${k} sent msg ${msg}`);\n }\n });\n } catch (ex) {\n log.error(`${key} unable to process message`, ex);\n if (node) {\n const socket = socketsByNodeId.get(node)?.get(key);\n socket?.terminate();\n }\n }\n}\nlet handlerId = 0;\nasync function create(\n log: IOGateway.Logging.Logger,\n relays: Relays,\n env: { endpoint: string }\n): Promise<ServerWebSocketHandler> {\n const socketsByNodeId = new Map<string, Map<string, WebSocket>>();\n relays.on('message', (k, nodeId, msg) => {\n try {\n const sockets = socketsByNodeId.get(nodeId);\n if (sockets && sockets.size > 0) {\n if (log.enabledFor('trace')) {\n log.debug(`${k} sending message to ${[...sockets.keys()]}`); // list of keys\n }\n for (const [key, socket] of sockets) {\n socket.send(msg, {binary: false}, (err?: Error) => {\n if (err) {\n log.warn(`${key} error writing from ${k} msg ${msg}: ${err}`);\n return;\n }\n if (log.enabledFor('trace')) {\n log.debug(`${key} sent from ${k} msg ${msg}`);\n }\n });\n }\n } else {\n log.warn(`${k} dropped msg ${msg}.`);\n }\n } catch (ex) {\n log.error(`${k} unable to process message`, ex);\n }\n });\n relays.on('disconnect', (k, nodeId) => {\n const sockets = socketsByNodeId.get(nodeId);\n if (sockets) {\n for (const [key, socket] of sockets) {\n socket.terminate();\n log.info(`${key} terminated because ${k} disconnected ${nodeId}`);\n }\n }\n });\n\n const id = ++handlerId;\n let keyId = 0;\n\n return async ({socket, handshake}) => {\n const logPrefix = handshake.logPrefix ?? '';\n const query = handshake.url.searchParams;\n const key = `c.${id}.${++keyId}`;\n log.info(`${logPrefix}connected on /cluster with ${query} and assigned key ${key}`);\n\n const node = query.get('node');\n if (node) {\n let sockets = socketsByNodeId.get(node);\n if (!sockets) {\n sockets = new Map<string, WebSocket>();\n socketsByNodeId.set(node, sockets);\n }\n sockets.set(key, socket);\n } else {\n socket.terminate();\n return;\n }\n //onOpen(connectedNodes, key);\n socket.on('error', (err: Error) => {\n log.error(`${key} websocket error: ${err}`, err);\n });\n socket.on('message', (data, _isBinary) => {\n if (Array.isArray(data)) {\n data = Buffer.concat(data);\n }\n onMessage(relays, log, key, node, socketsByNodeId, data as unknown as string);\n });\n socket.on('close', (_code, _reason) => {\n log.info(`${key} disconnected from cluster`);\n const sockets = socketsByNodeId.get(node);\n if (sockets) {\n sockets.delete(key);\n if (sockets.size === 0) {\n socketsByNodeId.delete(node);\n }\n }\n });\n };\n}\n\nexport const meshCluster = ({logger, relays}: { logger: IOGateway.Logging.Logger, relays: Relays }) => {\n return async (environment: { endpoint: string }) => {\n return await create(logger, relays, environment);\n }\n};\n", "import restDirectory from './mesh/rest-directory/routes.ts';\nimport { meshRelays } from './mesh/ws/relays/core.ts';\nimport { meshCluster } from './mesh/ws/cluster/core.ts';\nimport type {ServerConfigurer, ServerWebSocketOptions} from '@interopio/gateway-server/web/server';\nimport type { Relays, NodeConnections } from './mesh/types.ts';\nimport { GatewayServer } from '@interopio/gateway-server';\nimport type { Logger } from '@interopio/gateway/logging/api';\n\nfunction connectNodeRelays(logger: Logger, relays: Relays, connections: NodeConnections) {\n relays.on('connect', (key, node) => {\n try {\n connections.add(node);\n }\n catch (e) {\n logger.warn(`${key} error adding node ${node} to connections: ${e}`);\n }\n });\n relays.on('disconnect', (key, node, links) => {\n try {\n connections.remove(node);\n }\n catch (e) {\n logger.warn(`${key} error removing node ${node} from connections: ${e}`);\n }\n for (const [linkNode, linkKey] of links) {\n try {\n relays.send(linkKey, linkNode, { type: 'bye', from: node, to: linkNode }, (k, err?) => {\n if (err) {\n logger.warn(`${k} error writing 'bye' msg to ${linkNode}: ${err}`);\n return;\n }\n if (logger.enabledFor('debug')) {\n logger.debug(`${k} sent 'bye' msg to ${linkNode} from ${node}`);\n }\n });\n } catch (err) {\n logger.warn(`${linkKey} exception writing 'bye' msg to ${linkNode} from ${node}: ${err}`);\n }\n }\n });\n\n}\n\nexport const mesh = async (\n options: {\n logger: Logger,\n enabled?: boolean,\n relays: Relays,\n connections: NodeConnections,\n socket: ServerWebSocketOptions\n },\n configurer: ServerConfigurer,\n config: GatewayServer.ServerConfig\n) => {\n const {enabled, logger, relays, connections} = options;\n if (enabled !== true) {\n if (logger.enabledFor('debug')) {\n logger.debug(`no mesh`);\n }\n return;\n }\n let {socket} = options;\n const authorize = socket.authorize ?? {access: config.auth.type === 'none' ? 'permitted' : 'authenticated'};\n socket = {ping: 30000, authorize: authorize, ...socket};\n connectNodeRelays(logger, relays, connections);\n restDirectory({connections, authorize}, configurer);\n configurer.socket(\n {\n path: '/cluster', options: socket,\n factory: meshCluster({logger, relays})\n },\n {\n path: '/relays', options: socket,\n factory: meshRelays({logger, relays})\n }\n );\n}\n\nimport BridgeMeshChannel from './mesh/gateway/mesh.ts';\nexport { BridgeMeshChannel };\n", "import { nanoid } from 'nanoid';\nimport type InMemoryNodeConnections from '../connections.ts';\nimport type { Relays, RelayMessageHandler, NodeConnections, NodeAnnouncement } from '../types.ts';\nimport type { MeshChannel, MeshSubscriber, MeshAction, MeshEvent, MeshMessage } from '@interopio/gateway/mesh/api';\nimport type { Logger } from '@interopio/gateway/logging/api';\nimport gateway from '@interopio/gateway/package.json' with { type: 'json' };\n\nlet instanceId = 0;\n\ntype NodeState<T=string> = {\n subscriber: MeshSubscriber<T>,\n users: Set<string>,\n members: Set<string>,\n outgoing: Set<string>\n};\n\nexport default class BridgeMeshChannel implements MeshChannel {\n readonly #logger: Logger;\n readonly #relays: Relays;\n readonly #connections: InMemoryNodeConnections;\n readonly #state: Map<string, NodeState<unknown>>;\n readonly #keyPrefix: string;\n\n constructor(relays: Relays,\n nodes: InMemoryNodeConnections,\n logger: Logger\n ) {\n this.#relays = relays;\n this.#connections = nodes;\n this.#logger = logger;\n this.#state = new Map<string, NodeState<unknown>>();\n this.#keyPrefix = `g.${++instanceId}`;\n\n // When a node's WebSocket connection is actually established,\n // update outgoing in both directions.\n this.#connections.on('node-connected', (nodeId) => {\n // Check if the newly connected node is a connect target for any local node\n for (const [n, state] of this.#state) {\n if (n === nodeId) {\n continue;\n }\n const connect = this.#connections.find(n);\n if (connect?.some((c) => c.node === nodeId)) {\n state.outgoing.add(nodeId);\n if (!state.members.has(nodeId)) {\n state.members.add(nodeId);\n state.subscriber({type: 'member-added', node: nodeId}, n, this);\n }\n }\n }\n\n // Check the newly connected node's own connect list for already-connected targets\n const nodeState = this.#state.get(nodeId);\n if (nodeState) {\n const connect = this.#connections.find(nodeId);\n if (connect) {\n for (const c of connect) {\n if (this.#connections.isConnected(c.node) && !nodeState.outgoing.has(c.node)) {\n nodeState.outgoing.add(c.node);\n if (!nodeState.members.has(c.node)) {\n nodeState.members.add(c.node);\n nodeState.subscriber({type: 'member-added', node: c.node}, nodeId, this);\n }\n }\n }\n }\n }\n });\n\n // When a node disconnects, remove it from outgoing and members for all local nodes.\n this.#connections.on('node-disconnected', (nodeId) => {\n for (const [n, state] of this.#state) {\n state.outgoing.delete(nodeId);\n if (state.members.has(nodeId)) {\n state.members.delete(nodeId);\n state.subscriber({type: 'member-removed', node: nodeId}, n, this);\n }\n }\n });\n }\n\n get relays(): Relays {\n return this.#relays;\n }\n get connections(): NodeConnections {\n return this.#connections;\n }\n\n #intervalId: ReturnType<typeof setInterval>;\n\n subscribe<T = string>(node?: string, subscriber?: MeshSubscriber<T>): string {\n node ??= nanoid();\n const key = `${this.#keyPrefix}-${node}`;\n if (this.#state.has(key)) {\n throw new Error(`already subscribed to node ${node}`);\n }\n this.#state.set(node, {subscriber, users: new Set<string>(), members: new Set<string>(), outgoing: new Set<string>()});\n this.#relays.add(key, this.createRelayClient(key, node));\n this.#announce(node);\n this.#relays.receive(key, { type: 'hello' as const, from: node, to: 'all' });\n // Announce at half the timeout interval to ensure node doesn't expire\n this.#intervalId ??= setInterval(() => this.#announce(), this.#connections.timeout / 2);\n return node;\n }\n\n private createRelayClient<T>(key: string, node: string): RelayMessageHandler {\n return (_msg: string, command, cb) => {\n\n const state = this.#state.get(node);\n if (state !== undefined) {\n try {\n switch (command.type) {\n case 'hello': {\n if (state.members.has(command.from)) {\n break;\n }\n state.members.add(command.from);\n state.subscriber({ type: 'member-added', node: command.from }, node, this);\n break;\n }\n case \"bye\": {\n if (!state.members.has(command.from)) {\n break;\n }\n state.members.delete(command.from);\n state.subscriber({ type: 'member-removed', node: command.from }, node, this);\n break;\n }\n case \"data\": {\n const event: MeshEvent<T> = {\n type: 'message-received',\n message: command.data as MeshMessage<T>\n };\n state.subscriber(event, node, this);\n\n break;\n }\n }\n }\n catch (err) {\n cb(key, err)\n }\n }\n\n }\n }\n\n unsubscribe(node: string): void {\n this.#delete(node);\n this.#relays.remove(`${this.#keyPrefix}-${node}`);\n }\n\n execute<T = string>(node: string, action: MeshAction<T>): void {\n switch (action.type) {\n case 'publish-message': {\n this.#onPublishMessage(node, action.message as MeshMessage);\n break;\n }\n case 'add-users': {\n this.#onAddUsers(node, action.added);\n break;\n }\n case 'remove-users': {\n this.#onRemoveUsers(node, action.removed);\n break;\n }\n }\n }\n\n #onPublishMessage(node: string, data: MeshMessage): void {\n const nodes = data.receiver.type === 'cluster'\n ? Array.from(this.#state.get(node)?.members ?? [])\n : [data.receiver['node'] as string];\n const key = `${this.#keyPrefix}-${node}`;\n const command = { type: 'data' as const, from: node, data };\n nodes.forEach((to) => {\n if (to === node) {\n return;\n }\n\n try {\n this.#relays.send(key, to, { ...command, to }, (k, err) => {\n if (err) {\n this.#logger.warn(`failed to send message from ${node} to ${to} via ${k}: ${err.message}`);\n }\n });\n } catch (err) {\n this.#logger.warn(`failed to send message from ${node} to ${to} via ${key}: ${(err as Error).message}`);\n }\n });\n }\n\n #onAddUsers(node: string, usersToAdd: readonly string[]) {\n let shouldAnnounce = false;\n const nodeState = this.#state.get(node);\n if (nodeState.users === undefined) {\n nodeState.users = new Set<string>(usersToAdd);\n shouldAnnounce = true;\n }\n else {\n for (const u of usersToAdd) {\n if (nodeState.users.has(u)) {\n continue;\n }\n nodeState.users.add(u);\n shouldAnnounce = true;\n }\n }\n if (shouldAnnounce) {\n this.#announce(node);\n }\n }\n\n #onRemoveUsers(node: string, usersToRemove: readonly string[]) {\n const nodeState = this.#state.get(node);\n const nodeUsers = nodeState?.users;\n if (nodeUsers === undefined) {\n return;\n }\n let shouldAnnounce = false;\n for (const u of usersToRemove) {\n if (!nodeUsers.has(u)) {\n continue;\n }\n nodeUsers.delete(u);\n shouldAnnounce = true;\n }\n if (shouldAnnounce) {\n this.#announce(node);\n }\n if (nodeUsers.size === 0) {\n // this.#delete(node);\n }\n }\n\n #announce(node?: string) {\n const entries: [string, NodeState<unknown>][] = node === undefined\n ? Array.from(this.#state.entries())\n : [[node, this.#state.get(node)]];\n const announcements: NodeAnnouncement[] = entries.map(entryToNodeAnnouncement);\n\n const nodeConnections = this.#connections.announce(announcements);\n\n // Sync outgoing: if connect includes nodes that are already connected\n // but not yet in outgoing, add them. This handles the case where the\n // user set changed after the connection was already established.\n for (const {node: n, connect} of nodeConnections) {\n const state = this.#state.get(n);\n if (state === undefined) {\n continue;\n }\n\n // Remove stale outgoing that are no longer in connect\n for (const prev of state.outgoing) {\n if (!connect.some((c) => c.node === prev)) {\n state.outgoing.delete(prev);\n if (state.members.has(prev)) {\n state.members.delete(prev);\n state.subscriber({type: 'member-removed', node: prev}, n, this);\n }\n }\n }\n\n // Add connect targets that are already connected\n for (const c of connect) {\n if (c.node !== n && this.#connections.isConnected(c.node) && !state.outgoing.has(c.node)) {\n state.outgoing.add(c.node);\n if (!state.members.has(c.node)) {\n state.members.add(c.node);\n state.subscriber({type: 'member-added', node: c.node}, n, this);\n }\n }\n }\n }\n }\n\n #delete(node: string) {\n this.#state.delete(node);\n this.#connections.remove(node);\n }\n\n async init(gossipTimestamp = 0) {\n await this.#connections.init(gossipTimestamp);\n }\n\n async close() {\n for (const node of this.#state.keys()) {\n this.#delete(node);\n this.#relays.remove(`${this.#keyPrefix}-${node}`);\n }\n clearInterval(this.#intervalId)\n await this.#connections.close();\n }\n}\n\nconst entryToNodeAnnouncement = ([node, state]: [string, NodeState]): NodeAnnouncement => {\n const users = Array.from(state?.users);\n\n return { node, users, metadata: { version: gateway.version, type: 'io.Bridge' } };\n}\n", "import type { Logger } from '@interopio/gateway/logging/api';\nimport { hrwHash } from 'hrw-hash';\nimport { LamportClock, type LamportTimestamp } from './lamport.ts';\nimport type { Node, NodeAnnouncement, NodeConnection, NodeConnections, NodeEventTypes } from './types.ts';\nimport { EventEmitter } from 'node:events';\n\ntype NodeValue = Omit<Node, 'users'> & {\n node: string\n readonly firstSeen: LamportTimestamp\n status: 'announced' | 'added' | 'expired' | 'removed'\n owner: string\n replicas: readonly string[]\n users: Set<string>\n lastSeen: number\n relayOwner?: string\n readonly metadata?: { [key: string]: unknown }\n}\n\nexport default class InMemoryNodeConnections implements NodeConnections {\n readonly #logger: Logger;\n readonly #eventEmitter = new EventEmitter<NodeEventTypes>();\n readonly #nodes = new Map<string, NodeValue>();\n readonly #clusterNodes: string[];\n readonly #lamport: LamportClock;\n readonly #timeout: number;\n\n constructor(logger: Logger,\n instanceId: string,\n timeout: number = 60000) {\n this.#logger = logger;\n this.#clusterNodes = [instanceId];\n this.#lamport = new LamportClock(instanceId);\n this.#timeout = timeout;\n }\n\n async init(gossipTimestamp = 0) {\n await this.#lamport.init(gossipTimestamp);\n }\n\n async close() {\n await this.#lamport.shutdown();\n }\n\n get timeout(): number {\n return this.#timeout;\n }\n\n announce(announcements: Array<NodeAnnouncement>): NodeConnection[] {\n const now = Date.now();\n for (const announcement of announcements) {\n const { node: nodeId, users, endpoint: announcedEndpoint, metadata } = announcement;\n\n const replicas : readonly string[] = hrwHash(nodeId, this.#clusterNodes);\n const owner = replicas[0];\n const externalEndpoint = announcedEndpoint !== undefined && announcedEndpoint !== `/cluster?node=${nodeId}`;\n const endpoint = externalEndpoint ? announcedEndpoint : `/cluster?node=${nodeId}&owner=${owner}`;\n\n let node: NodeValue = this.#nodes.get(nodeId);\n const userSet = new Set<string>(users ?? []);\n if (!node) {\n const lamport = this.#lamport.tick();\n node = {node: nodeId, users: userSet, firstSeen: lamport, lastSeen: now, owner, replicas, endpoint, metadata, status: 'announced' };\n this.#nodes.set(nodeId, node);\n this.#logger.info(`${nodeId} announced at endpoint ${endpoint} with meta: ${JSON.stringify(metadata)}`);\n }\n\n node.owner = owner;\n if (!externalEndpoint) {\n node.endpoint = endpoint;\n }\n node.replicas = replicas;\n node.lastSeen = now;\n if (!(node.status === 'announced' || node.status === 'added')) {\n node.status = 'announced';\n }\n node.users = userSet;\n\n this.#eventEmitter.emit('node-announced', nodeId, endpoint, userSet);\n }\n const sortedNodes = this.#sortedNodeValues();\n return announcements.map((e) => {\n const node = this.#nodes.get(e.node);\n const connect = this.#findConnections(sortedNodes, node);\n return { node: node.node, owner: node.owner, connect };\n });\n }\n\n find(nodeId: string): ReadonlyArray<Node> | undefined {\n const e = this.#nodes.get(nodeId);\n if (e !== undefined) {\n const sortedNodes = this.#sortedNodeValues();\n return this.#findConnections(sortedNodes, e);\n }\n return undefined;\n }\n\n isConnected(nodeId: string): boolean {\n return this.#nodes.get(nodeId)?.status === 'added';\n }\n\n add(nodeId: string) {\n const added = this.#nodes.get(nodeId);\n if (added !== undefined && (added.status === 'announced' || added.status === 'removed')) {\n added.status = 'added';\n this.#logger.info(`endpoint ${added.endpoint} connected for ${nodeId}`);\n this.#eventEmitter.emit('node-connected', nodeId);\n return true;\n }\n return false;\n }\n\n remove(nodeId: string) {\n const removed = this.#nodes.get(nodeId);\n if (removed !== undefined && (removed.status === 'announced' || removed.status === 'added')) {\n removed.status = 'removed';\n this.#logger.info(`endpoint ${removed.endpoint} removed for ${nodeId}`);\n this.#eventEmitter.emit('node-disconnected', nodeId, 'removed');\n return true;\n }\n return false;\n }\n\n #sortedNodeValues(): NodeValue[] {\n this.#cleanupOldNodes();\n return Array.from(this.#nodes.values())\n .filter((n) => n.status === 'announced' || n.status === 'added')\n .sort((a, b) => {\n const diff = a.firstSeen.timestamp - b.firstSeen.timestamp;\n if (diff === 0) {\n return a.node.localeCompare(b.node);\n }\n return diff;\n });\n }\n\n #cleanupOldNodes() {\n const now = Date.now();\n const expiredTimestamp = now - this.#timeout;\n const removedTimestamp = now - (this.#timeout * 2);\n const compactTimestamp = now - (this.#timeout * 10);\n for (const [nodeId, v] of this.#nodes) {\n if (v.lastSeen < compactTimestamp && v.status === 'removed') {\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${nodeId} compact - no announcement since ${new Date(v.lastSeen).toISOString()}, timeout is ${this.#timeout} ms and status is ${v.status}.`);\n }\n this.#nodes.delete(nodeId);\n }\n if (v.lastSeen < removedTimestamp && v.status === 'expired') {\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${nodeId} removed - no announcement since ${new Date(v.lastSeen).toISOString()}, timeout is ${this.#timeout} ms.`);\n }\n // mark as removed\n v.status = 'removed';\n }\n\n if (v.lastSeen < expiredTimestamp && (v.status === 'announced' || v.status === 'added')) {\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${nodeId} expired - no announcement since ${new Date(v.lastSeen).toISOString()}, timeout is ${this.#timeout} ms.`);\n }\n // mark as expired\n v.status = 'expired';\n this.#eventEmitter.emit('node-disconnected', nodeId, 'expired');\n }\n }\n }\n\n public on<K extends keyof NodeEventTypes>(event: K, listener: (K extends keyof NodeEventTypes ? NodeEventTypes[K] extends unknown[] ? (...args: NodeEventTypes[K]) => void : never : never)): this {\n this.#eventEmitter.on(event, listener);\n return this;\n }\n\n public off<K extends keyof NodeEventTypes>(event: K, listener: (K extends keyof NodeEventTypes ? NodeEventTypes[K] extends unknown[] ? (...args: NodeEventTypes[K]) => void : never : never)): this {\n this.#eventEmitter.off(event, listener);\n return this;\n }\n\n #findConnections(sortedNodes: NodeValue[], node: NodeValue): ReadonlyArray<Node> {\n const results = sortedNodes.reduce((l, c) => {\n if (c.node === node.node) {\n return l;\n }\n const isOlder = c.firstSeen.timestamp < node.firstSeen.timestamp;\n if (isOlder && this.#hasSharedUsers(node, c)) {\n const e: Node = { node: c.node, endpoint: c.endpoint, owner: c.owner };\n return l.concat(e);\n }\n return l;\n }, new Array<Node>());\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`found ${results.length} connection(s) for node ${node.node}: [${results.map((e) => `${e.node}@${e.endpoint}`).join(', ')}]`);\n }\n return results;\n }\n\n #hasSharedUsers(a: NodeValue, b: NodeValue): boolean {\n for (const user of a.users) {\n if (b.users.has(user)) {\n return true;\n }\n }\n return false;\n }\n}\n", "import { appendFile, readFile, rename, writeFile } from 'node:fs/promises';\n\nexport type LamportTimestamp = { readonly timestamp: number, readonly instanceId: string }\n\nexport class LamportClock {\n static #FLUSH_INTERVAL = 5000; // 5 seconds\n static #CLOCK_FILE = './lamport.clock';\n static #WAL_FILE = './lamport.wal';\n #timestamp: number;\n #instanceId: string;\n #flushIntervalId: ReturnType<typeof setInterval>;\n #pendingWrites = 0;\n\n constructor(instanceId: string) {\n this.#instanceId = instanceId;\n this.#timestamp = 0;\n this.#flushIntervalId = setInterval(() => {\n this.#flush().catch(err => {/* ignore */});\n }, LamportClock.#FLUSH_INTERVAL);\n }\n\n async init(gossipTimestamp = 0) {\n const baseTimestamp = await this.#loadSnapshot();\n const journaledIncrements = await this.#replayWal();\n this.#timestamp = Math.max(baseTimestamp + journaledIncrements, gossipTimestamp);\n }\n\n tick(): LamportTimestamp {\n this.#timestamp += 1;\n this.#pendingWrites += 1;\n this.#appendToWal().catch((_err) => {/* ignore */\n }); // async fire-and-forget, no need to await\n return { timestamp: this.#timestamp, instanceId: this.#instanceId };\n }\n\n observe(gossipTimestamp: number): LamportTimestamp {\n this.#timestamp = Math.max(this.#timestamp, gossipTimestamp) + 1;\n this.#pendingWrites += 1;\n this.#appendToWal().catch((_err) => {/* ignore */\n }); // async fire-and-forget, no need to await\n return { timestamp: this.#timestamp, instanceId: this.#instanceId };\n }\n\n timestamp(): LamportTimestamp {\n return { timestamp: this.#timestamp, instanceId: this.#instanceId };\n }\n\n async shutdown(): Promise<void> {\n clearInterval(this.#flushIntervalId);\n await this.#flush();\n }\n\n async #appendToWal(): Promise<void> {\n const data = `${this.#timestamp}\\n`;\n await appendFile(LamportClock.#WAL_FILE, data, 'utf-8');\n }\n\n async #replayWal() {\n try {\n const data = await readFile(LamportClock.#WAL_FILE, 'utf-8');\n return data.trim().split('\\n').filter(Boolean).length;\n }\n catch {\n // ignore\n }\n return 0;\n }\n\n async #loadSnapshot() {\n try {\n const data = await readFile(LamportClock.#CLOCK_FILE, 'utf-8');\n return parseInt(data, 10) || 0;\n }\n catch {\n // ignore\n }\n return 0;\n }\n\n async #flush() {\n if (this.#pendingWrites === 0) {\n return;\n }\n const tmp = `${LamportClock.#CLOCK_FILE}.tmp`;\n const data = `${this.#timestamp}\\n`;\n await writeFile(tmp, data, { flag: 'w' });\n await rename(tmp, LamportClock.#CLOCK_FILE);\n await writeFile(LamportClock.#WAL_FILE, '', { flag: 'w' }); // truncate WAL\n this.#pendingWrites = 0;\n }\n}\n", "import type { RelayEventTypes, RelayMessageHandler, Relays, Command, EncodedCommandType } from './types.ts';\nimport { IOGateway } from '@interopio/gateway';\nimport { EventEmitter } from 'node:events';\n\nconst codec = IOGateway.Encoding.transit<Command>({\n namespaces: new Map<string, string>([\n ['commands', 'gateway.common.commands']\n ]),\n keywordize: new Map<string, IOGateway.Encoding.KeywordizeCommand>([\n ['/type', '*'],\n ['/to', new Set<string>(['all'])],\n ['/data/origin', '*'],\n ['/data/receiver/type', '*'],\n ['/data/source/type', '*'],\n ['/data/body/type', '*'],\n ])\n});\n\n// type guard, checks if the message is encoded (string or Buffer) the guard is set to string because Buffer can be used as string in JSON.parse()\nfunction isEncoded(msg: EncodedCommandType | Command): msg is string {\n return typeof msg === 'string' || Buffer.isBuffer(msg);\n}\n\ntype KeyedLinkData = {\n key: string; // relay key\n node: string; // node id\n linksByNode: Map<string, string>; // linked nodes -> sender key\n}\n\nexport class InternalRelays implements Relays {\n readonly #logger: IOGateway.Logging.Logger;\n // key -> handler\n readonly #handlersByKey = new Map<string, RelayMessageHandler>();\n // node -> keyed link\n readonly #links = new Map<string, KeyedLinkData>();\n readonly #eventEmitter = new EventEmitter<RelayEventTypes>();\n\n constructor(logger: IOGateway.Logging.Logger) {\n this.#logger = logger;\n }\n\n add(key: string, handler: RelayMessageHandler) {\n this.#handlersByKey.set(key, handler);\n }\n\n remove(key: string) {\n this.#handlersByKey.delete(key);\n this.#disconnect(key);\n }\n\n #disconnect(key: string, from?: string) {\n for (const [node, k] of this.#links) {\n if (k.key === key && (from === undefined || k.node === from)) {\n const links = k.linksByNode;\n if (this.#logger.enabledFor('info')) {\n this.#logger.info(`${key} unregisters node ${node}, linked to ${Array.from(links.keys()).join(', ')}`);\n }\n this.#links.delete(node);\n this.#eventEmitter.emit('disconnect', key, node, links);\n }\n }\n }\n #connect(key: string, node: string) {\n if (this.#logger.enabledFor('info')) {\n this.#logger.info(`${key} registers node ${node}`);\n }\n this.#links.set(node, {key, node: node, linksByNode: new Map<string, string>()});\n this.#eventEmitter.emit('connect', key, node);\n }\n\n receive(key: string, msg: string | Command) {\n const {node, decoded, encoded} = this.link(key, msg);\n\n if (node) {\n this.#eventEmitter.emit('message', key, node, encoded, decoded);\n }\n }\n\n private link(key: string, msg: string | Command) {\n try {\n const decoded: Command = isEncoded(msg) ? codec.decode(msg) : msg;\n const {type, from, to} = decoded;\n if (to === 'all') {\n switch (type) {\n case 'hello': {\n this.#connect(key, from);\n break;\n }\n case 'bye': {\n this.#disconnect(key, from);\n break;\n }\n }\n return { decoded };\n }\n else {\n const node = decoded.to;\n const link = decoded.from;\n const type = decoded.type;\n const senderLinkData = this.#links.get(link);\n switch (type) {\n case 'hello':\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${key} connecting ${link} to ${node}`);\n }\n senderLinkData?.linksByNode.set(decoded.to, key);\n break;\n case 'bye':\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${key} disconnecting ${link} from ${node}`);\n }\n senderLinkData?.linksByNode.delete(decoded.to);\n break;\n }\n }\n\n const encoded: string = isEncoded(msg) ? msg : codec.encode(msg);\n return { node: from, decoded, encoded };\n }\n catch (e) {\n // probably a decode error or a bug\n if (!this.#eventEmitter.emit('error', key, e instanceof Error ? e : new Error(`link failed :${e}`))) {\n this.#logger.warn(`${key} unable to process ${msg}`, e);\n }\n }\n }\n\n on<K extends keyof RelayEventTypes>(event: K, listener: (K extends keyof RelayEventTypes ? RelayEventTypes[K] extends unknown[] ? (...args: RelayEventTypes[K]) => void : never : never)): this {\n this.#eventEmitter.on(event, listener);\n return this;\n }\n\n send(key: string, node: string, msg: string | Command, cb: (k: string, err?: Error) => void): void {\n if (this.#logger.enabledFor('trace')) {\n this.#logger.debug(`${key} sending msg to ${node}`);\n }\n\n const encoded = isEncoded(msg) ? msg : codec.encode(msg);\n const decoded = isEncoded(msg) ? codec.decode(msg) : msg;\n {\n node ??= decoded.to;\n const link = decoded.from;\n const type = decoded.type;\n const senderLinkData = this.#links.get(link);\n switch (type) {\n case 'hello':\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${key} connecting ${link} to ${node}`);\n }\n senderLinkData?.linksByNode.set(node, key);\n break;\n case 'bye':\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${key} disconnecting ${link} from ${node}`);\n }\n senderLinkData?.linksByNode.delete(node);\n break;\n }\n }\n {\n const receiverLinkData = this.#links.get(node);\n if (receiverLinkData?.key) {\n const handler = this.#handlersByKey.get(receiverLinkData?.key);\n if (handler) {\n handler(encoded, decoded, cb);\n return;\n }\n }\n }\n if (decoded.type === 'bye') {\n return;\n }\n throw new Error(`${key} no active link for ${node}`);\n }\n}\n", "{\n \"name\": \"@interopio/bridge\",\n \"version\": \"1.1.0\",\n \"license\": \"see license in license.md\",\n \"author\": \"interop.io\",\n \"homepage\": \"https://docs.interop.io/bridge\",\n \"keywords\": [\n \"io.bridge\",\n \"bridge\",\n \"io.connect\",\n \"glue42\",\n \"interop.io\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/InteropIO/bridge.git\",\n \"directory\": \"packages/bridge\"\n },\n \"type\": \"module\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"default\": \"./dist/index.js\"\n },\n \"./main\": {\n \"import\": {\n \"types\": \"./types/main.d.ts\",\n \"default\": \"./dist/main.js\"\n }\n }\n },\n \"bin\": {\n \"io-bridge\": \"bin/bridge.js\"\n },\n \"scripts\": {\n \"test\": \"mocha test --recursive\",\n \"build:types\": \"tsc --declaration --emitDeclarationOnly --outDir types\",\n \"build:main\": \"esbuild src/main.mts --outdir=dist --bundle --packages=external --sourcemap --platform=node --format=esm --target=node20.18\",\n \"build:index\": \"esbuild src/index.ts --outdir=dist --target=node20.18\",\n \"build\": \"npm run build:main && npm run build:index\"\n },\n \"dependencies\": {\n \"@interopio/gateway-server\": \"^0.23.1\",\n \"jsrsasign\": \"^11.1.1\",\n \"hrw-hash\": \"^2.0.3\",\n \"nanoid\": \"^5.1.7\"\n },\n \"devDependencies\": {\n \"@interopio/gateway\": \"^0.25.0\",\n \"@types/jsrsasign\": \"^10.5.15\",\n \"@types/ws\": \"^8.18.1\",\n \"rand-seed\": \"^3.0.0\"\n },\n \"engines\": {\n \"node\": \"^20.18.0 || ^22.2.0 || >=24\"\n }\n}\n", "function parse(version: string): [number, number, number] {\n // https://regex101.com/r/Ly7O1x/3/\n const pattern = /^(?<major>0|[1-9]\\d*)\\.(?<minor>0|[1-9]\\d*)\\.(?<patch>0|[1-9]\\d*)(?:-(?<prerelease>(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+(?<buildmetadata>[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/g;\n\n const {groups} = pattern.exec(version);\n const major = parseInt(groups['major']);\n const minor = parseInt(groups['minor']);\n const patch = parseInt(groups['patch']);\n\n return [major, minor, patch];\n}\n\nclass MemberVersion {\n\n readonly major: number;\n readonly minor: number;\n readonly patch: number;\n\n public get isUnknown(): boolean {\n return this.major === 0 && this.minor === 0 && this.patch === 0;\n }\n\n public toString(): string {\n return `${this.major}.${this.minor}.${this.patch}`;\n }\n\n constructor(major: number, minor: number, patch: number) {\n this.major = major;\n this.minor = minor;\n this.patch = patch;\n }\n}\n\nexport const UNKNOWN_VERSION: MemberVersion = new MemberVersion(0, 0, 0);\n\nexport function parseVersion(version?: string): MemberVersion {\n if (!version || version.startsWith('0.0.0')) {\n return UNKNOWN_VERSION;\n }\n return new MemberVersion(...parse(version));\n}\n\nexport type {MemberVersion};\n", "import {networkInterfaces} from 'node:os';\nimport {ADDRCONFIG, type LookupAddress} from 'node:dns';\nimport {lookup, lookupService} from 'node:dns/promises';\n\nimport {textToNumericFormatV4, textToNumericFormatV6} from './internal/IpAddressUtil.ts';\nimport {readFileSync} from \"node:fs\";\n\nconst INET_ADDRESS_V4_SIZE = 4;\n\nclass IpAddress {\n readonly address: string;\n readonly family: 4 | 6;\n private _hostname?: string;\n\n constructor(host: string | undefined, address: string, family: 4 | 6) {\n this._hostname = host;\n this.address = address;\n this.family = family;\n }\n\n get addressBytes(): Uint8Array {\n if (this.family === 4) {\n return textToNumericFormatV4(this.address);\n }\n //return textToNumericFormatV6(this.address);\n }\n\n async getHost(): Promise<string> {\n if (!this._hostname) {\n this._hostname = (await lookupService(this.address, 0)).hostname;\n }\n return this._hostname;\n }\n\n async getIpAddress(nonLoopback: boolean = false): Promise<LookupAddress> {\n const hints = nonLoopback ? ADDRCONFIG : undefined;\n return await lookup(this.address, {family: this.family, hints: hints});\n }\n}\n\nexport type {IpAddress};\n\nexport function isLoopback(address: IpAddress): boolean {\n return address.family === 4 && address.address.startsWith('127.') || address.family === 6 && address.address.startsWith('::1');\n}\n\nexport async function getByName(host: string): Promise<IpAddress> {\n const {address, family} = await lookup(host, {family: 4});\n if (family !== 4 && family !== 6) {\n throw new Error('unexpected address type');\n }\n return new IpAddress(undefined, address, family);\n}\n\nlet _anyLocalAddress: IpAddress;\n\nexport function anyLocalAddress(): IpAddress {\n if (!_anyLocalAddress) {\n _anyLocalAddress = getByAddress('0.0.0.0', 0);\n }\n return _anyLocalAddress;\n}\n\nexport function getByAddress(host: string, bytes: Uint8Array | number): IpAddress {\n if (typeof bytes === 'number') {\n const n = bytes;\n bytes = new Uint8Array(INET_ADDRESS_V4_SIZE);\n new DataView(bytes.buffer).setInt32(0, n);\n }\n const family = bytes.length === INET_ADDRESS_V4_SIZE ? 4 : 6;\n const address = Array.from(bytes).join('.');\n return new IpAddress(host, address, family);\n}\n\nexport async function resolveByAddress(host: string, address: string): Promise<IpAddress> {\n const byName = await getByName(address);\n // todo: check if address and host names are correct\n return new IpAddress(host, byName.address, byName.family);\n}\n\nexport async function getAllByName(host: string): Promise<IpAddress[]> {\n const addresses = await lookup(host, {all: true});\n return addresses.map(({address, family}) => {\n if (family !== 4 && family !== 6) {\n throw new Error('unexpected address type');\n }\n return new IpAddress(undefined, address, family);\n });\n}\n\nexport interface NetworkInterface {\n name: string\n loopback: boolean\n addresses: Array<IpAddress>\n}\n\nexport function getNetworkInterfaces(): NetworkInterface[] {\n return Object.entries(networkInterfaces()).map(([name, addresses]) => {\n return {\n name,\n loopback: addresses.some(info => info.internal),\n addresses: addresses.map(info => {\n return new IpAddress(undefined, info.address, info.family === 'IPv6' ? 6 : 4);\n })\n };\n });\n}\n\nfunction soMaxConn() {\n let somaxconn;\n if (process.platform === 'win32') {\n somaxconn = 200;\n }\n else if (process.platform === 'darwin') {\n somaxconn = 128;\n }\n else {\n somaxconn = 4096;\n }\n\n try {\n somaxconn = parseInt(readFileSync('/proc/sys/net/core/somaxconn').toString());\n } catch (error) {\n // todo log\n }\n return somaxconn;\n}\n\nexport const SOMAXCONN = soMaxConn();\n\n", "const DOT = '.'.charCodeAt(0);\nconst INET_ADDRESS_V4_SIZE = 4;\nconst INET_ADDRESS_V6_SIZE = 16;\nconst BYTE_SIZE = 2; // 8 bits in hex\nconst COLON = ':'.charCodeAt(0);\n\nexport function textToNumericFormatV4(address: string): Uint8Array {\n const result = new Uint8Array(4);\n const len = address.length;\n if (len == 0 || len > 15) {\n return;\n }\n\n let currentValue = 0;\n let currentByte = 0;\n let newByte = true;\n for (let i = 0; i < len; i++) {\n const ch = address.charCodeAt(i);\n if (ch === DOT) {\n if (newByte || currentValue < 0 || currentValue > 0xff || currentByte > 3) {\n return;\n }\n result[currentByte++] = currentValue & 0xff;\n currentValue = 0;\n newByte = true;\n } else {\n const digit = ch - 48;\n if (digit < 0) {\n return;\n }\n currentValue *= 10;\n currentValue += digit;\n newByte = false;\n }\n }\n if (newByte || currentValue < 0 || currentValue >= (1 << ((4 - currentByte) * 8))) {\n return;\n }\n\n switch (currentByte) {\n case 0:\n result[0] = (currentValue >> 24) & 0xff;\n //fall through\n case 1:\n result[1] = (currentValue >> 16) & 0xff;\n //fall through\n case 2:\n result[2] = (currentValue >> 8) & 0xff;\n //fall through\n case 3:\n result[3] = (currentValue >> 0) & 0xff;\n }\n return result;\n}\n\nexport function textToNumericFormatV6(address: string): Uint8Array {\n if (address.length < 2) {\n return;\n }\n\n // let colonp: number;\n // let char: number;\n // let saw_xdigit: boolean;\n // let val: number;\n // const dst = new Uint8Array(INET_ADDRESS_V6_SIZE);\n //\n // const srcb_length = address.length;\n // const pc = src.indexOf('%');\n // if (pc === srcb_length -1) {\n // return;\n // }\n //\n // colonp = -1;\n //\n // let i = 0, j = 0;\n // /* Leading :: requires some special handling. */\n // if (address.charAt(i) === ':')\n // if (address.charAt(++i) !== ':')\n // return;\n // curtok = i;\n // saw_xdigit = false;\n // val = 0;\n // while (i < srcb_length) {\n // const ch = address.charCodeAt(i++);\n // const chval = ch - 48;\n // if (chval !== -1) {\n // val <<= 4;\n // val |= chval;\n // if (val > 0xffff)\n // return;\n // saw_xdigit = true;\n // continue;\n // }\n // if (ch == ':') {\n // curtok = i;\n // if (!saw_xdigit) {\n // if (colonp != -1)\n // return null;\n // colonp = j;\n // continue;\n // } else if (i == srcb_length) {\n // return null;\n // }\n // if (j + INT16SZ > INADDR16SZ)\n // return null;\n // dst[j++] = (byte) ((val >> 8) & 0xff);\n // dst[j++] = (byte) (val & 0xff);\n // saw_xdigit = false;\n // val = 0;\n // continue;\n // }\n // if (ch == '.' && ((j + BYTE_SIZE) <= INET_ADDRESS_V6_SIZE)) {\n // const ia4 = address.substring(curtok, srcb_length);\n // /* check this IPv4 address has 3 dots, ie. A.B.C.D */\n // let dot_count = 0, index=0;\n // while ((index = ia4.indexOf ('.', index)) != -1) {\n // dot_count ++;\n // index ++;\n // }\n // if (dot_count != 3) {\n // return null;\n // }\n // const v4addr = textToNumericFormatV4(ia4);\n // if (v4addr == null) {\n // return null;\n // }\n // for (let k = 0; k < INET_ADDRESS_V4_SIZE; k++) {\n // dst[j++] = v4addr[k];\n // }\n // saw_xdigit = false;\n // break; /* '\\0' was seen by inet_pton4(). */\n // }\n // return null;\n // }\n // if (saw_xdigit) {\n // if (j + INT16SZ > INADDR16SZ)\n // return null;\n // dst[j++] = (byte) ((val >> 8) & 0xff);\n // dst[j++] = (byte) (val & 0xff);\n // }\n //\n // if (colonp != -1) {\n // const n = j - colonp;\n //\n // if (j == INADDR16SZ)\n // return null;\n // for (i = 1; i <= n; i++) {\n // dst[INADDR16SZ - i] = dst[colonp + n - i];\n // dst[colonp + n - i] = 0;\n // }\n // j = INADDR16SZ;\n // }\n // if (j != INADDR16SZ)\n // return null;\n // const newdst = convertFromIPv4MappedAddress(dst);\n // if (newdst != null) {\n // return newdst;\n // } else {\n // return dst;\n // }\n}\n", "import {getByName, type IpAddress} from '../utils/network.ts';\nimport {type Comparator, compareArrays} from '../utils/collections.ts';\n\nexport type Address = Readonly<{\n type: 4 | 6,\n host: string,\n port: number,\n address: IpAddress\n}>;\nexport function addressAsString(address: Pick<Address, 'host' | 'port' | 'type'>): string {\n // todo: do better for ipv6\n return `${address.host}:${address.port}`;\n}\nexport async function toIpAddress(address: Address): Promise<IpAddress> {\n return await getByName(scopedHost(address));\n}\n\nexport async function fromHostname(hostname: string, port: number): Promise<Address> {\n return new AddressImpl(hostname, await getByName(hostname), port);\n}\nexport function fromIpAddress(address: IpAddress, port: number): Address {\n\n return new AddressImpl(undefined, address, port);\n}\n\nclass AddressImpl {\n readonly type: 4 | 6;\n readonly host: string;\n readonly port: number;\n readonly address: IpAddress;\n\n constructor(hostname: string | undefined, ipAddress: IpAddress, port : number) {\n const type = ipAddress.family;\n if (type !== 4 && type !== 6) {\n throw new Error('unexpected address type');\n }\n this.type= type;\n this.host = hostname ?? ipAddress.address;\n this.port = port;\n this.address = ipAddress;\n }\n}\n\nfunction scopedHost(address: Address): string {\n if (address.type === 6) {\n return `[${address.host}]`;\n }\n return address.host;\n}\n\nexport const compareAddress: Comparator<Address> = (a1: Address, a2: Address) => {\n const addressBytes1 = a1.address.addressBytes;\n const addressBytes2 = a2.address.addressBytes;\n const result = compareArrays(addressBytes1, 0, addressBytes1.length, addressBytes2, 0, addressBytes2.length, (b1, b2) => {\n return b1 === b2 ? 0 : (b1 > b2 ? 1 : -1);\n });\n if (result !== 0) {\n return result;\n }\n\n return a1.port === a2.port ? 0 : (a1.port > a2.port ? 1 : -1);\n}\n", "export interface PropertyDefinition {\n readonly key: string\n readonly optional: boolean\n readonly converter: PropertyTypeConverter<PropertyType>\n}\n\nexport type PropertyType = string | number | boolean;\nexport type Properties = { [key: string]: PropertyType };\n\nexport interface PropertyTypeConverter<T extends PropertyType> {\n convert(value: unknown): T\n}\n\nexport const BOOLEAN = new class implements PropertyTypeConverter<boolean> {\n convert(value: unknown): boolean {\n if (typeof value === 'boolean') {\n return value;\n }\n else if (typeof value === \"string\") {\n return value.toLowerCase() === \"true\";\n }\n throw new Error(\"Cannot convert value to boolean: \" + value);\n }\n};\n\nexport const STRING = new class implements PropertyTypeConverter<string> {\n convert(value: unknown): string {\n if (value === undefined) {\n throw new Error(\"Cannot convert undefined \");\n }\n return String(value);\n }\n}\n\nexport const NUMBER = new class implements PropertyTypeConverter<number> {\n convert(value: unknown): number {\n if (value === undefined) {\n throw new Error(\"Cannot convert undefined \");\n }\n if (typeof value === \"object\") {\n throw new Error(\"Cannot convert object/array to number: \" + value);\n }\n return Number(value);\n }\n}\n\nexport function property<T extends PropertyType>(name: string, converter: PropertyTypeConverter<T>): PropertyDefinition {\n return {key: name, optional: true, converter: converter};\n}\n", "import { BOOLEAN } from './Properties.ts';\n\nexport abstract class NamedDiscoveryConfig {\n readonly #tag: string;\n #enabled: boolean = false;\n readonly #properties: Map<string, string>;\n\n protected constructor(tag: string) {\n this.#tag = tag;\n this.#properties = new Map();\n }\n\n get tag(): string {\n return this.#tag;\n }\n\n setEnabled(enabled: boolean): this {\n this.#enabled = enabled;\n return this;\n }\n\n get enabled(): boolean {\n return this.#enabled;\n }\n\n setProperty(key: string, value: string): this {\n if ('enabled' === key) {\n this.#enabled = BOOLEAN.convert(value);\n }\n else {\n this.#properties.set(key, value);\n }\n return this;\n }\n\n getProperty(key: string): string | undefined {\n return this.#properties.get(key);\n }\n\n get properties(): Map<string, string> {\n return this.#properties;\n }\n}\n", "import { NamedDiscoveryConfig } from './NamedDiscoveryConfig.ts';\n\nexport class KubernetesConfig extends NamedDiscoveryConfig {\n constructor() {\n super(\"kubernetes\");\n }\n}\n", "import type { DiscoveryServiceFactory, DiscoveryStrategyFactory } from '../discovery/index.ts';\nimport type { PropertyType } from './Properties.ts';\n\nexport interface DiscoveryStrategyConfig {\n readonly discoveryStrategyFactory?: DiscoveryStrategyFactory\n readonly constructorName: string\n readonly properties: Map<string, PropertyType>\n}\nexport interface DiscoveryConfig {\n readonly discoveryStrategyConfigs: ReadonlyArray<DiscoveryStrategyConfig>\n readonly discoveryServiceFactory?: DiscoveryServiceFactory\n}\n\nexport class DefaultDiscoveryConfig implements DiscoveryConfig\n{\n discoveryStrategyConfigs: DiscoveryStrategyConfig[] = [];\n discoveryServiceFactory?: DiscoveryServiceFactory;\n\n get enabled() {\n return this.discoveryStrategyConfigs.length > 0;\n }\n}\n", "import type { Properties, PropertyType } from './Properties.ts';\nimport { KubernetesConfig } from './KubernetesConfig.ts';\nimport {\n DefaultDiscoveryConfig,\n type DiscoveryConfig\n} from './DiscoveryConfig.ts';\n\nexport class AutoDetectionConfig {\n enabled: boolean = true;\n}\n\nexport interface MulticastConfig {\n readonly group: string\n readonly port: number\n}\n\nclass DefaultMulticastConfig implements MulticastConfig {\n enabled: boolean = false;\n group: string = '239.1.2.3';\n port: number = 34567;\n}\n\nexport interface TcpIpConfig {\n members: string[]\n}\n\nclass DefaultTcpIpConfig implements TcpIpConfig {\n enabled: boolean = false;\n members: string[] = [];\n}\n\nexport class JoinConfig {\n private _multicast = new DefaultMulticastConfig();\n private _tcpIp = new DefaultTcpIpConfig();\n private _kubernetes = new KubernetesConfig();\n private _discovery = new DefaultDiscoveryConfig();\n private _autoDetection = new AutoDetectionConfig();\n\n get discovery(): DiscoveryConfig {\n return this._discovery;\n }\n\n get multicast(): MulticastConfig {\n return this._multicast;\n }\n\n get kubernetes(): KubernetesConfig {\n return this._kubernetes;\n }\n\n get autoDetectionEnabled(): boolean {\n return this._autoDetection.enabled\n && !this._multicast.enabled\n && !this._tcpIp.enabled\n && !this._kubernetes.enabled\n && !this._discovery.enabled;\n }\n}\n\nexport class NetworkConfig {\n public static readonly DEFAULT_PORT: number = 8383;\n port: number = NetworkConfig.DEFAULT_PORT;\n reuseAddress: boolean;\n publicAddress?: string;\n join = new JoinConfig();\n\n constructor() {\n this.reuseAddress = process.platform !== \"win32\";\n }\n}\n\nexport class CorsConfig {\n #allowOrigin?: '*' | string[] = undefined;\n set allowOrigin(value: string | undefined) {\n if (value !== undefined) {\n if (value === '*') {\n this.#allowOrigin = value;\n }\n else if (Array.isArray(value)) {\n this.#allowOrigin = value;\n }\n else {\n this.#allowOrigin = value.split(',');\n }\n }\n }\n\n get allowOrigin(): '*' | string[] | undefined {\n return this.#allowOrigin;\n }\n\n disabled?: true;\n allowCredentials: boolean = false;\n}\n\nexport class SslConfig {\n enabled?: boolean;\n key?: string;\n cert?: string;\n ca?: string;\n}\n\nexport class ServerConfig {\n port?: number = undefined;\n host?: string = undefined;\n ssl = new SslConfig();\n cors = new CorsConfig();\n auth: {\n type: 'none' | 'basic' | 'x509' | 'oauth2',\n basic?: {\n realm?: string\n },\n x509?: {\n key?: string\n },\n oauth2?: { jwt: { issuerUri: string, issuer?: string, audience?: string | string[] } }\n } = {\n type: 'none',\n basic: {\n realm: 'io.Bridge'\n },\n oauth2: {\n jwt: {issuerUri: ''}\n },\n x509: {\n\n }\n };\n wsPingInterval?: number = 30000; // 30 seconds\n}\n\nexport class MeshConfig {\n timeout?: number\n}\n\nexport class GatewayConfig {\n enabled?: boolean;\n contexts: {\n lifetime: 'retained' | 'ref-counted' | 'ownership'\n } = {lifetime: 'retained'};\n}\n\nexport class Config {\n properties: Properties = {};\n network = new NetworkConfig();\n license: string\n readonly server: ServerConfig;\n readonly mesh: MeshConfig;\n readonly gateway: GatewayConfig;\n\n constructor() {\n this.server = new ServerConfig();\n this.mesh = new MeshConfig();\n this.gateway = new GatewayConfig();\n }\n\n get<T extends PropertyType>(name: string): T {\n const value = this.properties[name] as T;\n return value;\n }\n\n set<T extends PropertyType>(name: string, value: T): this {\n this.properties[name] = value;\n return this;\n }\n}\n", "import {\n type DiscoveryNode,\n type DiscoveryStrategyFactory,\n DiscoveryStrategyPriorities\n} from '../discovery/index.ts';\nimport {stat} from 'node:fs/promises';\nimport {lookup} from 'node:dns/promises'\nimport {KubernetesDiscoveryStrategy} from './KubernetesDiscoveryStrategy.ts';\nimport type {Properties, PropertyDefinition} from '../config/Properties.ts';\nimport {\n EXPOSE_EXTERNALLY, KUBERNETES_API_TOKEN,\n KUBERNETES_MASTER_URL,\n NAMESPACE, POD_LABEL_NAME, POD_LABEL_VALUE, RESOLVE_NOT_READY_ADDRESSES,\n SERVICE_DNS,\n SERVICE_LABEL_NAME,\n SERVICE_LABEL_VALUE,\n SERVICE_NAME, SERVICE_PORT\n} from './KubernetesProperties.ts';\nimport {type ClusterTopologyIntentTracker} from '../instance/ClusterTopologyIntentTracker.ts';\nimport {type Logger} from '../logging.ts';\n\nconst PROPERTY_DEFINITIONS: ReadonlyArray<PropertyDefinition> = [\n SERVICE_DNS,\n SERVICE_NAME,\n SERVICE_LABEL_NAME,\n SERVICE_LABEL_VALUE,\n NAMESPACE,\n POD_LABEL_NAME,\n POD_LABEL_VALUE,\n RESOLVE_NOT_READY_ADDRESSES,\n EXPOSE_EXTERNALLY,\n KUBERNETES_MASTER_URL,\n KUBERNETES_API_TOKEN,\n SERVICE_PORT\n];\n\nexport class KubernetesDiscoveryStrategyFactory implements DiscoveryStrategyFactory {\n private readonly tokenPath: string;\n readonly priority = DiscoveryStrategyPriorities.PLATFORM;\n constructor(tokenPath = '/var/run/secrets/kubernetes.io/serviceaccount/token') {\n this.tokenPath = tokenPath;\n }\n\n getDiscoveryStrategyType() {\n return KubernetesDiscoveryStrategy;\n }\n\n private async defaultKubernetesMasterReachable() {\n try {\n await lookup('kubernetes.default.svc');\n return true;\n } catch (e) {\n // todo log that io.Bridge running on Kubernetes, but \"kubernetes.default.svc\" is not reachable.\n return false;\n }\n }\n\n async tokenFileExists(){\n try {\n await stat(this.tokenPath);\n return true;\n } catch (e) {\n return false;\n }\n }\n\n async isAutoDetectionApplicable() {\n return await this.tokenFileExists() && await this.defaultKubernetesMasterReachable()\n }\n\n newDiscoveryStrategy(node: DiscoveryNode | undefined, logger: Logger, properties: Properties) {\n const tracker = node?.properties.get(\"internal.discovery.cluster.topology.intent.tracker\");\n return new KubernetesDiscoveryStrategy(logger, properties, tracker as ClusterTopologyIntentTracker | undefined);\n }\n\n getConfigurationProperties(): ReadonlyArray<PropertyDefinition> {\n return PROPERTY_DEFINITIONS;\n }\n}\n", "import {type DiscoveryNode} from '../discovery/index.ts';\nimport {getByName} from '../utils/network.ts';\nimport type {Logger} from '../logging.ts';\n\nconst DNS_RETRY = 5;\n\nexport abstract class KubernetesEndpointResolver {\n protected readonly logger: Logger;\n constructor(logger: Logger) {\n this.logger = logger;\n }\n async start() {\n // do nothing\n }\n\n abstract resolve(): Promise<DiscoveryNode[]>\n\n async close() {\n // do nothing\n }\n\n protected async mapAddress(address?: string) {\n if (!address) {\n return;\n }\n\n try {\n let retry = 0;\n try {\n return await getByName(address);\n } catch (e) {\n if (retry < DNS_RETRY) {\n retry++;\n } else {\n throw e;\n }\n }\n } catch (e) {\n // todo log address cloud not be resolved\n }\n\n }\n}\n", "import { readFileSync} from 'node:fs';\nimport { getOrDefault, getOrUndefined } from '../discovery/settings.ts';\nimport {\n KUBERNETES_API_TOKEN,\n KUBERNETES_MASTER_URL,\n KUBERNETES_ENV_PREFIX,\n NAMESPACE,\n RESOLVE_NOT_READY_ADDRESSES,\n SERVICE_DNS,\n SERVICE_NAME,\n SERVICE_PORT,\n EXPOSE_EXTERNALLY,\n SERVICE_LABEL_NAME,\n SERVICE_LABEL_VALUE,\n POD_LABEL_NAME,\n POD_LABEL_VALUE,\n SERVICE_PER_POD_LABEL_NAME, SERVICE_PER_POD_LABEL_VALUE\n} from './KubernetesProperties.ts';\nimport {type Properties} from '../config/Properties.ts';\n\nexport type DiscoveryMode = 'kubernetes-api' | 'dns-lookup';\nexport type ExposeExternallyMode = 'auto' | 'enabled' | 'disabled';\n\nfunction readFileContents(fileName: string): string {\n return readFileSync(fileName, 'utf-8').toString();\n}\n\n\nexport class KubernetesConfig {\n readonly serviceDns?: string\n\n readonly serviceName?: string\n readonly serviceLabelName?: string\n readonly serviceLabelValue?: string\n readonly namespace: string\n readonly podLabelName?: string\n readonly podLabelValue?: string\n readonly resolveNotReadyAddresses: boolean\n readonly exposeExternallyMode: ExposeExternallyMode\n readonly servicePerPodLabelName?: string\n readonly servicePerPodLabelValue?: string\n readonly kubernetesMasterUrl: string\n readonly kubernetesApiToken?: string\n\n readonly servicePort: number\n private readonly fileContentsReader: (fileName: string) => string;\n\n readonly tokenProvider: () => string;\n\n constructor(properties: Properties, fileContentsReader: (fileName: string) => string = readFileContents) {\n this.fileContentsReader = fileContentsReader;\n this.serviceDns = getOrDefault(properties, KUBERNETES_ENV_PREFIX, SERVICE_DNS);\n this.serviceName = getOrDefault(properties, KUBERNETES_ENV_PREFIX, SERVICE_NAME);\n this.serviceLabelName = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, SERVICE_LABEL_NAME);\n this.serviceLabelValue = getOrDefault(properties, KUBERNETES_ENV_PREFIX, SERVICE_LABEL_VALUE, \"true\");\n this.resolveNotReadyAddresses = getOrDefault(properties, KUBERNETES_ENV_PREFIX, RESOLVE_NOT_READY_ADDRESSES, true);\n this.podLabelName = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, POD_LABEL_NAME);\n this.podLabelValue = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, POD_LABEL_VALUE);\n\n this.exposeExternallyMode = this.getExposeExternallyMode(properties);\n this.servicePerPodLabelName = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, SERVICE_PER_POD_LABEL_NAME);\n this.servicePerPodLabelValue = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, SERVICE_PER_POD_LABEL_VALUE);\n this.kubernetesMasterUrl = getOrDefault(properties, KUBERNETES_ENV_PREFIX, KUBERNETES_MASTER_URL, \"https://kubernetes.default.svc\");\n this.tokenProvider = this.buildTokenProvider(properties);\n this.servicePort = getOrDefault(properties, KUBERNETES_ENV_PREFIX, SERVICE_PORT, 0);\n this.namespace = this.getNamespaceWithFallbacks(properties);\n }\n\n private getExposeExternallyMode(properties: Properties): ExposeExternallyMode {\n const exposeExternally: boolean | undefined = getOrUndefined<boolean>(properties, KUBERNETES_ENV_PREFIX, EXPOSE_EXTERNALLY);\n if (exposeExternally === undefined) {\n return 'auto';\n }\n else if (exposeExternally) {\n return 'enabled';\n }\n else {\n return 'disabled';\n }\n }\n\n private getNamespaceWithFallbacks(properties: Properties): string {\n let namespace: string | undefined = getOrDefault(properties, KUBERNETES_ENV_PREFIX, NAMESPACE);\n if (!namespace) {\n namespace = process.env['KUBERNETES_NAMESPACE'];\n }\n if (!namespace && this.mode === 'kubernetes-api') {\n namespace = this.readNamespace();\n }\n return namespace;\n }\n\n private buildTokenProvider(properties: {}): () => string {\n const apiToken: string | undefined = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, KUBERNETES_API_TOKEN);\n if (!apiToken && this.mode === 'kubernetes-api') {\n return () => readFileContents('/var/run/secrets/kubernetes.io/serviceaccount/token')\n } else {\n return () => apiToken;\n }\n }\n\n private readNamespace(): string {\n return this.fileContentsReader('/var/run/secrets/kubernetes.io/serviceaccount/namespace');\n }\n\n\n get mode(): DiscoveryMode {\n if (this.serviceDns) {\n return 'dns-lookup';\n }\n return 'kubernetes-api';\n }\n\n toString() {\n return \"KubernetesConfig: {\"\n + \"service-dns: \" + this.serviceDns\n + \", service-name: \" + this.serviceName\n + \", service-port: \" + this.servicePort\n + \", service-label-name: \" + this.serviceLabelName\n + \", service-label-value: \" + this.serviceLabelValue\n + \", namespace: \" + this.namespace\n + \", pod-label-name: \" + this.podLabelName\n + \", pod-label-value: \" + this.podLabelValue\n + \", resolve-not-ready-addresses: \" + this.resolveNotReadyAddresses\n + \", expose-externally-mode: \" + this.exposeExternallyMode\n + \", service-per-pod-label-name: \" + this.servicePerPodLabelName\n + \", service-per-pod-label-value: \" + this.servicePerPodLabelValue\n + \", kubernetes-master-url: \" + this.kubernetesMasterUrl + \"}\";\n }\n}\n", "import {type Properties, type PropertyDefinition, type PropertyType} from '../config/Properties.ts';\n\nfunction getProperty(prefix: string, property: PropertyDefinition) {\n let s = prefix;\n if (!s.endsWith('.')) {\n s += '.';\n }\n return s + property.key;\n}\n\nfunction readProperty(prefix: string | undefined, property: PropertyDefinition): PropertyType | undefined {\n if (prefix) {\n const p = getProperty(prefix, property);\n const v = process.env[p];\n // todo convert\n return v;\n }\n}\n\nexport function getOrUndefined<T extends PropertyType>(properties: Properties, prefix: string, property?: PropertyDefinition): T | undefined {\n return getOrDefault(properties, prefix, property);\n}\n\nexport function getOrDefault<T extends PropertyType>(properties: Properties, prefix: string, property?: PropertyDefinition, defaultValue?: T) {\n if (property === undefined) {\n return defaultValue;\n }\n\n let value = readProperty(prefix, property);\n if (value === undefined) {\n value = properties[property.key];\n }\n if (value === undefined) {\n return defaultValue;\n }\n return value as T;\n}\n", "import {BOOLEAN, NUMBER, property, STRING} from '../config/Properties.ts';\n\nexport const KUBERNETES_ENV_PREFIX = 'io.bridge.kubernetes';\n\n\n\n\nexport const SERVICE_DNS = property<string>('service-dns', STRING);\nexport const SERVICE_NAME = property<string>('service-name', STRING);\nexport const SERVICE_LABEL_NAME = property<string>('service-label-name', STRING);\nexport const SERVICE_LABEL_VALUE = property<string>('service-label-value', STRING);\nexport const NAMESPACE = property<string>('namespace', STRING);\nexport const POD_LABEL_NAME = property<string>('pod-label-name', STRING);\nexport const POD_LABEL_VALUE = property<string>('pod-label-value', STRING);\nexport const EXPOSE_EXTERNALLY = property<boolean>('expose-externally', BOOLEAN);\nexport const SERVICE_PER_POD_LABEL_NAME = property<string>('service-per-pod-label-name', STRING);\nexport const SERVICE_PER_POD_LABEL_VALUE = property<string>('service-per-pod-label-value', STRING);\nexport const RESOLVE_NOT_READY_ADDRESSES = property<boolean>('resolve-not-ready-addresses', BOOLEAN);\n\nexport const KUBERNETES_MASTER_URL = property<string>('kubernetes-master', STRING);\nexport const KUBERNETES_API_TOKEN = property<string>('api-token', STRING);\nexport const SERVICE_PORT = property<number>('service-port', NUMBER);\n", "import {type DiscoveryNode} from './index.ts';\nimport {type Address} from '../cluster/Address.ts';\n\nexport class SimpleDiscoveryNode implements DiscoveryNode {\n readonly privateAddress: Address;\n readonly publicAddress: Address;\n readonly properties: ReadonlyMap<string, unknown>;\n constructor(privateAddress: Address, publicAddress?: Address, properties?: ReadonlyMap<string, unknown>)\n {\n this.privateAddress = privateAddress;\n this.publicAddress = publicAddress ?? privateAddress;\n this.properties = properties ?? new Map();\n }\n}\n", "import { type DiscoveryNode } from '../discovery/index.ts';\nimport { getAllByName, type IpAddress } from '../utils/network.ts';\nimport { KubernetesEndpointResolver } from './KubernetesEndpointResolver.ts';\nimport { KubernetesConfig } from './KubernetesConfig.ts';\nimport { NetworkConfig } from '../config/Config.ts';\nimport type { Logger } from '../logging.ts';\nimport { SimpleDiscoveryNode } from '../discovery/SimpleDiscoveryNode.ts';\nimport { fromHostname } from '../cluster/Address.ts';\n\nexport type LookupProvider = (host: string) => Promise<IpAddress[]>;\n\nexport class DnsEndpointResolver extends KubernetesEndpointResolver {\n readonly #lookupProvider: LookupProvider;\n readonly #serviceDns: string;\n readonly #port: number;\n\n static of(logger: Logger, config: KubernetesConfig): DnsEndpointResolver {\n return new DnsEndpointResolver(logger, getAllByName, config.serviceDns, config.servicePort);\n }\n\n /*testing*/ constructor(logger: Logger, lookupProvider: LookupProvider, serviceDns?: string, port: number = 0) {\n super(logger);\n this.#lookupProvider = lookupProvider;\n this.#serviceDns = serviceDns;\n this.#port = port;\n }\n\n async resolve(): Promise<DiscoveryNode[]> {\n try {\n return await this.lookup();\n } catch (e) {\n this.logger.warn(`DNS lookup for serviceDns ${this.#serviceDns} failed`, e);\n return [];\n }\n }\n\n private async lookup() {\n\n const addresses = new Set<string>();\n\n for (const ipAddress of await this.#lookupProvider(this.#serviceDns)) {\n const address = ipAddress.address;\n if (addresses.has(address)) {\n continue;\n }\n if (this.logger.enabledFor('debug')) {\n this.logger.debug(`Found node service with address: ${ipAddress}`);\n }\n addresses.add(address);\n }\n if (addresses.size === 0) {\n this.logger.warn(`No nodes found for service: ${this.#serviceDns}`);\n return [];\n }\n\n const result: Array<DiscoveryNode> = [];\n for (const address of addresses) {\n const privateAddress = await fromHostname(address, DnsEndpointResolver.getBridgePort(this.#port));\n const node = new SimpleDiscoveryNode(privateAddress);\n result.push(node);\n }\n return result;\n }\n\n private static getBridgePort(port: number): number {\n if (port > 0) {\n return port;\n }\n return NetworkConfig.DEFAULT_PORT;\n }\n}\n", "import {Endpoint, EndpointAddress} from './KubernetesClient.ts';\n\nexport interface KubernetesApiProvider {\n getEndpointsByNameUrlString(kubernetesMaster: string, namespace: string, endpointName: string): string;\n\n getEndpointsByServiceLabelUrlString(kubernetesMaster: string, namespace: string, serviceLabel: string): string;\n\n parseEndpoints(param: any): Endpoint[];\n}\n\nexport class KubernetesApiEndpointSlicesProvider implements KubernetesApiProvider {\n getEndpointsByServiceLabelUrlString(kubernetesMaster: string, namespace: string, param: string): string {\n return `${kubernetesMaster}/apis/discovery.k8s.io/v1/namespaces/${namespace}/endpointslices?${param}`;\n }\n\n getEndpointsByNameUrlString(kubernetesMaster: string, namespace: string, endpointName: string): string {\n return `${kubernetesMaster}/apis/discovery.k8s.io/v1/namespaces/${namespace}/endpointslices?labelSelector=kubernetes.io/service-name=${endpointName}`;\n }\n\n parseEndpoints(param: {\n items: Array<{ endpoints: Array<{ conditions: { ready: boolean }, addresses: Array<string> }>, ports: Array<{}> }>\n }): Endpoint[] {\n const endpoints = new Array<Endpoint>();\n for (const item of param.items) {\n endpoints.push(...this.parseEndpointSlices(item));\n }\n return endpoints;\n }\n\n private parseEndpointSlices(item: {\n endpoints: Array<{\n conditions: {\n ready: boolean\n },\n addresses: Array<string>\n }>,\n ports: Array<{name?: string, port?: number}>\n }): Endpoint[] {\n const addresses = new Array<Endpoint>();\n const endpointPort = this.extractPort(item);\n for (const endpoint of item.endpoints) {\n const ready = endpoint.conditions.ready;\n for (const address of endpoint.addresses) {\n addresses.push(new Endpoint(new EndpointAddress({ip: address, port: endpointPort}), undefined, ready))\n }\n\n }\n return addresses;\n }\n\n private extractPort(item: {\n ports: Array<{\n name?: string,\n port?: number\n\n }>\n }): number | undefined {\n for (const port of item.ports) {\n const bridgeServicePort = port.name;\n if (bridgeServicePort && bridgeServicePort === 'io-bridge') {\n const servicePort = port.port;\n if (servicePort !== undefined) {\n return servicePort;\n }\n }\n }\n if (item.ports.length === 1) {\n const port = item.ports[0];\n const servicePort = port.port;\n if (servicePort !== undefined) {\n return servicePort;\n }\n }\n }\n}\n", "import {type ExposeExternallyMode} from './KubernetesConfig.ts';\nimport {KubernetesApiEndpointSlicesProvider, type KubernetesApiProvider} from './KubernetesApiProvider.ts';\nimport {type ClusterTopologyIntentTracker} from '../instance/ClusterTopologyIntentTracker.ts';\n\nclass Address {\n readonly ip: string;\n\n readonly port?: number;\n\n constructor(ip: string, port?: number) {\n this.ip = ip;\n this.port = port;\n }\n}\n\nexport type {Address};\n\nexport class EndpointAddress {\n readonly targetRefName?: string;\n\n private readonly address: Address;\n\n constructor(address: Address, targetRefName?: string) {\n this.address = address;\n this.targetRefName = targetRefName;\n }\n\n get ip(): string {\n return this.address.ip;\n }\n\n get port(): number | undefined {\n return this.address.port;\n }\n}\n\nexport class Endpoint {\n\n readonly privateAddress: EndpointAddress;\n readonly publicAddress: EndpointAddress | undefined = undefined;\n readonly ready: boolean;\n readonly additionalProperties: ReadonlyMap<string, string> = new Map();\n\n constructor(privateAddress: EndpointAddress,\n publicAddress: EndpointAddress | undefined = undefined,\n ready: boolean,\n additionalProperties: ReadonlyMap<string, string> = new Map()) {\n this.privateAddress = privateAddress;\n this.publicAddress = publicAddress;\n this.ready = ready;\n this.additionalProperties = additionalProperties;\n }\n}\n\nconst READ_TIMEOUT_SECONDS = 10;\n\nfunction isReady(podItemStatus: { containerStatuses?: Array<{ ready?: boolean }> }): boolean {\n for (const containerStatus of podItemStatus.containerStatuses) {\n if (containerStatus.ready !== true) {\n return false;\n }\n }\n return true;\n}\n\nfunction containerPort(container: {\n ports?: Array<{\n containerPort?: number\n }>\n}): number | undefined {\n const ports = container.ports;\n if (ports.length > 0) {\n const port = ports[0];\n return port.containerPort;\n }\n}\n\nfunction extractContainerPort(item: {\n spec: {\n containers?: Array<{ name?: string, ports?: Array<{ containerPort?: number }> }>\n }\n}): number | undefined {\n const containers = item.spec.containers;\n if (containers.length === 1) {\n const container = containers[0];\n return containerPort(container);\n } else {\n for (const container of containers) {\n if (container.name === 'io-bridge') {\n return containerPort(container);\n }\n }\n }\n}\n\nfunction parsePodsList(podList: {\n items?: Array<{\n metadata: {\n name: string\n },\n status: {\n podIP?: string\n containerStatuses?: Array<{ ready?: boolean }>\n },\n spec: {}\n }>\n}): Array<Endpoint> {\n const addresses = new Array<Endpoint>();\n for (const item of podList.items) {\n const podName = item.metadata.name;\n const status = item.status;\n const ip = status.podIP;\n if (ip) {\n const port = extractContainerPort(item);\n addresses.push(new Endpoint(new EndpointAddress({ip, port}, podName), undefined, isReady(status)));\n }\n }\n return addresses;\n}\n\nfunction getLabelSelectorParameter(labelNames: string, labelValues: string): string {\n const labelNameArray = labelNames.split(',');\n const labelValueArray = labelValues.split(',');\n const selectorList = [];\n for (let i = 0; i < labelNameArray.length; i++) {\n selectorList[i] = (`${labelNameArray[i]}=${labelValueArray[i]}`);\n }\n return `labelSelector=${selectorList.join(',')}`;\n}\n\nexport class KubernetesClient {\n\n private readonly namespace: string;\n private readonly kubernetesMaster: string;\n private readonly exposeExternallyMode: ExposeExternallyMode;\n private readonly tokenProvider: () => string;\n private readonly servicePerPodLabelName?: string;\n private readonly servicePerPodLabelValue?: string;\n private readonly clientTopologyIntentTracker?: ClusterTopologyIntentTracker;\n private readonly apiProvider: KubernetesApiProvider\n\n /*testing*/\n constructor(namespace: string,\n kubernetesMaster: string,\n exposeExternallyMode: ExposeExternallyMode,\n tokenProvider: () => string,\n servicePerPodLabelName?: string,\n servicePerPodLabelValue?: string,\n clientTopologyIntentTracker?: ClusterTopologyIntentTracker,\n apiProvider?: KubernetesApiProvider) {\n\n this.namespace = namespace;\n this.kubernetesMaster = kubernetesMaster;\n this.exposeExternallyMode = exposeExternallyMode;\n this.tokenProvider = tokenProvider;\n this.servicePerPodLabelName = servicePerPodLabelName;\n this.servicePerPodLabelValue = servicePerPodLabelValue;\n if (clientTopologyIntentTracker) {\n clientTopologyIntentTracker.init();\n }\n this.apiProvider = apiProvider ?? new KubernetesApiEndpointSlicesProvider();\n }\n\n start(): void {\n\n }\n\n destroy(): void {\n if (this.clientTopologyIntentTracker) {\n this.clientTopologyIntentTracker.destroy();\n }\n }\n\n /**\n * Returns POD addresses in the specified namespace.\n *\n */\n async endpoints(): Promise<Endpoint[]> {\n try {\n const url = `${this.kubernetesMaster}/api/v1/namespaces/${this.namespace}/pods`;\n return this.enrichWithPublicAddresses(parsePodsList(await this.callGet(url)));\n } catch (e) {\n return this.handleUnknownError(e);\n }\n }\n\n /**\n * Retrieves POD addresses for all services in the specified namespace filtered by service labels and values.\n * @param serviceLabels comma separated list of service labels\n * @param serviceLabelValues comma separated list of service label values\n * @return all POD addresses from the specified namespace filtered by labels\n */\n async endpointsByServiceLabel(serviceLabels: string, serviceLabelValues: string): Promise<Endpoint[]> {\n try {\n const param = getLabelSelectorParameter(serviceLabels, serviceLabelValues);\n const url = this.apiProvider.getEndpointsByServiceLabelUrlString(this.kubernetesMaster, this.namespace, param);\n return this.enrichWithPublicAddresses(this.apiProvider.parseEndpoints(this.callGet(url)));\n } catch (e) {\n return this.handleUnknownError(e);\n }\n }\n\n /**\n * Retrieves POD addresses from the specified namespace and given endpointName.\n * @param endpointName endpoint name\n * @return all POD addresses from the specified namespace and the given endpointName\n */\n async endpointsByName(endpointName: string): Promise<Endpoint[]> {\n try {\n const url = this.apiProvider.getEndpointsByNameUrlString(this.kubernetesMaster, this.namespace, endpointName);\n return this.enrichWithPublicAddresses(this.apiProvider.parseEndpoints(await this.callGet(url)));\n } catch (e) {\n return this.handleUnknownError(e);\n }\n }\n\n /**\n * Retrieves POD addresses for all services in the specified namespace filtered by pod labels and values.\n * @param podLabels comma separated list of pod labels\n * @param podLabelValues comma separated list of pod label values\n * @return all POD addresses from the specified namespace filtered by the labels\n */\n async endpointsByPodLabel(podLabels: string, podLabelValues: string) {\n try {\n const param = getLabelSelectorParameter(podLabels, podLabelValues);\n const url = `${this.kubernetesMaster}/api/v1/namespaces/${this.namespace}/pods?${param}`;\n return this.enrichWithPublicAddresses(parsePodsList(await this.callGet(url)));\n } catch (e) {\n return this.handleUnknownError(e);\n }\n }\n\n private enrichWithPublicAddresses(endpoints: Endpoint[]): Endpoint[] {\n if (this.exposeExternallyMode === 'disabled') {\n return endpoints;\n }\n\n }\n\n private handleUnknownError(e): Endpoint[] {\n // todo handle error\n return [];\n }\n\n private async callGet(url: string): Promise<any> {\n const controller = new AbortController();\n const timeout = setTimeout(() => {\n controller.abort(`request to ${url} timed out`);\n }, READ_TIMEOUT_SECONDS * 1000);\n try {\n const response = await fetch(url, {\n signal: controller.signal,\n headers: [[\"Authorization\", `Bearer ${this.tokenProvider()}`]]\n }).catch((err) => {\n throw err;\n });\n\n return await response.json();\n\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n", "import { getLogger as getGatewayLogger } from '@interopio/gateway/logging/core';\n\nexport type Logger = ReturnType<typeof getGatewayLogger>;\n\nexport default function getLogger(name: string): Logger {\n return getGatewayLogger(`gateway.bridge.${name}`);\n}\n", "import {Endpoint, EndpointAddress, KubernetesClient} from './KubernetesClient.ts';\nimport {type DiscoveryNode} from '../discovery/index.ts';\nimport {type Address, fromIpAddress} from '../cluster/Address.ts';\nimport {type Logger} from '../logging.ts';\nimport {KubernetesEndpointResolver} from './KubernetesEndpointResolver.ts';\nimport {KubernetesConfig} from './KubernetesConfig.ts';\nimport {NetworkConfig} from '../config/Config.ts';\nimport {type ClusterTopologyIntentTracker} from '../instance/ClusterTopologyIntentTracker.ts';\nimport {SimpleDiscoveryNode} from '../discovery/SimpleDiscoveryNode.ts';\n\nfunction buildKubernetesClient(config: KubernetesConfig, clusterTopologyIntentTracker?: ClusterTopologyIntentTracker): KubernetesClient {\n return new KubernetesClient(config.namespace, config.kubernetesMasterUrl, config.exposeExternallyMode, config.tokenProvider, config.servicePerPodLabelName, config.servicePerPodLabelValue, clusterTopologyIntentTracker);\n}\n\nexport class KubernetesApiEndpointResolver extends KubernetesEndpointResolver {\n\n private readonly client: KubernetesClient;\n private readonly serviceName?: string;\n private readonly port: number = 0;\n private readonly serviceLabel?: string;\n private readonly serviceLabelValue?: string;\n private readonly podLabel?: string;\n private readonly podLabelValue?: string;\n private readonly resolveNotReadyAddresses?: boolean;\n\n static of(logger: Logger, config: KubernetesConfig, tracker?: ClusterTopologyIntentTracker): KubernetesApiEndpointResolver {\n return new KubernetesApiEndpointResolver(logger, buildKubernetesClient(config, tracker),\n config.serviceName, config.servicePort, config.serviceLabelName,\n config.serviceLabelValue, config.podLabelName, config.podLabelValue, config.resolveNotReadyAddresses);\n }\n\n /*testing*/ constructor(logger: Logger,\n client: KubernetesClient,\n serviceName?: string,\n port: number = 0,\n serviceLabel?: string,\n serviceLabelValue?: string,\n podLabel?: string,\n podLabelValue?: string,\n resolveNotReadyAddresses?: boolean) {\n super(logger);\n this.client = client;\n this.serviceName = serviceName;\n this.port = port;\n this.serviceLabel = serviceLabel;\n this.serviceLabelValue = serviceLabelValue;\n this.podLabel = podLabel;\n this.podLabelValue = podLabelValue;\n this.resolveNotReadyAddresses = resolveNotReadyAddresses;\n }\n\n async resolve(): Promise<DiscoveryNode[]> {\n if (this.serviceName) {\n return await this.getSimpleDiscoveryNodes(await this.client.endpointsByName(this.serviceName));\n }\n else if (this.serviceLabel) {\n return await this.getSimpleDiscoveryNodes(await this.client.endpointsByServiceLabel(this.serviceLabel, this.serviceLabelValue));\n }\n else if (this.podLabel) {\n return await this.getSimpleDiscoveryNodes(await this.client.endpointsByPodLabel(this.podLabel, this.podLabelValue));\n }\n return await this.getSimpleDiscoveryNodes(await this.client.endpoints());\n }\n\n private async getSimpleDiscoveryNodes(endpoints: readonly Endpoint[]): Promise<DiscoveryNode[]> {\n const discoveredNodes = new Array<DiscoveryNode>();\n for (const endpoint of endpoints) {\n await this.addAddress(discoveredNodes, endpoint);\n }\n return discoveredNodes;\n }\n\n private async addAddress(discoveredNodes: Array<DiscoveryNode>, endpoint: Endpoint): Promise<void> {\n if (this.resolveNotReadyAddresses === true || endpoint.ready) {\n const privateAddress = await this.createAddress(endpoint.privateAddress, this.resolvePort.bind(this));\n const publicAddress = await this.createAddress(endpoint.publicAddress, this.resolvePortPublic.bind(this));\n discoveredNodes.push(new SimpleDiscoveryNode(privateAddress, publicAddress, new Map<string, string>()));\n }\n }\n\n private async createAddress(address: EndpointAddress | undefined, portResolver: (address: EndpointAddress) => number): Promise<Address> {\n if (address === undefined) {\n return undefined;\n }\n const ip = address.ip;\n const ipAddress = await this.mapAddress(ip);\n const port = portResolver(address);\n return fromIpAddress(ipAddress, port);\n }\n\n private resolvePort(address: EndpointAddress) {\n if (this.port > 0) {\n return this.port;\n }\n if (address.port) {\n\n return address.port;\n }\n return NetworkConfig.DEFAULT_PORT;\n }\n\n private resolvePortPublic(address: EndpointAddress) {\n if (address.port) {\n return address.port;\n }\n if (this.port > 0) {\n return this.port;\n }\n return NetworkConfig.DEFAULT_PORT;\n }\n}\n", "import {type DiscoveryNode, type DiscoveryStrategy} from '../discovery/index.ts';\nimport { DnsEndpointResolver } from \"./DnsEndpointResolver.ts\";\nimport {KubernetesConfig} from './KubernetesConfig.ts';\nimport {KubernetesApiEndpointResolver} from './KubernetesApiEndpointResolver.ts';\nimport {KubernetesEndpointResolver} from './KubernetesEndpointResolver.ts';\nimport {type ClusterTopologyIntentTracker} from '../instance/ClusterTopologyIntentTracker.ts';\nimport {type Logger} from '../logging.ts';\n\nexport class KubernetesDiscoveryStrategy implements DiscoveryStrategy {\n private readonly logger: Logger;\n readonly #endpointResolver: KubernetesEndpointResolver;\n\n constructor(logger: Logger, properties: {[key: string]: string | number | boolean}, intentTracker?: ClusterTopologyIntentTracker) {\n this.logger = logger;\n const config = new KubernetesConfig(properties);\n this.logger.info(`${config}`);\n if ('dns-lookup' === config.mode) {\n this.#endpointResolver = DnsEndpointResolver.of(logger, config);\n }\n else {\n this.#endpointResolver = KubernetesApiEndpointResolver.of(logger, config, intentTracker);\n }\n logger.info(`Kubernetes Discovery activated with mode: ${config.mode}`);\n }\n async start() {\n await this.#endpointResolver.start();\n }\n\n async discover(): Promise<Iterable<DiscoveryNode> | undefined> {\n return undefined\n }\n\n async close() {\n await this.#endpointResolver.close();\n }\n}\n", "import {createSocket, type RemoteInfo, Socket} from 'node:dgram';\nimport {type DiscoveryNode, type DiscoveryStrategy} from '../index.ts';\nimport {SimpleDiscoveryNode} from '../SimpleDiscoveryNode.ts';\nimport {type Properties} from '../../config/Properties.ts';\nimport {GROUP, PORT} from './MulticastProperties.ts';\nimport {getOrDefault} from '../settings.ts';\nimport {fromHostname, toIpAddress} from '../../cluster/Address.ts';\nimport {isLoopback} from '../../utils/network.ts';\nimport {type Logger} from '../../logging.ts';\n\nconst DATA_OUTPUT_BUFFER_SIZE = 64 * 1024;\nconst DEFAULT_MULTICAST_PORT = 34567;\nconst DEFAULT_MULTICAST_GROUP = '239.1.2.3';\nconst SOCKET_TIME_TO_LIVE = 255; // unrestricted (other possible values would be 1 (local-network), 15 (site-local), 32(local-area), 64(regional), 128(global))\n\ninterface MulticastMemberInfo {\n readonly host: string;\n readonly port: number;\n}\n\nfunction multicastDiscoverySender(discoveryNode: DiscoveryNode | undefined, socket: Socket, group: string, port: number): () => void {\n let multicastMemberInfo: MulticastMemberInfo;\n if (discoveryNode) {\n const address = discoveryNode.publicAddress;\n multicastMemberInfo = {host: address.host, port: address.port};\n }\n const msg: Buffer = Buffer.from(JSON.stringify(multicastMemberInfo));\n\n return () => {\n socket.send(msg, port, group, (error) => {\n console.error(error);\n });\n }\n}\n\nfunction multicastDiscoveryReceiver(socket: Socket): () => Promise<MulticastMemberInfo> {\n return () => {\n return new Promise<MulticastMemberInfo>((resolve, reject) => {\n socket.on('message', (message: Buffer, remote: RemoteInfo) => {\n resolve(JSON.parse(message as unknown as string));\n });\n socket.on('error', (err: Error) => {\n reject(err);\n });\n });\n }\n}\n\nexport class MulticastDiscoveryStrategy implements DiscoveryStrategy {\n private readonly logger: Logger;\n private readonly properties: Properties;\n private readonly discoveryNode?: DiscoveryNode;\n private isClient?: boolean;\n private discoverySender?: () => void;\n private discoveryReceiver?: () => Promise<MulticastMemberInfo>;\n private sendIntervalId?: ReturnType<typeof setInterval>;\n private socket?: Socket;\n constructor(discoveryNode: DiscoveryNode | undefined,\n logger: Logger,\n properties: Properties) {\n this.logger = logger;\n this.properties = properties;\n this.discoveryNode = discoveryNode;\n }\n\n private async initializeMulticastSocket() {\n const port = getOrDefault(this.properties, '', PORT, DEFAULT_MULTICAST_PORT);\n if (port < 0 || port > 65535) {\n throw new Error('port number must be between 0 and 65535');\n }\n const group = getOrDefault(this.properties, '', GROUP, DEFAULT_MULTICAST_GROUP);\n this.socket = createSocket({\n type: 'udp4',\n reuseAddr: true,\n recvBufferSize: DATA_OUTPUT_BUFFER_SIZE,\n sendBufferSize: DATA_OUTPUT_BUFFER_SIZE});\n\n if (this.discoveryNode) {\n const address = await toIpAddress(this.discoveryNode.privateAddress);\n if (!isLoopback(address)) {\n this.socket.setMulticastInterface(address.address);\n }\n }\n\n this.socket.bind(port, () => {\n this.socket.setMulticastTTL(SOCKET_TIME_TO_LIVE);\n this.socket.addMembership(group);\n });\n\n this.discoverySender = multicastDiscoverySender(this.discoveryNode, this.socket, group, port);\n this.discoveryReceiver = multicastDiscoveryReceiver(this.socket);\n if (this.discoveryNode == null) {\n this.isClient = true;\n }\n }\n\n async discover(): Promise<Iterable<DiscoveryNode> | undefined> {\n const multicastMemberInfo = await this.discoveryReceiver();\n if (multicastMemberInfo) {\n const list = [];\n try {\n const discoveryNode = new SimpleDiscoveryNode(await fromHostname(multicastMemberInfo.host, multicastMemberInfo.port));\n list.push(discoveryNode);\n }\n catch (e) {\n if (this.logger.enabledFor('trace')) {\n this.logger.debug(e.message);\n }\n }\n return list;\n }\n }\n\n async start() {\n await this.initializeMulticastSocket();\n if (!this.isClient) {\n this.sendIntervalId = setInterval(() => {\n this.discoverySender();\n }, 2000);\n }\n }\n\n async close() {\n if (this.sendIntervalId) {\n clearInterval(this.sendIntervalId);\n delete this.sendIntervalId;\n }\n return new Promise<void>((resolve, reject) => {\n if (this.socket)\n {\n this.socket.close(() => {\n resolve()\n });\n }\n else\n {\n resolve();\n }\n });\n\n }\n\n}\n", "import {NUMBER, property, STRING} from '../../config/Properties.ts';\n\nexport const PORT = property<number>('port', NUMBER);\nexport const GROUP = property<string>('group', STRING);\n", "import {\n type DiscoveryNode,\n type DiscoveryStrategy,\n type DiscoveryStrategyFactory,\n DiscoveryStrategyPriorities\n} from '../index.ts';\nimport {MulticastDiscoveryStrategy} from './MulticastDiscoveryStrategy.ts';\nimport {GROUP, PORT} from './MulticastProperties.ts';\nimport {type Properties, type PropertyDefinition} from '../../config/Properties.ts';\nimport {type Logger} from '../../logging.ts';\n\nconst PROPERTY_DEFINITIONS: ReadonlyArray<PropertyDefinition> = [\n GROUP,\n PORT\n];\n\nexport class MulticastDiscoveryStrategyFactory implements DiscoveryStrategyFactory {\n readonly priority = DiscoveryStrategyPriorities.UNKNOWN;\n\n getDiscoveryStrategyType() {\n return MulticastDiscoveryStrategy;\n }\n\n newDiscoveryStrategy(discoveryNode: DiscoveryNode, logger: Logger, prop: Properties): DiscoveryStrategy {\n return new MulticastDiscoveryStrategy(discoveryNode, logger, prop);\n }\n\n async isAutoDetectionApplicable(): Promise<boolean> {\n return false;\n }\n\n getConfigurationProperties(): ReadonlyArray<PropertyDefinition> {\n return PROPERTY_DEFINITIONS;\n }\n}\n", "import type { Address } from '../cluster/Address.ts';\nimport type { Properties, PropertyDefinition, PropertyType } from '../config/Properties.ts';\nimport type { DiscoveryConfig, DiscoveryStrategyConfig } from '../config/DiscoveryConfig.ts';\nimport type { Logger } from '../logging.ts';\nimport { KubernetesDiscoveryStrategyFactory } from '../kubernetes/KubernetesDiscoveryStrategyFactory.ts';\nimport { MulticastDiscoveryStrategyFactory } from './multicast/MulticastDiscoveryStrategyFactory.ts';\n\nexport interface DiscoveryServiceFactory {\n newDiscoveryService(settings: DiscoveryServiceSettings): DiscoveryService\n}\n\nexport interface DiscoveryService {\n start(): Promise<void>\n discover(): Promise<Iterable<DiscoveryNode>>\n close(): Promise<void>\n}\n\n\nexport type DiscoveryServiceSettings = {\n readonly node: Promise<DiscoveryNode>\n readonly mode: DiscoveryMode\n readonly conf: DiscoveryConfig\n readonly auto: boolean\n readonly logger: Logger\n}\n\nexport type DiscoveryMode = 'member' | 'client';\n\nexport class DefaultDiscoveryServiceFactory implements DiscoveryServiceFactory {\n newDiscoveryService(settings: DiscoveryServiceSettings): DiscoveryService {\n return new DefaultDiscoveryService(settings);\n }\n}\n\nfunction verifyNoUnknownProperties(mappedProperties: Properties, allProperties: string[]) {\n const unknownProperties = allProperties.filter(key => !mappedProperties.hasOwnProperty(key));\n if (unknownProperties.length > 0) {\n throw new Error(`Unknown properties: ${unknownProperties.join(', ')} on discovery strategy`);\n }\n}\n\nfunction prepareProperties(properties: Map<string, PropertyType>,\n propertyDefinitions: readonly PropertyDefinition[]) {\n const mappedProperties: Properties = {};\n for (const propertyDefinition of propertyDefinitions) {\n const propertyKey = propertyDefinition.key;\n if (!properties.has(propertyKey)) {\n if (!propertyDefinition.optional) {\n throw new Error(`Missing required property: ${propertyKey} on discovery strategy`);\n }\n continue;\n }\n const value = properties.get(propertyKey);\n const converter = propertyDefinition.converter;\n const mappedValue = converter.convert(value);\n\n mappedProperties[propertyKey] = mappedValue;\n }\n\n verifyNoUnknownProperties(mappedProperties, Array.from(properties.keys()));\n return mappedProperties;\n\n}\n\nexport class DefaultDiscoveryService implements DiscoveryService {\n private readonly settings: DiscoveryServiceSettings;\n readonly #strategies: Array<DiscoveryStrategy> = [];\n constructor(settings: DiscoveryServiceSettings) {\n this.settings = settings;\n }\n\n get strategies(): ReadonlyArray<DiscoveryStrategy> {\n return this.#strategies;\n }\n\n async start(): Promise<void> {\n this.#strategies.push(...await this.loadDiscoveryStrategies());\n for (const strategy of this.#strategies) {\n await strategy.start();\n }\n }\n\n async discover(): Promise<Iterable<DiscoveryNode>> {\n const discoveryNodes = new Set<DiscoveryNode>();\n for (const strategy of this.#strategies) {\n const candidates = await strategy.discover();\n if (candidates) {\n for (const candidate of candidates) {\n if (this.validateCandidate(candidate)) {\n discoveryNodes.add(candidate);\n }\n }\n }\n\n }\n\n return discoveryNodes;\n }\n\n async close(): Promise<void> {\n for (const strategy of this.#strategies) {\n await strategy.close();\n }\n }\n\n private validateCandidate(candidate: DiscoveryNode) : boolean {\n // todo\n return true;\n }\n\n private async loadDiscoveryStrategies(): Promise<Iterable<DiscoveryStrategy>> {\n\n const discoveryStrategyConfigs = this.settings.conf.discoveryStrategyConfigs;\n const factories = this.collectFactories(discoveryStrategyConfigs);\n\n const discoveryStrategies = new Array<DiscoveryStrategy>();\n for (const config of discoveryStrategyConfigs) {\n const discoveryStrategy = await this.buildDiscoveryStrategy(config, factories);\n discoveryStrategies.push(discoveryStrategy);\n }\n const logger = this.settings.logger;\n if (discoveryStrategies.length == 0 && this.settings.auto) {\n logger.debug(`Discovery auto-detection enabled, trying to detect discovery strategy`);\n const autoDetectedFactory = await this.detectDiscoveryStrategyFactory(factories);\n if (autoDetectedFactory) {\n logger.debug(`Auto-detected discovery strategy: ${autoDetectedFactory.constructor.name}`);\n discoveryStrategies.push(autoDetectedFactory.newDiscoveryStrategy(await this.settings.node, logger, {}));\n }\n else {\n logger.debug(`No discovery strategy auto-detected`);\n }\n }\n return discoveryStrategies;\n }\n\n private collectFactories(strategyConfigs: ReadonlyArray<DiscoveryStrategyConfig>): DiscoveryStrategyFactory[] {\n\n const knownFactories = [new MulticastDiscoveryStrategyFactory(), new KubernetesDiscoveryStrategyFactory()]\n\n const factories = new Array<DiscoveryStrategyFactory>();\n\n for (const factory of knownFactories) {\n factories.push(factory);\n }\n\n for (const config of strategyConfigs) {\n const factory = config.discoveryStrategyFactory;\n if (factory) {\n factories.push(factory);\n }\n }\n\n return factories;\n }\n\n private async buildDiscoveryStrategy(config: DiscoveryStrategyConfig,\n factories: DiscoveryStrategyFactory[]): Promise<DiscoveryStrategy> {\n const discoveryNode = await this.settings.node;\n const logger = this.settings.logger;\n\n for (const factory of factories) {\n const constructorName = factory.getDiscoveryStrategyType().name;\n if (constructorName === this.getFactoryConstructorName(config)) {\n const properties = prepareProperties(config.properties, factory.getConfigurationProperties() ?? []);\n return factory.newDiscoveryStrategy(discoveryNode, logger, properties);\n }\n }\n throw new Error('DiscoveryStrategyFactory not found');\n }\n\n private getFactoryConstructorName(config: DiscoveryStrategyConfig): string {\n if (config.discoveryStrategyFactory) {\n const factory = config.discoveryStrategyFactory;\n return factory.getDiscoveryStrategyType().name;\n }\n return config.constructorName;\n }\n\n private async detectDiscoveryStrategyFactory(factories: DiscoveryStrategyFactory[]) {\n let highestPriorityFactory: DiscoveryStrategyFactory;\n for (const factory of factories) {\n try {\n if (await factory.isAutoDetectionApplicable()) {\n if (highestPriorityFactory === undefined || factory.priority > highestPriorityFactory.priority) {\n highestPriorityFactory = factory;\n }\n }\n } catch (error) {\n // todo log error\n }\n }\n return highestPriorityFactory;\n }\n\n\n}\n\nexport interface DiscoveryStrategy {\n start(): Promise<void>\n discover(): Promise<Iterable<DiscoveryNode> | undefined>\n close(): Promise<void>\n}\n\nexport interface DiscoveryStrategyFactory {\n readonly priority: number\n isAutoDetectionApplicable(): Promise<boolean>\n newDiscoveryStrategy(node: DiscoveryNode, logger: Logger, settings: Properties): DiscoveryStrategy\n getDiscoveryStrategyType(): new (...args: unknown[]) => DiscoveryStrategy\n getConfigurationProperties(): ReadonlyArray<PropertyDefinition>\n}\nexport const DiscoveryStrategyPriorities = {\n UNKNOWN: 0,\n PLATFORM: 20,\n CUSTOM: 50,\n}\n\nexport interface DiscoveryNode {\n readonly publicAddress: Address;\n readonly privateAddress: Address;\n readonly properties: ReadonlyMap<string, unknown>;\n}\n", "import type { JoinConfig } from '../../config/Config.ts';\nimport type { DiscoveryStrategyConfig } from \"../../config/DiscoveryConfig.ts\";\nimport type { NamedDiscoveryConfig } from \"../../config/NamedDiscoveryConfig.ts\";\nimport type { PropertyType } from \"../../config/Properties.ts\";\n\nexport function namedDiscoveryConfigsFrom(config: JoinConfig): NamedDiscoveryConfig[] {\n return [config.kubernetes];\n}\n\nfunction mapConfigs(configs: NamedDiscoveryConfig[]) {\n const result = new Array<DiscoveryStrategyConfig>();\n for (const config of configs) {\n if (config.enabled !== false) {\n result.push(createStrategyConfig(config));\n }\n }\n return result;\n}\n\nconst NAME_MAPPINGS = new Map<string, string>([\n ['kubernetes', 'KubernetesDiscoveryStrategy'],\n]);\n\nfunction discoveryStrategyFrom(config: NamedDiscoveryConfig) {\n return NAME_MAPPINGS.get(config.tag);\n}\n\nfunction createStrategyConfig(config: NamedDiscoveryConfig): DiscoveryStrategyConfig {\n\n const constructorName = discoveryStrategyFrom(config);\n const properties = new Map<string, PropertyType>();\n for (const [key, value] of config.properties) {\n if (value !== undefined) {\n properties.set(key, value);\n }\n }\n return { constructorName, properties }\n}\n\nexport function createDiscoveryStrategyConfigs(config: JoinConfig) {\n return mapConfigs(namedDiscoveryConfigsFrom(config));\n}\n", "import type {Logger} from \"../logging.ts\";\n\nexport type LicenseValidatorOptions = {\n validationKey: string;\n logger?: Logger\n}\n\nexport type LicenseValidationOptions = {\n logSuccessMessages?: boolean\n};\n\nexport type LicensePayload = {\n \"type\": \"paid\" | \"trial\";\n \"expiration\": number // in milliseconds\n \"email\": string,\n \"issuedBy\": string;\n \"iat\": number; // in seconds\n \"licensee\": string;\n \"organization\": {\n \"displayName\": string,\n \"identifier\": string\n }\n}\n\nexport type LicenseEvaluationResult = {\n licenseType: 'paid' | 'trial' | 'none';\n expired: boolean;\n fatal: boolean;\n license?: LicensePayload;\n error?: string;\n}\n\n\nexport const licenseValidationResults = {\n TRIAL_LICENSE_EXPIRED: {licenseType: 'trial', expired: true, fatal: true} as LicenseEvaluationResult,\n TRIAL_LICENSE_VALID: {licenseType: 'trial', expired: false, fatal: false} as LicenseEvaluationResult,\n PAID_LICENSE_EXPIRED: {licenseType: 'paid', expired: true, fatal: false} as LicenseEvaluationResult,\n PAID_LICENSE_VALID: {licenseType: 'paid', expired: false, fatal: false} as LicenseEvaluationResult,\n NO_LICENSE: {licenseType: 'none', expired: false, fatal: true} as LicenseEvaluationResult,\n};", "import getLogger, {type Logger} from \"../logging.ts\";\nimport {\n type LicensePayload,\n type LicenseEvaluationResult,\n type LicenseValidatorOptions,\n licenseValidationResults, type LicenseValidationOptions\n} from \"./types.ts\";\nimport {KJUR} from 'jsrsasign';\n\nexport class LicenseError extends Error {\n public readonly licensePayload: LicensePayload | string;\n\n constructor(message: string, licensePayload: string | LicensePayload) {\n super(message);\n this.licensePayload = licensePayload;\n }\n}\n\nexport class LicenseEvaluator {\n private readonly tokenResultMap = {\n 'trial-false': licenseValidationResults.TRIAL_LICENSE_VALID,\n 'trial-true': licenseValidationResults.TRIAL_LICENSE_EXPIRED,\n 'paid-false': licenseValidationResults.PAID_LICENSE_VALID,\n 'paid-true': licenseValidationResults.PAID_LICENSE_EXPIRED,\n };\n\n private readonly validationKey: string;\n\n constructor(validationKey: string) {\n if (!validationKey || typeof validationKey !== 'string') {\n throw new Error(`Validation key must be a non-empty string`);\n }\n this.validationKey = validationKey;\n }\n\n private decrypt(token: string): object {\n if (KJUR.jws.JWS.verifyJWT(token, this.validationKey, {alg: ['RS256']})) {\n return KJUR.jws.JWS.parse(token).payloadObj;\n } else {\n throw new LicenseError('invalid jwt token', token);\n }\n }\n\n private validateBasicTokenData(token: string): LicensePayload {\n const decoded = this.decrypt(token) as LicensePayload;\n if (['paid', 'trial'].indexOf(decoded.type) === -1) {\n throw new LicenseError('Invalid license type', token);\n }\n return decoded;\n }\n\n getLicenseStatus(token: string, now: Date = new Date()): LicenseEvaluationResult {\n try {\n const license = this.validateBasicTokenData(token);\n const isExpired = license.expiration < now.getTime();\n const licenseValidationResult = this.tokenResultMap[`${license.type}-${isExpired}`];\n return {\n ...licenseValidationResult,\n license\n };\n } catch (e) {\n return {\n ...licenseValidationResults.NO_LICENSE,\n error: e.message,\n };\n }\n\n }\n}\n\nexport class LicenseValidator {\n private readonly licenseHelper: LicenseEvaluator;\n private readonly logger: Logger;\n\n constructor({validationKey, logger}: LicenseValidatorOptions) {\n this.licenseHelper = new LicenseEvaluator(validationKey);\n this.logger = logger ?? getLogger(\"LicenseValidator\"); // Default to console if no logger provided\n }\n\n public validate(licenseKeyString: string, options?: LicenseValidationOptions): void {\n if (typeof licenseKeyString !== 'string') {\n throw new LicenseError('Invalid license key format', licenseKeyString);\n }\n\n const licenseStatus = this.licenseHelper.getLicenseStatus(licenseKeyString);\n this.printLicenseMessage(licenseStatus, options?.logSuccessMessages ?? true);\n if (licenseStatus.fatal) {\n throw new LicenseError('License validation failed', licenseStatus.license);\n }\n }\n\n private printLicenseMessage(licenseStatus: LicenseEvaluationResult, logSuccessMessages: boolean): void {\n if (!licenseStatus || licenseStatus.licenseType === 'none') {\n this.logger.error('This license is invalid. Please contact us at sales@interop.io to get a valid license');\n return;\n }\n\n const message = [\n licenseStatus.licenseType === 'paid' ? `This is a paid license that was issued for client ` : `This is a trial license that was issued for `,\n licenseStatus.license.organization.displayName,\n licenseStatus.expired ? `, but it has expired at ` : ` and is valid until `,\n new Date(licenseStatus.license.expiration).toString(),\n '.'\n ].join('');\n\n if (licenseStatus.fatal) {\n this.logger.error(message);\n } else if (licenseStatus.expired) {\n this.logger.warn(message);\n } else if(logSuccessMessages) {\n this.logger.info(message);\n }\n }\n}", "import type {Logger} from \"../logging.ts\";\nimport {LicenseValidator} from \"./LicenseValidator.ts\";\n\nconst validationKey = `-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAyyZrtwcQCMfyOkZDcjxZ\n+07BrvgcAvoQETF+ho8VLfaDxgNPZd6Q7jZEfrtv0+wn0pxx8pUDeBh8mCYvkwmb\n9tkFH47GJuDhWasNgyp4ugRX4bzoPV3SnHsBR4KJ/F76kBbike6sdIfO2lYGZ36s\nLJPHV7epOYsfhoc4343/vOxEPvNbwacbXWl4NsCGev4qUmWhe9iMpb/JPd3o4hIU\nSR31AmR2xoh3BkAJc2q/cSeQK6Kn9nZYocyW367+7FOvYsrOYotsuUASp0OWp+Lh\nWGfR7F6d016+u6kbvLvcceGztiP1u25QmPNCUmw49cTatthiEwwGHb01CR58mStZ\nxg5t9+N7X9hPO2K59b8EbOnnFTlwtMMF7MKR56S4YwMamCChr9WGgpOQV+lrqyx2\nyn9lwn8Yf4gLoLPKBEhHTEy6r/we9qymmlSSe4wr5Fctov2odSE535nvtdRYZkKk\nt32gOXuwnKg2kRlRSAErpyou1mz7/mWEt1H3sGTRArjNTP2KqZkc14vPToEEJt93\nZKjhD1pVEchDiWBOMj9o12pq80tGZ8PhGJasJVVi0JPUiaznG4r12JdyDAjuXMru\n6f4Tx0ULkdwn9ia7lchcq7xC2PlTnYz+fGpfU7V0Ci56QDTp6oP567L1EIeddkaI\nnIsi4KHT7Ctp047FTTelntUCAwEAAQ==\n-----END PUBLIC KEY-----`;\n\nexport const BridgeLicenseValidator = (logger: Logger) => new LicenseValidator({validationKey, logger});\n", "import {nanoid} from 'nanoid';\n\nexport function newUUID() : string {\n return nanoid();\n}\n", "import {type Address} from '../cluster/Address.ts';\nimport {getByName, getNetworkInterfaces, type IpAddress} from '../utils/network.ts';\nimport { type AddressInfo, Server, createServer} from 'node:net';\nimport { type Logger } from '../logging.ts';\nimport { type Config} from '../config/Config.ts';\n\nexport type EndpointType = 'member' | 'client';\n\nexport interface AddressPicker {\n pickAddress(): Promise<void>;\n getPublicAddressFor(endpoint: EndpointType): Address ;\n getPublicAddressMap(): ReadonlyMap<EndpointType, Address>;\n getBindAddressMap(): ReadonlyMap<EndpointType, Address>;\n getServers(): ReadonlyMap<string, Server>;\n close(): Promise<void>;\n}\n\nasync function createAddress(addressDef: AddressDef, port: number): Promise<Address> {\n if (addressDef.host) {\n return {type: addressDef.ipAddress.family, host: addressDef.host, port, address: addressDef.ipAddress};\n }\n return {type: addressDef.ipAddress.family, host: await addressDef.ipAddress.getHost(), port, address: addressDef.ipAddress}\n}\n\nfunction createNetServer(logger: Logger, host: string, range: number | string): Promise<Server> {\n const ports = portRange(range);\n return new Promise((resolve, reject) => {\n let server = createServer({}, () => {});\n server.on('error', (err: Error) => {\n if (err['code'] === 'EADDRINUSE') {\n logger.debug(`port ${err['port']} already in use on address ${err['address']}`);\n const {value: port} = ports.next();\n if (port) {\n logger.info(`retry starting server on port ${port} and host ${host ?? '<unspecified>'}`);\n server.close();\n server.listen(port, host);\n } else {\n logger.warn(`all configured port(s) ${range} are in use. closing...`);\n server.close();\n reject(err);\n }\n } else {\n logger.error(`server error: ${err.message}`, err);\n reject(err);\n }\n });\n server.on('listening', () => {\n const info = server.address() as AddressInfo;\n logger.info(`listening on ${info.address}:${info.port}`);\n resolve(server);\n });\n try {\n const {value: port} = ports.next();\n server.listen(port, host);\n } catch (e) {\n logger.error(`error starting socket server`, e);\n reject(e instanceof Error ? e : new Error(`listen failed: ${e}`));\n }\n });\n}\n\nclass InterfaceAddress {\n readonly address: string;\n readonly host?: string;\n constructor(address: string, host?: string) {\n this.address = address;\n this.host = host;\n }\n}\n\nclass AddressDef extends InterfaceAddress {\n\n readonly ipAddress: IpAddress;\n readonly port: number;\n constructor(ipAddress: IpAddress, host?: string, port?: number) {\n super(ipAddress.address, host);\n this.ipAddress = ipAddress;\n this.port = port ?? 0;\n }\n}\n\nexport class DefaultAddressPicker implements AddressPicker {\n\n readonly #logger: Logger;\n readonly #config: Config;\n readonly #publicAddressConfig?: string;\n #publicAddress: Address;\n #bindAddress: Address;\n #server: Server;\n readonly #port: string | number;\n constructor(config: Config,\n logger: Logger)\n {\n this.#logger = logger;\n this.#config = config;\n this.#port = config.network.port;\n this.#publicAddressConfig = config.network.publicAddress;\n }\n\n async close() {\n await new Promise<void>((resolve, reject) => {\n this.#server.close((err?) => {\n if (err) {\n reject(err);\n }\n else {\n resolve();\n }\n });\n });\n }\n\n async pickAddress(): Promise<void> {\n if (this.#publicAddress || this.#bindAddress)\n {\n return;\n }\n const publicAddressDef = await this.getPublicAddressByPortSearch();\n this.#publicAddress = this.#bindAddress;\n\n }\n\n getPublicAddressFor(endpoint: EndpointType): Address {\n return this.#publicAddress;\n }\n\n getBindAddressMap(): ReadonlyMap<EndpointType, Address> {\n return new Map([['member', this.#bindAddress]]);\n }\n getPublicAddressMap(): ReadonlyMap<EndpointType, Address> {\n return new Map([['member', this.#publicAddress]]);\n }\n\n getServers(): ReadonlyMap<string, Server> {\n return new Map([['member', this.#server]]);\n }\n\n private async getPublicAddressByPortSearch() {\n const bindAddressDef = await this.pickAddressDef();\n\n\n this.#server = await createNetServer(this.#logger, '0.0.0.0', bindAddressDef.port === 0 ? this.#port: bindAddressDef.port);\n\n const port = (this.#server.address() as AddressInfo).port;\n this.#bindAddress = await createAddress(bindAddressDef, port);\n\n return this.getPublicAddress(port);\n }\n\n private async getPublicAddress(port: number) {\n let address = this.#publicAddressConfig;\n if (address) {\n address = address.trim();\n if (!address) {\n throw new Error('Public address is empty');\n } else if ('127.0.0.1' === address) {\n return this.pickLoopbackAddressDef(address, port);\n }\n else\n {\n const ipAddress = await getByName(address);\n return new AddressDef(ipAddress, address, port);\n }\n }\n }\n\n private async pickAddressDef() {\n let addressDef = this.pickInterfaceAddressDef();\n if (addressDef) {\n\n }\n if (addressDef === undefined) {\n addressDef = await this.pickLoopbackAddressDef();\n }\n return addressDef;\n }\n\n private pickInterfaceAddressDef(): AddressDef {\n const interfaces = this.getInterfaces();\n if (interfaces) {\n const address = this.pickMatchingAddress(interfaces);\n if (address) {\n return address;\n }\n }\n return this.pickMatchingAddress();\n }\n\n private getInterfaces(): InterfaceAddress[] | undefined {\n return [];\n }\n\n private async pickLoopbackAddressDef(host?: string, defaultPort?: number) {\n const address = await getByName('127.0.0.1');\n return new AddressDef(address, host, defaultPort);\n }\n\n private match(ipAddress: IpAddress, interfaces: InterfaceAddress[]) {\n for (const iface of interfaces) {\n if (ipAddress.address === iface.address) {\n return iface;\n }\n }\n return undefined;\n }\n\n private getMatchingAddress(ipAddress: IpAddress, interfaces?: InterfaceAddress[]) {\n if (interfaces) {\n return this.match(ipAddress, interfaces);\n } else {\n return ipAddress;\n }\n }\n\n private pickMatchingAddress(interfaces?: InterfaceAddress[]): AddressDef | undefined {\n const preferIPv4 = true;\n const networkInterfaces = getNetworkInterfaces();\n let matchingAddress;\n for (const ni of networkInterfaces) {\n if (!interfaces && ni.loopback) {\n continue;\n }\n for (const ipAddress of ni.addresses) {\n if (preferIPv4 && ipAddress.family === 6) {\n continue;\n }\n const address = this.getMatchingAddress(ipAddress, interfaces);\n break;\n }\n }\n return matchingAddress;\n }\n}\n\n\n\n// stolen from gateway-server\n\n\nconst PORT_RANGE_MATCHER = /^(\\d+|(0x[\\da-f]+))(-(\\d+|(0x[\\da-f]+)))?$/i;\nfunction validPort(port: number) {\n if (port > 0xFFFF) throw new Error(`bad port ${port}`);\n return port;\n}\n\n/**\n * parse port range. port can be number or string representing comma separated\n * list of port ranges for e.g. \"3434,8380-8385\"\n * @param port\n */\nfunction* portRange(port: number | string): Generator<number> {\n if (typeof port === 'string') {\n for (const portRange of port.split(',')) {\n const trimmed = portRange.trim();\n const matchResult = PORT_RANGE_MATCHER.exec(trimmed);\n if (matchResult) {\n const start = parseInt(matchResult[1]);\n const end = parseInt(matchResult[4] ?? matchResult[1]);\n for (let i = validPort(start); i < validPort(end) + 1; i++) {\n yield i;\n }\n }\n else {\n throw new Error(`'${portRange}' is not a valid port or range.`);\n }\n }\n } else {\n yield validPort(port);\n }\n}\n", "import { BridgeNode } from './instance/BridgeNode.ts';\nimport { Config } from './config/Config.ts';\nimport { BOOLEAN, NUMBER, type PropertyType, type PropertyTypeConverter, STRING } from './config/Properties.ts';\n\nimport info from '../package.json' with { type: 'json' };\n\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { format } from 'node:util';\nimport { parentPort } from 'node:worker_threads';\n\nlet hadFatalError = false;\nconst reportedErrors = new Set();\nfunction getErrorMessage(error: unknown) {\n if (typeof error !== 'object' || error === null) {\n return String(error);\n }\n if (typeof error['stack'] === 'string') {\n return error['stack'];\n }\n return format('%o', error);\n}\n\nfunction onFatalError(error: unknown) {\n\n process.exitCode = 2;\n hadFatalError = true;\n\n const errorMessage = `\nio.Bridge: ${info.version}\n\n${getErrorMessage(error)}`;\n\n if (!reportedErrors.has(errorMessage)) {\n console.error(error);\n reportedErrors.add(errorMessage);\n }\n}\n\nfunction propertyNameToEnvKey(name: string): string {\n return `IO_BRIDGE_${name.toUpperCase().replaceAll('-', '').replaceAll('.', '_')}`;\n}\n\nfunction loadConfig<T extends PropertyType=string>(name: string, converter: PropertyTypeConverter<T>): T | undefined {\n const cmdArg = process.argv.find(arg => {return arg.startsWith(`--${name}=`);})?.split('=')[1];\n if (cmdArg) {\n return converter.convert(cmdArg);\n }\n const envKey = propertyNameToEnvKey(name);\n const envVar = process.env[envKey];\n if (envVar) {\n return converter.convert(envVar);\n }\n}\n\nfunction loadLicense() {\n const config = loadConfig('license.key', STRING);\n if (config !== undefined) {\n return config;\n }\n const file = loadConfig('license.key.file', STRING);\n if (file !== undefined) {\n return readFileSync(file, { encoding: 'ascii'}).trim();\n }\n}\n\ntry {\n process.on('uncaughtException', onFatalError);\n process.on('unhandledRejection', onFatalError);\n\n try {\n process.loadEnvFile();\n }\n catch (e) {\n if (e.code === 'ENOENT') {\n // fine, no .env file\n }\n else {\n throw e;\n }\n }\n\n const config = new Config();\n config.license ??= loadLicense();\n config.server.port ??= loadConfig('server.port', NUMBER) ?? 8084;\n config.server.host ??= loadConfig('server.host', STRING);\n config.server.ssl.enabled ??= loadConfig('server.ssl.enabled', BOOLEAN);\n config.server.ssl.key ??= loadConfig('server.ssl.key.file', STRING);\n config.server.ssl.cert ??= loadConfig('server.ssl.cert.file', STRING);\n config.server.ssl.ca ??= loadConfig('server.ssl.ca.file', STRING);\n config.server.wsPingInterval ??= loadConfig('server.ws-ping-interval', NUMBER);\n config.gateway.enabled ??= loadConfig('gateway.enabled', BOOLEAN);\n config.gateway.contexts.lifetime ??= loadConfig('gateway.contexts.lifetime', STRING) as 'retained' | 'ref-counted' | 'ownership';\n config.server.auth.type = (loadConfig('server.auth.type', STRING) ?? 'none') as 'none' | 'basic' | 'x509' | 'oauth2';\n config.server.auth.oauth2.jwt.issuerUri = loadConfig('server.auth.oauth2.jwt.issuer-uri', STRING) ?? undefined;\n config.server.auth.oauth2.jwt.issuer = loadConfig('server.auth.oauth2.jwt.issuer', STRING) ?? undefined;\n config.server.auth.oauth2.jwt.audience = loadConfig('server.auth.oauth2.jwt.audience', STRING) ?? undefined;\n config.server.auth.x509.key ??= loadConfig('server.auth.x509.key.file', STRING) ?? undefined;\n\n config.server.cors.allowOrigin = loadConfig('server.cors.allow-origin', STRING) ?? '*';\n config.server.cors.allowCredentials = loadConfig('server.cors.allow-credentials', BOOLEAN) ?? true;\n config.server.cors.disabled = (loadConfig('server.cors.disabled', BOOLEAN) ?? false) ? true: undefined;\n\n config.network.join.kubernetes.setEnabled(loadConfig('network.join.kubernetes.enabled', BOOLEAN) ?? false);\n config.network.join.kubernetes.setProperty('service-dns', loadConfig('network.join.kubernetes.service-dns', STRING) ?? undefined);\n\n const bridge = new BridgeNode(config);\n\n await bridge.start();\n\n reportPort(bridge);\n\n}\ncatch (error) {\n onFatalError(error);\n}\n\n\n/**\n * Report the bound address/port to parent process via IPC, worker thread, or file\n */\nfunction reportPort(bridge: BridgeNode) {\n const address = bridge.address;\n\n if (!address) {\n // Server not started or address not available\n return;\n }\n\n // Send bound address to parent process if available\n if (process?.send) {\n // Send via IPC if available (child process)\n process.send({ type: 'io.bridge:ready', address });\n }\n else if (parentPort) {\n // Send via parentPort if available (worker thread)\n parentPort.postMessage({ type: 'io.bridge:ready', address });\n }\n\n // Write to file if --print.port is specified\n const printPort = loadConfig('print.port', STRING);\n if (printPort) {\n // Write address to file (for processes without IPC)\n writeFileSync(printPort, JSON.stringify(address), { encoding: 'utf-8' });\n }\n}\n"],
5
- "mappings": ";AAAA,OAAO,mBAAsC;AAE7C,SAAS,gBAAgB;;;ACDlB,SAAS,0BAA0B,MAAM,QAAQ,KAAc;AAClE,SAAO,IAAI,0BAA0B;AACzC;AAmBO,SAAS,qBAAqB,MAAM,QAAQ,KAAsB;AACrE,MAAI,CAAC,0BAA0B,GAAG,GAAG;AACjC,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACvD;AACA,SAAO,KAAK,MAAM,IAAI,qBAAqB;AAC/C;;;ACvBA,OAA0B;;;ACJ1B,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,cAAc;AAEvB,SAAS,UAAU;AACf,SAAO,QAAQ,aAAa;AAChC;AACO,SAAS,gBAAgB,MAAc,iBAAiB,OAAO;AAClE,QAAM,WAAW,QAAQ,IAAI,gBAAgB,IAAI,KAAK,KAAK,OAAO,GAAG,GAAG,IAAI,OAAO;AACnF,MAAI,CAAC,QAAQ,KAAK,gBAAgB;AAC9B,QAAI;AACA,aAAO,QAAQ;AAAA,IACnB,SACO,GAAG;AAAA,IAEV;AAAA,EACJ;AACA,SAAO;AACX;;;AChBA,SAAS,oBAAoB;AAE7B,SAAS,yBAAyB,EAAE,aAAa,QAAQ,KAAK,GAAuB;AACjF,SAAO,gBAAgB,UAAU,WAAW,IAAI,MAAM,IAAI,IAAI,IAAI,IAAI;AAC1E;AAEO,SAAS,2BAA2B,EAAE,QAAQ,MAAM,cAAc,GAAsB;AAC3F,QAAM,WAAW,yBAAyB,aAAa;AACvD,SAAO,KAAK,oBAAoB,IAAI,aAAa,QAAQ,EAAE;AAC3D,QAAM,SAAS,aAAa,CAAC,WAAW;AACpC,WAAO,KAAK,mCAAmC;AAC/C,WAAO,MAAM,IAAI;AACjB,WAAO,IAAI,MAAM;AACb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MAAM;AACjD,MAAI,WAAW;AAEX,kBAAc,WAAW,KAAK,UAAU,OAAO,GAAG,EAAE,UAAU,QAAQ,CAAC;AAAA,EAC3E;AACJ;",
4
+ "sourcesContent": ["import gatewayServer, { GatewayServer } from '@interopio/gateway-server';\nimport type { ServerConfig } from '@interopio/gateway-server/config';\nimport { userInfo } from 'node:os';\nimport { onGatewayStarted, serverGatewayConfig } from '../../../bridge-gateway/src/index.ts';\nimport { BridgeMeshChannel, mesh } from '../../../bridge-mesh/src/index.ts';\nimport Connections from '../../../bridge-mesh/src/mesh/connections.ts';\nimport { InternalRelays } from '../../../bridge-mesh/src/mesh/relays.ts';\nimport info from '../../package.json' with { type: 'json' };\nimport { type Member } from '../cluster/Member.ts';\nimport { Config, JoinConfig } from '../config/Config.ts';\nimport { type DiscoveryConfig, type DiscoveryStrategyConfig } from '../config/DiscoveryConfig.ts';\nimport {\n DefaultDiscoveryService,\n DefaultDiscoveryServiceFactory,\n type DiscoveryService,\n type DiscoveryServiceSettings\n} from '../discovery/index.ts';\nimport { SimpleDiscoveryNode } from '../discovery/SimpleDiscoveryNode.ts';\nimport { createDiscoveryStrategyConfigs } from '../internal/config/NamedDiscoveryConfigUtils.ts';\nimport { BridgeLicenseValidator } from \"../license/BridgeLicenseValidator.ts\";\nimport { type LicenseValidator } from \"../license/LicenseValidator.ts\";\nimport getLogger, { type Logger } from '../logging.ts';\nimport { newUUID } from '../utils/uuid.ts';\nimport { type MemberVersion, parseVersion } from '../version/MemberVersion.ts';\nimport { type AddressPicker, DefaultAddressPicker } from './AddressPicker.ts';\n\nfunction logStartingInfo(logger: Logger) {\n logger.info(`Starting io.Bridge v${info.version} using Node.js ${process.version} with PID ${process.pid} (started by ${userInfo().username} in ${process.cwd()})`);\n}\n\nfunction createJoiner(logger: Logger, config: JoinConfig) {\n\n}\n\nfunction createDiscoveryService(logger: Logger,\n conf: DiscoveryConfig,\n isAutoDetectionEnabled: boolean,\n localMember: Promise<Member>): DiscoveryService {\n const factory = new DefaultDiscoveryServiceFactory();\n\n const node = localMember.then(member => new SimpleDiscoveryNode(member.address)) ;\n\n const settings: DiscoveryServiceSettings = {\n mode: 'member',\n node: node,\n conf: conf,\n auto: isAutoDetectionEnabled,\n logger: logger,\n };\n return factory.newDiscoveryService(settings);\n}\n\nfunction createAddressPicker(node: BridgeNode): AddressPicker {\n const config = node.config;\n const logger = node.getLogger('AddressPicker');\n return new DefaultAddressPicker(config, logger);\n}\n\nfunction isAnyNamedConfigEnabled(join: JoinConfig) {\n return createDiscoveryStrategyConfigs(join).length > 0;\n}\n\nexport class BridgeNode {\n readonly config: Config;\n #uuid: string;\n readonly #discoveryService: DiscoveryService;\n private readonly meshChannel: BridgeMeshChannel;\n private readonly version: MemberVersion;\n private server?: GatewayServer.Server;\n private readonly licenseValidator: LicenseValidator;\n #licenseCheckIntervalId: ReturnType<typeof setInterval> | undefined;\n\n constructor(config: Config) {\n this.config = config;\n\n this.licenseValidator = BridgeLicenseValidator(this.getLogger('license'));\n this.licenseValidator.validate(config.license);\n\n this.uuid = newUUID();\n this.version = parseVersion(info.version);\n const addressPicker = createAddressPicker(this);\n\n\n const localMemberPromise: Promise<Member> = addressPicker.pickAddress()\n .then(() => addressPicker.getPublicAddressFor('member'))\n .then((publicAddress) => {\n return {\n local: true,\n address: publicAddress,\n uuid: this.uuid,\n version: this.version,\n };\n }).finally(() => {\n addressPicker.close();\n });\n\n const joinConfig = config.network.join;\n\n const discoveryConfig: DiscoveryConfig = {\n discoveryServiceFactory: joinConfig.discovery.discoveryServiceFactory,\n discoveryStrategyConfigs: joinConfig.discovery.discoveryStrategyConfigs.concat(createDiscoveryStrategyConfigs(joinConfig)),\n };\n\n const strategyConfigs = createDiscoveryStrategyConfigs(joinConfig);\n\n const isAutoDetectionEnabled = joinConfig.autoDetectionEnabled;\n\n this.#discoveryService = createDiscoveryService(getLogger(\"discovery\"), discoveryConfig, isAutoDetectionEnabled, localMemberPromise);\n\n const relays = new InternalRelays(this.getLogger('relays'));\n\n const connections = new Connections(this.getLogger('nodes'), this.uuid, this.config.mesh.timeout ?? 60000);\n\n this.meshChannel = new BridgeMeshChannel(relays, connections, this.getLogger(\"channel\"));\n }\n\n getLogger(name: string) {\n return getLogger(name);\n }\n /**\n * Get the address on which the server is bound\n * @returns The server address info, undefined if not started, or null if stopped\n */\n\n get address() {\n return this.server?.address;\n }\n\n private scheduleLicenseCheck() {\n const task = async () => {\n try {\n this.licenseValidator.validate(this.config.license, {\n logSuccessMessages: false,\n });\n }\n catch (error) {\n // this.logger.error(error);\n await this.stop();\n }\n };\n\n const licenseCheckInterval = 1000 * 60 * 60 * 24; // 1 day\n return setInterval(task, licenseCheckInterval);\n }\n\n get uuid() {\n return this.#uuid;\n }\n\n set uuid(uuid: string) {\n this.#uuid = uuid;\n }\n\n async start() {\n await this.meshChannel.init();\n const config: ServerConfig = {\n port: this.config.server.port,\n host: this.config.server.host,\n ssl: this.config.server.ssl.enabled ? {\n requestCert: this.config.server.auth.type === 'x509',\n ...(this.config.server.ssl)\n } : undefined,\n auth: { type: 'none', ...(this.config.server.auth) },\n cors: this.config.server.cors.disabled ? false : this.config.server.cors,\n app: async (configurer, config) => {\n await mesh({\n logger: this.getLogger('mesh'),\n enabled: true,\n relays: this.meshChannel.relays,\n connections: this.meshChannel.connections,\n socket: {\n ping: this.config.server.wsPingInterval ?? 30000, // 30 seconds\n }\n }, configurer, config);\n },\n ...(await serverGatewayConfig(this.config.gateway, {\n meshChannel: this.meshChannel,\n wsPingInterval: this.config.server.wsPingInterval,\n uuid: this.uuid\n }))\n };\n\n logStartingInfo(this.getLogger('node'));\n\n const join = this.config.network.join;\n if (isAnyNamedConfigEnabled(join) || (join.autoDetectionEnabled && !this.#isEmptyDiscoveryStrategies())) {\n await this.#discoveryService.start();\n }\n\n this.server = await gatewayServer(config);\n if (config.gateway !== undefined) {\n onGatewayStarted(this.getLogger('gw'))(this.server.gateway);\n }\n this.#licenseCheckIntervalId = this.scheduleLicenseCheck();\n this.join();\n }\n\n join() {\n\n }\n\n async stop() {\n if (this.server)\n {\n await this.server.close()\n }\n try {\n await this.#discoveryService.close();\n }\n catch (e) {\n // ignore\n }\n\n await this.meshChannel.close();\n if (this.#licenseCheckIntervalId !== undefined) {\n clearInterval(this.#licenseCheckIntervalId);\n this.#licenseCheckIntervalId = undefined;\n }\n }\n\n #isEmptyDiscoveryStrategies() {\n return this.#discoveryService instanceof DefaultDiscoveryService && this.#discoveryService.strategies.length === 0;\n }\n}\n", "import type { GatewayConfig } from '@interopio/gateway-server/gateway-ent'\nexport function isRunningInConnectDesktop(env = process.env): boolean {\n return env._GD_STARTING_CONTEXT_ !== undefined;\n}\n\nexport type ApplicationConfig = {\n name: string;\n customProperties?: {\n gatewayApp?: boolean\n [key: string]: unknown\n } | GatewayConfig,\n [key: string]: unknown\n}\n\nexport type StartingContext = {\n instanceId: string\n env: string\n region: string\n applicationConfig?: ApplicationConfig\n [key: string]: unknown\n}\n\nexport function parseStartingContext(env = process.env): StartingContext {\n if (!isRunningInConnectDesktop(env)) {\n throw new Error(\"Not running in io.Connect Desktop\");\n }\n return JSON.parse(env._GD_STARTING_CONTEXT_);\n}\n", "import type { MeshChannel } from '@interopio/gateway/mesh/api';\nimport { isRunningInConnectDesktop, parseStartingContext } from './desktop.ts';\nimport type { Logger } from '@interopio/gateway/logging/api';\nimport { IOGateway } from '@interopio/gateway';\nimport type { ServerConfig } from '@interopio/gateway-server/config';\nimport { gatewayDiscoveryPipeServer } from './pipes/discovery.ts';\nimport { getPipeFileName } from './pipes/common.ts';\nimport type { GatewayConfig } from \"@interopio/gateway-server/gateway-ent\";\n\nexport function onGatewayStarted(log: Logger, env = process.env): (gateway: IOGateway.Gateway) => void {\n return (gateway) => {\n const info = JSON.stringify({...gateway.info(), pid: process.pid});\n if (isRunningInConnectDesktop(env)) {\n const startingContext = parseStartingContext(env);\n const environment = startingContext.env ?? env.IO_CD_ENV ?? env[\"GLUE-ENV\"] ?? 'DEMO';\n const region = startingContext.region ?? env.IO_CD_REGION ?? env[\"GLUE-REGION\"] ?? 'INTEROP.IO';\n const user = env.USERNAME ?? env.USER;\n const options = {\n logger: log,\n info,\n pipeNameProps: {environment, region, user}\n } as const;\n gatewayDiscoveryPipeServer(options);\n }\n else {\n log.info(`gateway started: ${info}`);\n }\n }\n}\n\nexport type GatewayServerConfig = Pick<ServerConfig, 'gateway' | 'management' | 'port' | 'host'>;\n\nexport async function serverGatewayConfig(gateway: {\n enabled?: boolean,\n contexts: {\n lifetime?: 'ref-counted' | 'ownership' | 'retained'\n }\n },\n bridge: {\n meshChannel: MeshChannel,\n wsPingInterval?: number,\n uuid?: string,\n management?: ServerConfig['management']\n }, env = process.env): Promise<GatewayServerConfig | undefined> {\n let enabled = gateway.enabled;\n let management = bridge.management;\n let port: number | string | undefined;\n let host: string | undefined;\n let route: string | undefined;\n\n if (isRunningInConnectDesktop(env)) {\n const startingContext = parseStartingContext(env);\n if (enabled === undefined) {\n const applicationConfig = startingContext.applicationConfig;\n enabled = applicationConfig?.customProperties?.gatewayApp === true || applicationConfig?.name === 'io-connect-gateway';\n const gatewayConfig = applicationConfig?.customProperties as GatewayConfig | undefined;\n port = gatewayConfig?.port ?? 8385;\n host = gatewayConfig?.ip ?? '127.0.0.1';\n route = gatewayConfig?.route ?? '/';\n }\n if (enabled) {\n const environment = startingContext.env ?? env.IO_CD_ENV ?? env[\"GLUE-ENV\"] ?? 'DEMO';\n const region = startingContext.region ?? env.IO_CD_REGION ?? env[\"GLUE-REGION\"] ?? 'INTEROP.IO';\n const user = env.USERNAME ?? env.USER;\n\n management ??= {server: {}};\n management.server.path ??= getPipeFileName(`glue42-gateway-${environment}-${region}-${user}`);\n management.commands ??= {};\n management.commands.shutdown ??= {};\n management.commands.shutdown.enabled ??= true;\n }\n\n }\n let contextsLifetime = gateway.contexts.lifetime;\n if (contextsLifetime === undefined) {\n if (isRunningInConnectDesktop(env)) {\n contextsLifetime = 'retained';\n }\n }\n if (enabled) {\n const result: GatewayServerConfig = {\n gateway: {\n clients: {\n inactive_seconds: 0,\n },\n mesh: {\n auth: { user: null },\n node: bridge.uuid,\n channel: bridge.meshChannel\n },\n contexts: {\n lifetime: contextsLifetime,\n visibility: [\n { context: /___channel___.+/, restrictions: 'cluster' },\n { context: '__insights_pi_storage__', restrictions: 'cluster' },\n { context: /T42\\..*/, restrictions: 'local' },\n { context: \"___platform_prefs___\", restrictions: 'local' },\n { context: /___workspace___.+/, restrictions: 'local' },\n { context: /___window-hibernation___.+/, restrictions: 'local' },\n { context: /___instance___.+/, restrictions: 'local' },\n { context: /___window___.+/, restrictions: 'local' },\n { restrictions: 'cluster' }\n ]\n },\n methods: {\n visibility: [\n { method: /T42\\..*/, restrictions: 'local' },\n { restrictions: 'cluster' }\n ]\n },\n peers: {\n visibility: [\n { domain: 'context', restrictions: 'cluster' },\n { domain: 'interop', restrictions: 'cluster' },\n { domain: 'bus', restrictions: 'local' }\n ]\n }\n }\n };\n if (host !== undefined) {\n result.host = host;\n }\n if (port !== undefined) {\n result.port = port;\n }\n if (route !== undefined) {\n result.gateway.route = route;\n }\n if (bridge.wsPingInterval !== undefined) {\n result.gateway.ping = bridge.wsPingInterval;\n }\n if (management !== undefined) {\n result.management = management;\n }\n return result;\n }\n}\n", "import { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { rmSync } from \"node:fs\";\n\nfunction isWinOS() {\n return process.platform === \"win32\";\n}\nexport function getPipeFileName(pipe: string, removeExisting = false) {\n const fileName = isWinOS() ? `\\\\\\\\.\\\\pipe\\\\${pipe}` : join(tmpdir(), `${pipe}.sock`);\n if (!isWinOS() && removeExisting) {\n try {\n rmSync(fileName);\n }\n catch (e) {\n // Ignore error if file does not exist or cannot be removed\n }\n }\n return fileName;\n}\n", "import { getPipeFileName } from './common.ts';\nimport type { PipeNameProperties, PipeServerOptions } from './types.ts';\nimport { createServer } from 'node:net';\n\nfunction getDiscoveryPipeFileName({ environment, region, user }: PipeNameProperties) {\n return getPipeFileName(`glue42-${environment}-${region}-${user}`, true);\n}\n\nexport function gatewayDiscoveryPipeServer({ logger, info, pipeNameProps }: PipeServerOptions) {\n const pipeName = getDiscoveryPipeFileName(pipeNameProps);\n logger.info(`gateway started: ${info}, opening ${pipeName}`);\n const server = createServer((stream) => {\n logger.info(`stream connected, sending info...`);\n stream.write(info);\n stream.end(() => {\n server.close();\n });\n });\n server.listen(pipeName);\n return server;\n}\n", "import type { Node, NodeAnnouncement, NodeConnections } from '../types.ts';\nimport type {\n ServerConfigurer,\n ServerConfigurerHandlerSpec,\n ServerHttpRequest\n} from '@interopio/gateway-server/web/server';\nimport type {AuthorizationRule} from '@interopio/gateway-server/auth/api';\n\nfunction buildCanonicalBaseURL(request: ServerHttpRequest): URL {\n const requestURL = request.URL;\n const protocol = requestURL.protocol === 'https:' ? 'wss://' : 'ws://';\n return new URL(protocol + requestURL.host);\n}\n\nfunction toCanonicalEndpoint(endpoint: string, request: ServerHttpRequest): string {\n\n const canonicalBaseURL = buildCanonicalBaseURL(request);\n\n const endpointURL = new URL(endpoint, canonicalBaseURL);\n if (endpointURL.protocol == canonicalBaseURL.protocol && endpointURL.host === canonicalBaseURL.host) {\n return endpointURL.pathname + endpointURL.search + endpointURL.hash;\n }\n else {\n return endpointURL.href;\n }\n}\n\nfunction fromCanonicalEndpoint(endpoint: string, request: ServerHttpRequest): string {\n const canonicalBaseURL = buildCanonicalBaseURL(request);\n const endpointURL = new URL(endpoint, canonicalBaseURL);\n return endpointURL.href;\n}\n\nfunction fromRequestNode(node: NodeAnnouncement, request: ServerHttpRequest): NodeAnnouncement {\n const endpoint = toCanonicalEndpoint(node.endpoint ?? `/cluster?node=${node.node}`, request);\n if (endpoint !== node.endpoint) {\n return { ...node, endpoint };\n }\n return node;\n}\nfunction toRequestNode(node: Node, request: ServerHttpRequest): Node {\n const endpoint = fromCanonicalEndpoint(node.endpoint, request);\n if (endpoint !== node.endpoint) {\n return { ...node, endpoint };\n }\n return node;\n}\n\nfunction routes(config: { connections: NodeConnections, authorize?: AuthorizationRule }, {handle}: ServerConfigurer) {\n const {connections, authorize} = config;\n handle(\n {\n request: {method: 'POST', path: '/api/nodes'}, options: {cors: true, authorize},\n handler: async ({request, response}) => {\n const json = await request.json();\n if (!Array.isArray(json)) {\n response.setRawStatusCode(400 /*Bad Request*/);\n await response.end();\n }\n else {\n const nodes = (json as NodeAnnouncement[]).map((node) => {\n return fromRequestNode(node, request);\n });\n const result = connections.announce(nodes).map((connection) => {\n const connect = connection.connect?.map((node) => {\n return toRequestNode(node, request);\n });\n return { ...connection, connect: connect }\n });\n const buffer = Buffer.from(JSON.stringify(result), 'utf8');\n response.setRawStatusCode(200 /*OK*/);\n response.headers.set('Content-Type', 'application/json; charset=utf8');\n await response.body(buffer);\n }\n }\n },\n {\n request: {method: 'GET', path: /^\\/api\\/nodes\\/(?<nodeId>.+)$/}, options: {cors: true, authorize},\n handler: async ({request, response}, {nodeId}) => {\n const result = connections.find(nodeId)?.map((node) => toRequestNode(node, request));\n if (result !== undefined) {\n const buffer = Buffer.from(JSON.stringify(result), 'utf8');\n response.setRawStatusCode(200 /* OK */);\n response.headers.set('Content-Type', 'application/json; charset=utf8');\n await response.body(buffer);\n } else {\n response.setRawStatusCode(404 /* Not Found */);\n await response.end();\n }\n },\n } as ServerConfigurerHandlerSpec<'nodeId'>,\n {\n request: {method: 'DELETE', path: /^\\/api\\/nodes\\/(?<nodeId>.*)$/}, options: {cors: true, authorize},\n handler: async ({response}, {nodeId}) => {\n\n const removed = connections.remove(nodeId);\n if (removed) {\n response.setRawStatusCode(200 /* OK */);\n } else {\n response.setRawStatusCode(404 /* Not Found */);\n }\n await response.end();\n }\n } as ServerConfigurerHandlerSpec<'nodeId'>,\n );\n}\n\nexport default routes;\n", "import type { Relays } from '../../types.ts';\n\nimport type {ServerWebSocketHandler} from '@interopio/gateway-server/web/server';\nimport {IOGateway} from '@interopio/gateway';\n\nlet handlerId = 0;\nasync function create(log: IOGateway.Logging.Logger,\n internal: Relays,\n env: { endpoint: string }): Promise<ServerWebSocketHandler> {\n\n const id = ++handlerId;\n log.info(`relays-${id} server is listening on ${env.endpoint}`);\n let keyId = 0;\n return async ({socket, handshake}) => {\n const logPrefix = handshake.logPrefix ?? '';\n const query = handshake.url.searchParams;\n const key = `r.${id}.${++keyId}`\n log.info(`${logPrefix}connected on /relays with ${query} and assigned key ${key}`);\n internal.add(key, (msg: string, c, cb) => {\n if (log.enabledFor('trace')) {\n log.debug(`${logPrefix}sending with key ${key}: ${msg}`);\n }\n socket.send(msg, {binary: false}, (err?: Error) => {\n cb(key, err);\n });\n });\n //onOpen(connectedNodes, key);\n socket.on('error', (err: Error) => {\n log.error(`${logPrefix}websocket error: ${err.message}`, err);\n });\n socket.on('message', (data, _isBinary) => {\n if (Array.isArray(data)) {\n data = Buffer.concat(data);\n }\n try {\n internal.receive(key, data as unknown as string);\n } catch (e) {\n log.warn(`${logPrefix}error processing received data '${data}'`, e);\n }\n });\n socket.on('close', (code, reason) => {\n internal.remove(key);\n\n log.info(`${logPrefix}disconnected from relays (code: ${code}, reason: '${reason.toString('utf8')}')`);\n });\n };\n}\n\nexport const meshRelays = ({logger, relays}: { logger: IOGateway.Logging.Logger, relays: Relays }) => {\n return async (env: { endpoint: string }) => {\n return await create(logger, relays, env);\n }\n}\n", "import type { WebSocket } from 'ws';\nimport type { Relays } from '../../types.ts';\nimport type { ServerWebSocketHandler } from '@interopio/gateway-server/web/server';\nimport { IOGateway } from '@interopio/gateway';\n\nfunction onMessage(relays: Relays,\n log: IOGateway.Logging.Logger,\n key: string,\n node: string,\n socketsByNodeId: Map<string, Map<string, WebSocket>>,\n msg: string) {\n try {\n relays.send(key, node, msg, (k, err?: Error) => {\n if (err) {\n log.warn(`${k} error writing msg ${msg}: ${err}`);\n return;\n }\n if (log.enabledFor('trace')) {\n log.debug(`${k} sent msg ${msg}`);\n }\n });\n } catch (ex) {\n log.error(`${key} unable to process message`, ex);\n if (node) {\n const socket = socketsByNodeId.get(node)?.get(key);\n socket?.terminate();\n }\n }\n}\nlet handlerId = 0;\nasync function create(\n log: IOGateway.Logging.Logger,\n relays: Relays,\n env: { endpoint: string }\n): Promise<ServerWebSocketHandler> {\n const socketsByNodeId = new Map<string, Map<string, WebSocket>>();\n relays.on('message', (k, nodeId, msg) => {\n try {\n const sockets = socketsByNodeId.get(nodeId);\n if (sockets && sockets.size > 0) {\n if (log.enabledFor('trace')) {\n log.debug(`${k} sending message to ${[...sockets.keys()]}`); // list of keys\n }\n for (const [key, socket] of sockets) {\n socket.send(msg, {binary: false}, (err?: Error) => {\n if (err) {\n log.warn(`${key} error writing from ${k} msg ${msg}: ${err}`);\n return;\n }\n if (log.enabledFor('trace')) {\n log.debug(`${key} sent from ${k} msg ${msg}`);\n }\n });\n }\n } else {\n log.warn(`${k} dropped msg ${msg}.`);\n }\n } catch (ex) {\n log.error(`${k} unable to process message`, ex);\n }\n });\n relays.on('disconnect', (k, nodeId) => {\n const sockets = socketsByNodeId.get(nodeId);\n if (sockets) {\n for (const [key, socket] of sockets) {\n socket.terminate();\n log.info(`${key} terminated because ${k} disconnected ${nodeId}`);\n }\n }\n });\n\n const id = ++handlerId;\n let keyId = 0;\n\n return async ({socket, handshake}) => {\n const logPrefix = handshake.logPrefix ?? '';\n const query = handshake.url.searchParams;\n const key = `c.${id}.${++keyId}`;\n log.info(`${logPrefix}connected on /cluster with ${query} and assigned key ${key}`);\n\n const node = query.get('node');\n if (node) {\n let sockets = socketsByNodeId.get(node);\n if (!sockets) {\n sockets = new Map<string, WebSocket>();\n socketsByNodeId.set(node, sockets);\n }\n sockets.set(key, socket);\n } else {\n socket.terminate();\n return;\n }\n //onOpen(connectedNodes, key);\n socket.on('error', (err: Error) => {\n log.error(`${key} websocket error: ${err}`, err);\n });\n socket.on('message', (data, _isBinary) => {\n if (Array.isArray(data)) {\n data = Buffer.concat(data);\n }\n onMessage(relays, log, key, node, socketsByNodeId, data as unknown as string);\n });\n socket.on('close', (_code, _reason) => {\n log.info(`${key} disconnected from cluster`);\n const sockets = socketsByNodeId.get(node);\n if (sockets) {\n sockets.delete(key);\n if (sockets.size === 0) {\n socketsByNodeId.delete(node);\n }\n }\n });\n };\n}\n\nexport const meshCluster = ({logger, relays}: { logger: IOGateway.Logging.Logger, relays: Relays }) => {\n return async (environment: { endpoint: string }) => {\n return await create(logger, relays, environment);\n }\n};\n", "import restDirectory from './mesh/rest-directory/routes.ts';\nimport { meshRelays } from './mesh/ws/relays/core.ts';\nimport { meshCluster } from './mesh/ws/cluster/core.ts';\nimport type {ServerConfigurer, ServerWebSocketOptions} from '@interopio/gateway-server/web/server';\nimport type { Relays, NodeConnections } from './mesh/types.ts';\nimport { GatewayServer } from '@interopio/gateway-server';\nimport type { Logger } from '@interopio/gateway/logging/api';\n\nfunction connectNodeRelays(logger: Logger, relays: Relays, connections: NodeConnections) {\n relays.on('connect', (key, node) => {\n try {\n connections.add(node);\n }\n catch (e) {\n logger.warn(`${key} error adding node ${node} to connections: ${e}`);\n }\n });\n relays.on('disconnect', (key, node, links) => {\n try {\n connections.remove(node);\n }\n catch (e) {\n logger.warn(`${key} error removing node ${node} from connections: ${e}`);\n }\n for (const [linkNode, linkKey] of links) {\n try {\n relays.send(linkKey, linkNode, { type: 'bye', from: node, to: linkNode }, (k, err?) => {\n if (err) {\n logger.warn(`${k} error writing 'bye' msg to ${linkNode}: ${err}`);\n return;\n }\n if (logger.enabledFor('debug')) {\n logger.debug(`${k} sent 'bye' msg to ${linkNode} from ${node}`);\n }\n });\n } catch (err) {\n logger.warn(`${linkKey} exception writing 'bye' msg to ${linkNode} from ${node}: ${err}`);\n }\n }\n });\n\n}\n\nexport const mesh = async (\n options: {\n logger: Logger,\n enabled?: boolean,\n relays: Relays,\n connections: NodeConnections,\n socket: ServerWebSocketOptions\n },\n configurer: ServerConfigurer,\n config: GatewayServer.ServerConfig\n) => {\n const {enabled, logger, relays, connections} = options;\n if (enabled !== true) {\n if (logger.enabledFor('debug')) {\n logger.debug(`no mesh`);\n }\n return;\n }\n let {socket} = options;\n const authorize = socket.authorize ?? {access: config.auth.type === 'none' ? 'permitted' : 'authenticated'};\n socket = {ping: 30000, authorize: authorize, ...socket};\n connectNodeRelays(logger, relays, connections);\n restDirectory({connections, authorize}, configurer);\n configurer.socket(\n {\n path: '/cluster', options: socket,\n factory: meshCluster({logger, relays})\n },\n {\n path: '/relays', options: socket,\n factory: meshRelays({logger, relays})\n }\n );\n}\n\nimport BridgeMeshChannel from './mesh/gateway/mesh.ts';\nexport { BridgeMeshChannel };\n", "import { nanoid } from 'nanoid';\nimport type InMemoryNodeConnections from '../connections.ts';\nimport type { Relays, RelayMessageHandler, NodeConnections, NodeAnnouncement } from '../types.ts';\nimport type { MeshChannel, MeshSubscriber, MeshAction, MeshEvent, MeshMessage } from '@interopio/gateway/mesh/api';\nimport type { Logger } from '@interopio/gateway/logging/api';\nimport gateway from '@interopio/gateway/package.json' with { type: 'json' };\n\nlet instanceId = 0;\n\ntype NodeState<T=string> = {\n subscriber: MeshSubscriber<T>,\n users: Set<string>,\n members: Set<string>,\n outgoing: Set<string>\n};\n\nexport default class BridgeMeshChannel implements MeshChannel {\n readonly #logger: Logger;\n readonly #relays: Relays;\n readonly #connections: InMemoryNodeConnections;\n readonly #state: Map<string, NodeState<unknown>>;\n readonly #keyPrefix: string;\n\n constructor(relays: Relays,\n nodes: InMemoryNodeConnections,\n logger: Logger\n ) {\n this.#relays = relays;\n this.#connections = nodes;\n this.#logger = logger;\n this.#state = new Map<string, NodeState<unknown>>();\n this.#keyPrefix = `g.${++instanceId}`;\n\n // When a node's WebSocket connection is actually established,\n // update outgoing in both directions.\n this.#connections.on('node-connected', (nodeId) => {\n // Check if the newly connected node is a connect target for any local node\n for (const [n, state] of this.#state) {\n if (n === nodeId) {\n continue;\n }\n const connect = this.#connections.find(n);\n if (connect?.some((c) => c.node === nodeId)) {\n state.outgoing.add(nodeId);\n if (!state.members.has(nodeId)) {\n state.members.add(nodeId);\n state.subscriber({type: 'member-added', node: nodeId}, n, this);\n }\n }\n }\n\n // Check the newly connected node's own connect list for already-connected targets\n const nodeState = this.#state.get(nodeId);\n if (nodeState) {\n const connect = this.#connections.find(nodeId);\n if (connect) {\n for (const c of connect) {\n if (this.#connections.isConnected(c.node) && !nodeState.outgoing.has(c.node)) {\n nodeState.outgoing.add(c.node);\n if (!nodeState.members.has(c.node)) {\n nodeState.members.add(c.node);\n nodeState.subscriber({type: 'member-added', node: c.node}, nodeId, this);\n }\n }\n }\n }\n }\n });\n\n // When a node disconnects, remove it from outgoing and members for all local nodes.\n this.#connections.on('node-disconnected', (nodeId) => {\n for (const [n, state] of this.#state) {\n state.outgoing.delete(nodeId);\n if (state.members.has(nodeId)) {\n state.members.delete(nodeId);\n state.subscriber({type: 'member-removed', node: nodeId}, n, this);\n }\n }\n });\n }\n\n get relays(): Relays {\n return this.#relays;\n }\n get connections(): NodeConnections {\n return this.#connections;\n }\n\n #intervalId: ReturnType<typeof setInterval>;\n\n subscribe<T = string>(node?: string, subscriber?: MeshSubscriber<T>): string {\n node ??= nanoid();\n const key = `${this.#keyPrefix}-${node}`;\n if (this.#state.has(key)) {\n throw new Error(`already subscribed to node ${node}`);\n }\n this.#state.set(node, {subscriber, users: new Set<string>(), members: new Set<string>(), outgoing: new Set<string>()});\n this.#relays.add(key, this.createRelayClient(key, node));\n this.#announce(node);\n this.#relays.receive(key, { type: 'hello' as const, from: node, to: 'all' });\n // Announce at half the timeout interval to ensure node doesn't expire\n this.#intervalId ??= setInterval(() => this.#announce(), this.#connections.timeout / 2);\n return node;\n }\n\n private createRelayClient<T>(key: string, node: string): RelayMessageHandler {\n return (_msg: string, command, cb) => {\n\n const state = this.#state.get(node);\n if (state !== undefined) {\n try {\n switch (command.type) {\n case 'hello': {\n if (state.members.has(command.from)) {\n break;\n }\n state.members.add(command.from);\n state.subscriber({ type: 'member-added', node: command.from }, node, this);\n break;\n }\n case \"bye\": {\n if (!state.members.has(command.from)) {\n break;\n }\n state.members.delete(command.from);\n state.subscriber({ type: 'member-removed', node: command.from }, node, this);\n break;\n }\n case \"data\": {\n const event: MeshEvent<T> = {\n type: 'message-received',\n message: command.data as MeshMessage<T>\n };\n state.subscriber(event, node, this);\n\n break;\n }\n }\n }\n catch (err) {\n cb(key, err)\n }\n }\n\n }\n }\n\n unsubscribe(node: string): void {\n this.#delete(node);\n this.#relays.remove(`${this.#keyPrefix}-${node}`);\n }\n\n execute<T = string>(node: string, action: MeshAction<T>): void {\n switch (action.type) {\n case 'publish-message': {\n this.#onPublishMessage(node, action.message as MeshMessage);\n break;\n }\n case 'add-users': {\n this.#onAddUsers(node, action.added);\n break;\n }\n case 'remove-users': {\n this.#onRemoveUsers(node, action.removed);\n break;\n }\n }\n }\n\n #onPublishMessage(node: string, data: MeshMessage): void {\n const nodes = data.receiver.type === 'cluster'\n ? Array.from(this.#state.get(node)?.members ?? [])\n : [data.receiver['node'] as string];\n const key = `${this.#keyPrefix}-${node}`;\n const command = { type: 'data' as const, from: node, data };\n nodes.forEach((to) => {\n if (to === node) {\n return;\n }\n\n try {\n this.#relays.send(key, to, { ...command, to }, (k, err) => {\n if (err) {\n this.#logger.warn(`failed to send message from ${node} to ${to} via ${k}: ${err.message}`);\n }\n });\n } catch (err) {\n this.#logger.warn(`failed to send message from ${node} to ${to} via ${key}: ${(err as Error).message}`);\n }\n });\n }\n\n #onAddUsers(node: string, usersToAdd: readonly string[]) {\n let shouldAnnounce = false;\n const nodeState = this.#state.get(node);\n if (nodeState.users === undefined) {\n nodeState.users = new Set<string>(usersToAdd);\n shouldAnnounce = true;\n }\n else {\n for (const u of usersToAdd) {\n if (nodeState.users.has(u)) {\n continue;\n }\n nodeState.users.add(u);\n shouldAnnounce = true;\n }\n }\n if (shouldAnnounce) {\n this.#announce(node);\n }\n }\n\n #onRemoveUsers(node: string, usersToRemove: readonly string[]) {\n const nodeState = this.#state.get(node);\n const nodeUsers = nodeState?.users;\n if (nodeUsers === undefined) {\n return;\n }\n let shouldAnnounce = false;\n for (const u of usersToRemove) {\n if (!nodeUsers.has(u)) {\n continue;\n }\n nodeUsers.delete(u);\n shouldAnnounce = true;\n }\n if (shouldAnnounce) {\n this.#announce(node);\n }\n if (nodeUsers.size === 0) {\n // this.#delete(node);\n }\n }\n\n #announce(node?: string) {\n const entries: [string, NodeState<unknown>][] = node === undefined\n ? Array.from(this.#state.entries())\n : [[node, this.#state.get(node)]];\n const announcements: NodeAnnouncement[] = entries.map(entryToNodeAnnouncement);\n\n const nodeConnections = this.#connections.announce(announcements);\n\n // Sync outgoing: if connect includes nodes that are already connected\n // but not yet in outgoing, add them. This handles the case where the\n // user set changed after the connection was already established.\n for (const {node: n, connect} of nodeConnections) {\n const state = this.#state.get(n);\n if (state === undefined) {\n continue;\n }\n\n // Remove stale outgoing that are no longer in connect\n for (const prev of state.outgoing) {\n if (!connect.some((c) => c.node === prev)) {\n state.outgoing.delete(prev);\n if (state.members.has(prev)) {\n state.members.delete(prev);\n state.subscriber({type: 'member-removed', node: prev}, n, this);\n }\n }\n }\n\n // Add connect targets that are already connected\n for (const c of connect) {\n if (c.node !== n && this.#connections.isConnected(c.node) && !state.outgoing.has(c.node)) {\n state.outgoing.add(c.node);\n if (!state.members.has(c.node)) {\n state.members.add(c.node);\n state.subscriber({type: 'member-added', node: c.node}, n, this);\n }\n }\n }\n }\n }\n\n #delete(node: string) {\n this.#state.delete(node);\n this.#connections.remove(node);\n }\n\n async init(gossipTimestamp = 0) {\n await this.#connections.init(gossipTimestamp);\n }\n\n async close() {\n for (const node of this.#state.keys()) {\n this.#delete(node);\n this.#relays.remove(`${this.#keyPrefix}-${node}`);\n }\n clearInterval(this.#intervalId)\n await this.#connections.close();\n }\n}\n\nconst entryToNodeAnnouncement = ([node, state]: [string, NodeState]): NodeAnnouncement => {\n const users = Array.from(state?.users);\n\n return { node, users, metadata: { version: gateway.version, type: 'io.Bridge' } };\n}\n", "import type { Logger } from '@interopio/gateway/logging/api';\nimport { hrwHash } from 'hrw-hash';\nimport { LamportClock, type LamportTimestamp } from './lamport.ts';\nimport type { Node, NodeAnnouncement, NodeConnection, NodeConnections, NodeEventTypes } from './types.ts';\nimport { EventEmitter } from 'node:events';\n\ntype NodeValue = Omit<Node, 'users'> & {\n node: string\n readonly firstSeen: LamportTimestamp\n status: 'announced' | 'added' | 'expired' | 'removed'\n owner: string\n replicas: readonly string[]\n users: Set<string>\n lastSeen: number\n relayOwner?: string\n readonly metadata?: { [key: string]: unknown }\n}\n\nexport default class InMemoryNodeConnections implements NodeConnections {\n readonly #logger: Logger;\n readonly #eventEmitter = new EventEmitter<NodeEventTypes>();\n readonly #nodes = new Map<string, NodeValue>();\n readonly #clusterNodes: string[];\n readonly #lamport: LamportClock;\n readonly #timeout: number;\n\n constructor(logger: Logger,\n instanceId: string,\n timeout: number = 60000) {\n this.#logger = logger;\n this.#clusterNodes = [instanceId];\n this.#lamport = new LamportClock(instanceId);\n this.#timeout = timeout;\n }\n\n async init(gossipTimestamp = 0) {\n await this.#lamport.init(gossipTimestamp);\n }\n\n async close() {\n await this.#lamport.shutdown();\n }\n\n get timeout(): number {\n return this.#timeout;\n }\n\n announce(announcements: Array<NodeAnnouncement>): NodeConnection[] {\n const now = Date.now();\n for (const announcement of announcements) {\n const { node: nodeId, users, endpoint: announcedEndpoint, metadata } = announcement;\n\n const replicas : readonly string[] = hrwHash(nodeId, this.#clusterNodes);\n const owner = replicas[0];\n const externalEndpoint = announcedEndpoint !== undefined && announcedEndpoint !== `/cluster?node=${nodeId}`;\n const endpoint = externalEndpoint ? announcedEndpoint : `/cluster?node=${nodeId}&owner=${owner}`;\n\n let node: NodeValue = this.#nodes.get(nodeId);\n const userSet = new Set<string>(users ?? []);\n if (!node) {\n const lamport = this.#lamport.tick();\n node = {node: nodeId, users: userSet, firstSeen: lamport, lastSeen: now, owner, replicas, endpoint, metadata, status: 'announced' };\n this.#nodes.set(nodeId, node);\n this.#logger.info(`${nodeId} announced at endpoint ${endpoint} with meta: ${JSON.stringify(metadata)}`);\n }\n\n node.owner = owner;\n if (!externalEndpoint) {\n node.endpoint = endpoint;\n }\n node.replicas = replicas;\n node.lastSeen = now;\n if (!(node.status === 'announced' || node.status === 'added')) {\n node.status = 'announced';\n }\n node.users = userSet;\n\n this.#eventEmitter.emit('node-announced', nodeId, endpoint, userSet);\n }\n const sortedNodes = this.#sortedNodeValues();\n return announcements.map((e) => {\n const node = this.#nodes.get(e.node);\n const connect = this.#findConnections(sortedNodes, node);\n return { node: node.node, owner: node.owner, connect };\n });\n }\n\n find(nodeId: string): ReadonlyArray<Node> | undefined {\n const e = this.#nodes.get(nodeId);\n if (e !== undefined) {\n const sortedNodes = this.#sortedNodeValues();\n return this.#findConnections(sortedNodes, e);\n }\n return undefined;\n }\n\n isConnected(nodeId: string): boolean {\n return this.#nodes.get(nodeId)?.status === 'added';\n }\n\n add(nodeId: string) {\n const added = this.#nodes.get(nodeId);\n if (added !== undefined && (added.status === 'announced' || added.status === 'removed')) {\n added.status = 'added';\n this.#logger.info(`endpoint ${added.endpoint} connected for ${nodeId}`);\n this.#eventEmitter.emit('node-connected', nodeId);\n return true;\n }\n return false;\n }\n\n remove(nodeId: string) {\n const removed = this.#nodes.get(nodeId);\n if (removed !== undefined && (removed.status === 'announced' || removed.status === 'added')) {\n removed.status = 'removed';\n this.#logger.info(`endpoint ${removed.endpoint} removed for ${nodeId}`);\n this.#eventEmitter.emit('node-disconnected', nodeId, 'removed');\n return true;\n }\n return false;\n }\n\n #sortedNodeValues(): NodeValue[] {\n this.#cleanupOldNodes();\n return Array.from(this.#nodes.values())\n .filter((n) => n.status === 'announced' || n.status === 'added')\n .sort((a, b) => {\n const diff = a.firstSeen.timestamp - b.firstSeen.timestamp;\n if (diff === 0) {\n return a.node.localeCompare(b.node);\n }\n return diff;\n });\n }\n\n #cleanupOldNodes() {\n const now = Date.now();\n const expiredTimestamp = now - this.#timeout;\n const removedTimestamp = now - (this.#timeout * 2);\n const compactTimestamp = now - (this.#timeout * 10);\n for (const [nodeId, v] of this.#nodes) {\n if (v.lastSeen < compactTimestamp && v.status === 'removed') {\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${nodeId} compact - no announcement since ${new Date(v.lastSeen).toISOString()}, timeout is ${this.#timeout} ms and status is ${v.status}.`);\n }\n this.#nodes.delete(nodeId);\n }\n if (v.lastSeen < removedTimestamp && v.status === 'expired') {\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${nodeId} removed - no announcement since ${new Date(v.lastSeen).toISOString()}, timeout is ${this.#timeout} ms.`);\n }\n // mark as removed\n v.status = 'removed';\n }\n\n if (v.lastSeen < expiredTimestamp && (v.status === 'announced' || v.status === 'added')) {\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${nodeId} expired - no announcement since ${new Date(v.lastSeen).toISOString()}, timeout is ${this.#timeout} ms.`);\n }\n // mark as expired\n v.status = 'expired';\n this.#eventEmitter.emit('node-disconnected', nodeId, 'expired');\n }\n }\n }\n\n public on<K extends keyof NodeEventTypes>(event: K, listener: (K extends keyof NodeEventTypes ? NodeEventTypes[K] extends unknown[] ? (...args: NodeEventTypes[K]) => void : never : never)): this {\n this.#eventEmitter.on(event, listener);\n return this;\n }\n\n public off<K extends keyof NodeEventTypes>(event: K, listener: (K extends keyof NodeEventTypes ? NodeEventTypes[K] extends unknown[] ? (...args: NodeEventTypes[K]) => void : never : never)): this {\n this.#eventEmitter.off(event, listener);\n return this;\n }\n\n #findConnections(sortedNodes: NodeValue[], node: NodeValue): ReadonlyArray<Node> {\n const results = sortedNodes.reduce((l, c) => {\n if (c.node === node.node) {\n return l;\n }\n const isOlder = c.firstSeen.timestamp < node.firstSeen.timestamp;\n if (isOlder && this.#hasSharedUsers(node, c)) {\n const e: Node = { node: c.node, endpoint: c.endpoint, owner: c.owner };\n return l.concat(e);\n }\n return l;\n }, new Array<Node>());\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`found ${results.length} connection(s) for node ${node.node}: [${results.map((e) => `${e.node}@${e.endpoint}`).join(', ')}]`);\n }\n return results;\n }\n\n #hasSharedUsers(a: NodeValue, b: NodeValue): boolean {\n for (const user of a.users) {\n if (b.users.has(user)) {\n return true;\n }\n }\n return false;\n }\n}\n", "import { appendFile, readFile, rename, writeFile } from 'node:fs/promises';\n\nexport type LamportTimestamp = { readonly timestamp: number, readonly instanceId: string }\n\nexport class LamportClock {\n static #FLUSH_INTERVAL = 5000; // 5 seconds\n static #CLOCK_FILE = './lamport.clock';\n static #WAL_FILE = './lamport.wal';\n #timestamp: number;\n #instanceId: string;\n #flushIntervalId: ReturnType<typeof setInterval>;\n #pendingWrites = 0;\n\n constructor(instanceId: string) {\n this.#instanceId = instanceId;\n this.#timestamp = 0;\n this.#flushIntervalId = setInterval(() => {\n this.#flush().catch(err => {/* ignore */});\n }, LamportClock.#FLUSH_INTERVAL);\n }\n\n async init(gossipTimestamp = 0) {\n const baseTimestamp = await this.#loadSnapshot();\n const journaledIncrements = await this.#replayWal();\n this.#timestamp = Math.max(baseTimestamp + journaledIncrements, gossipTimestamp);\n }\n\n tick(): LamportTimestamp {\n this.#timestamp += 1;\n this.#pendingWrites += 1;\n this.#appendToWal().catch((_err) => {/* ignore */\n }); // async fire-and-forget, no need to await\n return { timestamp: this.#timestamp, instanceId: this.#instanceId };\n }\n\n observe(gossipTimestamp: number): LamportTimestamp {\n this.#timestamp = Math.max(this.#timestamp, gossipTimestamp) + 1;\n this.#pendingWrites += 1;\n this.#appendToWal().catch((_err) => {/* ignore */\n }); // async fire-and-forget, no need to await\n return { timestamp: this.#timestamp, instanceId: this.#instanceId };\n }\n\n timestamp(): LamportTimestamp {\n return { timestamp: this.#timestamp, instanceId: this.#instanceId };\n }\n\n async shutdown(): Promise<void> {\n clearInterval(this.#flushIntervalId);\n await this.#flush();\n }\n\n async #appendToWal(): Promise<void> {\n const data = `${this.#timestamp}\\n`;\n await appendFile(LamportClock.#WAL_FILE, data, 'utf-8');\n }\n\n async #replayWal() {\n try {\n const data = await readFile(LamportClock.#WAL_FILE, 'utf-8');\n return data.trim().split('\\n').filter(Boolean).length;\n }\n catch {\n // ignore\n }\n return 0;\n }\n\n async #loadSnapshot() {\n try {\n const data = await readFile(LamportClock.#CLOCK_FILE, 'utf-8');\n return parseInt(data, 10) || 0;\n }\n catch {\n // ignore\n }\n return 0;\n }\n\n async #flush() {\n if (this.#pendingWrites === 0) {\n return;\n }\n const tmp = `${LamportClock.#CLOCK_FILE}.tmp`;\n const data = `${this.#timestamp}\\n`;\n await writeFile(tmp, data, { flag: 'w' });\n await rename(tmp, LamportClock.#CLOCK_FILE);\n await writeFile(LamportClock.#WAL_FILE, '', { flag: 'w' }); // truncate WAL\n this.#pendingWrites = 0;\n }\n}\n", "import type { RelayEventTypes, RelayMessageHandler, Relays, Command, EncodedCommandType } from './types.ts';\nimport { IOGateway } from '@interopio/gateway';\nimport { EventEmitter } from 'node:events';\n\nconst codec = IOGateway.Encoding.transit<Command>({\n namespaces: new Map<string, string>([\n ['commands', 'gateway.common.commands']\n ]),\n keywordize: new Map<string, IOGateway.Encoding.KeywordizeCommand>([\n ['/type', '*'],\n ['/to', new Set<string>(['all'])],\n ['/data/origin', '*'],\n ['/data/receiver/type', '*'],\n ['/data/source/type', '*'],\n ['/data/body/type', '*'],\n ])\n});\n\n// type guard, checks if the message is encoded (string or Buffer) the guard is set to string because Buffer can be used as string in JSON.parse()\nfunction isEncoded(msg: EncodedCommandType | Command): msg is string {\n return typeof msg === 'string' || Buffer.isBuffer(msg);\n}\n\ntype KeyedLinkData = {\n key: string; // relay key\n node: string; // node id\n linksByNode: Map<string, string>; // linked nodes -> sender key\n}\n\nexport class InternalRelays implements Relays {\n readonly #logger: IOGateway.Logging.Logger;\n // key -> handler\n readonly #handlersByKey = new Map<string, RelayMessageHandler>();\n // node -> keyed link\n readonly #links = new Map<string, KeyedLinkData>();\n readonly #eventEmitter = new EventEmitter<RelayEventTypes>();\n\n constructor(logger: IOGateway.Logging.Logger) {\n this.#logger = logger;\n }\n\n add(key: string, handler: RelayMessageHandler) {\n this.#handlersByKey.set(key, handler);\n }\n\n remove(key: string) {\n this.#handlersByKey.delete(key);\n this.#disconnect(key);\n }\n\n #disconnect(key: string, from?: string) {\n for (const [node, k] of this.#links) {\n if (k.key === key && (from === undefined || k.node === from)) {\n const links = k.linksByNode;\n if (this.#logger.enabledFor('info')) {\n this.#logger.info(`${key} unregisters node ${node}, linked to ${Array.from(links.keys()).join(', ')}`);\n }\n this.#links.delete(node);\n this.#eventEmitter.emit('disconnect', key, node, links);\n }\n }\n }\n #connect(key: string, node: string) {\n if (this.#logger.enabledFor('info')) {\n this.#logger.info(`${key} registers node ${node}`);\n }\n this.#links.set(node, {key, node: node, linksByNode: new Map<string, string>()});\n this.#eventEmitter.emit('connect', key, node);\n }\n\n receive(key: string, msg: string | Command) {\n const {node, decoded, encoded} = this.link(key, msg);\n\n if (node) {\n this.#eventEmitter.emit('message', key, node, encoded, decoded);\n }\n }\n\n private link(key: string, msg: string | Command) {\n try {\n const decoded: Command = isEncoded(msg) ? codec.decode(msg) : msg;\n const {type, from, to} = decoded;\n if (to === 'all') {\n switch (type) {\n case 'hello': {\n this.#connect(key, from);\n break;\n }\n case 'bye': {\n this.#disconnect(key, from);\n break;\n }\n }\n return { decoded };\n }\n else {\n const node = decoded.to;\n const link = decoded.from;\n const type = decoded.type;\n const senderLinkData = this.#links.get(link);\n switch (type) {\n case 'hello':\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${key} connecting ${link} to ${node}`);\n }\n senderLinkData?.linksByNode.set(decoded.to, key);\n break;\n case 'bye':\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${key} disconnecting ${link} from ${node}`);\n }\n senderLinkData?.linksByNode.delete(decoded.to);\n break;\n }\n }\n\n const encoded: string = isEncoded(msg) ? msg : codec.encode(msg);\n return { node: from, decoded, encoded };\n }\n catch (e) {\n // probably a decode error or a bug\n if (!this.#eventEmitter.emit('error', key, e instanceof Error ? e : new Error(`link failed :${e}`))) {\n this.#logger.warn(`${key} unable to process ${msg}`, e);\n }\n }\n }\n\n on<K extends keyof RelayEventTypes>(event: K, listener: (K extends keyof RelayEventTypes ? RelayEventTypes[K] extends unknown[] ? (...args: RelayEventTypes[K]) => void : never : never)): this {\n this.#eventEmitter.on(event, listener);\n return this;\n }\n\n send(key: string, node: string, msg: string | Command, cb: (k: string, err?: Error) => void): void {\n if (this.#logger.enabledFor('trace')) {\n this.#logger.debug(`${key} sending msg to ${node}`);\n }\n\n const encoded = isEncoded(msg) ? msg : codec.encode(msg);\n const decoded = isEncoded(msg) ? codec.decode(msg) : msg;\n {\n node ??= decoded.to;\n const link = decoded.from;\n const type = decoded.type;\n const senderLinkData = this.#links.get(link);\n switch (type) {\n case 'hello':\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${key} connecting ${link} to ${node}`);\n }\n senderLinkData?.linksByNode.set(node, key);\n break;\n case 'bye':\n if (this.#logger.enabledFor('debug')) {\n this.#logger.debug(`${key} disconnecting ${link} from ${node}`);\n }\n senderLinkData?.linksByNode.delete(node);\n break;\n }\n }\n {\n const receiverLinkData = this.#links.get(node);\n if (receiverLinkData?.key) {\n const handler = this.#handlersByKey.get(receiverLinkData?.key);\n if (handler) {\n handler(encoded, decoded, cb);\n return;\n }\n }\n }\n if (decoded.type === 'bye') {\n return;\n }\n throw new Error(`${key} no active link for ${node}`);\n }\n}\n", "{\n \"name\": \"@interopio/bridge\",\n \"version\": \"1.1.1\",\n \"license\": \"see license in license.md\",\n \"author\": \"interop.io\",\n \"homepage\": \"https://docs.interop.io/bridge\",\n \"keywords\": [\n \"io.bridge\",\n \"bridge\",\n \"io.connect\",\n \"glue42\",\n \"interop.io\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/InteropIO/bridge.git\",\n \"directory\": \"packages/bridge\"\n },\n \"type\": \"module\",\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"default\": \"./dist/index.js\"\n },\n \"./main\": {\n \"import\": {\n \"types\": \"./types/main.d.ts\",\n \"default\": \"./dist/main.js\"\n }\n }\n },\n \"bin\": {\n \"io-bridge\": \"bin/bridge.js\"\n },\n \"scripts\": {\n \"test\": \"mocha test --recursive\",\n \"build:types\": \"tsc --declaration --emitDeclarationOnly --outDir types\",\n \"build:main\": \"esbuild src/main.mts --outdir=dist --bundle --packages=external --sourcemap --platform=node --format=esm --target=node20.18\",\n \"build:index\": \"esbuild src/index.ts --outdir=dist --target=node20.18\",\n \"build\": \"npm run build:main && npm run build:index\"\n },\n \"dependencies\": {\n \"@interopio/gateway-server\": \"^0.23.1\",\n \"jsrsasign\": \"^11.1.1\",\n \"hrw-hash\": \"^2.0.3\",\n \"nanoid\": \"^5.1.7\"\n },\n \"devDependencies\": {\n \"@interopio/gateway\": \"^0.25.0\",\n \"@types/jsrsasign\": \"^10.5.15\",\n \"@types/ws\": \"^8.18.1\",\n \"rand-seed\": \"^3.0.0\"\n },\n \"engines\": {\n \"node\": \"^20.18.0 || ^22.2.0 || >=24\"\n }\n}\n", "function parse(version: string): [number, number, number] {\n // https://regex101.com/r/Ly7O1x/3/\n const pattern = /^(?<major>0|[1-9]\\d*)\\.(?<minor>0|[1-9]\\d*)\\.(?<patch>0|[1-9]\\d*)(?:-(?<prerelease>(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+(?<buildmetadata>[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/g;\n\n const {groups} = pattern.exec(version);\n const major = parseInt(groups['major']);\n const minor = parseInt(groups['minor']);\n const patch = parseInt(groups['patch']);\n\n return [major, minor, patch];\n}\n\nclass MemberVersion {\n\n readonly major: number;\n readonly minor: number;\n readonly patch: number;\n\n public get isUnknown(): boolean {\n return this.major === 0 && this.minor === 0 && this.patch === 0;\n }\n\n public toString(): string {\n return `${this.major}.${this.minor}.${this.patch}`;\n }\n\n constructor(major: number, minor: number, patch: number) {\n this.major = major;\n this.minor = minor;\n this.patch = patch;\n }\n}\n\nexport const UNKNOWN_VERSION: MemberVersion = new MemberVersion(0, 0, 0);\n\nexport function parseVersion(version?: string): MemberVersion {\n if (!version || version.startsWith('0.0.0')) {\n return UNKNOWN_VERSION;\n }\n return new MemberVersion(...parse(version));\n}\n\nexport type {MemberVersion};\n", "import {networkInterfaces} from 'node:os';\nimport {ADDRCONFIG, type LookupAddress} from 'node:dns';\nimport {lookup, lookupService} from 'node:dns/promises';\n\nimport {textToNumericFormatV4, textToNumericFormatV6} from './internal/IpAddressUtil.ts';\nimport {readFileSync} from \"node:fs\";\n\nconst INET_ADDRESS_V4_SIZE = 4;\n\nclass IpAddress {\n readonly address: string;\n readonly family: 4 | 6;\n private _hostname?: string;\n\n constructor(host: string | undefined, address: string, family: 4 | 6) {\n this._hostname = host;\n this.address = address;\n this.family = family;\n }\n\n get addressBytes(): Uint8Array {\n if (this.family === 4) {\n return textToNumericFormatV4(this.address);\n }\n //return textToNumericFormatV6(this.address);\n }\n\n async getHost(): Promise<string> {\n if (!this._hostname) {\n this._hostname = (await lookupService(this.address, 0)).hostname;\n }\n return this._hostname;\n }\n\n async getIpAddress(nonLoopback: boolean = false): Promise<LookupAddress> {\n const hints = nonLoopback ? ADDRCONFIG : undefined;\n return await lookup(this.address, {family: this.family, hints: hints});\n }\n}\n\nexport type {IpAddress};\n\nexport function isLoopback(address: IpAddress): boolean {\n return address.family === 4 && address.address.startsWith('127.') || address.family === 6 && address.address.startsWith('::1');\n}\n\nexport async function getByName(host: string): Promise<IpAddress> {\n const {address, family} = await lookup(host, {family: 4});\n if (family !== 4 && family !== 6) {\n throw new Error('unexpected address type');\n }\n return new IpAddress(undefined, address, family);\n}\n\nlet _anyLocalAddress: IpAddress;\n\nexport function anyLocalAddress(): IpAddress {\n if (!_anyLocalAddress) {\n _anyLocalAddress = getByAddress('0.0.0.0', 0);\n }\n return _anyLocalAddress;\n}\n\nexport function getByAddress(host: string, bytes: Uint8Array | number): IpAddress {\n if (typeof bytes === 'number') {\n const n = bytes;\n bytes = new Uint8Array(INET_ADDRESS_V4_SIZE);\n new DataView(bytes.buffer).setInt32(0, n);\n }\n const family = bytes.length === INET_ADDRESS_V4_SIZE ? 4 : 6;\n const address = Array.from(bytes).join('.');\n return new IpAddress(host, address, family);\n}\n\nexport async function resolveByAddress(host: string, address: string): Promise<IpAddress> {\n const byName = await getByName(address);\n // todo: check if address and host names are correct\n return new IpAddress(host, byName.address, byName.family);\n}\n\nexport async function getAllByName(host: string): Promise<IpAddress[]> {\n const addresses = await lookup(host, {all: true});\n return addresses.map(({address, family}) => {\n if (family !== 4 && family !== 6) {\n throw new Error('unexpected address type');\n }\n return new IpAddress(undefined, address, family);\n });\n}\n\nexport interface NetworkInterface {\n name: string\n loopback: boolean\n addresses: Array<IpAddress>\n}\n\nexport function getNetworkInterfaces(): NetworkInterface[] {\n return Object.entries(networkInterfaces()).map(([name, addresses]) => {\n return {\n name,\n loopback: addresses.some(info => info.internal),\n addresses: addresses.map(info => {\n return new IpAddress(undefined, info.address, info.family === 'IPv6' ? 6 : 4);\n })\n };\n });\n}\n\nfunction soMaxConn() {\n let somaxconn;\n if (process.platform === 'win32') {\n somaxconn = 200;\n }\n else if (process.platform === 'darwin') {\n somaxconn = 128;\n }\n else {\n somaxconn = 4096;\n }\n\n try {\n somaxconn = parseInt(readFileSync('/proc/sys/net/core/somaxconn').toString());\n } catch (error) {\n // todo log\n }\n return somaxconn;\n}\n\nexport const SOMAXCONN = soMaxConn();\n\n", "const DOT = '.'.charCodeAt(0);\nconst INET_ADDRESS_V4_SIZE = 4;\nconst INET_ADDRESS_V6_SIZE = 16;\nconst BYTE_SIZE = 2; // 8 bits in hex\nconst COLON = ':'.charCodeAt(0);\n\nexport function textToNumericFormatV4(address: string): Uint8Array {\n const result = new Uint8Array(4);\n const len = address.length;\n if (len == 0 || len > 15) {\n return;\n }\n\n let currentValue = 0;\n let currentByte = 0;\n let newByte = true;\n for (let i = 0; i < len; i++) {\n const ch = address.charCodeAt(i);\n if (ch === DOT) {\n if (newByte || currentValue < 0 || currentValue > 0xff || currentByte > 3) {\n return;\n }\n result[currentByte++] = currentValue & 0xff;\n currentValue = 0;\n newByte = true;\n } else {\n const digit = ch - 48;\n if (digit < 0) {\n return;\n }\n currentValue *= 10;\n currentValue += digit;\n newByte = false;\n }\n }\n if (newByte || currentValue < 0 || currentValue >= (1 << ((4 - currentByte) * 8))) {\n return;\n }\n\n switch (currentByte) {\n case 0:\n result[0] = (currentValue >> 24) & 0xff;\n //fall through\n case 1:\n result[1] = (currentValue >> 16) & 0xff;\n //fall through\n case 2:\n result[2] = (currentValue >> 8) & 0xff;\n //fall through\n case 3:\n result[3] = (currentValue >> 0) & 0xff;\n }\n return result;\n}\n\nexport function textToNumericFormatV6(address: string): Uint8Array {\n if (address.length < 2) {\n return;\n }\n\n // let colonp: number;\n // let char: number;\n // let saw_xdigit: boolean;\n // let val: number;\n // const dst = new Uint8Array(INET_ADDRESS_V6_SIZE);\n //\n // const srcb_length = address.length;\n // const pc = src.indexOf('%');\n // if (pc === srcb_length -1) {\n // return;\n // }\n //\n // colonp = -1;\n //\n // let i = 0, j = 0;\n // /* Leading :: requires some special handling. */\n // if (address.charAt(i) === ':')\n // if (address.charAt(++i) !== ':')\n // return;\n // curtok = i;\n // saw_xdigit = false;\n // val = 0;\n // while (i < srcb_length) {\n // const ch = address.charCodeAt(i++);\n // const chval = ch - 48;\n // if (chval !== -1) {\n // val <<= 4;\n // val |= chval;\n // if (val > 0xffff)\n // return;\n // saw_xdigit = true;\n // continue;\n // }\n // if (ch == ':') {\n // curtok = i;\n // if (!saw_xdigit) {\n // if (colonp != -1)\n // return null;\n // colonp = j;\n // continue;\n // } else if (i == srcb_length) {\n // return null;\n // }\n // if (j + INT16SZ > INADDR16SZ)\n // return null;\n // dst[j++] = (byte) ((val >> 8) & 0xff);\n // dst[j++] = (byte) (val & 0xff);\n // saw_xdigit = false;\n // val = 0;\n // continue;\n // }\n // if (ch == '.' && ((j + BYTE_SIZE) <= INET_ADDRESS_V6_SIZE)) {\n // const ia4 = address.substring(curtok, srcb_length);\n // /* check this IPv4 address has 3 dots, ie. A.B.C.D */\n // let dot_count = 0, index=0;\n // while ((index = ia4.indexOf ('.', index)) != -1) {\n // dot_count ++;\n // index ++;\n // }\n // if (dot_count != 3) {\n // return null;\n // }\n // const v4addr = textToNumericFormatV4(ia4);\n // if (v4addr == null) {\n // return null;\n // }\n // for (let k = 0; k < INET_ADDRESS_V4_SIZE; k++) {\n // dst[j++] = v4addr[k];\n // }\n // saw_xdigit = false;\n // break; /* '\\0' was seen by inet_pton4(). */\n // }\n // return null;\n // }\n // if (saw_xdigit) {\n // if (j + INT16SZ > INADDR16SZ)\n // return null;\n // dst[j++] = (byte) ((val >> 8) & 0xff);\n // dst[j++] = (byte) (val & 0xff);\n // }\n //\n // if (colonp != -1) {\n // const n = j - colonp;\n //\n // if (j == INADDR16SZ)\n // return null;\n // for (i = 1; i <= n; i++) {\n // dst[INADDR16SZ - i] = dst[colonp + n - i];\n // dst[colonp + n - i] = 0;\n // }\n // j = INADDR16SZ;\n // }\n // if (j != INADDR16SZ)\n // return null;\n // const newdst = convertFromIPv4MappedAddress(dst);\n // if (newdst != null) {\n // return newdst;\n // } else {\n // return dst;\n // }\n}\n", "import {getByName, type IpAddress} from '../utils/network.ts';\nimport {type Comparator, compareArrays} from '../utils/collections.ts';\n\nexport type Address = Readonly<{\n type: 4 | 6,\n host: string,\n port: number,\n address: IpAddress\n}>;\nexport function addressAsString(address: Pick<Address, 'host' | 'port' | 'type'>): string {\n // todo: do better for ipv6\n return `${address.host}:${address.port}`;\n}\nexport async function toIpAddress(address: Address): Promise<IpAddress> {\n return await getByName(scopedHost(address));\n}\n\nexport async function fromHostname(hostname: string, port: number): Promise<Address> {\n return new AddressImpl(hostname, await getByName(hostname), port);\n}\nexport function fromIpAddress(address: IpAddress, port: number): Address {\n\n return new AddressImpl(undefined, address, port);\n}\n\nclass AddressImpl {\n readonly type: 4 | 6;\n readonly host: string;\n readonly port: number;\n readonly address: IpAddress;\n\n constructor(hostname: string | undefined, ipAddress: IpAddress, port : number) {\n const type = ipAddress.family;\n if (type !== 4 && type !== 6) {\n throw new Error('unexpected address type');\n }\n this.type= type;\n this.host = hostname ?? ipAddress.address;\n this.port = port;\n this.address = ipAddress;\n }\n}\n\nfunction scopedHost(address: Address): string {\n if (address.type === 6) {\n return `[${address.host}]`;\n }\n return address.host;\n}\n\nexport const compareAddress: Comparator<Address> = (a1: Address, a2: Address) => {\n const addressBytes1 = a1.address.addressBytes;\n const addressBytes2 = a2.address.addressBytes;\n const result = compareArrays(addressBytes1, 0, addressBytes1.length, addressBytes2, 0, addressBytes2.length, (b1, b2) => {\n return b1 === b2 ? 0 : (b1 > b2 ? 1 : -1);\n });\n if (result !== 0) {\n return result;\n }\n\n return a1.port === a2.port ? 0 : (a1.port > a2.port ? 1 : -1);\n}\n", "export interface PropertyDefinition {\n readonly key: string\n readonly optional: boolean\n readonly converter: PropertyTypeConverter<PropertyType>\n}\n\nexport type PropertyType = string | number | boolean;\nexport type Properties = { [key: string]: PropertyType };\n\nexport interface PropertyTypeConverter<T extends PropertyType> {\n convert(value: unknown): T\n}\n\nexport const BOOLEAN = new class implements PropertyTypeConverter<boolean> {\n convert(value: unknown): boolean {\n if (typeof value === 'boolean') {\n return value;\n }\n else if (typeof value === \"string\") {\n return value.toLowerCase() === \"true\";\n }\n throw new Error(\"Cannot convert value to boolean: \" + value);\n }\n};\n\nexport const STRING = new class implements PropertyTypeConverter<string> {\n convert(value: unknown): string {\n if (value === undefined) {\n throw new Error(\"Cannot convert undefined \");\n }\n return String(value);\n }\n}\n\nexport const NUMBER = new class implements PropertyTypeConverter<number> {\n convert(value: unknown): number {\n if (value === undefined) {\n throw new Error(\"Cannot convert undefined \");\n }\n if (typeof value === \"object\") {\n throw new Error(\"Cannot convert object/array to number: \" + value);\n }\n return Number(value);\n }\n}\n\nexport function property<T extends PropertyType>(name: string, converter: PropertyTypeConverter<T>): PropertyDefinition {\n return {key: name, optional: true, converter: converter};\n}\n", "import { BOOLEAN } from './Properties.ts';\n\nexport abstract class NamedDiscoveryConfig {\n readonly #tag: string;\n #enabled: boolean = false;\n readonly #properties: Map<string, string>;\n\n protected constructor(tag: string) {\n this.#tag = tag;\n this.#properties = new Map();\n }\n\n get tag(): string {\n return this.#tag;\n }\n\n setEnabled(enabled: boolean): this {\n this.#enabled = enabled;\n return this;\n }\n\n get enabled(): boolean {\n return this.#enabled;\n }\n\n setProperty(key: string, value: string): this {\n if ('enabled' === key) {\n this.#enabled = BOOLEAN.convert(value);\n }\n else {\n this.#properties.set(key, value);\n }\n return this;\n }\n\n getProperty(key: string): string | undefined {\n return this.#properties.get(key);\n }\n\n get properties(): Map<string, string> {\n return this.#properties;\n }\n}\n", "import { NamedDiscoveryConfig } from './NamedDiscoveryConfig.ts';\n\nexport class KubernetesConfig extends NamedDiscoveryConfig {\n constructor() {\n super(\"kubernetes\");\n }\n}\n", "import type { DiscoveryServiceFactory, DiscoveryStrategyFactory } from '../discovery/index.ts';\nimport type { PropertyType } from './Properties.ts';\n\nexport interface DiscoveryStrategyConfig {\n readonly discoveryStrategyFactory?: DiscoveryStrategyFactory\n readonly constructorName: string\n readonly properties: Map<string, PropertyType>\n}\nexport interface DiscoveryConfig {\n readonly discoveryStrategyConfigs: ReadonlyArray<DiscoveryStrategyConfig>\n readonly discoveryServiceFactory?: DiscoveryServiceFactory\n}\n\nexport class DefaultDiscoveryConfig implements DiscoveryConfig\n{\n discoveryStrategyConfigs: DiscoveryStrategyConfig[] = [];\n discoveryServiceFactory?: DiscoveryServiceFactory;\n\n get enabled() {\n return this.discoveryStrategyConfigs.length > 0;\n }\n}\n", "import type { Properties, PropertyType } from './Properties.ts';\nimport { KubernetesConfig } from './KubernetesConfig.ts';\nimport {\n DefaultDiscoveryConfig,\n type DiscoveryConfig\n} from './DiscoveryConfig.ts';\n\nexport class AutoDetectionConfig {\n enabled: boolean = true;\n}\n\nexport interface MulticastConfig {\n readonly group: string\n readonly port: number\n}\n\nclass DefaultMulticastConfig implements MulticastConfig {\n enabled: boolean = false;\n group: string = '239.1.2.3';\n port: number = 34567;\n}\n\nexport interface TcpIpConfig {\n members: string[]\n}\n\nclass DefaultTcpIpConfig implements TcpIpConfig {\n enabled: boolean = false;\n members: string[] = [];\n}\n\nexport class JoinConfig {\n private _multicast = new DefaultMulticastConfig();\n private _tcpIp = new DefaultTcpIpConfig();\n private _kubernetes = new KubernetesConfig();\n private _discovery = new DefaultDiscoveryConfig();\n private _autoDetection = new AutoDetectionConfig();\n\n get discovery(): DiscoveryConfig {\n return this._discovery;\n }\n\n get multicast(): MulticastConfig {\n return this._multicast;\n }\n\n get kubernetes(): KubernetesConfig {\n return this._kubernetes;\n }\n\n get autoDetectionEnabled(): boolean {\n return this._autoDetection.enabled\n && !this._multicast.enabled\n && !this._tcpIp.enabled\n && !this._kubernetes.enabled\n && !this._discovery.enabled;\n }\n}\n\nexport class NetworkConfig {\n public static readonly DEFAULT_PORT: number = 8383;\n port: number = NetworkConfig.DEFAULT_PORT;\n reuseAddress: boolean;\n publicAddress?: string;\n join = new JoinConfig();\n\n constructor() {\n this.reuseAddress = process.platform !== \"win32\";\n }\n}\n\nexport class CorsConfig {\n #allowOrigin?: '*' | string[] = undefined;\n set allowOrigin(value: string | undefined) {\n if (value !== undefined) {\n if (value === '*') {\n this.#allowOrigin = value;\n }\n else if (Array.isArray(value)) {\n this.#allowOrigin = value;\n }\n else {\n this.#allowOrigin = value.split(',');\n }\n }\n }\n\n get allowOrigin(): '*' | string[] | undefined {\n return this.#allowOrigin;\n }\n\n disabled?: true;\n allowCredentials: boolean = false;\n}\n\nexport class SslConfig {\n enabled?: boolean;\n key?: string;\n cert?: string;\n ca?: string;\n}\n\nexport class ServerConfig {\n port?: number = undefined;\n host?: string = undefined;\n ssl = new SslConfig();\n cors = new CorsConfig();\n auth: {\n type: 'none' | 'basic' | 'x509' | 'oauth2',\n basic?: {\n realm?: string\n },\n x509?: {\n key?: string\n },\n oauth2?: { jwt: { issuerUri: string, issuer?: string, audience?: string | string[] } }\n } = {\n type: 'none',\n basic: {\n realm: 'io.Bridge'\n },\n oauth2: {\n jwt: {issuerUri: ''}\n },\n x509: {\n\n }\n };\n wsPingInterval?: number = 30000; // 30 seconds\n}\n\nexport class MeshConfig {\n timeout?: number\n}\n\nexport class GatewayConfig {\n enabled?: boolean;\n contexts: {\n lifetime: 'retained' | 'ref-counted' | 'ownership'\n } = {lifetime: 'retained'};\n}\n\nexport class Config {\n properties: Properties = {};\n network = new NetworkConfig();\n license: string\n readonly server: ServerConfig;\n readonly mesh: MeshConfig;\n readonly gateway: GatewayConfig;\n\n constructor() {\n this.server = new ServerConfig();\n this.mesh = new MeshConfig();\n this.gateway = new GatewayConfig();\n }\n\n get<T extends PropertyType>(name: string): T {\n const value = this.properties[name] as T;\n return value;\n }\n\n set<T extends PropertyType>(name: string, value: T): this {\n this.properties[name] = value;\n return this;\n }\n}\n", "import {\n type DiscoveryNode,\n type DiscoveryStrategyFactory,\n DiscoveryStrategyPriorities\n} from '../discovery/index.ts';\nimport {stat} from 'node:fs/promises';\nimport {lookup} from 'node:dns/promises'\nimport {KubernetesDiscoveryStrategy} from './KubernetesDiscoveryStrategy.ts';\nimport type {Properties, PropertyDefinition} from '../config/Properties.ts';\nimport {\n EXPOSE_EXTERNALLY, KUBERNETES_API_TOKEN,\n KUBERNETES_MASTER_URL,\n NAMESPACE, POD_LABEL_NAME, POD_LABEL_VALUE, RESOLVE_NOT_READY_ADDRESSES,\n SERVICE_DNS,\n SERVICE_LABEL_NAME,\n SERVICE_LABEL_VALUE,\n SERVICE_NAME, SERVICE_PORT\n} from './KubernetesProperties.ts';\nimport {type ClusterTopologyIntentTracker} from '../instance/ClusterTopologyIntentTracker.ts';\nimport {type Logger} from '../logging.ts';\n\nconst PROPERTY_DEFINITIONS: ReadonlyArray<PropertyDefinition> = [\n SERVICE_DNS,\n SERVICE_NAME,\n SERVICE_LABEL_NAME,\n SERVICE_LABEL_VALUE,\n NAMESPACE,\n POD_LABEL_NAME,\n POD_LABEL_VALUE,\n RESOLVE_NOT_READY_ADDRESSES,\n EXPOSE_EXTERNALLY,\n KUBERNETES_MASTER_URL,\n KUBERNETES_API_TOKEN,\n SERVICE_PORT\n];\n\nexport class KubernetesDiscoveryStrategyFactory implements DiscoveryStrategyFactory {\n private readonly tokenPath: string;\n readonly priority = DiscoveryStrategyPriorities.PLATFORM;\n constructor(tokenPath = '/var/run/secrets/kubernetes.io/serviceaccount/token') {\n this.tokenPath = tokenPath;\n }\n\n getDiscoveryStrategyType() {\n return KubernetesDiscoveryStrategy;\n }\n\n private async defaultKubernetesMasterReachable() {\n try {\n await lookup('kubernetes.default.svc');\n return true;\n } catch (e) {\n // todo log that io.Bridge running on Kubernetes, but \"kubernetes.default.svc\" is not reachable.\n return false;\n }\n }\n\n async tokenFileExists(){\n try {\n await stat(this.tokenPath);\n return true;\n } catch (e) {\n return false;\n }\n }\n\n async isAutoDetectionApplicable() {\n return await this.tokenFileExists() && await this.defaultKubernetesMasterReachable()\n }\n\n newDiscoveryStrategy(node: DiscoveryNode | undefined, logger: Logger, properties: Properties) {\n const tracker = node?.properties.get(\"internal.discovery.cluster.topology.intent.tracker\");\n return new KubernetesDiscoveryStrategy(logger, properties, tracker as ClusterTopologyIntentTracker | undefined);\n }\n\n getConfigurationProperties(): ReadonlyArray<PropertyDefinition> {\n return PROPERTY_DEFINITIONS;\n }\n}\n", "import {type DiscoveryNode} from '../discovery/index.ts';\nimport {getByName} from '../utils/network.ts';\nimport type {Logger} from '../logging.ts';\n\nconst DNS_RETRY = 5;\n\nexport abstract class KubernetesEndpointResolver {\n protected readonly logger: Logger;\n constructor(logger: Logger) {\n this.logger = logger;\n }\n async start() {\n // do nothing\n }\n\n abstract resolve(): Promise<DiscoveryNode[]>\n\n async close() {\n // do nothing\n }\n\n protected async mapAddress(address?: string) {\n if (!address) {\n return;\n }\n\n try {\n let retry = 0;\n try {\n return await getByName(address);\n } catch (e) {\n if (retry < DNS_RETRY) {\n retry++;\n } else {\n throw e;\n }\n }\n } catch (e) {\n // todo log address cloud not be resolved\n }\n\n }\n}\n", "import { readFileSync} from 'node:fs';\nimport { getOrDefault, getOrUndefined } from '../discovery/settings.ts';\nimport {\n KUBERNETES_API_TOKEN,\n KUBERNETES_MASTER_URL,\n KUBERNETES_ENV_PREFIX,\n NAMESPACE,\n RESOLVE_NOT_READY_ADDRESSES,\n SERVICE_DNS,\n SERVICE_NAME,\n SERVICE_PORT,\n EXPOSE_EXTERNALLY,\n SERVICE_LABEL_NAME,\n SERVICE_LABEL_VALUE,\n POD_LABEL_NAME,\n POD_LABEL_VALUE,\n SERVICE_PER_POD_LABEL_NAME, SERVICE_PER_POD_LABEL_VALUE\n} from './KubernetesProperties.ts';\nimport {type Properties} from '../config/Properties.ts';\n\nexport type DiscoveryMode = 'kubernetes-api' | 'dns-lookup';\nexport type ExposeExternallyMode = 'auto' | 'enabled' | 'disabled';\n\nfunction readFileContents(fileName: string): string {\n return readFileSync(fileName, 'utf-8').toString();\n}\n\n\nexport class KubernetesConfig {\n readonly serviceDns?: string\n\n readonly serviceName?: string\n readonly serviceLabelName?: string\n readonly serviceLabelValue?: string\n readonly namespace: string\n readonly podLabelName?: string\n readonly podLabelValue?: string\n readonly resolveNotReadyAddresses: boolean\n readonly exposeExternallyMode: ExposeExternallyMode\n readonly servicePerPodLabelName?: string\n readonly servicePerPodLabelValue?: string\n readonly kubernetesMasterUrl: string\n readonly kubernetesApiToken?: string\n\n readonly servicePort: number\n private readonly fileContentsReader: (fileName: string) => string;\n\n readonly tokenProvider: () => string;\n\n constructor(properties: Properties, fileContentsReader: (fileName: string) => string = readFileContents) {\n this.fileContentsReader = fileContentsReader;\n this.serviceDns = getOrDefault(properties, KUBERNETES_ENV_PREFIX, SERVICE_DNS);\n this.serviceName = getOrDefault(properties, KUBERNETES_ENV_PREFIX, SERVICE_NAME);\n this.serviceLabelName = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, SERVICE_LABEL_NAME);\n this.serviceLabelValue = getOrDefault(properties, KUBERNETES_ENV_PREFIX, SERVICE_LABEL_VALUE, \"true\");\n this.resolveNotReadyAddresses = getOrDefault(properties, KUBERNETES_ENV_PREFIX, RESOLVE_NOT_READY_ADDRESSES, true);\n this.podLabelName = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, POD_LABEL_NAME);\n this.podLabelValue = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, POD_LABEL_VALUE);\n\n this.exposeExternallyMode = this.getExposeExternallyMode(properties);\n this.servicePerPodLabelName = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, SERVICE_PER_POD_LABEL_NAME);\n this.servicePerPodLabelValue = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, SERVICE_PER_POD_LABEL_VALUE);\n this.kubernetesMasterUrl = getOrDefault(properties, KUBERNETES_ENV_PREFIX, KUBERNETES_MASTER_URL, \"https://kubernetes.default.svc\");\n this.tokenProvider = this.buildTokenProvider(properties);\n this.servicePort = getOrDefault(properties, KUBERNETES_ENV_PREFIX, SERVICE_PORT, 0);\n this.namespace = this.getNamespaceWithFallbacks(properties);\n }\n\n private getExposeExternallyMode(properties: Properties): ExposeExternallyMode {\n const exposeExternally: boolean | undefined = getOrUndefined<boolean>(properties, KUBERNETES_ENV_PREFIX, EXPOSE_EXTERNALLY);\n if (exposeExternally === undefined) {\n return 'auto';\n }\n else if (exposeExternally) {\n return 'enabled';\n }\n else {\n return 'disabled';\n }\n }\n\n private getNamespaceWithFallbacks(properties: Properties): string {\n let namespace: string | undefined = getOrDefault(properties, KUBERNETES_ENV_PREFIX, NAMESPACE);\n if (!namespace) {\n namespace = process.env['KUBERNETES_NAMESPACE'];\n }\n if (!namespace && this.mode === 'kubernetes-api') {\n namespace = this.readNamespace();\n }\n return namespace;\n }\n\n private buildTokenProvider(properties: {}): () => string {\n const apiToken: string | undefined = getOrUndefined(properties, KUBERNETES_ENV_PREFIX, KUBERNETES_API_TOKEN);\n if (!apiToken && this.mode === 'kubernetes-api') {\n return () => readFileContents('/var/run/secrets/kubernetes.io/serviceaccount/token')\n } else {\n return () => apiToken;\n }\n }\n\n private readNamespace(): string {\n return this.fileContentsReader('/var/run/secrets/kubernetes.io/serviceaccount/namespace');\n }\n\n\n get mode(): DiscoveryMode {\n if (this.serviceDns) {\n return 'dns-lookup';\n }\n return 'kubernetes-api';\n }\n\n toString() {\n return \"KubernetesConfig: {\"\n + \"service-dns: \" + this.serviceDns\n + \", service-name: \" + this.serviceName\n + \", service-port: \" + this.servicePort\n + \", service-label-name: \" + this.serviceLabelName\n + \", service-label-value: \" + this.serviceLabelValue\n + \", namespace: \" + this.namespace\n + \", pod-label-name: \" + this.podLabelName\n + \", pod-label-value: \" + this.podLabelValue\n + \", resolve-not-ready-addresses: \" + this.resolveNotReadyAddresses\n + \", expose-externally-mode: \" + this.exposeExternallyMode\n + \", service-per-pod-label-name: \" + this.servicePerPodLabelName\n + \", service-per-pod-label-value: \" + this.servicePerPodLabelValue\n + \", kubernetes-master-url: \" + this.kubernetesMasterUrl + \"}\";\n }\n}\n", "import {type Properties, type PropertyDefinition, type PropertyType} from '../config/Properties.ts';\n\nfunction getProperty(prefix: string, property: PropertyDefinition) {\n let s = prefix;\n if (!s.endsWith('.')) {\n s += '.';\n }\n return s + property.key;\n}\n\nfunction readProperty(prefix: string | undefined, property: PropertyDefinition): PropertyType | undefined {\n if (prefix) {\n const p = getProperty(prefix, property);\n const v = process.env[p];\n // todo convert\n return v;\n }\n}\n\nexport function getOrUndefined<T extends PropertyType>(properties: Properties, prefix: string, property?: PropertyDefinition): T | undefined {\n return getOrDefault(properties, prefix, property);\n}\n\nexport function getOrDefault<T extends PropertyType>(properties: Properties, prefix: string, property?: PropertyDefinition, defaultValue?: T) {\n if (property === undefined) {\n return defaultValue;\n }\n\n let value = readProperty(prefix, property);\n if (value === undefined) {\n value = properties[property.key];\n }\n if (value === undefined) {\n return defaultValue;\n }\n return value as T;\n}\n", "import {BOOLEAN, NUMBER, property, STRING} from '../config/Properties.ts';\n\nexport const KUBERNETES_ENV_PREFIX = 'io.bridge.kubernetes';\n\n\n\n\nexport const SERVICE_DNS = property<string>('service-dns', STRING);\nexport const SERVICE_NAME = property<string>('service-name', STRING);\nexport const SERVICE_LABEL_NAME = property<string>('service-label-name', STRING);\nexport const SERVICE_LABEL_VALUE = property<string>('service-label-value', STRING);\nexport const NAMESPACE = property<string>('namespace', STRING);\nexport const POD_LABEL_NAME = property<string>('pod-label-name', STRING);\nexport const POD_LABEL_VALUE = property<string>('pod-label-value', STRING);\nexport const EXPOSE_EXTERNALLY = property<boolean>('expose-externally', BOOLEAN);\nexport const SERVICE_PER_POD_LABEL_NAME = property<string>('service-per-pod-label-name', STRING);\nexport const SERVICE_PER_POD_LABEL_VALUE = property<string>('service-per-pod-label-value', STRING);\nexport const RESOLVE_NOT_READY_ADDRESSES = property<boolean>('resolve-not-ready-addresses', BOOLEAN);\n\nexport const KUBERNETES_MASTER_URL = property<string>('kubernetes-master', STRING);\nexport const KUBERNETES_API_TOKEN = property<string>('api-token', STRING);\nexport const SERVICE_PORT = property<number>('service-port', NUMBER);\n", "import {type DiscoveryNode} from './index.ts';\nimport {type Address} from '../cluster/Address.ts';\n\nexport class SimpleDiscoveryNode implements DiscoveryNode {\n readonly privateAddress: Address;\n readonly publicAddress: Address;\n readonly properties: ReadonlyMap<string, unknown>;\n constructor(privateAddress: Address, publicAddress?: Address, properties?: ReadonlyMap<string, unknown>)\n {\n this.privateAddress = privateAddress;\n this.publicAddress = publicAddress ?? privateAddress;\n this.properties = properties ?? new Map();\n }\n}\n", "import { type DiscoveryNode } from '../discovery/index.ts';\nimport { getAllByName, type IpAddress } from '../utils/network.ts';\nimport { KubernetesEndpointResolver } from './KubernetesEndpointResolver.ts';\nimport { KubernetesConfig } from './KubernetesConfig.ts';\nimport { NetworkConfig } from '../config/Config.ts';\nimport type { Logger } from '../logging.ts';\nimport { SimpleDiscoveryNode } from '../discovery/SimpleDiscoveryNode.ts';\nimport { fromHostname } from '../cluster/Address.ts';\n\nexport type LookupProvider = (host: string) => Promise<IpAddress[]>;\n\nexport class DnsEndpointResolver extends KubernetesEndpointResolver {\n readonly #lookupProvider: LookupProvider;\n readonly #serviceDns: string;\n readonly #port: number;\n\n static of(logger: Logger, config: KubernetesConfig): DnsEndpointResolver {\n return new DnsEndpointResolver(logger, getAllByName, config.serviceDns, config.servicePort);\n }\n\n /*testing*/ constructor(logger: Logger, lookupProvider: LookupProvider, serviceDns?: string, port: number = 0) {\n super(logger);\n this.#lookupProvider = lookupProvider;\n this.#serviceDns = serviceDns;\n this.#port = port;\n }\n\n async resolve(): Promise<DiscoveryNode[]> {\n try {\n return await this.lookup();\n } catch (e) {\n this.logger.warn(`DNS lookup for serviceDns ${this.#serviceDns} failed`, e);\n return [];\n }\n }\n\n private async lookup() {\n\n const addresses = new Set<string>();\n\n for (const ipAddress of await this.#lookupProvider(this.#serviceDns)) {\n const address = ipAddress.address;\n if (addresses.has(address)) {\n continue;\n }\n if (this.logger.enabledFor('debug')) {\n this.logger.debug(`Found node service with address: ${ipAddress}`);\n }\n addresses.add(address);\n }\n if (addresses.size === 0) {\n this.logger.warn(`No nodes found for service: ${this.#serviceDns}`);\n return [];\n }\n\n const result: Array<DiscoveryNode> = [];\n for (const address of addresses) {\n const privateAddress = await fromHostname(address, DnsEndpointResolver.getBridgePort(this.#port));\n const node = new SimpleDiscoveryNode(privateAddress);\n result.push(node);\n }\n return result;\n }\n\n private static getBridgePort(port: number): number {\n if (port > 0) {\n return port;\n }\n return NetworkConfig.DEFAULT_PORT;\n }\n}\n", "import {Endpoint, EndpointAddress} from './KubernetesClient.ts';\n\nexport interface KubernetesApiProvider {\n getEndpointsByNameUrlString(kubernetesMaster: string, namespace: string, endpointName: string): string;\n\n getEndpointsByServiceLabelUrlString(kubernetesMaster: string, namespace: string, serviceLabel: string): string;\n\n parseEndpoints(param: any): Endpoint[];\n}\n\nexport class KubernetesApiEndpointSlicesProvider implements KubernetesApiProvider {\n getEndpointsByServiceLabelUrlString(kubernetesMaster: string, namespace: string, param: string): string {\n return `${kubernetesMaster}/apis/discovery.k8s.io/v1/namespaces/${namespace}/endpointslices?${param}`;\n }\n\n getEndpointsByNameUrlString(kubernetesMaster: string, namespace: string, endpointName: string): string {\n return `${kubernetesMaster}/apis/discovery.k8s.io/v1/namespaces/${namespace}/endpointslices?labelSelector=kubernetes.io/service-name=${endpointName}`;\n }\n\n parseEndpoints(param: {\n items: Array<{ endpoints: Array<{ conditions: { ready: boolean }, addresses: Array<string> }>, ports: Array<{}> }>\n }): Endpoint[] {\n const endpoints = new Array<Endpoint>();\n for (const item of param.items) {\n endpoints.push(...this.parseEndpointSlices(item));\n }\n return endpoints;\n }\n\n private parseEndpointSlices(item: {\n endpoints: Array<{\n conditions: {\n ready: boolean\n },\n addresses: Array<string>\n }>,\n ports: Array<{name?: string, port?: number}>\n }): Endpoint[] {\n const addresses = new Array<Endpoint>();\n const endpointPort = this.extractPort(item);\n for (const endpoint of item.endpoints) {\n const ready = endpoint.conditions.ready;\n for (const address of endpoint.addresses) {\n addresses.push(new Endpoint(new EndpointAddress({ip: address, port: endpointPort}), undefined, ready))\n }\n\n }\n return addresses;\n }\n\n private extractPort(item: {\n ports: Array<{\n name?: string,\n port?: number\n\n }>\n }): number | undefined {\n for (const port of item.ports) {\n const bridgeServicePort = port.name;\n if (bridgeServicePort && bridgeServicePort === 'io-bridge') {\n const servicePort = port.port;\n if (servicePort !== undefined) {\n return servicePort;\n }\n }\n }\n if (item.ports.length === 1) {\n const port = item.ports[0];\n const servicePort = port.port;\n if (servicePort !== undefined) {\n return servicePort;\n }\n }\n }\n}\n", "import {type ExposeExternallyMode} from './KubernetesConfig.ts';\nimport {KubernetesApiEndpointSlicesProvider, type KubernetesApiProvider} from './KubernetesApiProvider.ts';\nimport {type ClusterTopologyIntentTracker} from '../instance/ClusterTopologyIntentTracker.ts';\n\nclass Address {\n readonly ip: string;\n\n readonly port?: number;\n\n constructor(ip: string, port?: number) {\n this.ip = ip;\n this.port = port;\n }\n}\n\nexport type {Address};\n\nexport class EndpointAddress {\n readonly targetRefName?: string;\n\n private readonly address: Address;\n\n constructor(address: Address, targetRefName?: string) {\n this.address = address;\n this.targetRefName = targetRefName;\n }\n\n get ip(): string {\n return this.address.ip;\n }\n\n get port(): number | undefined {\n return this.address.port;\n }\n}\n\nexport class Endpoint {\n\n readonly privateAddress: EndpointAddress;\n readonly publicAddress: EndpointAddress | undefined = undefined;\n readonly ready: boolean;\n readonly additionalProperties: ReadonlyMap<string, string> = new Map();\n\n constructor(privateAddress: EndpointAddress,\n publicAddress: EndpointAddress | undefined = undefined,\n ready: boolean,\n additionalProperties: ReadonlyMap<string, string> = new Map()) {\n this.privateAddress = privateAddress;\n this.publicAddress = publicAddress;\n this.ready = ready;\n this.additionalProperties = additionalProperties;\n }\n}\n\nconst READ_TIMEOUT_SECONDS = 10;\n\nfunction isReady(podItemStatus: { containerStatuses?: Array<{ ready?: boolean }> }): boolean {\n for (const containerStatus of podItemStatus.containerStatuses) {\n if (containerStatus.ready !== true) {\n return false;\n }\n }\n return true;\n}\n\nfunction containerPort(container: {\n ports?: Array<{\n containerPort?: number\n }>\n}): number | undefined {\n const ports = container.ports;\n if (ports.length > 0) {\n const port = ports[0];\n return port.containerPort;\n }\n}\n\nfunction extractContainerPort(item: {\n spec: {\n containers?: Array<{ name?: string, ports?: Array<{ containerPort?: number }> }>\n }\n}): number | undefined {\n const containers = item.spec.containers;\n if (containers.length === 1) {\n const container = containers[0];\n return containerPort(container);\n } else {\n for (const container of containers) {\n if (container.name === 'io-bridge') {\n return containerPort(container);\n }\n }\n }\n}\n\nfunction parsePodsList(podList: {\n items?: Array<{\n metadata: {\n name: string\n },\n status: {\n podIP?: string\n containerStatuses?: Array<{ ready?: boolean }>\n },\n spec: {}\n }>\n}): Array<Endpoint> {\n const addresses = new Array<Endpoint>();\n for (const item of podList.items) {\n const podName = item.metadata.name;\n const status = item.status;\n const ip = status.podIP;\n if (ip) {\n const port = extractContainerPort(item);\n addresses.push(new Endpoint(new EndpointAddress({ip, port}, podName), undefined, isReady(status)));\n }\n }\n return addresses;\n}\n\nfunction getLabelSelectorParameter(labelNames: string, labelValues: string): string {\n const labelNameArray = labelNames.split(',');\n const labelValueArray = labelValues.split(',');\n const selectorList = [];\n for (let i = 0; i < labelNameArray.length; i++) {\n selectorList[i] = (`${labelNameArray[i]}=${labelValueArray[i]}`);\n }\n return `labelSelector=${selectorList.join(',')}`;\n}\n\nexport class KubernetesClient {\n\n private readonly namespace: string;\n private readonly kubernetesMaster: string;\n private readonly exposeExternallyMode: ExposeExternallyMode;\n private readonly tokenProvider: () => string;\n private readonly servicePerPodLabelName?: string;\n private readonly servicePerPodLabelValue?: string;\n private readonly clientTopologyIntentTracker?: ClusterTopologyIntentTracker;\n private readonly apiProvider: KubernetesApiProvider\n\n /*testing*/\n constructor(namespace: string,\n kubernetesMaster: string,\n exposeExternallyMode: ExposeExternallyMode,\n tokenProvider: () => string,\n servicePerPodLabelName?: string,\n servicePerPodLabelValue?: string,\n clientTopologyIntentTracker?: ClusterTopologyIntentTracker,\n apiProvider?: KubernetesApiProvider) {\n\n this.namespace = namespace;\n this.kubernetesMaster = kubernetesMaster;\n this.exposeExternallyMode = exposeExternallyMode;\n this.tokenProvider = tokenProvider;\n this.servicePerPodLabelName = servicePerPodLabelName;\n this.servicePerPodLabelValue = servicePerPodLabelValue;\n if (clientTopologyIntentTracker) {\n clientTopologyIntentTracker.init();\n }\n this.apiProvider = apiProvider ?? new KubernetesApiEndpointSlicesProvider();\n }\n\n start(): void {\n\n }\n\n destroy(): void {\n if (this.clientTopologyIntentTracker) {\n this.clientTopologyIntentTracker.destroy();\n }\n }\n\n /**\n * Returns POD addresses in the specified namespace.\n *\n */\n async endpoints(): Promise<Endpoint[]> {\n try {\n const url = `${this.kubernetesMaster}/api/v1/namespaces/${this.namespace}/pods`;\n return this.enrichWithPublicAddresses(parsePodsList(await this.callGet(url)));\n } catch (e) {\n return this.handleUnknownError(e);\n }\n }\n\n /**\n * Retrieves POD addresses for all services in the specified namespace filtered by service labels and values.\n * @param serviceLabels comma separated list of service labels\n * @param serviceLabelValues comma separated list of service label values\n * @return all POD addresses from the specified namespace filtered by labels\n */\n async endpointsByServiceLabel(serviceLabels: string, serviceLabelValues: string): Promise<Endpoint[]> {\n try {\n const param = getLabelSelectorParameter(serviceLabels, serviceLabelValues);\n const url = this.apiProvider.getEndpointsByServiceLabelUrlString(this.kubernetesMaster, this.namespace, param);\n return this.enrichWithPublicAddresses(this.apiProvider.parseEndpoints(this.callGet(url)));\n } catch (e) {\n return this.handleUnknownError(e);\n }\n }\n\n /**\n * Retrieves POD addresses from the specified namespace and given endpointName.\n * @param endpointName endpoint name\n * @return all POD addresses from the specified namespace and the given endpointName\n */\n async endpointsByName(endpointName: string): Promise<Endpoint[]> {\n try {\n const url = this.apiProvider.getEndpointsByNameUrlString(this.kubernetesMaster, this.namespace, endpointName);\n return this.enrichWithPublicAddresses(this.apiProvider.parseEndpoints(await this.callGet(url)));\n } catch (e) {\n return this.handleUnknownError(e);\n }\n }\n\n /**\n * Retrieves POD addresses for all services in the specified namespace filtered by pod labels and values.\n * @param podLabels comma separated list of pod labels\n * @param podLabelValues comma separated list of pod label values\n * @return all POD addresses from the specified namespace filtered by the labels\n */\n async endpointsByPodLabel(podLabels: string, podLabelValues: string) {\n try {\n const param = getLabelSelectorParameter(podLabels, podLabelValues);\n const url = `${this.kubernetesMaster}/api/v1/namespaces/${this.namespace}/pods?${param}`;\n return this.enrichWithPublicAddresses(parsePodsList(await this.callGet(url)));\n } catch (e) {\n return this.handleUnknownError(e);\n }\n }\n\n private enrichWithPublicAddresses(endpoints: Endpoint[]): Endpoint[] {\n if (this.exposeExternallyMode === 'disabled') {\n return endpoints;\n }\n\n }\n\n private handleUnknownError(e): Endpoint[] {\n // todo handle error\n return [];\n }\n\n private async callGet(url: string): Promise<any> {\n const controller = new AbortController();\n const timeout = setTimeout(() => {\n controller.abort(`request to ${url} timed out`);\n }, READ_TIMEOUT_SECONDS * 1000);\n try {\n const response = await fetch(url, {\n signal: controller.signal,\n headers: [[\"Authorization\", `Bearer ${this.tokenProvider()}`]]\n }).catch((err) => {\n throw err;\n });\n\n return await response.json();\n\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n", "import { getLogger as getGatewayLogger } from '@interopio/gateway/logging/core';\n\nexport type Logger = ReturnType<typeof getGatewayLogger>;\n\nexport default function getLogger(name: string): Logger {\n return getGatewayLogger(`gateway.bridge.${name}`);\n}\n", "import {Endpoint, EndpointAddress, KubernetesClient} from './KubernetesClient.ts';\nimport {type DiscoveryNode} from '../discovery/index.ts';\nimport {type Address, fromIpAddress} from '../cluster/Address.ts';\nimport {type Logger} from '../logging.ts';\nimport {KubernetesEndpointResolver} from './KubernetesEndpointResolver.ts';\nimport {KubernetesConfig} from './KubernetesConfig.ts';\nimport {NetworkConfig} from '../config/Config.ts';\nimport {type ClusterTopologyIntentTracker} from '../instance/ClusterTopologyIntentTracker.ts';\nimport {SimpleDiscoveryNode} from '../discovery/SimpleDiscoveryNode.ts';\n\nfunction buildKubernetesClient(config: KubernetesConfig, clusterTopologyIntentTracker?: ClusterTopologyIntentTracker): KubernetesClient {\n return new KubernetesClient(config.namespace, config.kubernetesMasterUrl, config.exposeExternallyMode, config.tokenProvider, config.servicePerPodLabelName, config.servicePerPodLabelValue, clusterTopologyIntentTracker);\n}\n\nexport class KubernetesApiEndpointResolver extends KubernetesEndpointResolver {\n\n private readonly client: KubernetesClient;\n private readonly serviceName?: string;\n private readonly port: number = 0;\n private readonly serviceLabel?: string;\n private readonly serviceLabelValue?: string;\n private readonly podLabel?: string;\n private readonly podLabelValue?: string;\n private readonly resolveNotReadyAddresses?: boolean;\n\n static of(logger: Logger, config: KubernetesConfig, tracker?: ClusterTopologyIntentTracker): KubernetesApiEndpointResolver {\n return new KubernetesApiEndpointResolver(logger, buildKubernetesClient(config, tracker),\n config.serviceName, config.servicePort, config.serviceLabelName,\n config.serviceLabelValue, config.podLabelName, config.podLabelValue, config.resolveNotReadyAddresses);\n }\n\n /*testing*/ constructor(logger: Logger,\n client: KubernetesClient,\n serviceName?: string,\n port: number = 0,\n serviceLabel?: string,\n serviceLabelValue?: string,\n podLabel?: string,\n podLabelValue?: string,\n resolveNotReadyAddresses?: boolean) {\n super(logger);\n this.client = client;\n this.serviceName = serviceName;\n this.port = port;\n this.serviceLabel = serviceLabel;\n this.serviceLabelValue = serviceLabelValue;\n this.podLabel = podLabel;\n this.podLabelValue = podLabelValue;\n this.resolveNotReadyAddresses = resolveNotReadyAddresses;\n }\n\n async resolve(): Promise<DiscoveryNode[]> {\n if (this.serviceName) {\n return await this.getSimpleDiscoveryNodes(await this.client.endpointsByName(this.serviceName));\n }\n else if (this.serviceLabel) {\n return await this.getSimpleDiscoveryNodes(await this.client.endpointsByServiceLabel(this.serviceLabel, this.serviceLabelValue));\n }\n else if (this.podLabel) {\n return await this.getSimpleDiscoveryNodes(await this.client.endpointsByPodLabel(this.podLabel, this.podLabelValue));\n }\n return await this.getSimpleDiscoveryNodes(await this.client.endpoints());\n }\n\n private async getSimpleDiscoveryNodes(endpoints: readonly Endpoint[]): Promise<DiscoveryNode[]> {\n const discoveredNodes = new Array<DiscoveryNode>();\n for (const endpoint of endpoints) {\n await this.addAddress(discoveredNodes, endpoint);\n }\n return discoveredNodes;\n }\n\n private async addAddress(discoveredNodes: Array<DiscoveryNode>, endpoint: Endpoint): Promise<void> {\n if (this.resolveNotReadyAddresses === true || endpoint.ready) {\n const privateAddress = await this.createAddress(endpoint.privateAddress, this.resolvePort.bind(this));\n const publicAddress = await this.createAddress(endpoint.publicAddress, this.resolvePortPublic.bind(this));\n discoveredNodes.push(new SimpleDiscoveryNode(privateAddress, publicAddress, new Map<string, string>()));\n }\n }\n\n private async createAddress(address: EndpointAddress | undefined, portResolver: (address: EndpointAddress) => number): Promise<Address> {\n if (address === undefined) {\n return undefined;\n }\n const ip = address.ip;\n const ipAddress = await this.mapAddress(ip);\n const port = portResolver(address);\n return fromIpAddress(ipAddress, port);\n }\n\n private resolvePort(address: EndpointAddress) {\n if (this.port > 0) {\n return this.port;\n }\n if (address.port) {\n\n return address.port;\n }\n return NetworkConfig.DEFAULT_PORT;\n }\n\n private resolvePortPublic(address: EndpointAddress) {\n if (address.port) {\n return address.port;\n }\n if (this.port > 0) {\n return this.port;\n }\n return NetworkConfig.DEFAULT_PORT;\n }\n}\n", "import {type DiscoveryNode, type DiscoveryStrategy} from '../discovery/index.ts';\nimport { DnsEndpointResolver } from \"./DnsEndpointResolver.ts\";\nimport {KubernetesConfig} from './KubernetesConfig.ts';\nimport {KubernetesApiEndpointResolver} from './KubernetesApiEndpointResolver.ts';\nimport {KubernetesEndpointResolver} from './KubernetesEndpointResolver.ts';\nimport {type ClusterTopologyIntentTracker} from '../instance/ClusterTopologyIntentTracker.ts';\nimport {type Logger} from '../logging.ts';\n\nexport class KubernetesDiscoveryStrategy implements DiscoveryStrategy {\n private readonly logger: Logger;\n readonly #endpointResolver: KubernetesEndpointResolver;\n\n constructor(logger: Logger, properties: {[key: string]: string | number | boolean}, intentTracker?: ClusterTopologyIntentTracker) {\n this.logger = logger;\n const config = new KubernetesConfig(properties);\n this.logger.info(`${config}`);\n if ('dns-lookup' === config.mode) {\n this.#endpointResolver = DnsEndpointResolver.of(logger, config);\n }\n else {\n this.#endpointResolver = KubernetesApiEndpointResolver.of(logger, config, intentTracker);\n }\n logger.info(`Kubernetes Discovery activated with mode: ${config.mode}`);\n }\n async start() {\n await this.#endpointResolver.start();\n }\n\n async discover(): Promise<Iterable<DiscoveryNode> | undefined> {\n return undefined\n }\n\n async close() {\n await this.#endpointResolver.close();\n }\n}\n", "import {createSocket, type RemoteInfo, Socket} from 'node:dgram';\nimport {type DiscoveryNode, type DiscoveryStrategy} from '../index.ts';\nimport {SimpleDiscoveryNode} from '../SimpleDiscoveryNode.ts';\nimport {type Properties} from '../../config/Properties.ts';\nimport {GROUP, PORT} from './MulticastProperties.ts';\nimport {getOrDefault} from '../settings.ts';\nimport {fromHostname, toIpAddress} from '../../cluster/Address.ts';\nimport {isLoopback} from '../../utils/network.ts';\nimport {type Logger} from '../../logging.ts';\n\nconst DATA_OUTPUT_BUFFER_SIZE = 64 * 1024;\nconst DEFAULT_MULTICAST_PORT = 34567;\nconst DEFAULT_MULTICAST_GROUP = '239.1.2.3';\nconst SOCKET_TIME_TO_LIVE = 255; // unrestricted (other possible values would be 1 (local-network), 15 (site-local), 32(local-area), 64(regional), 128(global))\n\ninterface MulticastMemberInfo {\n readonly host: string;\n readonly port: number;\n}\n\nfunction multicastDiscoverySender(discoveryNode: DiscoveryNode | undefined, socket: Socket, group: string, port: number): () => void {\n let multicastMemberInfo: MulticastMemberInfo;\n if (discoveryNode) {\n const address = discoveryNode.publicAddress;\n multicastMemberInfo = {host: address.host, port: address.port};\n }\n const msg: Buffer = Buffer.from(JSON.stringify(multicastMemberInfo));\n\n return () => {\n socket.send(msg, port, group, (error) => {\n console.error(error);\n });\n }\n}\n\nfunction multicastDiscoveryReceiver(socket: Socket): () => Promise<MulticastMemberInfo> {\n return () => {\n return new Promise<MulticastMemberInfo>((resolve, reject) => {\n socket.on('message', (message: Buffer, remote: RemoteInfo) => {\n resolve(JSON.parse(message as unknown as string));\n });\n socket.on('error', (err: Error) => {\n reject(err);\n });\n });\n }\n}\n\nexport class MulticastDiscoveryStrategy implements DiscoveryStrategy {\n private readonly logger: Logger;\n private readonly properties: Properties;\n private readonly discoveryNode?: DiscoveryNode;\n private isClient?: boolean;\n private discoverySender?: () => void;\n private discoveryReceiver?: () => Promise<MulticastMemberInfo>;\n private sendIntervalId?: ReturnType<typeof setInterval>;\n private socket?: Socket;\n constructor(discoveryNode: DiscoveryNode | undefined,\n logger: Logger,\n properties: Properties) {\n this.logger = logger;\n this.properties = properties;\n this.discoveryNode = discoveryNode;\n }\n\n private async initializeMulticastSocket() {\n const port = getOrDefault(this.properties, '', PORT, DEFAULT_MULTICAST_PORT);\n if (port < 0 || port > 65535) {\n throw new Error('port number must be between 0 and 65535');\n }\n const group = getOrDefault(this.properties, '', GROUP, DEFAULT_MULTICAST_GROUP);\n this.socket = createSocket({\n type: 'udp4',\n reuseAddr: true,\n recvBufferSize: DATA_OUTPUT_BUFFER_SIZE,\n sendBufferSize: DATA_OUTPUT_BUFFER_SIZE});\n\n if (this.discoveryNode) {\n const address = await toIpAddress(this.discoveryNode.privateAddress);\n if (!isLoopback(address)) {\n this.socket.setMulticastInterface(address.address);\n }\n }\n\n this.socket.bind(port, () => {\n this.socket.setMulticastTTL(SOCKET_TIME_TO_LIVE);\n this.socket.addMembership(group);\n });\n\n this.discoverySender = multicastDiscoverySender(this.discoveryNode, this.socket, group, port);\n this.discoveryReceiver = multicastDiscoveryReceiver(this.socket);\n if (this.discoveryNode == null) {\n this.isClient = true;\n }\n }\n\n async discover(): Promise<Iterable<DiscoveryNode> | undefined> {\n const multicastMemberInfo = await this.discoveryReceiver();\n if (multicastMemberInfo) {\n const list = [];\n try {\n const discoveryNode = new SimpleDiscoveryNode(await fromHostname(multicastMemberInfo.host, multicastMemberInfo.port));\n list.push(discoveryNode);\n }\n catch (e) {\n if (this.logger.enabledFor('trace')) {\n this.logger.debug(e.message);\n }\n }\n return list;\n }\n }\n\n async start() {\n await this.initializeMulticastSocket();\n if (!this.isClient) {\n this.sendIntervalId = setInterval(() => {\n this.discoverySender();\n }, 2000);\n }\n }\n\n async close() {\n if (this.sendIntervalId) {\n clearInterval(this.sendIntervalId);\n delete this.sendIntervalId;\n }\n return new Promise<void>((resolve, reject) => {\n if (this.socket)\n {\n this.socket.close(() => {\n resolve()\n });\n }\n else\n {\n resolve();\n }\n });\n\n }\n\n}\n", "import {NUMBER, property, STRING} from '../../config/Properties.ts';\n\nexport const PORT = property<number>('port', NUMBER);\nexport const GROUP = property<string>('group', STRING);\n", "import {\n type DiscoveryNode,\n type DiscoveryStrategy,\n type DiscoveryStrategyFactory,\n DiscoveryStrategyPriorities\n} from '../index.ts';\nimport {MulticastDiscoveryStrategy} from './MulticastDiscoveryStrategy.ts';\nimport {GROUP, PORT} from './MulticastProperties.ts';\nimport {type Properties, type PropertyDefinition} from '../../config/Properties.ts';\nimport {type Logger} from '../../logging.ts';\n\nconst PROPERTY_DEFINITIONS: ReadonlyArray<PropertyDefinition> = [\n GROUP,\n PORT\n];\n\nexport class MulticastDiscoveryStrategyFactory implements DiscoveryStrategyFactory {\n readonly priority = DiscoveryStrategyPriorities.UNKNOWN;\n\n getDiscoveryStrategyType() {\n return MulticastDiscoveryStrategy;\n }\n\n newDiscoveryStrategy(discoveryNode: DiscoveryNode, logger: Logger, prop: Properties): DiscoveryStrategy {\n return new MulticastDiscoveryStrategy(discoveryNode, logger, prop);\n }\n\n async isAutoDetectionApplicable(): Promise<boolean> {\n return false;\n }\n\n getConfigurationProperties(): ReadonlyArray<PropertyDefinition> {\n return PROPERTY_DEFINITIONS;\n }\n}\n", "import type { Address } from '../cluster/Address.ts';\nimport type { Properties, PropertyDefinition, PropertyType } from '../config/Properties.ts';\nimport type { DiscoveryConfig, DiscoveryStrategyConfig } from '../config/DiscoveryConfig.ts';\nimport type { Logger } from '../logging.ts';\nimport { KubernetesDiscoveryStrategyFactory } from '../kubernetes/KubernetesDiscoveryStrategyFactory.ts';\nimport { MulticastDiscoveryStrategyFactory } from './multicast/MulticastDiscoveryStrategyFactory.ts';\n\nexport interface DiscoveryServiceFactory {\n newDiscoveryService(settings: DiscoveryServiceSettings): DiscoveryService\n}\n\nexport interface DiscoveryService {\n start(): Promise<void>\n discover(): Promise<Iterable<DiscoveryNode>>\n close(): Promise<void>\n}\n\n\nexport type DiscoveryServiceSettings = {\n readonly node: Promise<DiscoveryNode>\n readonly mode: DiscoveryMode\n readonly conf: DiscoveryConfig\n readonly auto: boolean\n readonly logger: Logger\n}\n\nexport type DiscoveryMode = 'member' | 'client';\n\nexport class DefaultDiscoveryServiceFactory implements DiscoveryServiceFactory {\n newDiscoveryService(settings: DiscoveryServiceSettings): DiscoveryService {\n return new DefaultDiscoveryService(settings);\n }\n}\n\nfunction verifyNoUnknownProperties(mappedProperties: Properties, allProperties: string[]) {\n const unknownProperties = allProperties.filter(key => !mappedProperties.hasOwnProperty(key));\n if (unknownProperties.length > 0) {\n throw new Error(`Unknown properties: ${unknownProperties.join(', ')} on discovery strategy`);\n }\n}\n\nfunction prepareProperties(properties: Map<string, PropertyType>,\n propertyDefinitions: readonly PropertyDefinition[]) {\n const mappedProperties: Properties = {};\n for (const propertyDefinition of propertyDefinitions) {\n const propertyKey = propertyDefinition.key;\n if (!properties.has(propertyKey)) {\n if (!propertyDefinition.optional) {\n throw new Error(`Missing required property: ${propertyKey} on discovery strategy`);\n }\n continue;\n }\n const value = properties.get(propertyKey);\n const converter = propertyDefinition.converter;\n const mappedValue = converter.convert(value);\n\n mappedProperties[propertyKey] = mappedValue;\n }\n\n verifyNoUnknownProperties(mappedProperties, Array.from(properties.keys()));\n return mappedProperties;\n\n}\n\nexport class DefaultDiscoveryService implements DiscoveryService {\n private readonly settings: DiscoveryServiceSettings;\n readonly #strategies: Array<DiscoveryStrategy> = [];\n constructor(settings: DiscoveryServiceSettings) {\n this.settings = settings;\n }\n\n get strategies(): ReadonlyArray<DiscoveryStrategy> {\n return this.#strategies;\n }\n\n async start(): Promise<void> {\n this.#strategies.push(...await this.loadDiscoveryStrategies());\n for (const strategy of this.#strategies) {\n await strategy.start();\n }\n }\n\n async discover(): Promise<Iterable<DiscoveryNode>> {\n const discoveryNodes = new Set<DiscoveryNode>();\n for (const strategy of this.#strategies) {\n const candidates = await strategy.discover();\n if (candidates) {\n for (const candidate of candidates) {\n if (this.validateCandidate(candidate)) {\n discoveryNodes.add(candidate);\n }\n }\n }\n\n }\n\n return discoveryNodes;\n }\n\n async close(): Promise<void> {\n for (const strategy of this.#strategies) {\n await strategy.close();\n }\n }\n\n private validateCandidate(candidate: DiscoveryNode) : boolean {\n // todo\n return true;\n }\n\n private async loadDiscoveryStrategies(): Promise<Iterable<DiscoveryStrategy>> {\n\n const discoveryStrategyConfigs = this.settings.conf.discoveryStrategyConfigs;\n const factories = this.collectFactories(discoveryStrategyConfigs);\n\n const discoveryStrategies = new Array<DiscoveryStrategy>();\n for (const config of discoveryStrategyConfigs) {\n const discoveryStrategy = await this.buildDiscoveryStrategy(config, factories);\n discoveryStrategies.push(discoveryStrategy);\n }\n const logger = this.settings.logger;\n if (discoveryStrategies.length == 0 && this.settings.auto) {\n logger.debug(`Discovery auto-detection enabled, trying to detect discovery strategy`);\n const autoDetectedFactory = await this.detectDiscoveryStrategyFactory(factories);\n if (autoDetectedFactory) {\n logger.debug(`Auto-detected discovery strategy: ${autoDetectedFactory.constructor.name}`);\n discoveryStrategies.push(autoDetectedFactory.newDiscoveryStrategy(await this.settings.node, logger, {}));\n }\n else {\n logger.debug(`No discovery strategy auto-detected`);\n }\n }\n return discoveryStrategies;\n }\n\n private collectFactories(strategyConfigs: ReadonlyArray<DiscoveryStrategyConfig>): DiscoveryStrategyFactory[] {\n\n const knownFactories = [new MulticastDiscoveryStrategyFactory(), new KubernetesDiscoveryStrategyFactory()]\n\n const factories = new Array<DiscoveryStrategyFactory>();\n\n for (const factory of knownFactories) {\n factories.push(factory);\n }\n\n for (const config of strategyConfigs) {\n const factory = config.discoveryStrategyFactory;\n if (factory) {\n factories.push(factory);\n }\n }\n\n return factories;\n }\n\n private async buildDiscoveryStrategy(config: DiscoveryStrategyConfig,\n factories: DiscoveryStrategyFactory[]): Promise<DiscoveryStrategy> {\n const discoveryNode = await this.settings.node;\n const logger = this.settings.logger;\n\n for (const factory of factories) {\n const constructorName = factory.getDiscoveryStrategyType().name;\n if (constructorName === this.getFactoryConstructorName(config)) {\n const properties = prepareProperties(config.properties, factory.getConfigurationProperties() ?? []);\n return factory.newDiscoveryStrategy(discoveryNode, logger, properties);\n }\n }\n throw new Error('DiscoveryStrategyFactory not found');\n }\n\n private getFactoryConstructorName(config: DiscoveryStrategyConfig): string {\n if (config.discoveryStrategyFactory) {\n const factory = config.discoveryStrategyFactory;\n return factory.getDiscoveryStrategyType().name;\n }\n return config.constructorName;\n }\n\n private async detectDiscoveryStrategyFactory(factories: DiscoveryStrategyFactory[]) {\n let highestPriorityFactory: DiscoveryStrategyFactory;\n for (const factory of factories) {\n try {\n if (await factory.isAutoDetectionApplicable()) {\n if (highestPriorityFactory === undefined || factory.priority > highestPriorityFactory.priority) {\n highestPriorityFactory = factory;\n }\n }\n } catch (error) {\n // todo log error\n }\n }\n return highestPriorityFactory;\n }\n\n\n}\n\nexport interface DiscoveryStrategy {\n start(): Promise<void>\n discover(): Promise<Iterable<DiscoveryNode> | undefined>\n close(): Promise<void>\n}\n\nexport interface DiscoveryStrategyFactory {\n readonly priority: number\n isAutoDetectionApplicable(): Promise<boolean>\n newDiscoveryStrategy(node: DiscoveryNode, logger: Logger, settings: Properties): DiscoveryStrategy\n getDiscoveryStrategyType(): new (...args: unknown[]) => DiscoveryStrategy\n getConfigurationProperties(): ReadonlyArray<PropertyDefinition>\n}\nexport const DiscoveryStrategyPriorities = {\n UNKNOWN: 0,\n PLATFORM: 20,\n CUSTOM: 50,\n}\n\nexport interface DiscoveryNode {\n readonly publicAddress: Address;\n readonly privateAddress: Address;\n readonly properties: ReadonlyMap<string, unknown>;\n}\n", "import type { JoinConfig } from '../../config/Config.ts';\nimport type { DiscoveryStrategyConfig } from \"../../config/DiscoveryConfig.ts\";\nimport type { NamedDiscoveryConfig } from \"../../config/NamedDiscoveryConfig.ts\";\nimport type { PropertyType } from \"../../config/Properties.ts\";\n\nexport function namedDiscoveryConfigsFrom(config: JoinConfig): NamedDiscoveryConfig[] {\n return [config.kubernetes];\n}\n\nfunction mapConfigs(configs: NamedDiscoveryConfig[]) {\n const result = new Array<DiscoveryStrategyConfig>();\n for (const config of configs) {\n if (config.enabled !== false) {\n result.push(createStrategyConfig(config));\n }\n }\n return result;\n}\n\nconst NAME_MAPPINGS = new Map<string, string>([\n ['kubernetes', 'KubernetesDiscoveryStrategy'],\n]);\n\nfunction discoveryStrategyFrom(config: NamedDiscoveryConfig) {\n return NAME_MAPPINGS.get(config.tag);\n}\n\nfunction createStrategyConfig(config: NamedDiscoveryConfig): DiscoveryStrategyConfig {\n\n const constructorName = discoveryStrategyFrom(config);\n const properties = new Map<string, PropertyType>();\n for (const [key, value] of config.properties) {\n if (value !== undefined) {\n properties.set(key, value);\n }\n }\n return { constructorName, properties }\n}\n\nexport function createDiscoveryStrategyConfigs(config: JoinConfig) {\n return mapConfigs(namedDiscoveryConfigsFrom(config));\n}\n", "import type {Logger} from \"../logging.ts\";\n\nexport type LicenseValidatorOptions = {\n validationKey: string;\n logger?: Logger\n}\n\nexport type LicenseValidationOptions = {\n logSuccessMessages?: boolean\n};\n\nexport type LicensePayload = {\n \"type\": \"paid\" | \"trial\";\n \"expiration\": number // in milliseconds\n \"email\": string,\n \"issuedBy\": string;\n \"iat\": number; // in seconds\n \"licensee\": string;\n \"organization\": {\n \"displayName\": string,\n \"identifier\": string\n }\n}\n\nexport type LicenseEvaluationResult = {\n licenseType: 'paid' | 'trial' | 'none';\n expired: boolean;\n fatal: boolean;\n license?: LicensePayload;\n error?: string;\n}\n\n\nexport const licenseValidationResults = {\n TRIAL_LICENSE_EXPIRED: {licenseType: 'trial', expired: true, fatal: true} as LicenseEvaluationResult,\n TRIAL_LICENSE_VALID: {licenseType: 'trial', expired: false, fatal: false} as LicenseEvaluationResult,\n PAID_LICENSE_EXPIRED: {licenseType: 'paid', expired: true, fatal: false} as LicenseEvaluationResult,\n PAID_LICENSE_VALID: {licenseType: 'paid', expired: false, fatal: false} as LicenseEvaluationResult,\n NO_LICENSE: {licenseType: 'none', expired: false, fatal: true} as LicenseEvaluationResult,\n};", "import getLogger, {type Logger} from \"../logging.ts\";\nimport {\n type LicensePayload,\n type LicenseEvaluationResult,\n type LicenseValidatorOptions,\n licenseValidationResults, type LicenseValidationOptions\n} from \"./types.ts\";\nimport {KJUR} from 'jsrsasign';\n\nexport class LicenseError extends Error {\n public readonly licensePayload: LicensePayload | string;\n\n constructor(message: string, licensePayload: string | LicensePayload) {\n super(message);\n this.licensePayload = licensePayload;\n }\n}\n\nexport class LicenseEvaluator {\n private readonly tokenResultMap = {\n 'trial-false': licenseValidationResults.TRIAL_LICENSE_VALID,\n 'trial-true': licenseValidationResults.TRIAL_LICENSE_EXPIRED,\n 'paid-false': licenseValidationResults.PAID_LICENSE_VALID,\n 'paid-true': licenseValidationResults.PAID_LICENSE_EXPIRED,\n };\n\n private readonly validationKey: string;\n\n constructor(validationKey: string) {\n if (!validationKey || typeof validationKey !== 'string') {\n throw new Error(`Validation key must be a non-empty string`);\n }\n this.validationKey = validationKey;\n }\n\n private decrypt(token: string): object {\n if (KJUR.jws.JWS.verifyJWT(token, this.validationKey, {alg: ['RS256']})) {\n return KJUR.jws.JWS.parse(token).payloadObj;\n } else {\n throw new LicenseError('invalid jwt token', token);\n }\n }\n\n private validateBasicTokenData(token: string): LicensePayload {\n const decoded = this.decrypt(token) as LicensePayload;\n if (['paid', 'trial'].indexOf(decoded.type) === -1) {\n throw new LicenseError('Invalid license type', token);\n }\n return decoded;\n }\n\n getLicenseStatus(token: string, now: Date = new Date()): LicenseEvaluationResult {\n try {\n const license = this.validateBasicTokenData(token);\n const isExpired = license.expiration < now.getTime();\n const licenseValidationResult = this.tokenResultMap[`${license.type}-${isExpired}`];\n return {\n ...licenseValidationResult,\n license\n };\n } catch (e) {\n return {\n ...licenseValidationResults.NO_LICENSE,\n error: e.message,\n };\n }\n\n }\n}\n\nexport class LicenseValidator {\n private readonly licenseHelper: LicenseEvaluator;\n private readonly logger: Logger;\n\n constructor({validationKey, logger}: LicenseValidatorOptions) {\n this.licenseHelper = new LicenseEvaluator(validationKey);\n this.logger = logger ?? getLogger(\"LicenseValidator\"); // Default to console if no logger provided\n }\n\n public validate(licenseKeyString: string, options?: LicenseValidationOptions): void {\n if (typeof licenseKeyString !== 'string') {\n throw new LicenseError('Invalid license key format', licenseKeyString);\n }\n\n const licenseStatus = this.licenseHelper.getLicenseStatus(licenseKeyString);\n this.printLicenseMessage(licenseStatus, options?.logSuccessMessages ?? true);\n if (licenseStatus.fatal) {\n throw new LicenseError('License validation failed', licenseStatus.license);\n }\n }\n\n private printLicenseMessage(licenseStatus: LicenseEvaluationResult, logSuccessMessages: boolean): void {\n if (!licenseStatus || licenseStatus.licenseType === 'none') {\n this.logger.error('This license is invalid. Please contact us at sales@interop.io to get a valid license');\n return;\n }\n\n const message = [\n licenseStatus.licenseType === 'paid' ? `This is a paid license that was issued for client ` : `This is a trial license that was issued for `,\n licenseStatus.license.organization.displayName,\n licenseStatus.expired ? `, but it has expired at ` : ` and is valid until `,\n new Date(licenseStatus.license.expiration).toString(),\n '.'\n ].join('');\n\n if (licenseStatus.fatal) {\n this.logger.error(message);\n } else if (licenseStatus.expired) {\n this.logger.warn(message);\n } else if(logSuccessMessages) {\n this.logger.info(message);\n }\n }\n}", "import type {Logger} from \"../logging.ts\";\nimport {LicenseValidator} from \"./LicenseValidator.ts\";\n\nconst validationKey = `-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAyyZrtwcQCMfyOkZDcjxZ\n+07BrvgcAvoQETF+ho8VLfaDxgNPZd6Q7jZEfrtv0+wn0pxx8pUDeBh8mCYvkwmb\n9tkFH47GJuDhWasNgyp4ugRX4bzoPV3SnHsBR4KJ/F76kBbike6sdIfO2lYGZ36s\nLJPHV7epOYsfhoc4343/vOxEPvNbwacbXWl4NsCGev4qUmWhe9iMpb/JPd3o4hIU\nSR31AmR2xoh3BkAJc2q/cSeQK6Kn9nZYocyW367+7FOvYsrOYotsuUASp0OWp+Lh\nWGfR7F6d016+u6kbvLvcceGztiP1u25QmPNCUmw49cTatthiEwwGHb01CR58mStZ\nxg5t9+N7X9hPO2K59b8EbOnnFTlwtMMF7MKR56S4YwMamCChr9WGgpOQV+lrqyx2\nyn9lwn8Yf4gLoLPKBEhHTEy6r/we9qymmlSSe4wr5Fctov2odSE535nvtdRYZkKk\nt32gOXuwnKg2kRlRSAErpyou1mz7/mWEt1H3sGTRArjNTP2KqZkc14vPToEEJt93\nZKjhD1pVEchDiWBOMj9o12pq80tGZ8PhGJasJVVi0JPUiaznG4r12JdyDAjuXMru\n6f4Tx0ULkdwn9ia7lchcq7xC2PlTnYz+fGpfU7V0Ci56QDTp6oP567L1EIeddkaI\nnIsi4KHT7Ctp047FTTelntUCAwEAAQ==\n-----END PUBLIC KEY-----`;\n\nexport const BridgeLicenseValidator = (logger: Logger) => new LicenseValidator({validationKey, logger});\n", "import {nanoid} from 'nanoid';\n\nexport function newUUID() : string {\n return nanoid();\n}\n", "import {type Address} from '../cluster/Address.ts';\nimport {getByName, getNetworkInterfaces, type IpAddress} from '../utils/network.ts';\nimport { type AddressInfo, Server, createServer} from 'node:net';\nimport { type Logger } from '../logging.ts';\nimport { type Config} from '../config/Config.ts';\n\nexport type EndpointType = 'member' | 'client';\n\nexport interface AddressPicker {\n pickAddress(): Promise<void>;\n getPublicAddressFor(endpoint: EndpointType): Address ;\n getPublicAddressMap(): ReadonlyMap<EndpointType, Address>;\n getBindAddressMap(): ReadonlyMap<EndpointType, Address>;\n getServers(): ReadonlyMap<string, Server>;\n close(): Promise<void>;\n}\n\nasync function createAddress(addressDef: AddressDef, port: number): Promise<Address> {\n if (addressDef.host) {\n return {type: addressDef.ipAddress.family, host: addressDef.host, port, address: addressDef.ipAddress};\n }\n return {type: addressDef.ipAddress.family, host: await addressDef.ipAddress.getHost(), port, address: addressDef.ipAddress}\n}\n\nfunction createNetServer(logger: Logger, host: string, range: number | string): Promise<Server> {\n const ports = portRange(range);\n return new Promise((resolve, reject) => {\n let server = createServer({}, () => {});\n server.on('error', (err: Error) => {\n if (err['code'] === 'EADDRINUSE') {\n logger.debug(`port ${err['port']} already in use on address ${err['address']}`);\n const {value: port} = ports.next();\n if (port) {\n logger.info(`retry starting server on port ${port} and host ${host ?? '<unspecified>'}`);\n server.close();\n server.listen(port, host);\n } else {\n logger.warn(`all configured port(s) ${range} are in use. closing...`);\n server.close();\n reject(err);\n }\n } else {\n logger.error(`server error: ${err.message}`, err);\n reject(err);\n }\n });\n server.on('listening', () => {\n const info = server.address() as AddressInfo;\n logger.info(`listening on ${info.address}:${info.port}`);\n resolve(server);\n });\n try {\n const {value: port} = ports.next();\n server.listen(port, host);\n } catch (e) {\n logger.error(`error starting socket server`, e);\n reject(e instanceof Error ? e : new Error(`listen failed: ${e}`));\n }\n });\n}\n\nclass InterfaceAddress {\n readonly address: string;\n readonly host?: string;\n constructor(address: string, host?: string) {\n this.address = address;\n this.host = host;\n }\n}\n\nclass AddressDef extends InterfaceAddress {\n\n readonly ipAddress: IpAddress;\n readonly port: number;\n constructor(ipAddress: IpAddress, host?: string, port?: number) {\n super(ipAddress.address, host);\n this.ipAddress = ipAddress;\n this.port = port ?? 0;\n }\n}\n\nexport class DefaultAddressPicker implements AddressPicker {\n\n readonly #logger: Logger;\n readonly #config: Config;\n readonly #publicAddressConfig?: string;\n #publicAddress: Address;\n #bindAddress: Address;\n #server: Server;\n readonly #port: string | number;\n constructor(config: Config,\n logger: Logger)\n {\n this.#logger = logger;\n this.#config = config;\n this.#port = config.network.port;\n this.#publicAddressConfig = config.network.publicAddress;\n }\n\n async close() {\n await new Promise<void>((resolve, reject) => {\n this.#server.close((err?) => {\n if (err) {\n reject(err);\n }\n else {\n resolve();\n }\n });\n });\n }\n\n async pickAddress(): Promise<void> {\n if (this.#publicAddress || this.#bindAddress)\n {\n return;\n }\n const publicAddressDef = await this.getPublicAddressByPortSearch();\n this.#publicAddress = this.#bindAddress;\n\n }\n\n getPublicAddressFor(endpoint: EndpointType): Address {\n return this.#publicAddress;\n }\n\n getBindAddressMap(): ReadonlyMap<EndpointType, Address> {\n return new Map([['member', this.#bindAddress]]);\n }\n getPublicAddressMap(): ReadonlyMap<EndpointType, Address> {\n return new Map([['member', this.#publicAddress]]);\n }\n\n getServers(): ReadonlyMap<string, Server> {\n return new Map([['member', this.#server]]);\n }\n\n private async getPublicAddressByPortSearch() {\n const bindAddressDef = await this.pickAddressDef();\n\n\n this.#server = await createNetServer(this.#logger, '0.0.0.0', bindAddressDef.port === 0 ? this.#port: bindAddressDef.port);\n\n const port = (this.#server.address() as AddressInfo).port;\n this.#bindAddress = await createAddress(bindAddressDef, port);\n\n return this.getPublicAddress(port);\n }\n\n private async getPublicAddress(port: number) {\n let address = this.#publicAddressConfig;\n if (address) {\n address = address.trim();\n if (!address) {\n throw new Error('Public address is empty');\n } else if ('127.0.0.1' === address) {\n return this.pickLoopbackAddressDef(address, port);\n }\n else\n {\n const ipAddress = await getByName(address);\n return new AddressDef(ipAddress, address, port);\n }\n }\n }\n\n private async pickAddressDef() {\n let addressDef = this.pickInterfaceAddressDef();\n if (addressDef) {\n\n }\n if (addressDef === undefined) {\n addressDef = await this.pickLoopbackAddressDef();\n }\n return addressDef;\n }\n\n private pickInterfaceAddressDef(): AddressDef {\n const interfaces = this.getInterfaces();\n if (interfaces) {\n const address = this.pickMatchingAddress(interfaces);\n if (address) {\n return address;\n }\n }\n return this.pickMatchingAddress();\n }\n\n private getInterfaces(): InterfaceAddress[] | undefined {\n return [];\n }\n\n private async pickLoopbackAddressDef(host?: string, defaultPort?: number) {\n const address = await getByName('127.0.0.1');\n return new AddressDef(address, host, defaultPort);\n }\n\n private match(ipAddress: IpAddress, interfaces: InterfaceAddress[]) {\n for (const iface of interfaces) {\n if (ipAddress.address === iface.address) {\n return iface;\n }\n }\n return undefined;\n }\n\n private getMatchingAddress(ipAddress: IpAddress, interfaces?: InterfaceAddress[]) {\n if (interfaces) {\n return this.match(ipAddress, interfaces);\n } else {\n return ipAddress;\n }\n }\n\n private pickMatchingAddress(interfaces?: InterfaceAddress[]): AddressDef | undefined {\n const preferIPv4 = true;\n const networkInterfaces = getNetworkInterfaces();\n let matchingAddress;\n for (const ni of networkInterfaces) {\n if (!interfaces && ni.loopback) {\n continue;\n }\n for (const ipAddress of ni.addresses) {\n if (preferIPv4 && ipAddress.family === 6) {\n continue;\n }\n const address = this.getMatchingAddress(ipAddress, interfaces);\n break;\n }\n }\n return matchingAddress;\n }\n}\n\n\n\n// stolen from gateway-server\n\n\nconst PORT_RANGE_MATCHER = /^(\\d+|(0x[\\da-f]+))(-(\\d+|(0x[\\da-f]+)))?$/i;\nfunction validPort(port: number) {\n if (port > 0xFFFF) throw new Error(`bad port ${port}`);\n return port;\n}\n\n/**\n * parse port range. port can be number or string representing comma separated\n * list of port ranges for e.g. \"3434,8380-8385\"\n * @param port\n */\nfunction* portRange(port: number | string): Generator<number> {\n if (typeof port === 'string') {\n for (const portRange of port.split(',')) {\n const trimmed = portRange.trim();\n const matchResult = PORT_RANGE_MATCHER.exec(trimmed);\n if (matchResult) {\n const start = parseInt(matchResult[1]);\n const end = parseInt(matchResult[4] ?? matchResult[1]);\n for (let i = validPort(start); i < validPort(end) + 1; i++) {\n yield i;\n }\n }\n else {\n throw new Error(`'${portRange}' is not a valid port or range.`);\n }\n }\n } else {\n yield validPort(port);\n }\n}\n", "import { BridgeNode } from './instance/BridgeNode.ts';\nimport { Config } from './config/Config.ts';\nimport { BOOLEAN, NUMBER, type PropertyType, type PropertyTypeConverter, STRING } from './config/Properties.ts';\n\nimport info from '../package.json' with { type: 'json' };\n\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { format } from 'node:util';\nimport { parentPort } from 'node:worker_threads';\n\nlet hadFatalError = false;\nconst reportedErrors = new Set();\nfunction getErrorMessage(error: unknown) {\n if (typeof error !== 'object' || error === null) {\n return String(error);\n }\n if (typeof error['stack'] === 'string') {\n return error['stack'];\n }\n return format('%o', error);\n}\n\nfunction onFatalError(error: unknown) {\n\n process.exitCode = 2;\n hadFatalError = true;\n\n const errorMessage = `\nio.Bridge: ${info.version}\n\n${getErrorMessage(error)}`;\n\n if (!reportedErrors.has(errorMessage)) {\n console.error(error);\n reportedErrors.add(errorMessage);\n }\n}\n\nfunction propertyNameToEnvKey(name: string): string {\n return `IO_BRIDGE_${name.toUpperCase().replaceAll('-', '').replaceAll('.', '_')}`;\n}\n\nfunction loadConfig<T extends PropertyType=string>(name: string, converter: PropertyTypeConverter<T>): T | undefined {\n const cmdArg = process.argv.find(arg => {return arg.startsWith(`--${name}=`);})?.split('=')[1];\n if (cmdArg) {\n return converter.convert(cmdArg);\n }\n const envKey = propertyNameToEnvKey(name);\n const envVar = process.env[envKey];\n if (envVar) {\n return converter.convert(envVar);\n }\n}\n\nfunction loadLicense() {\n const config = loadConfig('license.key', STRING);\n if (config !== undefined) {\n return config;\n }\n const file = loadConfig('license.key.file', STRING);\n if (file !== undefined) {\n return readFileSync(file, { encoding: 'ascii'}).trim();\n }\n}\n\ntry {\n process.on('uncaughtException', onFatalError);\n process.on('unhandledRejection', onFatalError);\n\n try {\n process.loadEnvFile();\n }\n catch (e) {\n if (e.code === 'ENOENT') {\n // fine, no .env file\n }\n else {\n throw e;\n }\n }\n\n const config = new Config();\n config.license ??= loadLicense();\n config.server.port ??= loadConfig('server.port', NUMBER) ?? 8084;\n config.server.host ??= loadConfig('server.host', STRING);\n config.server.ssl.enabled ??= loadConfig('server.ssl.enabled', BOOLEAN);\n config.server.ssl.key ??= loadConfig('server.ssl.key.file', STRING);\n config.server.ssl.cert ??= loadConfig('server.ssl.cert.file', STRING);\n config.server.ssl.ca ??= loadConfig('server.ssl.ca.file', STRING);\n config.server.wsPingInterval ??= loadConfig('server.ws-ping-interval', NUMBER);\n config.gateway.enabled ??= loadConfig('gateway.enabled', BOOLEAN);\n config.gateway.contexts.lifetime ??= loadConfig('gateway.contexts.lifetime', STRING) as 'retained' | 'ref-counted' | 'ownership';\n config.server.auth.type = (loadConfig('server.auth.type', STRING) ?? 'none') as 'none' | 'basic' | 'x509' | 'oauth2';\n config.server.auth.oauth2.jwt.issuerUri = loadConfig('server.auth.oauth2.jwt.issuer-uri', STRING) ?? undefined;\n config.server.auth.oauth2.jwt.issuer = loadConfig('server.auth.oauth2.jwt.issuer', STRING) ?? undefined;\n config.server.auth.oauth2.jwt.audience = loadConfig('server.auth.oauth2.jwt.audience', STRING) ?? undefined;\n config.server.auth.x509.key ??= loadConfig('server.auth.x509.key.file', STRING) ?? undefined;\n\n config.server.cors.allowOrigin = loadConfig('server.cors.allow-origin', STRING) ?? '*';\n config.server.cors.allowCredentials = loadConfig('server.cors.allow-credentials', BOOLEAN) ?? true;\n config.server.cors.disabled = (loadConfig('server.cors.disabled', BOOLEAN) ?? false) ? true: undefined;\n\n config.network.join.kubernetes.setEnabled(loadConfig('network.join.kubernetes.enabled', BOOLEAN) ?? false);\n config.network.join.kubernetes.setProperty('service-dns', loadConfig('network.join.kubernetes.service-dns', STRING) ?? undefined);\n\n const bridge = new BridgeNode(config);\n\n await bridge.start();\n\n reportPort(bridge);\n\n}\ncatch (error) {\n onFatalError(error);\n}\n\n\n/**\n * Report the bound address/port to parent process via IPC, worker thread, or file\n */\nfunction reportPort(bridge: BridgeNode) {\n const address = bridge.address;\n\n if (!address) {\n // Server not started or address not available\n return;\n }\n\n // Send bound address to parent process if available\n if (process?.send) {\n // Send via IPC if available (child process)\n process.send({ type: 'io.bridge:ready', address });\n }\n else if (parentPort) {\n // Send via parentPort if available (worker thread)\n parentPort.postMessage({ type: 'io.bridge:ready', address });\n }\n\n // Write to file if --print.port is specified\n const printPort = loadConfig('print.port', STRING);\n if (printPort) {\n // Write address to file (for processes without IPC)\n writeFileSync(printPort, JSON.stringify(address), { encoding: 'utf-8' });\n }\n}\n"],
5
+ "mappings": ";AAAA,OAAO,mBAAsC;AAE7C,SAAS,gBAAgB;;;ACDlB,SAAS,0BAA0B,MAAM,QAAQ,KAAc;AAClE,SAAO,IAAI,0BAA0B;AACzC;AAmBO,SAAS,qBAAqB,MAAM,QAAQ,KAAsB;AACrE,MAAI,CAAC,0BAA0B,GAAG,GAAG;AACjC,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACvD;AACA,SAAO,KAAK,MAAM,IAAI,qBAAqB;AAC/C;;;ACxBA,OAA0B;;;ACH1B,SAAS,cAAc;AACvB,SAAS,YAA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CAAqC,MAAM,KAAK;AACrG,SAAO,OAAO,KAAK,OAAO,IAAI,SAAS,WAAW,iCAAiC,MAAM,KAAK;AAC9F,SAAO,OAAO,KAAK,OAAO,IAAI,WAAW,WAAW,mCAAmC,MAAM,KAAK;AAClG,SAAO,OAAO,KAAK,KAAK,QAAQ,WAAW,6BAA6B,MAAM,KAAK;AAEnF,SAAO,OAAO,KAAK,cAAc,WAAW,4BAA4B,MAAM,KAAK;AACnF,SAAO,OAAO,KAAK,mBAAmB,WAAW,iCAAiC,OAAO,KAAK;AAC9F,SAAO,OAAO,KAAK,WAAY,WAAW,wBAAwB,OAAO,KAAK,QAAS,OAAM;AAE7F,SAAO,QAAQ,KAAK,WAAW,WAAW,WAAW,mCAAmC,OAAO,KAAK,KAAK;AACzG,SAAO,QAAQ,KAAK,WAAW,YAAY,eAAe,WAAW,uCAAuC,MAAM,KAAK,MAAS;AAEhI,QAAM,SAAS,IAAI,WAAW,MAAM;AAEpC,QAAM,OAAO,MAAM;AAEnB,aAAW,MAAM;AAErB,SACO,OAAO;AACV,eAAa,KAAK;AACtB;AAMA,SAAS,WAAW,QAAoB;AACpC,QAAM,UAAU,OAAO;AAEvB,MAAI,CAAC,SAAS;AAEV;AAAA,EACJ;AAGA,MAAI,SAAS,MAAM;AAEf,YAAQ,KAAK,EAAE,MAAM,mBAAmB,QAAQ,CAAC;AAAA,EACrD,WACS,YAAY;AAEjB,eAAW,YAAY,EAAE,MAAM,mBAAmB,QAAQ,CAAC;AAAA,EAC/D;AAGA,QAAM,YAAY,WAAW,cAAc,MAAM;AACjD,MAAI,WAAW;AAEX,kBAAc,WAAW,KAAK,UAAU,OAAO,GAAG,EAAE,UAAU,QAAQ,CAAC;AAAA,EAC3E;AACJ;",
6
6
  "names": ["gateway", "handlerId", "create", "instanceId", "instanceId", "IOGateway", "EventEmitter", "type", "lookup", "readFileSync", "property", "readFileSync", "KubernetesConfig", "KubernetesConfig", "lookup", "PROPERTY_DEFINITIONS", "validationKey", "nanoid", "createServer", "createServer", "networkInterfaces", "portRange", "join", "config", "readFileSync"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interopio/bridge",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "license": "see license in license.md",
5
5
  "author": "interop.io",
6
6
  "homepage": "https://docs.interop.io/bridge",