{"version":3,"file":"server.cjs","names":["debug","createDebug","reviveBigInts","toJSONSafe","ActionClient","ActionUuid","ActionInterfaces","EventEmitter","debug","createDebug","WebSocketServer","debug","createDebug","http"],"sources":["../lib/runtime/capability_registry.js","../lib/runtime/dispatcher.js","../lib/runtime/connection.js","../lib/runtime/transport_adapter.js","../lib/runtime/transports/ws.js","../lib/runtime/transports/http.js","../lib/runtime/index.js"],"sourcesContent":["// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n\n/**\n * Declarative allow-list of ROS 2 capabilities exposed to the Web Runtime.\n *\n * The registry is the single source of truth for \"what may a connected client\n * do?\" — every dispatched frame is checked against it. Capabilities not listed\n * here are rejected at the runtime layer before any rclnodejs Node API is\n * touched.\n *\n * Each capability is a tuple `(kind, name, type)` where:\n *   - `kind` is one of `'call' | 'publish' | 'subscribe' | 'action'`\n *   - `name` is the ROS 2 service, topic, or action name (e.g. `'/cmd_vel'`)\n *   - `type` is the ROS 2 interface name (e.g. `'std_msgs/msg/String'`)\n */\nclass CapabilityRegistry {\n  constructor() {\n    // Per-kind allow-lists. Each map is keyed by ROS name and stores the\n    // resolved interface type, e.g. `_call.get('/add_two_ints')` returns\n    // `'example_interfaces/srv/AddTwoInts'`. Looked up at dispatch time\n    // by Dispatcher.resolve(kind, name).\n    this._call = new Map(); //      ROS service name -> srv type\n    this._publish = new Map(); //   ROS topic name   -> msg type\n    this._subscribe = new Map(); // ROS topic name   -> msg type\n    this._action = new Map(); //    ROS action name  -> action type\n  }\n\n  /**\n   * Register one or more capabilities.\n   *\n   * @example Shorthand (string value = type name)\n   *   registry.expose({\n   *     call:      { '/add':    'example_interfaces/srv/AddTwoInts' },\n   *     publish:   { '/chatter':'std_msgs/msg/String' },\n   *     subscribe: { '/scan':   'sensor_msgs/msg/LaserScan' },\n   *   });\n   *\n   * @example Rich form (object value with metadata)\n   *   registry.expose({\n   *     subscribe: {\n   *       '/scan': { type: 'sensor_msgs/msg/LaserScan' /* future: qos, keep_last, ... *\\/ },\n   *     },\n   *   });\n   *\n   * The rich form is accepted today but the runtime only consumes\n   * `type`; additional fields are reserved for forward-compatibility\n   * (e.g. future QoS metadata). Snapshots via {@link list} always\n   * return the canonical `{ name: typeName }` form regardless of\n   * which form was used here.\n   *\n   * @param {{\n   *   call?:      Object<string, string | {type:string}>,\n   *   publish?:   Object<string, string | {type:string}>,\n   *   subscribe?: Object<string, string | {type:string}>,\n   *   action?:    Object<string, string | {type:string}>,\n   * }} spec\n   * @returns {CapabilityRegistry} this (chainable)\n   */\n  expose(spec = {}) {\n    for (const [name, value] of Object.entries(spec.call || {})) {\n      this._call.set(name, _typeOf(value, 'call', name));\n    }\n    for (const [name, value] of Object.entries(spec.publish || {})) {\n      this._publish.set(name, _typeOf(value, 'publish', name));\n    }\n    for (const [name, value] of Object.entries(spec.subscribe || {})) {\n      this._subscribe.set(name, _typeOf(value, 'subscribe', name));\n    }\n    for (const [name, value] of Object.entries(spec.action || {})) {\n      this._action.set(name, _typeOf(value, 'action', name));\n    }\n    return this;\n  }\n\n  /**\n   * Resolve a capability lookup.\n   * @param {'call'|'publish'|'subscribe'|'action'} kind\n   * @param {string} name\n   * @returns {{kind:string, name:string, type:string}|null}\n   */\n  resolve(kind, name) {\n    const map = this._mapFor(kind);\n    if (!map) return null;\n    const type = map.get(name);\n    return type ? { kind, name, type } : null;\n  }\n\n  /**\n   * Snapshot the registered capabilities as a plain object.\n   *\n   * Always returns the canonical shorthand form\n   * (`{ [name]: typeName }`) regardless of how `expose()` was called.\n   * Useful for introspection and future OpenAPI export.\n   */\n  list() {\n    return {\n      call: Object.fromEntries(this._call),\n      publish: Object.fromEntries(this._publish),\n      subscribe: Object.fromEntries(this._subscribe),\n      action: Object.fromEntries(this._action),\n    };\n  }\n\n  _mapFor(kind) {\n    if (kind === 'call') return this._call;\n    if (kind === 'publish') return this._publish;\n    if (kind === 'subscribe') return this._subscribe;\n    if (kind === 'action') return this._action;\n    return null;\n  }\n}\n\nfunction _typeOf(value, kind, name) {\n  if (typeof value === 'string') {\n    if (!value) {\n      throw new TypeError(\n        `expose.${kind}[\"${name}\"] is an empty string; expected a ROS type name`\n      );\n    }\n    return value;\n  }\n  if (value && typeof value === 'object' && typeof value.type === 'string') {\n    if (!value.type) {\n      throw new TypeError(\n        `expose.${kind}[\"${name}\"].type is empty; expected a ROS type name`\n      );\n    }\n    return value.type;\n  }\n  throw new TypeError(\n    `expose.${kind}[\"${name}\"]: expected a string or { type: string }`\n  );\n}\n\nexport { CapabilityRegistry };\n","// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n\nimport createDebug from 'debug';\nimport { toJSONSafe, reviveBigInts } from '../message_serialization.js';\nimport ActionClient from '../action/client.js';\nimport ActionInterfaces from '../action/interfaces.js';\nimport ActionUuid from '../action/uuid.js';\n\nconst debug = createDebug('rclnodejs:runtime');\n\nconst ACTION_DISCONNECT_GRACE_MS = 30 * 1000;\n\n/**\n * Per-connection request handler. Statelessly routes inbound capability\n * frames to the registered ROS 2 endpoints, lazily creating publishers,\n * subscriptions, and clients on first use and tearing them down on close.\n *\n * Rejects any frame whose capability is not in the {@link CapabilityRegistry}\n * — this is the security contract that distinguishes the runtime from the\n * raw rosocket gateway.\n */\nclass Dispatcher {\n  /**\n   * @param {object} options\n   * @param {import('../node.js')} options.node\n   * @param {import('./capability_registry.js').CapabilityRegistry} options.registry\n   */\n  constructor({ node, registry }) {\n    if (!node) throw new TypeError('Dispatcher: options.node is required');\n    if (!registry)\n      throw new TypeError('Dispatcher: options.registry is required');\n    this.node = node;\n    this.registry = registry;\n  }\n\n  /**\n   * Bind handlers for a freshly-accepted connection. The dispatcher takes\n   * full ownership of the connection's lifecycle from this point on.\n   * @param {import('./connection.js').Connection} conn\n   */\n  handle(conn) {\n    const state = {\n      publishers: new Map(), //     capability name -> Publisher\n      subscriptions: new Map(), //  subId           -> { name, Subscription }\n      clients: new Map(), //        capability name -> Client\n      actionClients: new Map(), //  capability name -> ActionClient\n      pendingGoals: new Map(), //   goal id         -> capability name\n      pendingCancels: new Map(), // token           -> capability name\n      goals: new Map(), //          goal id         -> { name, goalHandle }\n      closed: false,\n      expired: false,\n      cleanupTimer: null,\n    };\n\n    const cleanup = () => {\n      if (state.closed) return;\n      state.closed = true;\n      for (const { subscription } of state.subscriptions.values()) {\n        try {\n          this.node.destroySubscription(subscription);\n        } catch {\n          /* destroy is best-effort during connection teardown */\n        }\n      }\n      state.subscriptions.clear();\n      for (const pub of state.publishers.values()) {\n        try {\n          this.node.destroyPublisher(pub);\n        } catch {\n          /* destroy is best-effort during connection teardown */\n        }\n      }\n      state.publishers.clear();\n      for (const cli of state.clients.values()) {\n        try {\n          this.node.destroyClient(cli);\n        } catch {\n          /* destroy is best-effort during connection teardown */\n        }\n      }\n      state.clients.clear();\n      if (state.actionClients.size > 0) {\n        state.cleanupTimer = setTimeout(() => {\n          state.expired = true;\n          state.pendingGoals.clear();\n          state.pendingCancels.clear();\n          state.goals.clear();\n          for (const name of state.actionClients.keys()) {\n            _releaseActionClientIfIdle(state, name);\n          }\n        }, ACTION_DISCONNECT_GRACE_MS);\n        state.cleanupTimer.unref();\n      }\n      setImmediate(() => {\n        for (const name of state.actionClients.keys()) {\n          _releaseActionClientIfIdle(state, name);\n        }\n      });\n    };\n\n    conn.on('close', cleanup);\n    conn.on('message', (frame) => this._dispatchFrame(conn, frame, state));\n  }\n\n  _dispatchFrame(conn, frame, state) {\n    if (state.closed) return;\n    if (!frame || typeof frame !== 'object') {\n      conn.send({\n        ok: false,\n        error: 'invalid frame: expected JSON object',\n        code: 'invalid_frame',\n      });\n      return;\n    }\n    const { id, kind, capability } = frame;\n    try {\n      switch (kind) {\n        case 'call':\n          return this._handleCall(conn, id, capability, frame.payload, state);\n        case 'publish':\n          return this._handlePublish(\n            conn,\n            id,\n            capability,\n            frame.payload,\n            state\n          );\n        case 'subscribe':\n          return this._handleSubscribe(conn, id, capability, state);\n        case 'unsubscribe':\n          return this._handleUnsubscribe(conn, id, frame.subId, state);\n        case 'action':\n          return this._handleAction(conn, id, capability, frame, state);\n        default:\n          conn.send({\n            id,\n            ok: false,\n            error: `unknown kind: ${kind}`,\n            code: 'unknown_kind',\n          });\n      }\n    } catch (e) {\n      debug('dispatch error: %s', e.stack || e.message);\n      conn.send({\n        id,\n        ok: false,\n        error: e.message,\n        code: 'internal_error',\n      });\n    }\n  }\n\n  _handleCall(conn, id, name, payload, { clients }) {\n    const cap = this.registry.resolve('call', name);\n    if (!cap) return this._notExposed(conn, id, 'call', name);\n    let client = clients.get(name);\n    if (!client) {\n      client = this.node.createClient(cap.type, name);\n      clients.set(name, client);\n    }\n    const request = reviveBigInts(payload);\n    try {\n      client.sendRequest(request, (response) => {\n        conn.send({ id, ok: true, payload: toJSONSafe(response) });\n      });\n    } catch (e) {\n      conn.send({\n        id,\n        ok: false,\n        error: `call failed: ${e.message}`,\n        code: 'call_failed',\n      });\n    }\n  }\n\n  _handlePublish(conn, id, name, payload, { publishers }) {\n    const cap = this.registry.resolve('publish', name);\n    if (!cap) return this._notExposed(conn, id, 'publish', name);\n    let pub = publishers.get(name);\n    if (!pub) {\n      pub = this.node.createPublisher(cap.type, name);\n      publishers.set(name, pub);\n    }\n    try {\n      pub.publish(reviveBigInts(payload));\n      conn.send({ id, ok: true });\n    } catch (e) {\n      conn.send({\n        id,\n        ok: false,\n        error: `publish failed: ${e.message}`,\n        code: 'publish_failed',\n      });\n    }\n  }\n\n  _handleSubscribe(conn, id, name, { subscriptions }) {\n    const cap = this.registry.resolve('subscribe', name);\n    if (!cap) return this._notExposed(conn, id, 'subscribe', name);\n    if (id === undefined || id === null) {\n      conn.send({\n        ok: false,\n        error: 'subscribe requires an id',\n        code: 'missing_id',\n      });\n      return;\n    }\n    if (subscriptions.has(id)) {\n      conn.send({\n        id,\n        ok: false,\n        error: `id already in use: ${id}`,\n        code: 'duplicate_id',\n      });\n      return;\n    }\n    const subscription = this.node.createSubscription(cap.type, name, (msg) => {\n      conn.send({ event: 'message', subId: id, payload: toJSONSafe(msg) });\n    });\n    subscriptions.set(id, { name, subscription });\n    conn.send({ id, ok: true });\n  }\n\n  _handleUnsubscribe(conn, id, subId, { subscriptions }) {\n    if (subId === undefined || subId === null) {\n      conn.send({\n        id,\n        ok: false,\n        error: 'unsubscribe requires subId',\n        code: 'missing_sub_id',\n      });\n      return;\n    }\n    const entry = subscriptions.get(subId);\n    if (!entry) {\n      conn.send({\n        id,\n        ok: false,\n        error: `unknown subId: ${subId}`,\n        code: 'unknown_sub_id',\n      });\n      return;\n    }\n    try {\n      this.node.destroySubscription(entry.subscription);\n    } catch {\n      /* destroy is best-effort */\n    }\n    subscriptions.delete(subId);\n    conn.send({ id, ok: true });\n  }\n\n  _notExposed(conn, id, kind, name) {\n    conn.send({\n      id,\n      ok: false,\n      error: `capability not exposed: ${kind} ${name}`,\n      code: 'not_exposed',\n    });\n  }\n\n  _handleAction(conn, id, name, frame, state) {\n    const op = frame.op;\n    if (op === 'send_goal') {\n      return this._handleActionSendGoal(conn, id, name, frame.payload, state);\n    }\n    if (op === 'cancel') {\n      return this._handleActionCancel(conn, id, frame.goalId, state);\n    }\n    conn.send({\n      id,\n      ok: false,\n      error: `unknown action op: ${op}`,\n      code: 'unknown_op',\n    });\n  }\n\n  _handleActionSendGoal(conn, id, name, payload, state) {\n    const { actionClients, pendingGoals, goals } = state;\n    const cap = this.registry.resolve('action', name);\n    if (!cap) return this._notExposed(conn, id, 'action', name);\n    if (id === undefined || id === null) {\n      conn.send({\n        ok: false,\n        error: 'action send_goal requires an id',\n        code: 'missing_id',\n      });\n      return;\n    }\n    if (pendingGoals.has(id) || goals.has(id)) {\n      conn.send({\n        id,\n        ok: false,\n        error: `id already in use: ${id}`,\n        code: 'duplicate_id',\n      });\n      return;\n    }\n    let actionClient = actionClients.get(name);\n    if (!actionClient) {\n      actionClient = new ActionClient(this.node, cap.type, name);\n      actionClients.set(name, actionClient);\n    }\n    if (!actionClient.isActionServerAvailable()) {\n      conn.send({\n        id,\n        ok: false,\n        error: `action server unavailable: ${name}`,\n        code: 'action_unavailable',\n      });\n      return;\n    }\n    const goal = reviveBigInts(payload);\n    const actionGoal = {\n      id,\n      name,\n      actionClient,\n      goalUuid: ActionUuid.randomMessage(),\n      goalHandle: null,\n      finished: false,\n    };\n    const feedbackCallback = (feedback) => {\n      if (actionGoal.finished || state.closed) return;\n      conn.send({\n        event: 'feedback',\n        goalId: id,\n        payload: toJSONSafe(feedback),\n      });\n    };\n    const onError = (error) =>\n      this._finalizeActionGoal(conn, state, actionGoal, {\n        id,\n        ok: false,\n        error: `send_goal failed: ${error.message}`,\n        code: 'action_failed',\n      });\n    pendingGoals.set(id, name);\n    try {\n      actionClient\n        .sendGoal(goal, feedbackCallback, actionGoal.goalUuid)\n        .then(\n          (handle) =>\n            this._handleActionGoalResponse(conn, state, actionGoal, handle),\n          onError\n        );\n    } catch (error) {\n      onError(error);\n    }\n  }\n\n  _handleActionGoalResponse(conn, state, actionGoal, handle) {\n    const { id, actionClient } = actionGoal;\n    state.pendingGoals.delete(id);\n    if (state.expired || actionClient.isDestroyed()) {\n      this._finalizeActionGoal(conn, state, actionGoal);\n      return;\n    }\n    actionGoal.goalHandle = handle;\n    if (!handle.isAccepted()) {\n      this._finalizeActionGoal(conn, state, actionGoal, {\n        id,\n        ok: false,\n        error: 'goal rejected',\n        code: 'goal_rejected',\n      });\n      return;\n    }\n    state.goals.set(id, actionGoal);\n    conn.send({ id, ok: true, payload: { accepted: true } });\n    return this._watchActionResult(conn, state, actionGoal);\n  }\n\n  async _watchActionResult(conn, state, actionGoal) {\n    const { id, goalHandle } = actionGoal;\n    let response;\n    try {\n      const result = await goalHandle.getResult();\n      response = {\n        payload: toJSONSafe(result),\n        status: _goalStatusName(goalHandle.status),\n      };\n    } catch (error) {\n      response = {\n        ok: false,\n        error: `get result failed: ${error.message}`,\n        code: 'action_failed',\n      };\n    }\n    this._finalizeActionGoal(conn, state, actionGoal, {\n      event: 'result',\n      goalId: id,\n      ...response,\n    });\n  }\n\n  _finalizeActionGoal(conn, state, actionGoal, response) {\n    if (actionGoal.finished) return;\n    actionGoal.finished = true;\n    const { id, name, actionClient, goalUuid } = actionGoal;\n    actionClient._removeFeedbackCallback(goalUuid);\n    state.pendingGoals.delete(id);\n    state.goals.delete(id);\n    try {\n      if (response) conn.send(response);\n    } finally {\n      _releaseActionClientIfIdle(state, name);\n    }\n  }\n\n  _handleActionCancel(conn, id, goalId, state) {\n    const { goals, pendingCancels } = state;\n    if (goalId === undefined || goalId === null) {\n      conn.send({\n        id,\n        ok: false,\n        error: 'action cancel requires goalId',\n        code: 'missing_goal_id',\n      });\n      return;\n    }\n    const entry = goals.get(goalId);\n    if (!entry) {\n      conn.send({\n        id,\n        ok: false,\n        error: `unknown goal: ${goalId}`,\n        code: 'unknown_goal_id',\n      });\n      return;\n    }\n    const actionCancel = {\n      id,\n      goalId,\n      name: entry.name,\n      goalHandle: entry.goalHandle,\n      token: Symbol('cancel'),\n    };\n    pendingCancels.set(actionCancel.token, actionCancel.name);\n    return this._watchActionCancel(conn, state, actionCancel);\n  }\n\n  async _watchActionCancel(conn, state, actionCancel) {\n    const { goalId, goalHandle } = actionCancel;\n    let response;\n    try {\n      const cancelResponse = await goalHandle.cancelGoal();\n      const payload = toJSONSafe(cancelResponse);\n      response = cancelResponse.goals_canceling?.length\n        ? { ok: true, payload }\n        : {\n            ok: false,\n            error: `cancel rejected: ${goalId}`,\n            code: 'cancel_rejected',\n            payload,\n          };\n    } catch (error) {\n      response = {\n        ok: false,\n        error: `cancel failed: ${error.message}`,\n        code: 'action_failed',\n      };\n    }\n    this._finalizeActionCancel(conn, state, actionCancel, response);\n  }\n\n  _finalizeActionCancel(conn, state, actionCancel, response) {\n    const { id, name, token } = actionCancel;\n    state.pendingCancels.delete(token);\n    try {\n      conn.send({ id, ...response });\n    } finally {\n      _releaseActionClientIfIdle(state, name);\n    }\n  }\n}\n\nfunction _releaseActionClientIfIdle(state, name) {\n  if (!state.closed) return;\n  if ([...state.pendingGoals.values()].includes(name)) return;\n  if ([...state.pendingCancels.values()].includes(name)) return;\n  for (const goal of state.goals.values()) {\n    if (goal.name === name) return;\n  }\n  const actionClient = state.actionClients.get(name);\n  if (!actionClient) return;\n  state.actionClients.delete(name);\n  if (state.actionClients.size === 0) {\n    clearTimeout(state.cleanupTimer);\n    state.cleanupTimer = null;\n  }\n  setImmediate(() => {\n    try {\n      actionClient.destroy();\n    } catch {\n      /* destroy is best-effort during connection teardown */\n    }\n  });\n}\n\n/** Map a numeric `GoalStatus` constant to the wire's lowercase status name. */\nfunction _goalStatusName(status) {\n  switch (status) {\n    case ActionInterfaces.GoalStatus.STATUS_SUCCEEDED:\n      return 'succeeded';\n    case ActionInterfaces.GoalStatus.STATUS_CANCELED:\n      return 'canceled';\n    case ActionInterfaces.GoalStatus.STATUS_ABORTED:\n      return 'aborted';\n    default:\n      return 'unknown';\n  }\n}\n\nexport { Dispatcher };\n","// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n\nimport EventEmitter from 'events';\n\n/**\n * @typedef {Object} CapabilityFrame\n * @property {string|number} [id]      - Caller-assigned request id (echoed in reply).\n * @property {'call'|'publish'|'subscribe'|'unsubscribe'|'action'} [kind] - Request kind (C→S only). `'action'` is reserved and currently returns `code: 'not_implemented'`.\n * @property {string} [capability]     - Capability name, e.g. `/cmd_vel`.\n * @property {*}     [payload]         - Message payload (call request, publish msg, sub event).\n * @property {string|number} [subId]   - For unsubscribe: id of the original subscribe.\n * @property {boolean} [ok]            - Reply success flag (S→C only).\n * @property {string} [event]          - `'message'` for streamed subscription deliveries.\n * @property {string} [error]          - Human-readable error message on failure.\n * @property {string} [code]           - Stable machine-readable error code.\n */\n\n/**\n * Per-connection abstraction handed to the runtime by a transport adapter.\n *\n * The transport owns the wire (WebSocket today; other adapters may follow)\n * and exposes each connection as a `Connection` so the runtime can stay\n * transport-agnostic. Concrete adapters subclass `Connection` and call\n * `this.emit('message', frame)` / `this.emit('close')` as frames arrive on\n * the wire, and implement `send(frame)` / `close(code, reason)` to push\n * frames back out.\n *\n * @experimental — the base class shape may grow (e.g. backpressure hooks)\n * and is not part of the SemVer-stable surface for third-party adapter\n * authors. The first-party `WebSocketTransport` is stable and recommended\n * for production use.\n *\n * @event Connection#message\n * @type {CapabilityFrame}\n *\n * @event Connection#close\n */\nclass Connection extends EventEmitter {\n  /**\n   * Push a frame to the remote peer. Implementations should silently drop\n   * sends on a closed connection rather than throwing.\n   * @param {CapabilityFrame} frame\n   */\n  // eslint-disable-next-line no-unused-vars\n  send(frame) {\n    throw new Error('Connection.send() must be implemented by the transport');\n  }\n\n  /**\n   * Close the connection.\n   * @param {number} [code]\n   * @param {string} [reason]\n   */\n  // eslint-disable-next-line no-unused-vars\n  close(code, reason) {\n    throw new Error('Connection.close() must be implemented by the transport');\n  }\n}\n\nexport { Connection };\n","// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n\n/**\n * Base class / contract for transport adapters.\n *\n * A transport adapter:\n *   1. Owns the network listener (WS / HTTP / SSE / ...).\n *   2. Builds a {@link import('./connection.js').Connection} per accepted client.\n *   3. Calls `onConnection(conn)` from the start options once per client.\n *\n * The runtime never speaks to the wire directly — it only consumes the\n * Connection event surface. This is the seam that lets future adapters\n * (HTTP, etc.) drop in without touching the runtime or the SDK.\n *\n * @experimental — same forward-compat caveat as\n * {@link import('./connection.js').Connection}: the adapter contract may\n * grow to support new transports. First-party `WebSocketTransport` is\n * stable.\n */\nclass TransportAdapter {\n  /**\n   * Begin accepting connections.\n   * @param {object} options\n   * @param {(conn: import('./connection.js').Connection) => void} options.onConnection\n   * @returns {Promise<{address: string, port: number}>}\n   */\n  // eslint-disable-next-line no-unused-vars\n  async start(options) {\n    throw new Error('TransportAdapter.start() must be implemented');\n  }\n\n  /** Stop accepting and close all open connections. */\n  async stop() {\n    throw new Error('TransportAdapter.stop() must be implemented');\n  }\n}\n\nexport { TransportAdapter };\n","// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n\nimport { WebSocketServer } from 'ws';\nimport createDebug from 'debug';\nimport { Connection } from '../connection.js';\nimport { TransportAdapter } from '../transport_adapter.js';\n\nconst debug = createDebug('rclnodejs:runtime:ws');\n\n/**\n * A {@link Connection} backed by a single `ws.WebSocket`. JSON-encodes every\n * outbound frame, JSON-decodes every inbound frame, and silently no-ops sends\n * on a closed socket.\n */\nclass WebSocketConnection extends Connection {\n  constructor(ws, req) {\n    super();\n    this.ws = ws;\n    this.req = req; // raw HTTP upgrade request (for auth hooks)\n    ws.on('message', (data, isBinary) => {\n      if (isBinary) {\n        this.send({\n          ok: false,\n          error: 'binary frames are not supported',\n          code: 'binary_unsupported',\n        });\n        return;\n      }\n      let frame;\n      try {\n        frame = JSON.parse(data.toString('utf8'));\n      } catch (e) {\n        this.send({\n          ok: false,\n          error: `invalid JSON: ${e.message}`,\n          code: 'invalid_json',\n        });\n        return;\n      }\n      this.emit('message', frame);\n    });\n    ws.on('close', () => this.emit('close'));\n    ws.on('error', (err) => debug('socket error: %s', err.message));\n  }\n\n  send(frame) {\n    if (this.ws.readyState !== this.ws.OPEN) return;\n    try {\n      this.ws.send(JSON.stringify(frame));\n    } catch (e) {\n      debug('send failed: %s', e.message);\n    }\n  }\n\n  close(code, reason) {\n    try {\n      this.ws.close(code, reason);\n    } catch {\n      /* underlying socket may already be closing */\n    }\n  }\n}\n\n/**\n * Layer-2 WebSocket adapter for the Web Runtime.\n *\n * Speaks the capability wire protocol on a single URL path (default\n * `/capability`). This is intentionally separate from the lower-level\n * {@link module:rosocket} gateway: rosocket exposes raw ROS-shaped URLs\n * (`/topic/*`, `/service/*`); this adapter exposes one duplex channel\n * for the runtime's capability frames.\n */\nclass WebSocketTransport extends TransportAdapter {\n  /**\n   * @param {object} [options]\n   * @param {number} [options.port=9000]\n   * @param {string} [options.host='0.0.0.0']\n   * @param {string} [options.path='/capability']\n   * @param {(req: import('http').IncomingMessage) => boolean} [options.verifyClient]\n   *   Optional auth hook called with the raw HTTP upgrade request. Return\n   *   `false` to reject the connection before any frames are exchanged.\n   */\n  constructor(options = {}) {\n    super();\n    this.port = options.port != null ? options.port : 9000;\n    this.host = options.host != null ? options.host : '0.0.0.0';\n    this.path = options.path != null ? options.path : '/capability';\n    this.verifyClient = options.verifyClient;\n    this._wss = null;\n  }\n\n  async start({ onConnection }) {\n    if (typeof onConnection !== 'function') {\n      throw new TypeError(\n        'WebSocketTransport.start: onConnection must be a function'\n      );\n    }\n    return new Promise((resolve, reject) => {\n      const wsVerify = this.verifyClient\n        ? (info) => this.verifyClient(info.req)\n        : undefined;\n      this._wss = new WebSocketServer({\n        host: this.host,\n        port: this.port,\n        path: this.path,\n        verifyClient: wsVerify,\n      });\n      this._wss.on('error', reject);\n      this._wss.on('connection', (ws, req) => {\n        const conn = new WebSocketConnection(ws, req);\n        try {\n          onConnection(conn);\n        } catch (e) {\n          debug('onConnection threw: %s', e.stack || e.message);\n          conn.close(1011, 'runtime error');\n        }\n      });\n      this._wss.on('listening', () => {\n        const addr = this._wss.address();\n        this.port = addr.port; // record bound port for ephemeral (port: 0)\n        debug(\n          'capability runtime listening on %s:%d%s',\n          addr.address,\n          addr.port,\n          this.path\n        );\n        resolve(addr);\n      });\n    });\n  }\n\n  async stop() {\n    if (!this._wss) return;\n    const wss = this._wss;\n    this._wss = null;\n    return new Promise((resolve) => {\n      for (const client of wss.clients) {\n        try {\n          client.close();\n        } catch {\n          /* client may already be closing */\n        }\n      }\n      wss.close(() => resolve());\n    });\n  }\n}\n\nexport { WebSocketTransport };\n","// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n\nimport http from 'node:http';\nimport createDebug from 'debug';\nimport { Connection } from '../connection.js';\nimport { TransportAdapter } from '../transport_adapter.js';\n\nconst debug = createDebug('rclnodejs:runtime:http');\n\n// Map dispatcher error codes to HTTP status codes. Codes not listed\n// here fall back to 500.\nconst _STATUS_BY_CODE = Object.freeze({\n  not_exposed: 404,\n  not_implemented: 501,\n  unknown_kind: 400,\n  invalid_frame: 400,\n  invalid_json: 400,\n  binary_unsupported: 400,\n  missing_id: 400,\n  duplicate_id: 400,\n  unknown_sub_id: 400,\n  missing_sub_id: 400,\n  internal_error: 500,\n  call_failed: 500,\n  publish_failed: 500,\n  schema_violation: 400,\n  goal_rejected: 409,\n  action_failed: 500,\n  unknown_goal_id: 400,\n  missing_goal_id: 400,\n});\n\nconst _MAX_BODY_BYTES = 1 * 1024 * 1024; // 1 MiB cap on request bodies\n\n/**\n * A request-scoped {@link Connection} used by the HTTP transport.\n *\n * Wraps a single inbound HTTP request/response pair: emits exactly one\n * `'message'` frame to the dispatcher, captures the dispatcher's single\n * reply via `send()`, and translates that reply back into HTTP semantics\n * (status code, JSON body, or 204 for void replies).\n *\n * The dispatcher remains transport-agnostic — it sees the same\n * `{kind, capability, payload, id}` envelope as on WebSocket. The only\n * thing this class does is collapse the long-lived `Connection`\n * abstraction into one round-trip.\n */\nclass HttpRequestConnection extends Connection {\n  /**\n   * @param {import('http').IncomingMessage} request\n   * @param {import('http').ServerResponse} response\n   * @param {'call'|'publish'} kind\n   * @param {string} capability\n   * @param {*} payload\n   */\n  constructor(request, response, kind, capability, payload) {\n    super();\n    this.request = request;\n    this.response = response;\n    this._kind = kind;\n    this._capability = capability;\n    this._payload = payload;\n    this._replied = false;\n    this._closed = false;\n    // Placeholder frame id. The dispatcher reads `frame.id` from incoming\n    // frames and echoes it on the reply; over HTTP we discard the reply id\n    // and write the body directly, so the value just needs to be present.\n    this._id = '__http__';\n\n    // NOTE: we deliberately do *not* wire `request.on('close')` /\n    // `response.on('close')` to `_emitCloseOnce()` here. Doing so would\n    // catch client-side disconnects, but the close event also fires\n    // on normal end-of-response, racing the still-in-flight rcl\n    // reply callback and tearing down the dispatcher's lazy Client\n    // mid-flight (rmw throws \"client will not receive response\" and\n    // crashes the process). For now, dispatcher cleanup runs from\n    // `send()` only — a long-running call that the client gave up\n    // on holds onto its Publisher/Client until `send()` completes.\n    // The leak is bounded (one entry per capability per request)\n    // and acceptable until we have a way to drive cleanup that\n    // doesn't race the rcl reply path.\n  }\n\n  /**\n   * Kick off dispatch. Must be called immediately after the dispatcher\n   * is wired up to this connection. Emits the synthesised frame.\n   */\n  begin() {\n    this.emit('message', {\n      id: this._id,\n      kind: this._kind,\n      capability: this._capability,\n      payload: this._payload,\n    });\n  }\n\n  /**\n   * Receive a reply from the dispatcher. Translates `{ok, payload,\n   * error, code}` into the appropriate HTTP response. Subsequent calls\n   * are no-ops — HTTP is one-shot. Always emits `'close'` exactly once\n   * after the reply is written so the dispatcher's per-connection\n   * cleanup runs and lazy-created Publishers/Clients are released.\n   */\n  send(frame) {\n    if (this._replied) return;\n    this._replied = true;\n\n    if (frame.event === 'message') {\n      // Subscribe deliveries are not valid over HTTP; the dispatcher\n      // shouldn't send them for kind=call/publish, but be defensive.\n      this._writeError(\n        400,\n        'streaming_unsupported',\n        'streaming events are not supported over HTTP'\n      );\n      return this._emitCloseOnce();\n    }\n\n    if (frame.ok === true) {\n      if (this._kind === 'publish') {\n        this.response.writeHead(204).end();\n      } else {\n        // call: serialise the payload (may be undefined for void replies).\n        const body = JSON.stringify(frame.payload ?? null);\n        this.response.writeHead(200, {\n          'content-type': 'application/json; charset=utf-8',\n          'content-length': Buffer.byteLength(body),\n        });\n        this.response.end(body);\n      }\n      return this._emitCloseOnce();\n    }\n\n    // Failure path.\n    const code = frame.code || 'internal_error';\n    const status = _STATUS_BY_CODE[code] || 500;\n    this._writeError(status, code, frame.error || 'request failed');\n    this._emitCloseOnce();\n  }\n\n  /** Force-close the response. The dispatcher's `cleanup` will follow. */\n  // eslint-disable-next-line no-unused-vars\n  close(code, reason) {\n    if (!this._replied) {\n      this._writeError(500, 'internal_error', 'connection closed');\n    }\n    this._emitCloseOnce();\n  }\n\n  /**\n   * Idempotent `'close'` emitter — guarantees the dispatcher's\n   * cleanup runs exactly once even if `send()` and `close()` race.\n   */\n  _emitCloseOnce() {\n    if (this._closed) return;\n    this._closed = true;\n    this.emit('close');\n  }\n\n  _writeError(status, code, message) {\n    const body = JSON.stringify({ ok: false, error: message, code });\n    try {\n      this.response.writeHead(status, {\n        'content-type': 'application/json; charset=utf-8',\n        'content-length': Buffer.byteLength(body),\n      });\n      this.response.end(body);\n    } catch (e) {\n      debug('writeError failed: %s', e.message);\n    }\n  }\n}\n\n/** Shared SSE framing, heartbeats, and response lifecycle. */\nclass HttpSseConnection extends Connection {\n  /**\n   * @param {import('http').IncomingMessage} request\n   * @param {import('http').ServerResponse} response\n   * @param {object} [options]\n   * @param {number} [options.keepAliveMs=15000] Heartbeat comment interval.\n   */\n  constructor(request, response, options = {}) {\n    super();\n    this.request = request;\n    this.response = response;\n    this._keepAliveMs =\n      options.keepAliveMs != null ? options.keepAliveMs : 15000;\n    this._streaming = false;\n    this._closed = false;\n    this._keepAlive = null;\n\n    // Use response: request.close marks POST body completion, not client disconnect.\n    const onClose = () => this._emitCloseOnce();\n    response.on('close', onClose);\n    response.on('error', (e) => {\n      debug('sse response error: %s', e.message);\n      this._emitCloseOnce();\n    });\n  }\n\n  /** Close the stream; the dispatcher's `cleanup` follows via `'close'`. */\n  // eslint-disable-next-line no-unused-vars\n  close(code, reason) {\n    this._emitCloseOnce();\n  }\n\n  _ensureStream() {\n    if (this._streaming) return;\n    this._streaming = true;\n    this.response.writeHead(200, {\n      'content-type': 'text/event-stream; charset=utf-8',\n      'cache-control': 'no-cache, no-transform',\n      connection: 'keep-alive',\n      // Disable proxy buffering (nginx) so events flush immediately.\n      'x-accel-buffering': 'no',\n    });\n    this.response.flushHeaders();\n    if (this._keepAliveMs > 0) {\n      this._keepAlive = setInterval(() => {\n        if (this._closed) return;\n        try {\n          this.response.write(': keep-alive\\n\\n');\n        } catch (e) {\n          debug('sse keep-alive write failed: %s', e.message);\n          this._emitCloseOnce();\n        }\n      }, this._keepAliveMs);\n      // Don't let the heartbeat keep the event loop alive on its own.\n      this._keepAlive.unref();\n    }\n  }\n\n  _writeEvent(event, data) {\n    if (this._closed) return;\n    const json = JSON.stringify(data ?? null);\n    // Each newline in the payload must become its own `data:` line.\n    let chunk = `event: ${event}\\n`;\n    for (const line of json.split('\\n')) {\n      chunk += `data: ${line}\\n`;\n    }\n    chunk += '\\n';\n    try {\n      this.response.write(chunk);\n    } catch (e) {\n      debug('sse write failed: %s', e.message);\n      this._emitCloseOnce();\n    }\n  }\n\n  _writeError(status, code, message) {\n    const body = JSON.stringify({ ok: false, error: message, code });\n    try {\n      this.response.writeHead(status, {\n        'content-type': 'application/json; charset=utf-8',\n        'content-length': Buffer.byteLength(body),\n      });\n      this.response.end(body);\n    } catch (e) {\n      debug('sse writeError failed: %s', e.message);\n    }\n  }\n\n  _emitCloseOnce() {\n    if (this._closed) return;\n    this._closed = true;\n    if (this._keepAlive) {\n      clearInterval(this._keepAlive);\n      this._keepAlive = null;\n    }\n    try {\n      this.response.end();\n    } catch {\n      /* response may already be finished */\n    }\n    this.emit('close');\n  }\n}\n\n/**\n * A long-lived {@link Connection} that streams a single subscription over\n * Server-Sent Events (`text/event-stream`).\n *\n * Unlike {@link HttpRequestConnection} (one request → one reply), this\n * connection stays open: it drives the dispatcher with exactly one\n * `subscribe` frame and then relays every `{event:'message'}` delivery to\n * the client as an SSE `message` event until the client disconnects.\n *\n * The dispatcher is unchanged — it sees the same `subscribe` frame and the\n * same `{event:'message', subId, payload}` deliveries it would send over\n * WebSocket. This class only reframes them as SSE lines.\n *\n * HTTP status semantics are preserved for the *establishment* of the\n * stream: the `200 text/event-stream` headers are not written until the\n * dispatcher acknowledges the subscribe (`{ok:true}`). If the subscribe is\n * rejected (e.g. `not_exposed`), the headers have not been sent yet, so the\n * failure surfaces as a normal JSON error response with the mapped status\n * code — exactly like `call`/`publish`.\n */\nclass HttpSubscriptionConnection extends HttpSseConnection {\n  /**\n   * @param {import('http').IncomingMessage} request\n   * @param {import('http').ServerResponse} response\n   * @param {string} capability ROS name to subscribe to.\n   * @param {object} [options]\n   * @param {number} [options.keepAliveMs=15000] Heartbeat comment interval.\n   */\n  constructor(request, response, capability, options = {}) {\n    super(request, response, options);\n    this._capability = capability;\n    // Fixed subId: an SSE connection carries exactly one subscription.\n    this._subId = 'sse';\n    request.on('close', () => this._emitCloseOnce());\n  }\n\n  /**\n   * Kick off dispatch: emit a single `subscribe` frame. The dispatcher\n   * replies synchronously with `{ok:true}` (→ start the stream) or an\n   * error (→ JSON failure response).\n   */\n  begin() {\n    this.emit('message', {\n      id: this._subId,\n      kind: 'subscribe',\n      capability: this._capability,\n    });\n  }\n\n  send(frame) {\n    if (this._closed) return;\n\n    // Subscription delivery — the steady-state case.\n    if (frame.event === 'message') {\n      this._ensureStream();\n      this._writeEvent('message', frame.payload);\n      return;\n    }\n\n    // Subscribe acknowledgement: switch the response into an event stream.\n    if (frame.ok === true) {\n      this._ensureStream();\n      this._writeEvent('ready', {\n        capability: this._capability,\n        subId: this._subId,\n      });\n      return;\n    }\n\n    // Failure path.\n    const code = frame.code || 'internal_error';\n    if (!this._streaming) {\n      // Headers not sent yet — surface as a normal HTTP error.\n      const status = _STATUS_BY_CODE[code] || 500;\n      this._writeError(status, code, frame.error || 'subscribe failed');\n    } else {\n      // Already streaming — emit a terminal SSE error event, then close.\n      this._writeEvent('error', { error: frame.error, code });\n    }\n    this._emitCloseOnce();\n  }\n}\n\n/** Streams one action over SSE; disconnecting does not cancel the goal. */\nclass HttpActionConnection extends HttpSseConnection {\n  /**\n   * @param {import('http').IncomingMessage} request\n   * @param {import('http').ServerResponse} response\n   * @param {string} capability ROS action name.\n   * @param {*} payload Parsed goal.\n   * @param {object} [options]\n   * @param {number} [options.keepAliveMs=15000] Heartbeat interval.\n   */\n  constructor(request, response, capability, payload, options = {}) {\n    super(request, response, options);\n    this._capability = capability;\n    this._payload = payload;\n    // Each HTTP connection owns one goal, so a fixed ID is sufficient.\n    this._goalId = 'http-action';\n  }\n\n  begin() {\n    this.emit('message', {\n      id: this._goalId,\n      kind: 'action',\n      op: 'send_goal',\n      capability: this._capability,\n      payload: this._payload,\n    });\n  }\n\n  send(frame) {\n    if (this._closed) return;\n\n    if (frame.event === 'feedback') {\n      this._ensureStream();\n      this._writeEvent('feedback', frame.payload);\n      return;\n    }\n\n    if (frame.event === 'result') {\n      this._ensureStream();\n      if (frame.ok === false) {\n        this._writeEvent('error', { error: frame.error, code: frame.code });\n      } else {\n        this._writeEvent('result', {\n          status: frame.status,\n          payload: frame.payload,\n        });\n      }\n      return this._emitCloseOnce();\n    }\n\n    if (frame.ok === true) {\n      this._ensureStream();\n      this._writeEvent('accepted', { capability: this._capability });\n      return;\n    }\n\n    // Failures before streaming use HTTP errors, not SSE events.\n    const code = frame.code || 'internal_error';\n    const status = _STATUS_BY_CODE[code] || 500;\n    this._writeError(status, code, frame.error || 'send_goal failed');\n    this._emitCloseOnce();\n  }\n}\n\n/**\n * HTTP adapter for the Web Runtime.\n *\n * Exposes `call` and `publish` capabilities over plain HTTP:\n *\n *     POST /capability/call/<name>\n *     POST /capability/publish/<name>\n *\n * Action goals use a JSON POST with an SSE response:\n *\n *     POST /capability/action/<name>     (text/event-stream response)\n *\n * Streams `accepted`, `feedback`, then one terminal `result` or `error`.\n * Use WebSocket for cancellation; an HTTP disconnect does not cancel the goal.\n *\n * When `sse: true`, it additionally exposes `subscribe` as a Server-Sent\n * Events stream:\n *\n *     GET /capability/subscribe/<name>     (text/event-stream)\n *\n * SSE subscribe is opt-in and intended for clients that cannot hold a\n * WebSocket open (curl, AI agents, serverless/edge functions). Browser\n * apps should keep using the WebSocket transport for `subscribe`, which\n * multiplexes many topics on one connection. Anything that isn't a\n * recognised route returns a 404 / 405 — the adapter does not serve\n * unrelated paths.\n *\n * @example\n *   const runtime = createRuntime({\n *     node,\n *     transports: [\n *       new WebSocketTransport({ port: 9000 }),\n *       new HttpTransport({ port: 9001, sse: true }),\n *     ],\n *   });\n */\nclass HttpTransport extends TransportAdapter {\n  /**\n   * @param {object} [options]\n   * @param {number} [options.port=9001]\n   * @param {string} [options.host='::']\n   * @param {string} [options.basePath='/capability']\n   * @param {boolean} [options.sse=false]\n   *   Enable `GET /capability/subscribe/<name>` Server-Sent Events\n   *   streaming. Off by default; `subscribe` returns `unsupported_kind`\n   *   unless this is set.\n   * @param {number} [options.sseKeepAliveMs=15000]\n   *   Heartbeat comment interval for SSE streams, in milliseconds. Set to\n   *   `0` to disable heartbeats.\n   * @param {boolean|string|string[]} [options.cors=false]\n   *   Cross-Origin Resource Sharing policy. `false` (default) sends no\n   *   CORS headers. `true` allows any origin (`Access-Control-Allow-Origin:\n   *   *`). A string or array of strings allows only those origins (the\n   *   request's `Origin` is echoed back when it matches). Required for a\n   *   browser on a different origin to `fetch()` / `EventSource()` this\n   *   transport.\n   * @param {(request: import('http').IncomingMessage) => boolean} [options.verifyRequest]\n   *   Optional auth hook called with the raw request. Return `false` to\n   *   reject the request with 401. Mirrors `WebSocketTransport.verifyClient`.\n   */\n  constructor(options = {}) {\n    super();\n    this.port = options.port != null ? options.port : 9001;\n    this.host = options.host != null ? options.host : '::';\n    this.basePath = _normaliseBasePath(options.basePath);\n    this.sse = options.sse === true;\n    this.sseKeepAliveMs =\n      options.sseKeepAliveMs != null ? options.sseKeepAliveMs : 15000;\n    this.cors = _normaliseCors(options.cors);\n    this.verifyRequest = options.verifyRequest;\n    this._server = null;\n    this._onConnection = null;\n  }\n\n  async start({ onConnection }) {\n    if (typeof onConnection !== 'function') {\n      throw new TypeError(\n        'HttpTransport.start: onConnection must be a function'\n      );\n    }\n    this._onConnection = onConnection;\n    return new Promise((resolve, reject) => {\n      const server = http.createServer((request, response) =>\n        this._route(request, response)\n      );\n      this._server = server;\n      server.on('error', reject);\n      server.listen(this.port, this.host, () => {\n        const addr = server.address();\n        this.port = typeof addr === 'object' && addr ? addr.port : this.port;\n        debug(\n          'HTTP capability runtime listening on %s:%d%s',\n          (addr && addr.address) || this.host,\n          this.port,\n          this.basePath\n        );\n        resolve(addr);\n      });\n    });\n  }\n\n  async stop() {\n    if (!this._server) return;\n    const server = this._server;\n    this._server = null;\n    return new Promise((resolve) => {\n      // Force-close keep-alive sockets so server.close() doesn't hang\n      // waiting for clients (notably Node's fetch/undici, which keeps\n      // sockets warm by default).\n      server.closeAllConnections();\n      server.close(() => resolve());\n    });\n  }\n\n  // ---------- internals ----------\n\n  _route(request, response) {\n    // Apply CORS headers (if configured) before anything else, so they\n    // appear on every response — JSON replies, 204s, SSE streams, and\n    // errors alike. setHeader persists through later writeHead() calls.\n    this._applyCors(request, response);\n\n    let pathname;\n    try {\n      pathname = new URL(request.url || '/', 'http://localhost').pathname;\n    } catch {\n      return _writeJson(response, 400, {\n        ok: false,\n        error: 'invalid request URL',\n        code: 'invalid_url',\n      });\n    }\n\n    if (!pathname.startsWith(this.basePath + '/')) {\n      return _writeJson(response, 404, {\n        ok: false,\n        error: `not a capability route: ${pathname}`,\n        code: 'not_found',\n      });\n    }\n\n    // Preflight: browsers send OPTIONS before a cross-origin POST with a\n    // JSON content-type. Answer it directly (no auth, no body) — but only\n    // for capability routes, so unrelated paths still 404 above.\n    if (request.method === 'OPTIONS' && this.cors) {\n      response.writeHead(204).end();\n      return;\n    }\n\n    if (this.verifyRequest) {\n      let allowed;\n      try {\n        allowed = this.verifyRequest(request);\n      } catch (e) {\n        debug('verifyRequest threw: %s', (e && e.stack) || e);\n        return _writeJson(response, 500, {\n          ok: false,\n          error: 'verifyRequest hook failed',\n          code: 'internal_error',\n        });\n      }\n      if (allowed === false) {\n        return _writeJson(response, 401, {\n          ok: false,\n          error: 'unauthorized',\n          code: 'unauthorized',\n        });\n      }\n    }\n\n    const tail = pathname.slice(this.basePath.length + 1); // strip basePath + '/'\n    // tail = \"<kind>/<rest...>\"; first segment is the kind, rest is the\n    // ROS name (which itself can contain slashes).\n    const slash = tail.indexOf('/');\n    if (slash <= 0) {\n      return _writeJson(response, 404, {\n        ok: false,\n        error: `expected ${this.basePath}/<kind>/<name>`,\n        code: 'not_found',\n      });\n    }\n    const kind = tail.slice(0, slash);\n    let name;\n    try {\n      name = '/' + decodeURIComponent(tail.slice(slash + 1));\n    } catch {\n      return _writeJson(response, 400, {\n        ok: false,\n        error: `invalid percent-encoding in capability name: ${tail.slice(slash + 1)}`,\n        code: 'invalid_url',\n      });\n    }\n\n    if (kind === 'subscribe') {\n      if (!this.sse) {\n        return _writeJson(response, 404, {\n          ok: false,\n          error:\n            'subscribe over HTTP is disabled (enable `sse` or use WebSocket)',\n          code: 'unsupported_kind',\n        });\n      }\n      if (request.method !== 'GET') {\n        response.setHeader('allow', 'GET');\n        return _writeJson(response, 405, {\n          ok: false,\n          error: `method not allowed: ${request.method} (use GET for SSE subscribe)`,\n          code: 'method_not_allowed',\n        });\n      }\n      const conn = new HttpSubscriptionConnection(request, response, name, {\n        keepAliveMs: this.sseKeepAliveMs,\n      });\n      try {\n        this._onConnection(conn);\n        conn.begin();\n      } catch (e) {\n        debug('onConnection threw: %s', e.stack || e.message);\n        conn.close();\n      }\n      return;\n    }\n\n    if (kind !== 'call' && kind !== 'publish' && kind !== 'action') {\n      return _writeJson(response, 404, {\n        ok: false,\n        error: `unsupported kind over HTTP: ${kind}`,\n        code: 'unsupported_kind',\n      });\n    }\n\n    if (request.method !== 'POST') {\n      response.setHeader('allow', 'POST');\n      return _writeJson(response, 405, {\n        ok: false,\n        error: `method not allowed: ${request.method}`,\n        code: 'method_not_allowed',\n      });\n    }\n\n    _readJsonBody(request, _MAX_BODY_BYTES, (err, payload) => {\n      if (err) {\n        const code = err.code || 'invalid_json';\n        const status = code === 'payload_too_large' ? 413 : 400;\n        return _writeJson(response, status, {\n          ok: false,\n          error: err.message,\n          code,\n        });\n      }\n      const conn =\n        kind === 'action'\n          ? new HttpActionConnection(request, response, name, payload, {\n              keepAliveMs: this.sseKeepAliveMs,\n            })\n          : new HttpRequestConnection(request, response, kind, name, payload);\n      try {\n        this._onConnection(conn);\n        conn.begin();\n      } catch (e) {\n        debug('onConnection threw: %s', e.stack || e.message);\n        conn.close();\n      }\n    });\n  }\n\n  /**\n   * Set CORS response headers per the configured policy. No-op when\n   * `cors` is disabled. For an allow-list, the request `Origin` is echoed\n   * only when it matches (and `Vary: Origin` is set so caches don't mix\n   * responses across origins).\n   *\n   * `Access-Control-Allow-Headers` reflects the browser's\n   * `Access-Control-Request-Headers` when present, so authenticated or\n   * custom-header requests (`Authorization`, `X-*`, …) pass preflight\n   * rather than being limited to `content-type`. The reflected value is\n   * added to `Vary` to keep caches correct.\n   */\n  _applyCors(request, response) {\n    if (!this.cors) return;\n    const allow = this.cors; // true → any; otherwise a Set of origins\n    if (allow === true) {\n      response.setHeader('access-control-allow-origin', '*');\n    } else {\n      const origin = request.headers.origin;\n      response.setHeader('vary', 'Origin');\n      if (origin && allow.has(origin)) {\n        response.setHeader('access-control-allow-origin', origin);\n      }\n    }\n    response.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS');\n    // Echo whatever headers the browser says it will send; fall back to\n    // `content-type` for non-preflight requests that carry no such hint.\n    const requested = request.headers['access-control-request-headers'];\n    if (requested) {\n      response.appendHeader('vary', 'Access-Control-Request-Headers');\n      response.setHeader('access-control-allow-headers', requested);\n    } else {\n      response.setHeader('access-control-allow-headers', 'content-type');\n    }\n    response.setHeader('access-control-max-age', '86400');\n  }\n}\n\nfunction _writeJson(response, status, body) {\n  const json = JSON.stringify(body);\n  response.writeHead(status, {\n    'content-type': 'application/json; charset=utf-8',\n    'content-length': Buffer.byteLength(json),\n  });\n  response.end(json);\n}\n\nfunction _readJsonBody(request, maxBytes, cb) {\n  // Guard against double-callback: the body may exceed maxBytes (we call\n  // cb(err) and request.destroy()), and the destroy itself can synchronously\n  // emit 'error' which would otherwise reach cb(err) a second time.\n  let done = false;\n  const finish = (err, value) => {\n    if (done) return;\n    done = true;\n    cb(err, value);\n  };\n\n  const ctype = (request.headers['content-type'] || '').toLowerCase();\n  // Only the media-type segment matters; ignore parameters like\n  // `; charset=utf-8` and reject sneaky values such as\n  // `text/plain;application/json` that include the right substring\n  // but mean something else.\n  const mediaType = ctype.split(';')[0].trim();\n  if (\n    request.method === 'POST' &&\n    ctype !== '' &&\n    mediaType !== 'application/json'\n  ) {\n    // Be lenient: empty bodies + missing content-type are treated as\n    // \"publish with no fields\", same as `{}`. Only reject explicit\n    // non-JSON content types.\n    const e = new Error(\n      `unsupported content-type: ${ctype} (expected application/json)`\n    );\n    e.code = 'invalid_content_type';\n    return finish(e);\n  }\n  let total = 0;\n  const chunks = [];\n  request.on('data', (chunk) => {\n    if (done) return;\n    total += chunk.length;\n    if (total > maxBytes) {\n      const e = new Error(`request body exceeds ${maxBytes} bytes`);\n      e.code = 'payload_too_large';\n      finish(e);\n      request.destroy();\n      return;\n    }\n    chunks.push(chunk);\n  });\n  request.on('end', () => {\n    if (done) return;\n    const raw = Buffer.concat(chunks).toString('utf8');\n    if (!raw) return finish(null, {});\n    try {\n      finish(null, JSON.parse(raw));\n    } catch (e) {\n      const err = new Error(`invalid JSON: ${e.message}`);\n      err.code = 'invalid_json';\n      finish(err);\n    }\n  });\n  request.on('error', (e) => {\n    e.code = e.code || 'request_error';\n    finish(e);\n  });\n}\n\nfunction _normaliseBasePath(value) {\n  if (value === undefined || value === null || value === '') {\n    return '/capability';\n  }\n  if (typeof value !== 'string') {\n    throw new TypeError(\n      `HttpTransport: basePath must be a string, got ${typeof value}`\n    );\n  }\n  // Ensure single leading slash, no trailing slash.\n  let p = value.replace(/\\/+$/, '');\n  if (!p.startsWith('/')) p = '/' + p;\n  if (p === '') {\n    throw new TypeError('HttpTransport: basePath must not be empty');\n  }\n  return p;\n}\n\n/**\n * Normalise the `cors` option into either `false`, `true` (any origin),\n * or a `Set<string>` of allowed origins. A `\"*\"` value (or an array that\n * contains `\"*\"`) means \"any origin\" and is treated as `true`, matching\n * the CLI's `--http-cors *` shorthand.\n */\nfunction _normaliseCors(value) {\n  if (value === undefined || value === null || value === false) return false;\n  if (value === true) return true;\n  if (typeof value === 'string') {\n    return value === '*' ? true : new Set([value]);\n  }\n  if (Array.isArray(value)) {\n    if (!value.every((v) => typeof v === 'string')) {\n      throw new TypeError(\n        'HttpTransport: cors array must contain only origin strings'\n      );\n    }\n    if (value.includes('*')) return true;\n    return new Set(value);\n  }\n  throw new TypeError(\n    `HttpTransport: cors must be a boolean, string, or string[], got ${typeof value}`\n  );\n}\n\nexport { HttpTransport };\n","// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n\nimport { CapabilityRegistry } from './capability_registry.js';\nimport { Dispatcher } from './dispatcher.js';\nimport { Connection } from './connection.js';\nimport { TransportAdapter } from './transport_adapter.js';\nimport { WebSocketTransport } from './transports/ws.js';\nimport { HttpTransport } from './transports/http.js';\n\n/**\n * The Web Runtime composes a capability registry, a dispatcher, and one or\n * more transport adapters around an existing rclnodejs `Node`.\n *\n * Lifecycle:\n *   1. Construct via {@link createRuntime}.\n *   2. Register capabilities with {@link Runtime#expose}.\n *   3. Begin accepting connections with {@link Runtime#start}.\n *   4. {@link Runtime#stop} when shutting down.\n *\n * The runtime is **additive** to the existing rclnodejs Node — it does not\n * take ownership of the Node and does not stop it on `runtime.stop()`. The\n * caller is responsible for `rclnodejs.shutdown()`.\n */\nclass Runtime {\n  /**\n   * @param {object} options\n   * @param {import('../node.js')} options.node\n   * @param {CapabilityRegistry} options.registry\n   * @param {TransportAdapter[]} options.transports\n   */\n  constructor({ node, registry, transports }) {\n    this.node = node;\n    this.registry = registry;\n    this.transports = transports;\n    this.dispatcher = new Dispatcher({ node, registry });\n    this._started = false;\n  }\n\n  /**\n   * Forward to the registry. Returns `this` for chaining.\n   * @param {Parameters<CapabilityRegistry['expose']>[0]} spec\n   */\n  expose(spec) {\n    this.registry.expose(spec);\n    return this;\n  }\n\n  /**\n   * Start every configured transport. Each transport begins listening and\n   * routes its connections through the shared dispatcher.\n   *\n   * If a later transport fails to start, every transport that *did* start\n   * is stopped before the original error propagates so the runtime never\n   * leaves stray listeners behind.\n   *\n   * @returns {Promise<Runtime>}\n   */\n  async start() {\n    if (this._started) return this;\n    const onConnection = (conn) => this.dispatcher.handle(conn);\n    const started = [];\n    try {\n      for (const t of this.transports) {\n        await t.start({ onConnection });\n        started.push(t);\n      }\n    } catch (err) {\n      for (const t of started.reverse()) {\n        try {\n          await t.stop();\n        } catch {\n          /* swallow rollback errors so the original failure surfaces */\n        }\n      }\n      throw err;\n    }\n    this._started = true;\n    return this;\n  }\n\n  /** Stop every configured transport. */\n  async stop() {\n    for (const t of this.transports) {\n      try {\n        await t.stop();\n      } catch {\n        /* best-effort: continue stopping the remaining transports */\n      }\n    }\n    this._started = false;\n  }\n}\n\n/**\n * Convenience factory. Defaults to a single {@link WebSocketTransport} on\n * port 9000, path `/capability`. Pass `transport` or `transports` to swap\n * or add other adapters.\n *\n * @param {object} options\n * @param {import('../node.js')} options.node\n * @param {TransportAdapter} [options.transport]\n * @param {TransportAdapter[]} [options.transports]\n * @returns {Runtime}\n */\nfunction createRuntime({ node, transport, transports } = {}) {\n  if (!node) throw new TypeError('createRuntime: options.node is required');\n  let resolvedTransports;\n  if (Array.isArray(transports) && transports.length > 0) {\n    resolvedTransports = transports;\n  } else if (transport) {\n    resolvedTransports = [transport];\n  } else {\n    resolvedTransports = [new WebSocketTransport()];\n  }\n  return new Runtime({\n    node,\n    registry: new CapabilityRegistry(),\n    transports: resolvedTransports,\n  });\n}\n\nexport {\n  createRuntime,\n  Runtime,\n  CapabilityRegistry,\n  Dispatcher,\n  Connection,\n  TransportAdapter,\n  WebSocketTransport,\n  HttpTransport,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,qBAAN,MAAyB;CACvB,cAAc;EAKZ,KAAK,wBAAQ,IAAI,IAAI;EACrB,KAAK,2BAAW,IAAI,IAAI;EACxB,KAAK,6BAAa,IAAI,IAAI;EAC1B,KAAK,0BAAU,IAAI,IAAI;CACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCA,OAAO,OAAO,CAAC,GAAG;EAChB,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,GACxD,KAAK,MAAM,IAAI,MAAM,QAAQ,OAAO,QAAQ,IAAI,CAAC;EAEnD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,WAAW,CAAC,CAAC,GAC3D,KAAK,SAAS,IAAI,MAAM,QAAQ,OAAO,WAAW,IAAI,CAAC;EAEzD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,aAAa,CAAC,CAAC,GAC7D,KAAK,WAAW,IAAI,MAAM,QAAQ,OAAO,aAAa,IAAI,CAAC;EAE7D,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,GAC1D,KAAK,QAAQ,IAAI,MAAM,QAAQ,OAAO,UAAU,IAAI,CAAC;EAEvD,OAAO;CACT;;;;;;;CAQA,QAAQ,MAAM,MAAM;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