@crvouga/mockingbird-runtime 0.0.0-reserved → 0.0.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.
Files changed (81) hide show
  1. package/README.md +130 -1
  2. package/dist/adapter-node.d.ts +2521 -0
  3. package/dist/adapter-node.js +6920 -0
  4. package/dist/adapter-node.js.map +7 -0
  5. package/dist/admin-ui.js +25 -0
  6. package/dist/admin-ui.js.map +7 -0
  7. package/dist/chunk-2KDYLZXC.js +118 -0
  8. package/dist/chunk-2KDYLZXC.js.map +7 -0
  9. package/dist/chunk-2Y25NPCV.js +1289 -0
  10. package/dist/chunk-2Y25NPCV.js.map +7 -0
  11. package/dist/chunk-4SAK6MQT.js +246 -0
  12. package/dist/chunk-4SAK6MQT.js.map +7 -0
  13. package/dist/chunk-ANCCZFF2.js +778 -0
  14. package/dist/chunk-ANCCZFF2.js.map +7 -0
  15. package/dist/chunk-EBGYPQPA.js +198 -0
  16. package/dist/chunk-EBGYPQPA.js.map +7 -0
  17. package/dist/chunk-EQLY2YOA.js +274 -0
  18. package/dist/chunk-EQLY2YOA.js.map +7 -0
  19. package/dist/chunk-G62YDIIJ.js +7664 -0
  20. package/dist/chunk-G62YDIIJ.js.map +7 -0
  21. package/dist/chunk-HU6IOAFC.js +437 -0
  22. package/dist/chunk-HU6IOAFC.js.map +7 -0
  23. package/dist/chunk-RNAHPNUJ.js +97 -0
  24. package/dist/chunk-RNAHPNUJ.js.map +7 -0
  25. package/dist/chunk-UP4QOSFD.js +87 -0
  26. package/dist/chunk-UP4QOSFD.js.map +7 -0
  27. package/dist/chunk-XNS34BPF.js +2489 -0
  28. package/dist/chunk-XNS34BPF.js.map +7 -0
  29. package/dist/core.d.ts +356 -0
  30. package/dist/core.js +51 -0
  31. package/dist/core.js.map +7 -0
  32. package/dist/crypto-XS5XCMRJ.js +21 -0
  33. package/dist/crypto-XS5XCMRJ.js.map +7 -0
  34. package/dist/helpers-UD7CG4WQ.js +18 -0
  35. package/dist/helpers-UD7CG4WQ.js.map +7 -0
  36. package/dist/http-codec.d.ts +72 -0
  37. package/dist/http-codec.js +25 -0
  38. package/dist/http-codec.js.map +7 -0
  39. package/dist/http-provider.d.ts +3243 -0
  40. package/dist/http-provider.js +37920 -0
  41. package/dist/http-provider.js.map +7 -0
  42. package/dist/index.d.ts +10 -0
  43. package/dist/index.js +23 -0
  44. package/dist/index.js.map +7 -0
  45. package/dist/mqtt-broker/node.d.ts +632 -0
  46. package/dist/mqtt-broker/node.js +355 -0
  47. package/dist/mqtt-broker/node.js.map +7 -0
  48. package/dist/mqtt-broker.d.ts +990 -0
  49. package/dist/mqtt-broker.js +913 -0
  50. package/dist/mqtt-broker.js.map +7 -0
  51. package/dist/openapi-metadata.d.ts +290 -0
  52. package/dist/openapi-metadata.js +28 -0
  53. package/dist/openapi-metadata.js.map +7 -0
  54. package/dist/openapi.d.ts +252 -0
  55. package/dist/openapi.js +45 -0
  56. package/dist/openapi.js.map +7 -0
  57. package/dist/preview/artifacts.d.ts +19 -0
  58. package/dist/preview/artifacts.js +40 -0
  59. package/dist/preview/artifacts.js.map +7 -0
  60. package/dist/preview/bridge.d.ts +21 -0
  61. package/dist/preview/bridge.js +9 -0
  62. package/dist/preview/bridge.js.map +7 -0
  63. package/dist/preview/harness.d.ts +12 -0
  64. package/dist/preview/harness.js +65 -0
  65. package/dist/preview/harness.js.map +7 -0
  66. package/dist/preview/host.d.ts +30 -0
  67. package/dist/preview/host.js +70 -0
  68. package/dist/preview/host.js.map +7 -0
  69. package/dist/service/admin.d.ts +106 -0
  70. package/dist/service/admin.js +340 -0
  71. package/dist/service/admin.js.map +7 -0
  72. package/dist/service.d.ts +2665 -0
  73. package/dist/service.js +264 -0
  74. package/dist/service.js.map +7 -0
  75. package/dist/sqlite.d.ts +69 -0
  76. package/dist/sqlite.js +19 -0
  77. package/dist/sqlite.js.map +7 -0
  78. package/dist/ui.d.ts +37 -0
  79. package/dist/ui.js +702 -0
  80. package/dist/ui.js.map +7 -0
  81. package/package.json +130 -6
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../mqtt/broker/src/reason.ts", "../../mqtt/broker/src/codec.ts", "../../mqtt/broker/src/runtime.ts"],
4
+ "sourcesContent": ["/**\n * MQTT 5.0 reason codes (2.4), by the specification's names.\n * https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901031\n */\nexport const ReasonCode = {\n /** Also \"Normal disconnection\" and \"Granted QoS 0\". */\n Success: 0x00,\n GrantedQoS1: 0x01,\n GrantedQoS2: 0x02,\n NoMatchingSubscribers: 0x10,\n NoSubscriptionExisted: 0x11,\n UnspecifiedError: 0x80,\n MalformedPacket: 0x81,\n ProtocolError: 0x82,\n ImplementationSpecificError: 0x83,\n UnsupportedProtocolVersion: 0x84,\n ClientIdentifierNotValid: 0x85,\n BadUserNameOrPassword: 0x86,\n NotAuthorized: 0x87,\n ServerUnavailable: 0x88,\n ServerBusy: 0x89,\n Banned: 0x8a,\n ServerShuttingDown: 0x8b,\n BadAuthenticationMethod: 0x8c,\n KeepAliveTimeout: 0x8d,\n SessionTakenOver: 0x8e,\n TopicFilterInvalid: 0x8f,\n TopicNameInvalid: 0x90,\n PacketIdentifierInUse: 0x91,\n PacketIdentifierNotFound: 0x92,\n ReceiveMaximumExceeded: 0x93,\n TopicAliasInvalid: 0x94,\n PacketTooLarge: 0x95,\n MessageRateTooHigh: 0x96,\n QuotaExceeded: 0x97,\n AdministrativeAction: 0x98,\n PayloadFormatInvalid: 0x99,\n RetainNotSupported: 0x9a,\n QoSNotSupported: 0x9b,\n UseAnotherServer: 0x9c,\n ServerMoved: 0x9d,\n SharedSubscriptionsNotSupported: 0x9e,\n ConnectionRateExceeded: 0x9f,\n MaximumConnectTime: 0xa0,\n SubscriptionIdentifiersNotSupported: 0xa1,\n WildcardSubscriptionsNotSupported: 0xa2,\n} as const\n\nexport type ReasonCodeName = keyof typeof ReasonCode\n", "/**\n * MQTT 5.0 control packet codec (OASIS Standard, 7 March 2019).\n *\n * Symmetric on purpose: the broker decodes what clients send and encodes its replies, and the\n * tests drive the broker with the same functions pointed the other way. Section numbers in the\n * comments are the specification's.\n *\n * https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html\n */\nimport { ReasonCode } from \"./reason.js\"\n\n/** A malformed packet or protocol violation, carrying the reason code a server answers with. */\nexport class MqttProtocolError extends Error {\n constructor(\n readonly reasonCode: number,\n message: string,\n ) {\n super(message)\n this.name = \"MqttProtocolError\"\n }\n}\n\nconst malformed = (message: string): MqttProtocolError =>\n new MqttProtocolError(ReasonCode.MalformedPacket, message)\nconst protocolError = (message: string): MqttProtocolError =>\n new MqttProtocolError(ReasonCode.ProtocolError, message)\n\n/** Properties (2.2.2.2), by the specification's names in camelCase. */\nexport type Properties = {\n payloadFormatIndicator?: number\n messageExpiryInterval?: number\n contentType?: string\n responseTopic?: string\n correlationData?: Uint8Array\n /** PUBLISH may carry several; SUBSCRIBE carries at most one. */\n subscriptionIdentifiers?: number[]\n sessionExpiryInterval?: number\n assignedClientIdentifier?: string\n serverKeepAlive?: number\n authenticationMethod?: string\n authenticationData?: Uint8Array\n requestProblemInformation?: number\n willDelayInterval?: number\n requestResponseInformation?: number\n responseInformation?: string\n serverReference?: string\n reasonString?: string\n receiveMaximum?: number\n topicAliasMaximum?: number\n topicAlias?: number\n maximumQoS?: number\n retainAvailable?: number\n userProperties?: [string, string][]\n maximumPacketSize?: number\n wildcardSubscriptionAvailable?: number\n subscriptionIdentifierAvailable?: number\n sharedSubscriptionAvailable?: number\n}\n\ntype PropertyKind = \"byte\" | \"u16\" | \"u32\" | \"varint\" | \"utf8\" | \"binary\" | \"pair\"\n\nconst PROPERTY_TABLE: readonly [number, keyof Properties, PropertyKind][] = [\n [0x01, \"payloadFormatIndicator\", \"byte\"],\n [0x02, \"messageExpiryInterval\", \"u32\"],\n [0x03, \"contentType\", \"utf8\"],\n [0x08, \"responseTopic\", \"utf8\"],\n [0x09, \"correlationData\", \"binary\"],\n [0x0b, \"subscriptionIdentifiers\", \"varint\"],\n [0x11, \"sessionExpiryInterval\", \"u32\"],\n [0x12, \"assignedClientIdentifier\", \"utf8\"],\n [0x13, \"serverKeepAlive\", \"u16\"],\n [0x15, \"authenticationMethod\", \"utf8\"],\n [0x16, \"authenticationData\", \"binary\"],\n [0x17, \"requestProblemInformation\", \"byte\"],\n [0x18, \"willDelayInterval\", \"u32\"],\n [0x19, \"requestResponseInformation\", \"byte\"],\n [0x1a, \"responseInformation\", \"utf8\"],\n [0x1c, \"serverReference\", \"utf8\"],\n [0x1f, \"reasonString\", \"utf8\"],\n [0x21, \"receiveMaximum\", \"u16\"],\n [0x22, \"topicAliasMaximum\", \"u16\"],\n [0x23, \"topicAlias\", \"u16\"],\n [0x24, \"maximumQoS\", \"byte\"],\n [0x25, \"retainAvailable\", \"byte\"],\n [0x26, \"userProperties\", \"pair\"],\n [0x27, \"maximumPacketSize\", \"u32\"],\n [0x28, \"wildcardSubscriptionAvailable\", \"byte\"],\n [0x29, \"subscriptionIdentifierAvailable\", \"byte\"],\n [0x2a, \"sharedSubscriptionAvailable\", \"byte\"],\n]\nconst PROPERTY_BY_ID = new Map(PROPERTY_TABLE.map((row) => [row[0], row]))\n\nexport type QoS = 0 | 1 | 2\n\nexport type Will = {\n topic: string\n payload: Uint8Array\n qos: QoS\n retain: boolean\n properties: Properties\n}\n\nexport type SubscriptionRequest = {\n topicFilter: string\n qos: QoS\n noLocal: boolean\n retainAsPublished: boolean\n retainHandling: number\n}\n\nexport type ConnectPacket = {\n type: \"connect\"\n protocolName: string\n protocolVersion: number\n cleanStart: boolean\n keepAlive: number\n properties: Properties\n clientId: string\n will?: Will\n username?: string\n password?: Uint8Array\n}\nexport type ConnackPacket = {\n type: \"connack\"\n sessionPresent: boolean\n reasonCode: number\n properties: Properties\n}\nexport type PublishPacket = {\n type: \"publish\"\n topic: string\n payload: Uint8Array\n qos: QoS\n retain: boolean\n dup: boolean\n /** Present when `qos` is 1 or 2. */\n packetId?: number\n properties: Properties\n}\nexport type AckPacket = {\n type: \"puback\" | \"pubrec\" | \"pubrel\" | \"pubcomp\"\n packetId: number\n reasonCode: number\n properties: Properties\n}\nexport type SubscribePacket = {\n type: \"subscribe\"\n packetId: number\n properties: Properties\n subscriptions: SubscriptionRequest[]\n}\nexport type SubackPacket = {\n type: \"suback\" | \"unsuback\"\n packetId: number\n properties: Properties\n reasonCodes: number[]\n}\nexport type UnsubscribePacket = {\n type: \"unsubscribe\"\n packetId: number\n properties: Properties\n topicFilters: string[]\n}\nexport type PingPacket = { type: \"pingreq\" | \"pingresp\" }\nexport type DisconnectPacket = { type: \"disconnect\"; reasonCode: number; properties: Properties }\nexport type AuthPacket = { type: \"auth\"; reasonCode: number; properties: Properties }\n\nexport type Packet =\n | ConnectPacket\n | ConnackPacket\n | PublishPacket\n | AckPacket\n | SubscribePacket\n | SubackPacket\n | UnsubscribePacket\n | PingPacket\n | DisconnectPacket\n | AuthPacket\n\nconst TYPE_CODES: Record<Packet[\"type\"], number> = {\n connect: 1,\n connack: 2,\n publish: 3,\n puback: 4,\n pubrec: 5,\n pubrel: 6,\n pubcomp: 7,\n subscribe: 8,\n suback: 9,\n unsubscribe: 10,\n unsuback: 11,\n pingreq: 12,\n pingresp: 13,\n disconnect: 14,\n auth: 15,\n}\nconst TYPE_NAMES = Object.fromEntries(\n Object.entries(TYPE_CODES).map(([name, code]) => [code, name]),\n) as Record<number, Packet[\"type\"]>\n\n/** Largest value a Variable Byte Integer holds (1.5.5). */\nexport const MAX_VARIABLE_BYTE_INTEGER = 268_435_455\n\nconst utf8Encoder = new TextEncoder()\nconst utf8Decoder = new TextDecoder(\"utf-8\", { fatal: true })\n\n// \u2500\u2500 writing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass Writer {\n private chunks: Uint8Array[] = []\n private size = 0\n\n bytes(value: Uint8Array): this {\n this.chunks.push(value)\n this.size += value.length\n return this\n }\n byte(value: number): this {\n return this.bytes(Uint8Array.of(value & 0xff))\n }\n u16(value: number): this {\n return this.bytes(Uint8Array.of((value >>> 8) & 0xff, value & 0xff))\n }\n u32(value: number): this {\n return this.bytes(\n Uint8Array.of(\n (value >>> 24) & 0xff,\n (value >>> 16) & 0xff,\n (value >>> 8) & 0xff,\n value & 0xff,\n ),\n )\n }\n varint(value: number): this {\n if (!Number.isInteger(value) || value < 0 || value > MAX_VARIABLE_BYTE_INTEGER) {\n throw new RangeError(`variable byte integer out of range: ${value}`)\n }\n const out: number[] = []\n let rest = value\n do {\n let digit = rest % 128\n rest = Math.floor(rest / 128)\n if (rest > 0) digit |= 0x80\n out.push(digit)\n } while (rest > 0)\n return this.bytes(Uint8Array.from(out))\n }\n binary(value: Uint8Array): this {\n if (value.length > 0xffff) throw new RangeError(\"binary data longer than 65535 bytes\")\n return this.u16(value.length).bytes(value)\n }\n utf8(value: string): this {\n return this.binary(utf8Encoder.encode(value))\n }\n get length(): number {\n return this.size\n }\n concat(): Uint8Array {\n const out = new Uint8Array(this.size)\n let offset = 0\n for (const chunk of this.chunks) {\n out.set(chunk, offset)\n offset += chunk.length\n }\n return out\n }\n}\n\nconst writeProperties = (writer: Writer, properties: Properties): void => {\n const body = new Writer()\n for (const [id, name, kind] of PROPERTY_TABLE) {\n const value = properties[name]\n if (value === undefined) continue\n if (kind === \"pair\") {\n for (const [key, text] of value as [string, string][]) body.byte(id).utf8(key).utf8(text)\n } else if (name === \"subscriptionIdentifiers\") {\n for (const each of value as number[]) body.byte(id).varint(each)\n } else if (kind === \"byte\") body.byte(id).byte(value as number)\n else if (kind === \"u16\") body.byte(id).u16(value as number)\n else if (kind === \"u32\") body.byte(id).u32(value as number)\n else if (kind === \"utf8\") body.byte(id).utf8(value as string)\n else if (kind === \"binary\") body.byte(id).binary(value as Uint8Array)\n }\n writer.varint(body.length).bytes(body.concat())\n}\n\nconst hasProperties = (properties: Properties): boolean =>\n Object.values(properties).some(\n (value) => value !== undefined && !(Array.isArray(value) && value.length === 0),\n )\n\nconst frame = (type: Packet[\"type\"], flags: number, body: Writer): Uint8Array =>\n new Writer()\n .byte((TYPE_CODES[type] << 4) | flags)\n .varint(body.length)\n .bytes(body.concat())\n .concat()\n\n/** Encode one control packet, fixed header included. */\nexport const encodePacket = (packet: Packet): Uint8Array => {\n const body = new Writer()\n switch (packet.type) {\n case \"connect\": {\n body.utf8(packet.protocolName).byte(packet.protocolVersion)\n const will = packet.will\n body.byte(\n (packet.username !== undefined ? 0x80 : 0) |\n (packet.password !== undefined ? 0x40 : 0) |\n (will?.retain ? 0x20 : 0) |\n ((will?.qos ?? 0) << 3) |\n (will ? 0x04 : 0) |\n (packet.cleanStart ? 0x02 : 0),\n )\n body.u16(packet.keepAlive)\n writeProperties(body, packet.properties)\n body.utf8(packet.clientId)\n if (will) {\n writeProperties(body, will.properties)\n body.utf8(will.topic).binary(will.payload)\n }\n if (packet.username !== undefined) body.utf8(packet.username)\n if (packet.password !== undefined) body.binary(packet.password)\n return frame(\"connect\", 0, body)\n }\n case \"connack\":\n body.byte(packet.sessionPresent ? 1 : 0).byte(packet.reasonCode)\n writeProperties(body, packet.properties)\n return frame(\"connack\", 0, body)\n case \"publish\": {\n body.utf8(packet.topic)\n if (packet.qos > 0) body.u16(packet.packetId ?? 0)\n writeProperties(body, packet.properties)\n body.bytes(packet.payload)\n const flags = (packet.dup ? 0x08 : 0) | (packet.qos << 1) | (packet.retain ? 0x01 : 0)\n return frame(\"publish\", flags, body)\n }\n case \"puback\":\n case \"pubrec\":\n case \"pubrel\":\n case \"pubcomp\": {\n body.u16(packet.packetId)\n // 3.4.2.1: the Reason Code and Property Length may be omitted for Success with no properties.\n if (hasProperties(packet.properties)) {\n body.byte(packet.reasonCode)\n writeProperties(body, packet.properties)\n } else if (packet.reasonCode !== ReasonCode.Success) body.byte(packet.reasonCode)\n return frame(packet.type, packet.type === \"pubrel\" ? 0x02 : 0, body)\n }\n case \"subscribe\":\n body.u16(packet.packetId)\n writeProperties(body, packet.properties)\n for (const each of packet.subscriptions) {\n body\n .utf8(each.topicFilter)\n .byte(\n each.qos |\n (each.noLocal ? 0x04 : 0) |\n (each.retainAsPublished ? 0x08 : 0) |\n ((each.retainHandling & 0x03) << 4),\n )\n }\n return frame(\"subscribe\", 0x02, body)\n case \"suback\":\n case \"unsuback\":\n body.u16(packet.packetId)\n writeProperties(body, packet.properties)\n body.bytes(Uint8Array.from(packet.reasonCodes))\n return frame(packet.type, 0, body)\n case \"unsubscribe\":\n body.u16(packet.packetId)\n writeProperties(body, packet.properties)\n for (const filter of packet.topicFilters) body.utf8(filter)\n return frame(\"unsubscribe\", 0x02, body)\n case \"pingreq\":\n case \"pingresp\":\n return frame(packet.type, 0, body)\n case \"disconnect\":\n case \"auth\":\n // 3.14.2.1: both may be omitted for Normal disconnection with no properties.\n if (hasProperties(packet.properties)) {\n body.byte(packet.reasonCode)\n writeProperties(body, packet.properties)\n } else if (packet.reasonCode !== ReasonCode.Success) body.byte(packet.reasonCode)\n return frame(packet.type, 0, body)\n }\n}\n\n/**\n * The MQTT 3.1.1 CONNACK that refuses a protocol level this broker does not speak\n * (return code 0x01, \"unacceptable protocol version\"): a 3.x client cannot parse a v5 CONNACK.\n */\nexport const LEGACY_UNSUPPORTED_VERSION_CONNACK: Uint8Array = Uint8Array.of(0x20, 0x02, 0x00, 0x01)\n\n// \u2500\u2500 reading \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass Reader {\n private offset = 0\n constructor(private readonly data: Uint8Array) {}\n\n get remaining(): number {\n return this.data.length - this.offset\n }\n private take(length: number): Uint8Array {\n if (length > this.remaining) throw malformed(\"packet is shorter than its fields\")\n const slice = this.data.subarray(this.offset, this.offset + length)\n this.offset += length\n return slice\n }\n byte(): number {\n return this.take(1)[0] as number\n }\n u16(): number {\n const bytes = this.take(2)\n return ((bytes[0] as number) << 8) | (bytes[1] as number)\n }\n u32(): number {\n const bytes = this.take(4)\n return (\n (bytes[0] as number) * 0x1000000 +\n (((bytes[1] as number) << 16) | ((bytes[2] as number) << 8) | (bytes[3] as number))\n )\n }\n varint(): number {\n let value = 0\n let multiplier = 1\n for (let index = 0; index < 4; index++) {\n const digit = this.byte()\n value += (digit & 0x7f) * multiplier\n if ((digit & 0x80) === 0) return value\n multiplier *= 128\n }\n throw malformed(\"variable byte integer longer than four bytes\")\n }\n binary(): Uint8Array {\n return this.take(this.u16()).slice()\n }\n utf8(): string {\n let text: string\n try {\n text = utf8Decoder.decode(this.take(this.u16()))\n } catch {\n throw malformed(\"string is not well-formed UTF-8\")\n }\n // 1.5.4: a UTF-8 Encoded String must not include the null character.\n if (text.includes(\"\\u0000\")) throw malformed(\"string contains U+0000\")\n return text\n }\n rest(): Uint8Array {\n return this.take(this.remaining).slice()\n }\n sub(length: number): Reader {\n return new Reader(this.take(length))\n }\n}\n\nconst readProperties = (reader: Reader): Properties => {\n const scope = reader.sub(reader.varint())\n const properties: Properties = {}\n while (scope.remaining > 0) {\n const id = scope.varint()\n const row = PROPERTY_BY_ID.get(id)\n if (!row) throw malformed(`unknown property 0x${id.toString(16)}`)\n const [, name, kind] = row\n if (kind === \"pair\") {\n const list = properties.userProperties ?? []\n list.push([scope.utf8(), scope.utf8()])\n properties.userProperties = list\n continue\n }\n if (name === \"subscriptionIdentifiers\") {\n const list = properties.subscriptionIdentifiers ?? []\n const value = scope.varint()\n // 3.8.2.1.2: a Subscription Identifier of 0 is a Protocol Error.\n if (value === 0) throw protocolError(\"subscription identifier 0\")\n list.push(value)\n properties.subscriptionIdentifiers = list\n continue\n }\n // 2.2.2.2: including any other property more than once is a Protocol Error.\n if (properties[name] !== undefined) throw protocolError(`duplicate property ${name}`)\n const value =\n kind === \"byte\"\n ? scope.byte()\n : kind === \"u16\"\n ? scope.u16()\n : kind === \"u32\"\n ? scope.u32()\n : kind === \"utf8\"\n ? scope.utf8()\n : scope.binary()\n ;(properties as Record<string, unknown>)[name] = value\n }\n return properties\n}\n\nconst requireFlags = (type: string, flags: number, expected: number): void => {\n // 2.1.3: a reserved flag with any other value is a Malformed Packet.\n if (flags !== expected) throw malformed(`${type} fixed header flags must be ${expected}`)\n}\n\nconst decodeBody = (type: Packet[\"type\"], flags: number, body: Reader): Packet => {\n switch (type) {\n case \"connect\": {\n requireFlags(type, flags, 0)\n const protocolName = body.utf8()\n const protocolVersion = body.byte()\n // 3.1.2.1 / 3.1.2.2: the rest is only defined for the protocol this codec speaks. The\n // caller refuses any other name or level, so nothing after the level is read.\n if (protocolName !== \"MQTT\" || protocolVersion !== 5) {\n return {\n type,\n protocolName,\n protocolVersion,\n cleanStart: false,\n keepAlive: 0,\n properties: {},\n clientId: \"\",\n }\n }\n const connectFlags = body.byte()\n // 3.1.2.3: the reserved bit must be 0.\n if (connectFlags & 0x01) throw malformed(\"CONNECT reserved flag is set\")\n const willFlag = (connectFlags & 0x04) !== 0\n const willQos = (connectFlags >> 3) & 0x03\n const willRetain = (connectFlags & 0x20) !== 0\n if (willQos === 3) throw malformed(\"Will QoS 3\")\n if (!willFlag && (willQos !== 0 || willRetain)) throw malformed(\"Will flags without a Will\")\n const keepAlive = body.u16()\n const properties = readProperties(body)\n const clientId = body.utf8()\n const packet: ConnectPacket = {\n type,\n protocolName,\n protocolVersion,\n cleanStart: (connectFlags & 0x02) !== 0,\n keepAlive,\n properties,\n clientId,\n }\n if (willFlag) {\n const willProperties = readProperties(body)\n const topic = body.utf8()\n packet.will = {\n topic,\n payload: body.binary(),\n qos: willQos as QoS,\n retain: willRetain,\n properties: willProperties,\n }\n }\n if (connectFlags & 0x80) packet.username = body.utf8()\n if (connectFlags & 0x40) packet.password = body.binary()\n if (body.remaining > 0) throw malformed(\"CONNECT has trailing bytes\")\n return packet\n }\n case \"connack\": {\n requireFlags(type, flags, 0)\n const acknowledgeFlags = body.byte()\n if (acknowledgeFlags & 0xfe) throw malformed(\"CONNACK reserved flags are set\")\n const reasonCode = body.byte()\n return {\n type,\n sessionPresent: acknowledgeFlags === 1,\n reasonCode,\n properties: readProperties(body),\n }\n }\n case \"publish\": {\n const qos = (flags >> 1) & 0x03\n // 3.3.1.2: both QoS bits set is a Malformed Packet.\n if (qos === 3) throw malformed(\"PUBLISH QoS 3\")\n const dup = (flags & 0x08) !== 0\n // 3.3.1.1: DUP must be 0 for QoS 0.\n if (qos === 0 && dup) throw malformed(\"PUBLISH DUP set at QoS 0\")\n const topic = body.utf8()\n const packetId = qos > 0 ? body.u16() : undefined\n // 2.2.1: a QoS > 0 PUBLISH needs a non-zero Packet Identifier.\n if (packetId === 0) throw protocolError(\"PUBLISH packet identifier 0\")\n const properties = readProperties(body)\n return {\n type,\n topic,\n payload: body.rest(),\n qos: qos as QoS,\n retain: (flags & 0x01) !== 0,\n dup,\n ...(packetId !== undefined ? { packetId } : {}),\n properties,\n }\n }\n case \"puback\":\n case \"pubrec\":\n case \"pubrel\":\n case \"pubcomp\": {\n requireFlags(type, flags, type === \"pubrel\" ? 0x02 : 0)\n const packetId = body.u16()\n const reasonCode = body.remaining > 0 ? body.byte() : ReasonCode.Success\n const properties = body.remaining > 0 ? readProperties(body) : {}\n return { type, packetId, reasonCode, properties }\n }\n case \"subscribe\": {\n requireFlags(type, flags, 0x02)\n const packetId = body.u16()\n if (packetId === 0) throw protocolError(\"SUBSCRIBE packet identifier 0\")\n const properties = readProperties(body)\n const subscriptions: SubscriptionRequest[] = []\n while (body.remaining > 0) {\n const topicFilter = body.utf8()\n const options = body.byte()\n // 3.8.3.1: reserved bits must be 0; QoS 3 and Retain Handling 3 are not defined.\n if (options & 0xc0) throw malformed(\"SUBSCRIBE reserved option bits are set\")\n if ((options & 0x03) === 3) throw malformed(\"SUBSCRIBE QoS 3\")\n const retainHandling = (options >> 4) & 0x03\n if (retainHandling === 3) throw protocolError(\"SUBSCRIBE Retain Handling 3\")\n subscriptions.push({\n topicFilter,\n qos: (options & 0x03) as QoS,\n noLocal: (options & 0x04) !== 0,\n retainAsPublished: (options & 0x08) !== 0,\n retainHandling,\n })\n }\n // 3.8.3: a SUBSCRIBE with no payload is a Protocol Error.\n if (subscriptions.length === 0) throw protocolError(\"SUBSCRIBE without a topic filter\")\n return { type, packetId, properties, subscriptions }\n }\n case \"suback\":\n case \"unsuback\": {\n requireFlags(type, flags, 0)\n const packetId = body.u16()\n const properties = readProperties(body)\n return { type, packetId, properties, reasonCodes: [...body.rest()] }\n }\n case \"unsubscribe\": {\n requireFlags(type, flags, 0x02)\n const packetId = body.u16()\n if (packetId === 0) throw protocolError(\"UNSUBSCRIBE packet identifier 0\")\n const properties = readProperties(body)\n const topicFilters: string[] = []\n while (body.remaining > 0) topicFilters.push(body.utf8())\n // 3.10.3: an UNSUBSCRIBE with no payload is a Protocol Error.\n if (topicFilters.length === 0) throw protocolError(\"UNSUBSCRIBE without a topic filter\")\n return { type, packetId, properties, topicFilters }\n }\n case \"pingreq\":\n case \"pingresp\":\n requireFlags(type, flags, 0)\n if (body.remaining > 0) throw malformed(`${type} has a body`)\n return { type }\n case \"disconnect\":\n case \"auth\": {\n requireFlags(type, flags, 0)\n const reasonCode = body.remaining > 0 ? body.byte() : ReasonCode.Success\n const properties = body.remaining > 0 ? readProperties(body) : {}\n return { type, reasonCode, properties }\n }\n }\n}\n\n/** Decode exactly one control packet. Throws {@link MqttProtocolError} when it is not one. */\nexport const decodePacket = (bytes: Uint8Array): Packet => {\n const reader = new Reader(bytes)\n const first = reader.byte()\n const type = TYPE_NAMES[first >> 4]\n // 2.1.2: packet type 0 is reserved.\n if (!type) throw malformed(\"reserved control packet type 0\")\n const body = reader.sub(reader.varint())\n if (reader.remaining > 0) throw malformed(\"bytes after the packet\")\n return decodeBody(type, first & 0x0f, body)\n}\n\n/**\n * Length of the first packet in `buffer` (fixed header included), or `undefined` when the\n * fixed header is not complete yet.\n */\nconst packetLength = (buffer: Uint8Array): number | undefined => {\n let value = 0\n let multiplier = 1\n for (let index = 1; index <= 4; index++) {\n const digit = buffer[index]\n if (digit === undefined) return undefined\n value += (digit & 0x7f) * multiplier\n if ((digit & 0x80) === 0) return index + 1 + value\n multiplier *= 128\n }\n throw malformed(\"remaining length longer than four bytes\")\n}\n\n/**\n * Reassembles control packets from a byte stream, in whatever chunks the transport delivers.\n * Chunks are held as they come and each packet's bytes are copied once, when it is complete,\n * so a large packet in many small chunks costs time linear in its size.\n */\nexport class PacketReader {\n private chunks: Uint8Array[] = []\n /** Bytes of `chunks[0]` already consumed. */\n private head = 0\n /** Bytes held and not yet consumed. */\n private buffered = 0\n\n /** `maxPacketSize` is the Maximum Packet Size this endpoint advertised (3.2.2.3.6). */\n constructor(private readonly maxPacketSize: number = MAX_VARIABLE_BYTE_INTEGER + 5) {}\n\n /**\n * The complete packets `chunk` finishes, as raw bytes and decoded. A packet that cannot be\n * decoded stops the stream: its error is returned after the packets before it.\n */\n push(chunk: Uint8Array): { packets: Packet[]; error?: MqttProtocolError } {\n if (chunk.length > 0) {\n this.chunks.push(chunk)\n this.buffered += chunk.length\n }\n const packets: Packet[] = []\n try {\n for (;;) {\n const length = packetLength(this.peek(5))\n if (length === undefined) break\n if (length > this.maxPacketSize) {\n throw new MqttProtocolError(ReasonCode.PacketTooLarge, `packet of ${length} bytes`)\n }\n if (this.buffered < length) break\n packets.push(decodePacket(this.take(length)))\n }\n } catch (error) {\n this.chunks = []\n this.head = 0\n this.buffered = 0\n if (error instanceof MqttProtocolError) return { packets, error }\n throw error\n }\n return { packets }\n }\n\n /** Up to the first `count` held bytes, without consuming them. */\n private peek(count: number): Uint8Array {\n const bytes: number[] = []\n let skip = this.head\n for (const chunk of this.chunks) {\n for (let index = skip; index < chunk.length && bytes.length < count; index++) {\n bytes.push(chunk[index] ?? 0)\n }\n if (bytes.length === count) break\n skip = 0\n }\n return Uint8Array.from(bytes)\n }\n\n /** Consume the first `length` held bytes into a fresh array (decoded packets keep views of it). */\n private take(length: number): Uint8Array {\n const out = new Uint8Array(length)\n let filled = 0\n let used = 0\n while (filled < length) {\n const chunk = this.chunks[used]\n if (!chunk) break\n const count = Math.min(chunk.length - this.head, length - filled)\n out.set(chunk.subarray(this.head, this.head + count), filled)\n filled += count\n this.head += count\n if (this.head === chunk.length) {\n used += 1\n this.head = 0\n }\n }\n // One splice per packet: shifting chunk by chunk would be quadratic in the chunk count.\n this.chunks.splice(0, used)\n this.buffered -= length\n return out\n }\n}\n", "/**\n * What every MQTT emulator's runtime needs around its brokers, written once: the admin routes\n * that inspect and steer a broker, a clock that settles expiries when a suite moves it, CONNECT\n * faults, and how a transport finds its namespace.\n */\nimport {\n type AdminRoutes,\n type Clock,\n type CredentialRegistry,\n DEFAULT_NAMESPACE,\n type FaultPreset,\n type FaultRegistry,\n fromBase64,\n matchNamespacePath,\n} from \"@crvouga/mockingbird-service\"\nimport type { Broker } from \"./broker.js\"\nimport type { ConnectPacket } from \"./codec.js\"\n\n/** The path MQTT over WebSocket is served on (EMQX's `mqtt_path`, AWS IoT's `/mqtt`). */\nexport const MQTT_WEBSOCKET_PATH = \"/mqtt\"\n\n/**\n * What an MQTT CONNECT is called in fault rules, since it is not an HTTP operation:\n * `POST /__admin/faults {\"operationId\": \"MqttConnect\", \"effect\": \"connack\", \"params\": {\"reasonCode\": 135}}`.\n */\nexport const MQTT_CONNECT_OPERATION = \"MqttConnect\"\n\n/** A fault preset that refuses CONNECT with `reasonCode`. */\nexport const connackPreset = (reasonCode: number, description: string): FaultPreset => ({\n description,\n rules: [{ operationId: MQTT_CONNECT_OPERATION, effect: \"connack\", params: { reasonCode } }],\n})\n\n/**\n * The reason code a fault rule armed for the next CONNECT in `namespace`, if any. Consumes one\n * use of each matching rule, as an HTTP request does.\n */\nexport const takeConnackFault = async (\n faults: FaultRegistry,\n namespace: string,\n): Promise<number | undefined> => {\n const hits = await faults.take({\n operationId: MQTT_CONNECT_OPERATION,\n method: \"CONNECT\",\n path: MQTT_WEBSOCKET_PATH,\n namespace,\n })\n for (const hit of hits) {\n const code = hit.effect?.name === \"connack\" ? hit.effect.params.reasonCode : undefined\n if (typeof code === \"number\") return code\n }\n return undefined\n}\n\n/** A clock that reports every jump, so expiries are settled the moment a suite moves time. */\nexport const observeClock = (clock: Clock, moved: () => void): Clock => ({\n now: clock.now,\n state: clock.state,\n freeze: clock.freeze,\n set: (epochMs) => {\n clock.set(epochMs)\n moved()\n },\n advance: (deltaMs) => {\n clock.advance(deltaMs)\n moved()\n },\n unfreeze: () => {\n clock.unfreeze()\n moved()\n },\n reset: () => {\n clock.reset()\n moved()\n },\n})\n\n/**\n * Whether an HTTP path is the MQTT WebSocket endpoint: `/mqtt`, or `<adminPrefix>/ns/<name>/mqtt`\n * to select a namespace. `undefined` when it is neither.\n */\nexport const webSocketNamespace = (\n pathname: string,\n adminPrefix: string,\n): { namespace: string | undefined } | undefined => {\n const prefixed = matchNamespacePath(pathname, adminPrefix)\n if ((prefixed ? prefixed[2] : pathname) !== MQTT_WEBSOCKET_PATH) return undefined\n return { namespace: prefixed ? decodeURIComponent(prefixed[1] as string) : undefined }\n}\n\n/**\n * The namespace a CONNECT belongs to when its transport named none: the one\n * `PUT /__admin/credentials` maps its username to, then its client identifier, then the default.\n */\nexport const connectNamespace = (\n credentials: CredentialRegistry,\n connect: Pick<ConnectPacket, \"username\" | \"clientId\">,\n username: string | undefined = connect.username,\n): string =>\n (username !== undefined ? credentials.get(username) : undefined) ??\n credentials.get(connect.clientId) ??\n DEFAULT_NAMESPACE\n\nconst json = (status: number, body: unknown) =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\nconst adminError = (status: number, message: string) =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\n/**\n * Admin routes over one namespace's broker: inspect clients, subscriptions and publish\n * metadata; inject raw payloads; cut and restore the transport; force a disconnect.\n */\nexport const brokerAdminRoutes = (brokerOf: (namespace: string) => Broker): AdminRoutes => {\n /** `undefined`: every client. `null`: not a client identifier. */\n const target = (body: unknown): string | undefined | null =>\n !isRecord(body) || body.clientId === undefined\n ? undefined\n : typeof body.clientId === \"string\" && body.clientId !== \"\"\n ? body.clientId\n : null\n return {\n \"GET /clients\": ({ namespace }) => json(200, { clients: brokerOf(namespace).clients() }),\n \"GET /clients/:clientId\": ({ params, namespace }) => {\n const broker = brokerOf(namespace)\n const client = broker.clients().find((each) => each.clientId === params.clientId)\n if (!client) return adminError(404, `no client ${params.clientId}`)\n return json(200, { ...client, topics: broker.subscriptionList(client.clientId) })\n },\n \"POST /clients/:clientId/disconnect\": ({ params, body, namespace }) => {\n const reasonCode = isRecord(body) ? body.reasonCode : undefined\n const valid =\n reasonCode === undefined ||\n (typeof reasonCode === \"number\" &&\n Number.isInteger(reasonCode) &&\n reasonCode >= 0 &&\n reasonCode <= 0xff)\n if (!valid) return adminError(400, \"reasonCode: an MQTT reason code, 0 to 255\")\n return brokerOf(namespace).disconnect(params.clientId as string, reasonCode)\n ? json(200, { disconnected: params.clientId })\n : adminError(404, `client ${params.clientId} is not connected`)\n },\n \"GET /subscriptions\": ({ url, namespace }) =>\n json(200, {\n subscriptions: brokerOf(namespace).subscriptionList(\n url.searchParams.get(\"clientId\") ?? undefined,\n ),\n }),\n \"GET /publishes\": ({ namespace }) => {\n const broker = brokerOf(namespace)\n return json(200, { total: broker.publishCount(), publishes: broker.publishLog() })\n },\n \"POST /inject\": ({ body, namespace }) => {\n if (!isRecord(body) || typeof body.topic !== \"string\" || body.topic === \"\") {\n return adminError(400, 'expected {\"topic\", \"payload\" | \"payloadBase64\", \"qos\"?}')\n }\n let payload: Uint8Array\n if (typeof body.payloadBase64 === \"string\") {\n try {\n payload = fromBase64(body.payloadBase64)\n } catch {\n return adminError(400, \"payloadBase64: not base64\")\n }\n } else if (typeof body.payload === \"string\") payload = new TextEncoder().encode(body.payload)\n else return adminError(400, \"payload: a string, or payloadBase64 for raw bytes\")\n const qos = body.qos ?? 1\n if (qos !== 0 && qos !== 1) return adminError(400, \"qos: 0 or 1\")\n const matched = brokerOf(namespace).publish({ topic: body.topic, payload, qos }, \"admin\")\n return json(200, { matched })\n },\n \"GET /transport\": ({ namespace }) => json(200, { cut: brokerOf(namespace).transportCuts() }),\n \"POST /transport/cut\": ({ body, namespace }) => {\n const clientId = target(body)\n if (clientId === null) return adminError(400, \"clientId: a client identifier, or omit it\")\n const broker = brokerOf(namespace)\n const dropped = broker.cutTransport(clientId)\n return json(200, { cut: broker.transportCuts(), dropped })\n },\n \"POST /transport/restore\": ({ body, namespace }) => {\n const clientId = target(body)\n if (clientId === null) return adminError(400, \"clientId: a client identifier, or omit it\")\n const broker = brokerOf(namespace)\n broker.restoreTransport(clientId)\n return json(200, { cut: broker.transportCuts() })\n },\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;AAIO,IAAM,aAAa;;EAExB,SAAS;EACT,aAAa;EACb,aAAa;EACb,uBAAuB;EACvB,uBAAuB;EACvB,kBAAkB;EAClB,iBAAiB;EACjB,eAAe;EACf,6BAA6B;EAC7B,4BAA4B;EAC5B,0BAA0B;EAC1B,uBAAuB;EACvB,eAAe;EACf,mBAAmB;EACnB,YAAY;EACZ,QAAQ;EACR,oBAAoB;EACpB,yBAAyB;EACzB,kBAA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M,WAAW,OAAO,IAAI;AAC5B,UAAI,aAAa;AAAM,eAAO,WAAW,KAAK,2CAA2C;AACzF,YAAM,SAAS,SAAS,SAAS;AACjC,YAAM,UAAU,OAAO,aAAa,QAAQ;AAC5C,aAAO,KAAK,KAAK,EAAE,KAAK,OAAO,cAAa,GAAI,QAAO,CAAE;IAC3D;IACA,2BAA2B,CAAC,EAAE,MAAM,UAAS,MAAM;AACjD,YAAM,WAAW,OAAO,IAAI;AAC5B,UAAI,aAAa;AAAM,eAAO,WAAW,KAAK,2CAA2C;AACzF,YAAM,SAAS,SAAS,SAAS;AACjC,aAAO,iBAAiB,QAAQ;AAChC,aAAO,KAAK,KAAK,EAAE,KAAK,OAAO,cAAa,EAAE,CAAE;IAClD;;AAEJ;",
6
+ "names": ["value"]
7
+ }
@@ -0,0 +1,198 @@
1
+ // src/preview/bridge.ts
2
+ var protocol = "mockingbird-preview/1";
3
+ var message = (error) => error instanceof Error ? error.message : String(error);
4
+ function createPreviewClient(port, options = {}) {
5
+ const pending = /* @__PURE__ */ new Set();
6
+ let disposed = false;
7
+ port.start();
8
+ const fetch = async (input, init) => {
9
+ if (disposed) throw new Error("Preview client disposed");
10
+ const request = new Request(input, init);
11
+ request.signal.throwIfAborted();
12
+ const body = request.body ? await request.arrayBuffer() : void 0;
13
+ request.signal.throwIfAborted();
14
+ if (disposed) throw new Error("Preview client disposed");
15
+ return new Promise((resolve, reject) => {
16
+ const channel = new MessageChannel();
17
+ let stream;
18
+ let done = false;
19
+ const finish = () => {
20
+ if (done) return;
21
+ done = true;
22
+ clearTimeout(timer);
23
+ pending.delete(fail);
24
+ request.signal.removeEventListener("abort", abort);
25
+ channel.port1.close();
26
+ channel.port2.close();
27
+ };
28
+ const fail = (reason) => {
29
+ if (done) return;
30
+ channel.port1.postMessage({ type: "cancel", error: reason.message });
31
+ stream?.error(reason);
32
+ reject(reason);
33
+ finish();
34
+ };
35
+ const abort = () => fail(new Error(message(request.signal.reason)));
36
+ const timer = setTimeout(
37
+ () => fail(new Error("Preview request deadline exceeded")),
38
+ options.timeoutMs ?? 3e4
39
+ );
40
+ pending.add(fail);
41
+ request.signal.addEventListener("abort", abort, { once: true });
42
+ channel.port1.onmessage = ({ data }) => {
43
+ if (done) return;
44
+ if (data.type === "headers") {
45
+ try {
46
+ const responseBody = data.body ? new ReadableStream(
47
+ {
48
+ start(controller) {
49
+ stream = controller;
50
+ },
51
+ pull() {
52
+ channel.port1.postMessage({ type: "pull" });
53
+ },
54
+ cancel(reason) {
55
+ fail(new Error(message(reason ?? "Response cancelled")));
56
+ }
57
+ },
58
+ { highWaterMark: 0 }
59
+ ) : null;
60
+ resolve(
61
+ new Response(responseBody, {
62
+ status: data.status,
63
+ statusText: data.statusText,
64
+ headers: data.headers
65
+ })
66
+ );
67
+ if (!data.body) finish();
68
+ } catch (error) {
69
+ fail(new Error(message(error)));
70
+ }
71
+ } else if (data.type === "chunk") stream?.enqueue(new Uint8Array(data.bytes));
72
+ else if (data.type === "end") {
73
+ stream?.close();
74
+ finish();
75
+ } else if (data.type === "error") fail(new Error(data.error));
76
+ };
77
+ channel.port1.onmessageerror = () => fail(new Error("Invalid preview response"));
78
+ try {
79
+ port.postMessage(
80
+ {
81
+ protocol,
82
+ type: "fetch",
83
+ url: request.url,
84
+ method: request.method,
85
+ headers: [...request.headers],
86
+ body,
87
+ port: channel.port2
88
+ },
89
+ body ? [channel.port2, body] : [channel.port2]
90
+ );
91
+ } catch (error) {
92
+ fail(new Error(message(error)));
93
+ }
94
+ });
95
+ };
96
+ return {
97
+ fetch,
98
+ dispose(reason = new Error("Preview client disposed")) {
99
+ if (disposed) return;
100
+ disposed = true;
101
+ for (const fail of pending) fail(reason);
102
+ port.postMessage({ protocol, type: "disconnect" });
103
+ port.close();
104
+ }
105
+ };
106
+ }
107
+ function attachPreviewHost(port, fetch, options = {}) {
108
+ let disposed = false;
109
+ const active = /* @__PURE__ */ new Set();
110
+ const receive = (event) => {
111
+ const data = event.data;
112
+ if (data?.protocol !== protocol) return;
113
+ if (data.type === "disconnect") {
114
+ dispose();
115
+ return;
116
+ }
117
+ if (data.type !== "fetch" || !data.port) return;
118
+ const reply = data.port;
119
+ const abort = new AbortController();
120
+ let reader;
121
+ let ended = false;
122
+ const stop = (cancel = true) => {
123
+ if (ended) return;
124
+ ended = true;
125
+ if (cancel) {
126
+ reply.postMessage({ type: "error", error: "Preview request disconnected" });
127
+ abort.abort(new Error("Preview request disconnected"));
128
+ void reader?.cancel().catch(() => void 0);
129
+ } else reader?.releaseLock();
130
+ active.delete(stop);
131
+ reply.close();
132
+ };
133
+ active.add(stop);
134
+ const fail = (error) => {
135
+ if (!ended) reply.postMessage({ type: "error", error: message(error) });
136
+ stop();
137
+ };
138
+ reply.onmessage = ({ data: command }) => {
139
+ if (command.type === "cancel") stop();
140
+ if (command.type === "pull" && reader && !ended) {
141
+ void reader.read().then(({ done, value }) => {
142
+ if (ended) return;
143
+ if (done) {
144
+ reply.postMessage({ type: "end" });
145
+ stop(false);
146
+ } else {
147
+ const bytes = new Uint8Array(value).buffer;
148
+ reply.postMessage({ type: "chunk", bytes }, [bytes]);
149
+ }
150
+ }, fail);
151
+ }
152
+ };
153
+ reply.onmessageerror = () => fail(new Error("Invalid preview request"));
154
+ void Promise.resolve().then(
155
+ () => fetch(
156
+ new Request(data.url, {
157
+ method: data.method,
158
+ headers: data.headers,
159
+ ...data.body ? { body: data.body } : {},
160
+ signal: abort.signal,
161
+ redirect: "manual",
162
+ credentials: "omit"
163
+ })
164
+ )
165
+ ).then(async (response) => {
166
+ if (ended) {
167
+ await response.body?.cancel();
168
+ return;
169
+ }
170
+ reader = response.body?.getReader();
171
+ reply.postMessage({
172
+ type: "headers",
173
+ status: response.status,
174
+ statusText: response.statusText,
175
+ headers: [...response.headers],
176
+ body: !!reader
177
+ });
178
+ if (!reader) stop(false);
179
+ }).catch(fail);
180
+ };
181
+ const dispose = () => {
182
+ if (disposed) return;
183
+ disposed = true;
184
+ port.removeEventListener("message", receive);
185
+ for (const stop of active) stop();
186
+ port.close();
187
+ options.onDisconnect?.();
188
+ };
189
+ port.addEventListener("message", receive);
190
+ port.start();
191
+ return { dispose };
192
+ }
193
+
194
+ export {
195
+ createPreviewClient,
196
+ attachPreviewHost
197
+ };
198
+ //# sourceMappingURL=chunk-EBGYPQPA.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/preview/bridge.ts"],
4
+ "sourcesContent": ["import type { FetchHandler, WebFetch } from \"./types.js\"\n\n/** MessagePort subset shared by browsers and node:worker_threads. */\nexport type PreviewPort = Pick<\n MessagePort,\n \"postMessage\" | \"addEventListener\" | \"removeEventListener\" | \"start\" | \"close\"\n>\nconst protocol = \"mockingbird-preview/1\"\nconst message = (error: unknown) => (error instanceof Error ? error.message : String(error))\n\n/** One channel per request; response chunks are pulled, never buffered without bound. */\nexport function createPreviewClient(port: PreviewPort, options: { timeoutMs?: number } = {}) {\n const pending = new Set<(reason: Error) => void>()\n let disposed = false\n port.start()\n const fetch: WebFetch = async (input, init) => {\n if (disposed) throw new Error(\"Preview client disposed\")\n const request = new Request(input, init)\n request.signal.throwIfAborted()\n // Browser cookies are intentionally not inherited. Applications own cookie jars.\n const body = request.body ? await request.arrayBuffer() : undefined\n request.signal.throwIfAborted()\n if (disposed) throw new Error(\"Preview client disposed\")\n return new Promise<Response>((resolve, reject) => {\n const channel = new MessageChannel()\n let stream: ReadableStreamDefaultController<Uint8Array> | undefined\n let done = false\n const finish = () => {\n if (done) return\n done = true\n clearTimeout(timer)\n pending.delete(fail)\n request.signal.removeEventListener(\"abort\", abort)\n channel.port1.close()\n channel.port2.close()\n }\n const fail = (reason: Error) => {\n if (done) return\n channel.port1.postMessage({ type: \"cancel\", error: reason.message })\n stream?.error(reason)\n reject(reason)\n finish()\n }\n const abort = () => fail(new Error(message(request.signal.reason)))\n const timer = setTimeout(\n () => fail(new Error(\"Preview request deadline exceeded\")),\n options.timeoutMs ?? 30_000,\n )\n pending.add(fail)\n request.signal.addEventListener(\"abort\", abort, { once: true })\n channel.port1.onmessage = ({ data }) => {\n if (done) return\n if (data.type === \"headers\") {\n try {\n const responseBody = data.body\n ? new ReadableStream<Uint8Array>(\n {\n start(controller) {\n stream = controller\n },\n pull() {\n channel.port1.postMessage({ type: \"pull\" })\n },\n cancel(reason) {\n fail(new Error(message(reason ?? \"Response cancelled\")))\n },\n },\n { highWaterMark: 0 },\n )\n : null\n resolve(\n new Response(responseBody, {\n status: data.status,\n statusText: data.statusText,\n headers: data.headers,\n }),\n )\n if (!data.body) finish()\n } catch (error) {\n fail(new Error(message(error)))\n }\n } else if (data.type === \"chunk\") stream?.enqueue(new Uint8Array(data.bytes))\n else if (data.type === \"end\") {\n stream?.close()\n finish()\n } else if (data.type === \"error\") fail(new Error(data.error))\n }\n channel.port1.onmessageerror = () => fail(new Error(\"Invalid preview response\"))\n try {\n port.postMessage(\n {\n protocol,\n type: \"fetch\",\n url: request.url,\n method: request.method,\n headers: [...request.headers],\n body,\n port: channel.port2,\n },\n body ? [channel.port2, body] : [channel.port2],\n )\n } catch (error) {\n fail(new Error(message(error)))\n }\n })\n }\n return {\n fetch,\n dispose(reason = new Error(\"Preview client disposed\")) {\n if (disposed) return\n disposed = true\n for (const fail of pending) fail(reason)\n port.postMessage({ protocol, type: \"disconnect\" })\n port.close()\n },\n }\n}\n\n/** Attach each dedicated-worker or SharedWorker client port to the same handler. */\nexport function attachPreviewHost(\n port: PreviewPort,\n fetch: FetchHandler,\n options: { onDisconnect?: () => void } = {},\n) {\n let disposed = false\n const active = new Set<() => void>()\n const receive = (event: MessageEvent) => {\n const data = event.data\n if (data?.protocol !== protocol) return\n if (data.type === \"disconnect\") {\n dispose()\n return\n }\n if (data.type !== \"fetch\" || !data.port) return\n const reply = data.port as MessagePort\n const abort = new AbortController()\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined\n let ended = false\n const stop = (cancel = true) => {\n if (ended) return\n ended = true\n if (cancel) {\n reply.postMessage({ type: \"error\", error: \"Preview request disconnected\" })\n abort.abort(new Error(\"Preview request disconnected\"))\n void reader?.cancel().catch(() => undefined)\n } else reader?.releaseLock()\n active.delete(stop)\n reply.close()\n }\n active.add(stop)\n const fail = (error: unknown) => {\n if (!ended) reply.postMessage({ type: \"error\", error: message(error) })\n stop()\n }\n reply.onmessage = ({ data: command }) => {\n if (command.type === \"cancel\") stop()\n if (command.type === \"pull\" && reader && !ended) {\n void reader.read().then(({ done, value }) => {\n if (ended) return\n if (done) {\n reply.postMessage({ type: \"end\" })\n stop(false)\n } else {\n const bytes = new Uint8Array(value).buffer\n reply.postMessage({ type: \"chunk\", bytes }, [bytes])\n }\n }, fail)\n }\n }\n reply.onmessageerror = () => fail(new Error(\"Invalid preview request\"))\n void Promise.resolve()\n .then(() =>\n fetch(\n new Request(data.url, {\n method: data.method,\n headers: data.headers,\n ...(data.body ? { body: data.body } : {}),\n signal: abort.signal,\n redirect: \"manual\",\n credentials: \"omit\",\n }),\n ),\n )\n .then(async (response) => {\n if (ended) {\n await response.body?.cancel()\n return\n }\n reader = response.body?.getReader()\n reply.postMessage({\n type: \"headers\",\n status: response.status,\n statusText: response.statusText,\n headers: [...response.headers],\n body: !!reader,\n })\n if (!reader) stop(false)\n })\n .catch(fail)\n }\n const dispose = () => {\n if (disposed) return\n disposed = true\n port.removeEventListener(\"message\", receive as EventListener)\n for (const stop of active) stop()\n port.close()\n options.onDisconnect?.()\n }\n port.addEventListener(\"message\", receive as EventListener)\n port.start()\n return { dispose }\n}\n"],
5
+ "mappings": ";AAOA,IAAM,WAAW;AACjB,IAAM,UAAU,CAAC,UAAoB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAGnF,SAAS,oBAAoB,MAAmB,UAAkC,CAAC,GAAG;AAC3F,QAAM,UAAU,oBAAI,IAA6B;AACjD,MAAI,WAAW;AACf,OAAK,MAAM;AACX,QAAM,QAAkB,OAAO,OAAO,SAAS;AAC7C,QAAI,SAAU,OAAM,IAAI,MAAM,yBAAyB;A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}
@@ -0,0 +1,274 @@
1
+ import {
2
+ deref,
3
+ jsonTypeOf,
4
+ listOperations,
5
+ resolveSchema,
6
+ schemaTypes,
7
+ validateValue,
8
+ walkSchema
9
+ } from "./chunk-HU6IOAFC.js";
10
+
11
+ // ../openapi/metadata/dist/types.js
12
+ var VOLATILE_KINDS = ["id", "timestamp", "token", "url", "account", "opaque"];
13
+ var SCOPE_VALUES = ["run-id", "walk-start-unix", "walk-start-iso"];
14
+ var EXTENSION_KEYS = {
15
+ operation: "x-mockingbird",
16
+ resource: "x-mockingbird-resource",
17
+ resourceRef: "x-mockingbird-resource-ref",
18
+ volatile: "x-mockingbird-volatile",
19
+ scope: "x-mockingbird-scope",
20
+ unsupported: "x-mockingbird-unsupported",
21
+ parityHeader: "x-mockingbird-parity-header"
22
+ };
23
+
24
+ // ../openapi/metadata/dist/read.js
25
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
26
+ var extensionOf = (holder, key) => holder[key];
27
+ var operationMetadata = (operation) => {
28
+ const raw = extensionOf(operation, EXTENSION_KEYS.operation);
29
+ const ext = isRecord(raw) ? raw : {};
30
+ const supported = ext.supported ?? true;
31
+ const parity = ext.parity ?? {};
32
+ return {
33
+ ...ext.path === void 0 ? {} : { path: ext.path },
34
+ supported,
35
+ reason: typeof ext.reason === "string" ? ext.reason : void 0,
36
+ parity: {
37
+ enabled: supported && (parity.enabled ?? true),
38
+ safe: parity.safe ?? true,
39
+ reason: typeof parity.reason === "string" ? parity.reason : void 0
40
+ }
41
+ };
42
+ };
43
+ var readResource = (raw) => {
44
+ if (!isRecord(raw) || typeof raw.type !== "string" || raw.identity !== true)
45
+ return void 0;
46
+ return { type: raw.type, identity: true };
47
+ };
48
+ var readResourceRef = (raw) => {
49
+ if (!isRecord(raw) || typeof raw.type !== "string")
50
+ return void 0;
51
+ return { type: raw.type, ...typeof raw.missing === "string" ? { missing: raw.missing } : {} };
52
+ };
53
+ var readVolatile = (raw) => {
54
+ if (!isRecord(raw) || typeof raw.kind !== "string")
55
+ return void 0;
56
+ const kind = VOLATILE_KINDS.find((k) => k === raw.kind);
57
+ return kind === void 0 ? void 0 : { kind };
58
+ };
59
+ var readScope = (raw) => {
60
+ if (!isRecord(raw) || typeof raw.value !== "string")
61
+ return void 0;
62
+ const value = SCOPE_VALUES.find((v) => v === raw.value);
63
+ return value === void 0 ? void 0 : { value };
64
+ };
65
+ var readUnsupported = (raw) => {
66
+ if (raw === true)
67
+ return { reason: void 0 };
68
+ if (isRecord(raw))
69
+ return { reason: typeof raw.reason === "string" ? raw.reason : void 0 };
70
+ return void 0;
71
+ };
72
+ var schemaMetadata = (holder) => ({
73
+ resource: readResource(extensionOf(holder, EXTENSION_KEYS.resource)),
74
+ resourceRef: readResourceRef(extensionOf(holder, EXTENSION_KEYS.resourceRef)),
75
+ volatile: readVolatile(extensionOf(holder, EXTENSION_KEYS.volatile)),
76
+ scope: readScope(extensionOf(holder, EXTENSION_KEYS.scope)),
77
+ unsupported: readUnsupported(extensionOf(holder, EXTENSION_KEYS.unsupported))
78
+ });
79
+ var parameterMetadata = (document, parameter) => {
80
+ const own = schemaMetadata(parameter);
81
+ const fromSchema = parameter.schema ? schemaMetadata(resolveSchema(document, parameter.schema)) : void 0;
82
+ return {
83
+ resource: own.resource ?? fromSchema?.resource,
84
+ resourceRef: own.resourceRef ?? fromSchema?.resourceRef,
85
+ volatile: own.volatile ?? fromSchema?.volatile,
86
+ scope: own.scope ?? fromSchema?.scope,
87
+ unsupported: own.unsupported ?? fromSchema?.unsupported
88
+ };
89
+ };
90
+ var parityHeaders = (document, response) => {
91
+ const names = [];
92
+ for (const [name, raw] of Object.entries(response.headers ?? {})) {
93
+ const header = deref(document, raw);
94
+ if (extensionOf(header, EXTENSION_KEYS.parityHeader) === true)
95
+ names.push(name.toLowerCase());
96
+ }
97
+ return names.sort();
98
+ };
99
+
100
+ // ../openapi/metadata/dist/annotate.js
101
+ var typeMatches = (schema, value) => {
102
+ const types = schemaTypes(schema);
103
+ if (types.length === 0)
104
+ return true;
105
+ const actual = jsonTypeOf(value);
106
+ return types.some((t) => t === actual || t === "number" && actual === "integer");
107
+ };
108
+ var selectBranch = (document, branches, value) => {
109
+ const resolved = branches.map((b) => resolveSchema(document, b));
110
+ const valid = resolved.find((b) => validateValue(document, b, value).length === 0);
111
+ if (valid)
112
+ return valid;
113
+ return resolved.find((b) => typeMatches(b, value));
114
+ };
115
+ var annotateValue = (document, schema, value, path = []) => {
116
+ const out = [];
117
+ const go = (node, current, at, depth) => {
118
+ if (depth > 64)
119
+ return;
120
+ const resolved = resolveSchema(document, node);
121
+ const meta = schemaMetadata(resolved);
122
+ if (meta.resource && typeof current === "string")
123
+ out.push({ kind: "identity", path: at, type: meta.resource.type });
124
+ else if (meta.volatile && current !== void 0) {
125
+ out.push({ kind: "volatile", path: at, volatile: meta.volatile.kind });
126
+ }
127
+ if (resolved.allOf)
128
+ for (const branch of resolved.allOf)
129
+ go(branch, current, at, depth + 1);
130
+ const union = resolved.oneOf ?? resolved.anyOf;
131
+ if (union) {
132
+ const branch = selectBranch(document, union, current);
133
+ if (branch)
134
+ go(branch, current, at, depth + 1);
135
+ }
136
+ if (Array.isArray(current)) {
137
+ current.forEach((item, index) => {
138
+ const itemSchema = resolved.prefixItems?.[index] ?? resolved.items;
139
+ if (itemSchema)
140
+ go(itemSchema, item, [...at, index], depth + 1);
141
+ });
142
+ return;
143
+ }
144
+ if (typeof current === "object" && current !== null) {
145
+ for (const [key, item] of Object.entries(current)) {
146
+ const property = resolved.properties?.[key];
147
+ if (property)
148
+ go(property, item, [...at, key], depth + 1);
149
+ else if (typeof resolved.additionalProperties === "object") {
150
+ go(resolved.additionalProperties, item, [...at, key], depth + 1);
151
+ }
152
+ }
153
+ }
154
+ };
155
+ go(schema, value, path, 0);
156
+ return out;
157
+ };
158
+ var pathKey = (path) => path.map((segment) => JSON.stringify(segment)).join(".");
159
+
160
+ // ../openapi/metadata/dist/validate.js
161
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
162
+ var validateMetadata = (document) => {
163
+ const issues = [];
164
+ const producedTypes = /* @__PURE__ */ new Set();
165
+ const referencedTypes = /* @__PURE__ */ new Map();
166
+ const inspectSchema = (schema, at) => {
167
+ const raw = schema;
168
+ for (const key of [
169
+ EXTENSION_KEYS.resource,
170
+ EXTENSION_KEYS.resourceRef,
171
+ EXTENSION_KEYS.volatile,
172
+ EXTENSION_KEYS.scope
173
+ ]) {
174
+ if (key in raw && !isRecord2(raw[key]))
175
+ issues.push(`${at}: ${key} must be an object`);
176
+ }
177
+ const meta = schemaMetadata(schema);
178
+ if (isRecord2(raw[EXTENSION_KEYS.resource]) && !meta.resource)
179
+ issues.push(`${at}: ${EXTENSION_KEYS.resource} needs { type, identity: true }`);
180
+ if (isRecord2(raw[EXTENSION_KEYS.resourceRef]) && !meta.resourceRef)
181
+ issues.push(`${at}: ${EXTENSION_KEYS.resourceRef} needs { type }`);
182
+ if (isRecord2(raw[EXTENSION_KEYS.volatile]) && !meta.volatile)
183
+ issues.push(`${at}: ${EXTENSION_KEYS.volatile} has an unknown kind`);
184
+ if (isRecord2(raw[EXTENSION_KEYS.scope]) && !meta.scope)
185
+ issues.push(`${at}: ${EXTENSION_KEYS.scope} has an unknown value`);
186
+ const types = schemaTypes(resolveSchema(document, schema)).filter((t) => t !== "null");
187
+ if (meta.resource) {
188
+ producedTypes.add(meta.resource.type);
189
+ if (types.length > 0 && !types.includes("string"))
190
+ issues.push(`${at}: resource identities must be strings`);
191
+ }
192
+ if (meta.resourceRef) {
193
+ referencedTypes.set(meta.resourceRef.type, at);
194
+ if (types.length > 0 && !types.includes("string"))
195
+ issues.push(`${at}: resource references must be strings`);
196
+ }
197
+ };
198
+ for (const [name, schema] of Object.entries(document.components?.schemas ?? {})) {
199
+ walkSchema(document, schema, (node, path) => inspectSchema(node, `components.schemas.${name}/${path.join("/")}`));
200
+ }
201
+ for (const operation of listOperations(document)) {
202
+ const label = `${operation.method.toUpperCase()} ${operation.path}`;
203
+ const raw = operation.operation[EXTENSION_KEYS.operation];
204
+ if (raw !== void 0 && !isRecord2(raw))
205
+ issues.push(`${label}: ${EXTENSION_KEYS.operation} must be an object`);
206
+ if (isRecord2(raw) && raw.path !== void 0) {
207
+ const path = raw.path;
208
+ if (!isRecord2(path) || typeof path.parameter !== "string" || !path.parameter || !operation.path.endsWith(`/{${path.parameter}}`) || path.allowEmpty !== void 0 && typeof path.allowEmpty !== "boolean")
209
+ issues.push(`${label}: path needs a terminal { parameter, allowEmpty?: boolean }`);
210
+ }
211
+ const meta = operationMetadata(operation.operation);
212
+ if (!meta.supported && meta.reason === void 0)
213
+ issues.push(`${label}: unsupported operations need a reason`);
214
+ if (meta.supported && !meta.parity.enabled && meta.parity.reason === void 0) {
215
+ issues.push(`${label}: parity-disabled operations need parity.reason`);
216
+ }
217
+ for (const parameter of operation.parameters) {
218
+ const pm = parameterMetadata(document, parameter);
219
+ if (pm.resourceRef)
220
+ referencedTypes.set(pm.resourceRef.type, `${label} parameter ${parameter.name}`);
221
+ if (parameter.schema) {
222
+ walkSchema(document, parameter.schema, (node, path) => inspectSchema(node, `${label} parameter ${parameter.name}/${path.join("/")}`));
223
+ }
224
+ }
225
+ for (const [mediaType, media] of Object.entries(operation.requestBody?.content ?? {})) {
226
+ if (media.schema)
227
+ walkSchema(document, media.schema, (node, path) => inspectSchema(node, `${label} body ${mediaType}/${path.join("/")}`));
228
+ }
229
+ for (const [status, response] of Object.entries(operation.responses)) {
230
+ for (const [mediaType, media] of Object.entries(response.content ?? {})) {
231
+ if (media.schema)
232
+ walkSchema(document, media.schema, (node, path) => inspectSchema(node, `${label} ${status} ${mediaType}/${path.join("/")}`));
233
+ }
234
+ }
235
+ }
236
+ for (const [type, at] of referencedTypes) {
237
+ if (!producedTypes.has(type))
238
+ issues.push(`${at}: references resource type ${JSON.stringify(type)} but no identity produces it`);
239
+ }
240
+ return issues;
241
+ };
242
+ var resourceTypes = (document) => {
243
+ const types = /* @__PURE__ */ new Set();
244
+ const inspect = (schema) => {
245
+ const meta = schemaMetadata(schema);
246
+ if (meta.resource)
247
+ types.add(meta.resource.type);
248
+ };
249
+ for (const schema of Object.values(document.components?.schemas ?? {}))
250
+ walkSchema(document, schema, inspect);
251
+ for (const operation of listOperations(document)) {
252
+ for (const response of Object.values(operation.responses)) {
253
+ for (const media of Object.values(response.content ?? {}))
254
+ if (media.schema)
255
+ walkSchema(document, media.schema, inspect);
256
+ }
257
+ }
258
+ return [...types].sort();
259
+ };
260
+
261
+ export {
262
+ VOLATILE_KINDS,
263
+ SCOPE_VALUES,
264
+ EXTENSION_KEYS,
265
+ operationMetadata,
266
+ schemaMetadata,
267
+ parameterMetadata,
268
+ parityHeaders,
269
+ annotateValue,
270
+ pathKey,
271
+ validateMetadata,
272
+ resourceTypes
273
+ };
274
+ //# sourceMappingURL=chunk-EQLY2YOA.js.map