@znight/websocket 0.0.0 → 0.6.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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +227 -0
  3. package/dist/bun.d.mts +4 -0
  4. package/dist/bun.mjs +112 -0
  5. package/dist/bun.mjs.map +1 -0
  6. package/dist/compiler.d.mts +90 -0
  7. package/dist/compiler.mjs +864 -0
  8. package/dist/compiler.mjs.map +1 -0
  9. package/dist/index.d.mts +501 -0
  10. package/dist/index.mjs +2088 -0
  11. package/dist/index.mjs.map +1 -0
  12. package/dist/server-CI_Bh9o1.d.mts +331 -0
  13. package/dist/server-D40_bC88.mjs +72 -0
  14. package/dist/server-D40_bC88.mjs.map +1 -0
  15. package/dist/testing.d.mts +60 -0
  16. package/dist/testing.mjs +189 -0
  17. package/dist/testing.mjs.map +1 -0
  18. package/dist/transport-xnJqvB93.d.mts +63 -0
  19. package/dist/ws.d.mts +9 -0
  20. package/dist/ws.mjs +143 -0
  21. package/dist/ws.mjs.map +1 -0
  22. package/package.json +102 -1
  23. package/src/client.ts +246 -0
  24. package/src/compiler/analyze.ts +850 -0
  25. package/src/compiler/constants.ts +102 -0
  26. package/src/compiler/data.ts +78 -0
  27. package/src/compiler/generate.ts +262 -0
  28. package/src/compiler/index.ts +53 -0
  29. package/src/compiler/validate.ts +81 -0
  30. package/src/connection.ts +455 -0
  31. package/src/context.ts +43 -0
  32. package/src/decorators.ts +83 -0
  33. package/src/dispatcher.ts +343 -0
  34. package/src/envelope.ts +136 -0
  35. package/src/exceptions.ts +91 -0
  36. package/src/index.ts +89 -0
  37. package/src/metadata.ts +74 -0
  38. package/src/options.ts +343 -0
  39. package/src/plugin.ts +820 -0
  40. package/src/rate-limit.ts +27 -0
  41. package/src/rooms.ts +185 -0
  42. package/src/server.ts +125 -0
  43. package/src/testing/index.ts +279 -0
  44. package/src/tokens.ts +23 -0
  45. package/src/transport.ts +72 -0
  46. package/src/transports/bun.ts +163 -0
  47. package/src/transports/memory.ts +174 -0
  48. package/src/transports/ws.ts +237 -0
  49. package/src/validate.ts +31 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compiler.mjs","names":[],"sources":["../src/compiler/constants.ts","../src/compiler/analyze.ts","../src/compiler/generate.ts","../src/compiler/validate.ts","../src/compiler/index.ts"],"sourcesContent":["/**\n * Constants shared by the compiler extension modules. This module stays free of runtime imports: the\n * extension entry is loaded by the compiler, which must never load the WebSocket runtime (spec §2).\n */\nimport type { ErrorCode } from '@znight/core'\n\n/** Name of the extension, also the key of `metadata.extensions.websocket`. */\nexport const EXTENSION_NAME = 'websocket'\n\n/** Module the generated code imports its helpers and types from. */\nexport const RUNTIME_MODULE = '@znight/websocket'\n\n/** Canonical identities of the decorators owned by the extension. */\nexport const WsDecorator: {\n readonly Gateway: '@znight/websocket#Gateway'\n readonly OnConnect: '@znight/websocket#OnConnect'\n readonly OnMessage: '@znight/websocket#OnMessage'\n readonly OnDisconnect: '@znight/websocket#OnDisconnect'\n readonly Payload: '@znight/websocket#Payload'\n readonly Conn: '@znight/websocket#Conn'\n readonly Ctx: '@znight/websocket#Ctx'\n readonly UseHandshakeGuard: '@znight/websocket#UseHandshakeGuard'\n readonly UseMessageGuard: '@znight/websocket#UseMessageGuard'\n} = Object.freeze({\n Gateway: '@znight/websocket#Gateway',\n OnConnect: '@znight/websocket#OnConnect',\n OnMessage: '@znight/websocket#OnMessage',\n OnDisconnect: '@znight/websocket#OnDisconnect',\n Payload: '@znight/websocket#Payload',\n Conn: '@znight/websocket#Conn',\n Ctx: '@znight/websocket#Ctx',\n UseHandshakeGuard: '@znight/websocket#UseHandshakeGuard',\n UseMessageGuard: '@znight/websocket#UseMessageGuard',\n})\n\n/** Decorators giving a method a role. */\nexport const ROLE_DECORATORS: ReadonlySet<string> = new Set([\n WsDecorator.OnConnect,\n WsDecorator.OnMessage,\n WsDecorator.OnDisconnect,\n])\n\n/** Decorators applied to methods (roles and message guards). */\nexport const METHOD_DECORATORS: ReadonlySet<string> = new Set([...ROLE_DECORATORS, WsDecorator.UseMessageGuard])\n\n/** Decorators applied to handler parameters. */\nexport const PARAMETER_DECORATORS: ReadonlySet<string> = new Set([\n WsDecorator.Payload,\n WsDecorator.Conn,\n WsDecorator.Ctx,\n])\n\n/** ZNIGHT005: invalid decorator usage. */\nexport const INVALID_DECORATOR: ErrorCode = 'ZNIGHT005'\n/** ZNIGHT007: invalid or conflicting gateway path. */\nexport const INVALID_ROUTE: ErrorCode = 'ZNIGHT007'\n/** ZNIGHT017: non-primitive `@Payload()` without schema. */\nexport const UNVALIDATED_INPUT: ErrorCode = 'ZNIGHT017'\n/** ZNIGHT023: a gateway without a decision of a required route decorator group (RFC 0001). */\nexport const MISSING_ROUTE_DECISION: ErrorCode = 'ZNIGHT023'\n/** ZNIGHT050: invalid gateway. */\nexport const INVALID_GATEWAY: ErrorCode = 'ZNIGHT050'\n\n/** Event names of the `events` protocol (the runtime `EVENT_NAME`, checked by the tests). */\nexport const EVENT_NAME: RegExp = /^[A-Za-z][\\w.:/-]{0,127}$/\n\n/** RFC 7230 token: subprotocol names. */\nexport const SUBPROTOCOL: RegExp = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\n\n/** Deterministic string comparison (never `localeCompare`). */\nexport function compareStrings(a: string, b: string): number {\n if (a === b) return 0\n return a < b ? -1 : 1\n}\n\nconst UNITS: Readonly<Record<string, number>> = {\n b: 1,\n k: 1024,\n kb: 1024,\n kib: 1024,\n m: 1024 ** 2,\n mb: 1024 ** 2,\n mib: 1024 ** 2,\n g: 1024 ** 3,\n gb: 1024 ** 3,\n gib: 1024 ** 3,\n}\n\nconst SIZE = /^(\\d+(?:\\.\\d+)?|\\.\\d+)\\s*([a-z]*)$/i\n\n/** A positive byte size (`'64kb'`, `65536`), the grammar of `ByteSize`; `undefined` otherwise. */\nexport function parseSize(value: unknown): number | undefined {\n if (typeof value === 'number') return Number.isSafeInteger(value) && value > 0 ? value : undefined\n if (typeof value !== 'string') return undefined\n const match = SIZE.exec(value.trim())\n if (match === null) return undefined\n const unit = (match[2] as string).toLowerCase()\n const multiplier = unit === '' ? 1 : UNITS[unit]\n if (multiplier === undefined) return undefined\n const bytes = Math.floor(Number(match[1]) * multiplier)\n return Number.isSafeInteger(bytes) && bytes > 0 ? bytes : undefined\n}\n","/**\n * `analyzeClass` of the websocket extension (RFC 0003 §6.2): reads `@Gateway` classes, their\n * lifecycle methods, `@OnMessage` handlers, parameters, guards and route decorators, registers the\n * gateway provider and reports what one class can tell (ZNIGHT005, ZNIGHT007, ZNIGHT017, ZNIGHT050).\n *\n * Handlers may be declared on base classes: the gateway inherits the websocket methods of its\n * analysable bases (the nearest declaration of a method carrying websocket decorators wins).\n */\nimport type {\n AnalyzeContext,\n ArgInfo,\n ClassInfo,\n ClassRef,\n DecoratorInfo,\n Location,\n MethodInfo,\n ParameterInfo,\n StaticValue,\n TypeInfo,\n ValueRef,\n} from '@znight/compiler'\nimport type { MetaEntry } from '@znight/http/compiler'\nimport type { GatewayOptionsData, HandlerData, LifecycleData, WebSocketData, WsParamData } from './data.ts'\n\nimport { readRouteMeta } from '@znight/http/compiler'\nimport { checkRoutePath, normalizePath } from '@znight/http/path'\n\nimport {\n EVENT_NAME,\n INVALID_DECORATOR,\n INVALID_GATEWAY,\n INVALID_ROUTE,\n METHOD_DECORATORS,\n PARAMETER_DECORATORS,\n parseSize,\n RUNTIME_MODULE,\n SUBPROTOCOL,\n UNVALIDATED_INPUT,\n WsDecorator,\n} from './constants.ts'\n\ntype Context = AnalyzeContext<WebSocketData>\n\n/** The websocket declarations of one method. */\ninterface MemberAnalysis {\n readonly method: string\n readonly declaredBy: string\n readonly onConnect: LifecycleData | undefined\n readonly onDisconnect: LifecycleData | undefined\n readonly handlers: readonly HandlerData[]\n /** The method has a role decorator (valid or not). */\n readonly role: boolean\n}\n\n/** Types a `@Payload()` without schema may have (RFC 0003 §5.5). */\nconst BINARY_TYPES: ReadonlySet<string> = new Set([\n 'globalThis#Uint8Array',\n 'globalThis#ArrayBuffer',\n 'globalThis#Buffer',\n 'node:buffer#Buffer',\n 'buffer#Buffer',\n])\n\nconst OPTION_KEYS: ReadonlySet<string> = new Set([\n 'path',\n 'scope',\n 'protocol',\n 'protocols',\n 'maxPayload',\n 'concurrency',\n 'rateLimit',\n 'backpressure',\n])\n\n/** Maximum depth of the base class chain walked for inherited handlers. */\nconst MAX_CHAIN = 32\n\n/** Analyses a class carrying at least one decorator of the extension. */\nexport function analyzeWebSocketClass(cls: ClassInfo, ctx: Context): void {\n const gateways = cls.decorators.filter(decorator => decorator.identity === WsDecorator.Gateway)\n const gateway = gateways[0]\n if (gateway === undefined) {\n // analysed anyway: errors on the methods are reported once, here, and validate() reports\n // the decorators of a class that is not a base of a gateway\n analyzeMembers(cls, ctx)\n const decorators = [\n ...cls.decorators.filter(isOwnClassDecorator),\n ...cls.methods.flatMap(method => method.decorators.filter(isOwnMethodDecorator)),\n ].map(decorator => ({ name: decorator.name, location: decorator.location }))\n if (decorators.length > 0) {\n ctx.store({\n kind: 'members',\n identity: cls.identity,\n displayName: cls.displayName,\n abstract: cls.abstract,\n decorators,\n })\n }\n return\n }\n for (const duplicate of gateways.slice(1)) {\n report(ctx, INVALID_DECORATOR, duplicate.location, `@Gateway is applied several times on ${cls.displayName}`, [\n 'Keep a single @Gateway: a class serves one path',\n ])\n }\n const read = readGatewayOptions(gateway, cls, ctx)\n const token = ctx.registerProvider(cls, { scope: read.scope })\n const chain = classChain(cls, ctx)\n\n const merged = new Map<string, MemberAnalysis>()\n for (let index = chain.length - 1; index >= 0; index--) {\n const owner = chain[index] as ClassInfo\n for (const [name, member] of analyzeMembers(owner, ctx, index === 0 ? undefined : cls)) merged.set(name, member)\n }\n const members = [...merged.values()]\n const handlers = members.flatMap(member => member.handlers)\n const onConnect = single(ctx, cls, members, 'onConnect', '@OnConnect')\n const onDisconnect = single(ctx, cls, members, 'onDisconnect', '@OnDisconnect')\n checkHandlers(cls, read.options.protocol, handlers, ctx)\n if (!members.some(member => member.role)) {\n report(\n ctx,\n INVALID_GATEWAY,\n gateway.location,\n `@Gateway ${cls.displayName} has no handler`,\n ['Decorate a public method with @OnMessage(\"event\"), @OnConnect() or @OnDisconnect()'],\n 'warning',\n )\n }\n\n ctx.store({\n kind: 'gateway',\n token,\n identity: cls.identity,\n displayName: cls.displayName,\n path: read.path,\n options: read.options,\n meta: readRouteMeta(ctx, cls),\n handshakeGuards: guardRefs(ctx, cls, cls.decorators, WsDecorator.UseHandshakeGuard),\n messageGuards: guardRefs(ctx, cls, cls.decorators, WsDecorator.UseMessageGuard),\n onConnect,\n onDisconnect,\n handlers,\n chain: chain.map(owner => owner.identity),\n location: gateway.location,\n })\n}\n\nfunction isOwnClassDecorator(decorator: DecoratorInfo): boolean {\n return decorator.identity === WsDecorator.UseHandshakeGuard || decorator.identity === WsDecorator.UseMessageGuard\n}\n\nfunction isOwnMethodDecorator(decorator: DecoratorInfo): boolean {\n return decorator.identity !== undefined && METHOD_DECORATORS.has(decorator.identity)\n}\n\nfunction report(\n ctx: Context,\n code: string,\n location: Location,\n message: string,\n hints?: readonly string[],\n severity: 'error' | 'warning' = 'error',\n related?: readonly { readonly message: string; readonly location: Location }[],\n): void {\n ctx.report({\n code: code as never,\n severity,\n message,\n location,\n ...(hints === undefined ? {} : { hints }),\n ...(related === undefined ? {} : { related }),\n })\n}\n\n// ------------------------------------------------------------------------------------------ options\n\ninterface ReadOptions {\n readonly path: string | undefined\n readonly scope: 'singleton' | 'request'\n readonly options: GatewayOptionsData\n}\n\nfunction isRecord(value: StaticValue): value is Readonly<Record<string, StaticValue>> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const prototype: unknown = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\nfunction describe(value: StaticValue): string {\n if (value === undefined) return 'undefined'\n if (value === null) return 'null'\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value !== 'object') return String(value)\n if (Array.isArray(value)) return 'an array'\n return isRecord(value) ? 'an object' : 'a reference'\n}\n\nfunction isPositiveInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value > 0\n}\n\n/** `@Gateway()`, `@Gateway('/chat')` or `@Gateway({ path, scope, protocol, ... })`. */\nfunction readGatewayOptions(decorator: DecoratorInfo, cls: ClassInfo, ctx: Context): ReadOptions {\n const prefix = `@Gateway ${cls.displayName}`\n const fallback: ReadOptions = { path: undefined, scope: 'singleton', options: { protocol: 'events' } }\n const arg = decorator.args[0]\n if (!decorator.called) return fallback // reported by the compiler\n if (arg === undefined) return { ...fallback, path: '/' }\n if (!arg.evaluated) return fallback // not statically evaluable: reported by the compiler\n const value = arg.value\n if (typeof value === 'string') return { ...fallback, path: checkPath(ctx, prefix, value, arg.location) }\n if (value === undefined) return { ...fallback, path: '/' }\n if (!isRecord(value)) {\n report(\n ctx,\n INVALID_DECORATOR,\n arg.location,\n `${prefix}: expected a path or an options object, got ${describe(value)}`,\n [\"Write @Gateway('/chat') or @Gateway({ path: '/chat', protocol: 'raw' })\"],\n )\n return fallback\n }\n const fail = (message: string, hints?: readonly string[]): void => {\n report(ctx, INVALID_GATEWAY, arg.location, `${prefix}: ${message}`, hints)\n }\n for (const key of Object.keys(value)) {\n if (!OPTION_KEYS.has(key)) fail(`unknown option \"${key}\"`, [`Known options: ${[...OPTION_KEYS].join(', ')}`])\n }\n let path: string | undefined = '/'\n const rawPath = value['path']\n if (rawPath !== undefined) {\n if (typeof rawPath === 'string') path = checkPath(ctx, prefix, rawPath, arg.location)\n else {\n fail(`\"path\" must be a string, got ${describe(rawPath)}`)\n path = undefined\n }\n }\n let scope: 'singleton' | 'request' = 'singleton'\n const rawScope = value['scope']\n if (rawScope === 'request') scope = 'request'\n else if (rawScope === 'transient') {\n fail(\"a gateway cannot be 'transient'\", [\n \"Use scope: 'request' for one instance per connection, or the default singleton\",\n ])\n } else if (rawScope !== undefined && rawScope !== 'singleton') {\n fail(`\"scope\" must be 'singleton' or 'request', got ${describe(rawScope)}`)\n }\n let protocol: 'events' | 'raw' = 'events'\n const rawProtocol = value['protocol']\n if (rawProtocol === 'raw') protocol = 'raw'\n else if (rawProtocol !== undefined && rawProtocol !== 'events') {\n fail(`\"protocol\" must be 'events' or 'raw', got ${describe(rawProtocol)}`)\n }\n const options: { -readonly [K in keyof GatewayOptionsData]: GatewayOptionsData[K] } = { protocol }\n const protocols = value['protocols']\n if (protocols !== undefined) {\n if (\n !Array.isArray(protocols) ||\n protocols.length === 0 ||\n !protocols.every(item => typeof item === 'string' && SUBPROTOCOL.test(item)) ||\n new Set(protocols).size !== protocols.length\n ) {\n fail(`\"protocols\" must be a non-empty list of distinct subprotocol tokens, got ${describe(protocols)}`, [\n \"protocols: ['chat.v1']\",\n ])\n } else {\n options.protocols = protocols as string[]\n }\n }\n const maxPayload = value['maxPayload']\n if (maxPayload !== undefined) {\n const bytes = parseSize(maxPayload)\n if (bytes === undefined)\n fail(`\"maxPayload\" must be a positive byte size ('64kb', 65536), got ${describe(maxPayload)}`)\n else options.maxPayload = bytes\n }\n const concurrency = value['concurrency']\n if (concurrency !== undefined) {\n if (isPositiveInteger(concurrency)) options.concurrency = concurrency\n else fail(`\"concurrency\" must be a positive integer, got ${describe(concurrency)}`)\n }\n const rateLimit = value['rateLimit']\n if (rateLimit !== undefined) {\n const onLimit = isRecord(rateLimit) ? (rateLimit['onLimit'] ?? 'reject') : undefined\n if (\n !isRecord(rateLimit) ||\n !isPositiveInteger(rateLimit['messages']) ||\n !isPositiveInteger(rateLimit['intervalMs']) ||\n (onLimit !== 'reject' && onLimit !== 'close') ||\n Object.keys(rateLimit).some(key => key !== 'messages' && key !== 'intervalMs' && key !== 'onLimit')\n ) {\n fail(`\"rateLimit\" must be { messages, intervalMs, onLimit?: 'reject' | 'close' }, got ${describe(rateLimit)}`, [\n 'rateLimit: { messages: 30, intervalMs: 1000 }',\n ])\n } else {\n options.rateLimit = {\n messages: rateLimit['messages'] as number,\n intervalMs: rateLimit['intervalMs'] as number,\n onLimit: onLimit as 'reject' | 'close',\n }\n }\n }\n const backpressure = value['backpressure']\n if (backpressure !== undefined) {\n const limit = isRecord(backpressure) ? backpressure['limit'] : undefined\n const onLimit = isRecord(backpressure) ? backpressure['onLimit'] : undefined\n const bytes = limit === undefined ? undefined : parseSize(limit)\n if (\n !isRecord(backpressure) ||\n (limit !== undefined && bytes === undefined) ||\n (onLimit !== undefined && onLimit !== 'close' && onLimit !== 'drop') ||\n Object.keys(backpressure).some(key => key !== 'limit' && key !== 'onLimit')\n ) {\n fail(`\"backpressure\" must be { limit?: ByteSize, onLimit?: 'close' | 'drop' }, got ${describe(backpressure)}`)\n } else {\n options.backpressure = {\n ...(bytes === undefined ? {} : { limit: bytes }),\n ...(onLimit === undefined ? {} : { onLimit: onLimit as 'close' | 'drop' }),\n }\n }\n }\n return { path, scope, options }\n}\n\n/** The normalised path, or `undefined` when it breaks the route grammar (ZNIGHT007). */\nfunction checkPath(ctx: Context, prefix: string, raw: string, location: Location): string | undefined {\n const path = normalizePath(raw)\n const issue = checkRoutePath(path)\n if (issue === undefined) return path\n report(ctx, INVALID_ROUTE, location, `${prefix}: invalid path \"${raw}\": ${issue.message}`, [\n \"Gateway paths use the route grammar: '/chat', '/docs/:docId', '/feeds/*'\",\n ])\n return undefined\n}\n\n/** The class and its analysable base classes (nearest first). */\nfunction classChain(cls: ClassInfo, ctx: Context): ClassInfo[] {\n const chain = [cls]\n const seen = new Set([cls.identity])\n let current = cls\n while (current.superClass !== undefined && chain.length < MAX_CHAIN) {\n const base = ctx.classInfo(current.superClass.identity)\n if (base === undefined || seen.has(base.identity)) break\n chain.push(base)\n seen.add(base.identity)\n current = base\n }\n return chain\n}\n\n/** `@UseHandshakeGuard` / `@UseMessageGuard` arguments, bound with a gateway → guard edge. */\nfunction guardRefs(ctx: Context, from: ClassInfo, decorators: readonly DecoratorInfo[], identity: string): ClassRef[] {\n const refs: ClassRef[] = []\n for (const decorator of decorators) {\n if (decorator.identity !== identity) continue\n if (decorator.called && decorator.args.length === 0) {\n report(ctx, INVALID_DECORATOR, decorator.location, `@${decorator.name} requires at least one guard`, [\n `@${decorator.name}(MyGuard)`,\n ])\n }\n for (const arg of decorator.args) {\n const ref = ctx.resolveClassRef(arg, { from, role: 'guard' })\n if (ref) refs.push(ref)\n }\n }\n return refs\n}\n\n/** The single `@OnConnect` / `@OnDisconnect` of a gateway (ZNIGHT050 for several). */\nfunction single(\n ctx: Context,\n cls: ClassInfo,\n members: readonly MemberAnalysis[],\n key: 'onConnect' | 'onDisconnect',\n name: string,\n): LifecycleData | undefined {\n const found = members.flatMap(member => (member[key] === undefined ? [] : [member[key] as LifecycleData]))\n const first = found[0]\n for (const extra of found.slice(1)) {\n report(\n ctx,\n INVALID_GATEWAY,\n extra.location,\n `${cls.displayName} has several ${name} methods: ${found.map(item => `${item.declaredBy}.${item.method}`).join(', ')}`,\n [`Keep a single ${name} method per gateway`],\n 'error',\n [{ message: `First ${name} method`, location: (first as LifecycleData).location }],\n )\n }\n return first\n}\n\n/** Events handled twice, several default handlers, events on raw gateways (ZNIGHT050). */\nfunction checkHandlers(\n cls: ClassInfo,\n protocol: 'events' | 'raw',\n handlers: readonly HandlerData[],\n ctx: Context,\n): void {\n const label = (handler: HandlerData): string => `${handler.declaredBy}.${handler.method}`\n if (protocol === 'raw') {\n for (const handler of handlers) {\n if (handler.event === undefined) continue\n report(\n ctx,\n INVALID_GATEWAY,\n handler.location,\n `@OnMessage(\"${handler.event}\") on the raw gateway ${cls.displayName}`,\n ['A raw gateway has no events: use @OnMessage() for its single handler, or protocol: \"events\"'],\n )\n }\n const first = handlers[0]\n for (const extra of handlers.slice(1)) {\n report(\n ctx,\n INVALID_GATEWAY,\n extra.location,\n `The raw gateway ${cls.displayName} has several handlers: ${handlers.map(label).join(', ')}`,\n ['A raw gateway has a single @OnMessage() handler receiving every frame'],\n 'error',\n [{ message: 'First handler', location: (first as HandlerData).location }],\n )\n }\n return\n }\n let fallback: HandlerData | undefined\n const byEvent = new Map<string, HandlerData>()\n for (const handler of handlers) {\n if (handler.event === undefined) {\n if (fallback === undefined) {\n fallback = handler\n continue\n }\n report(\n ctx,\n INVALID_GATEWAY,\n handler.location,\n `${cls.displayName} has several default handlers: ${label(fallback)} and ${label(handler)}`,\n ['Give one of them an event: @OnMessage(\"message.send\")'],\n 'error',\n [{ message: 'First default handler', location: fallback.location }],\n )\n continue\n }\n const first = byEvent.get(handler.event)\n if (first === undefined) {\n byEvent.set(handler.event, handler)\n continue\n }\n report(\n ctx,\n INVALID_GATEWAY,\n handler.location,\n `${cls.displayName} handles \"${handler.event}\" twice: ${label(first)} and ${label(handler)}`,\n ['An event has a single handler per gateway: merge the methods, or rename one of the events'],\n 'error',\n [{ message: 'first handled here', location: first.location }],\n )\n }\n}\n\n// ------------------------------------------------------------------------------------------- members\n\n/**\n * Websocket methods declared by `cls` itself, by name. `host` is the gateway when `cls` is one of\n * its bases (its methods were already reported when the base was analysed: no second report).\n */\nfunction analyzeMembers(cls: ClassInfo, ctx: Context, host?: ClassInfo): Map<string, MemberAnalysis> {\n const members = new Map<string, MemberAnalysis>()\n const quiet = host === undefined ? ctx : silenced(ctx)\n for (const method of cls.methods) {\n const member = analyzeMethod(cls, method, quiet, host ?? cls)\n if (member !== undefined) members.set(method.name, member)\n }\n return members\n}\n\n/** The context without reports (a base class analysed again for a gateway). */\nfunction silenced(ctx: Context): Context {\n return new Proxy(ctx, {\n get(target, key, receiver) {\n if (key === 'report') return () => undefined\n const value: unknown = Reflect.get(target, key, receiver)\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n}\n\nfunction analyzeMethod(cls: ClassInfo, method: MethodInfo, ctx: Context, host: ClassInfo): MemberAnalysis | undefined {\n const onConnect = method.decorators.filter(decorator => decorator.identity === WsDecorator.OnConnect)\n const onDisconnect = method.decorators.filter(decorator => decorator.identity === WsDecorator.OnDisconnect)\n const onMessage = method.decorators.filter(decorator => decorator.identity === WsDecorator.OnMessage)\n const guards = method.decorators.filter(decorator => decorator.identity === WsDecorator.UseMessageGuard)\n const decoratedParams = method.params.some(param => param.decorators.some(isParameterDecorator))\n if (onConnect.length + onDisconnect.length + onMessage.length + guards.length === 0 && !decoratedParams) {\n return undefined\n }\n const where = `${cls.displayName}.${method.name}`\n const roles = [onConnect[0], onDisconnect[0], onMessage[0]].filter(item => item !== undefined) as DecoratorInfo[]\n const primary = roles[0]\n if (primary === undefined) {\n for (const guard of guards) {\n report(\n ctx,\n INVALID_DECORATOR,\n guard.location,\n `@UseMessageGuard has no effect on ${where}: it is not an @OnMessage handler`,\n ['Add @OnMessage(\"event\") to the method, or put the guard on the gateway class'],\n )\n }\n reportStrayParameters(method, where, ctx)\n return {\n method: method.name,\n declaredBy: cls.displayName,\n onConnect: undefined,\n onDisconnect: undefined,\n handlers: [],\n role: false,\n }\n }\n checkMethodShape(method, primary, where, ctx)\n if (roles.length > 1) {\n report(\n ctx,\n INVALID_GATEWAY,\n (roles[1] as DecoratorInfo).location,\n `${where} has several roles (${roles.map(role => `@${role.name}`).join(', ')})`,\n ['A method is either @OnConnect, @OnDisconnect or an @OnMessage handler: split it'],\n )\n }\n for (const duplicate of [...onConnect.slice(1), ...onDisconnect.slice(1)]) {\n report(ctx, INVALID_DECORATOR, duplicate.location, `@${duplicate.name} is applied several times on ${where}`, [\n `Keep a single @${duplicate.name}`,\n ])\n }\n const location = primary.location\n if (onMessage.length === 0) {\n for (const guard of guards) {\n report(\n ctx,\n INVALID_DECORATOR,\n guard.location,\n `@UseMessageGuard has no effect on ${where}: it is not an @OnMessage handler`,\n ['Message guards run before @OnMessage handlers; guard the handshake with @UseHandshakeGuard on the class'],\n )\n }\n const lifecycle: LifecycleData = {\n method: method.name,\n params: analyzeParams(method, where, 'lifecycle', ctx),\n declaredBy: cls.displayName,\n location,\n }\n return {\n method: method.name,\n declaredBy: cls.displayName,\n onConnect: onConnect.length > 0 ? lifecycle : undefined,\n onDisconnect: onConnect.length === 0 ? lifecycle : undefined,\n handlers: [],\n role: true,\n }\n }\n const params = analyzeParams(method, where, 'message', ctx)\n const meta: readonly MetaEntry[] = readRouteMeta(ctx, cls, method)\n const methodGuards = guardRefs(ctx, host, method.decorators, WsDecorator.UseMessageGuard)\n const handlers = onMessage.flatMap(decorator => {\n const event = eventOf(decorator, where, ctx)\n if (event === false) return []\n return [\n Object.freeze({\n method: method.name,\n event,\n meta,\n guards: methodGuards,\n params,\n declaredBy: cls.displayName,\n location: decorator.location,\n }),\n ]\n })\n return {\n method: method.name,\n declaredBy: cls.displayName,\n onConnect: undefined,\n onDisconnect: undefined,\n handlers,\n role: true,\n }\n}\n\n/** The event of `@OnMessage(event?)`: a string, `undefined` (default handler) or `false` (invalid). */\nfunction eventOf(decorator: DecoratorInfo, where: string, ctx: Context): string | undefined | false {\n const arg = decorator.args[0]\n if (arg === undefined || (arg.evaluated && arg.value === undefined)) return undefined\n if (!arg.evaluated) return false\n const value = arg.value\n if (typeof value !== 'string') {\n report(\n ctx,\n INVALID_DECORATOR,\n arg.location,\n `@OnMessage on ${where} expects an event name (a string), got ${describe(value)}`,\n ['Use @OnMessage() for the default handler'],\n )\n return false\n }\n if (value.startsWith('$')) {\n report(ctx, INVALID_GATEWAY, arg.location, `Event name \"${value}\" is reserved (${where})`, [\n `Names starting with \"$\" are protocol events${value === '$ping' ? '; \"$ping\" is answered by Znight itself' : ''}`,\n ])\n return false\n }\n if (!EVENT_NAME.test(value)) {\n report(ctx, INVALID_GATEWAY, arg.location, `Invalid event name \"${value}\" (${where})`, [\n 'An event name starts with a letter, then up to 127 letters, digits or _ . : / -',\n ])\n return false\n }\n return value\n}\n\n/** Handlers are called by the generated code: `gateway.method(...)`. */\nfunction checkMethodShape(method: MethodInfo, decorator: DecoratorInfo, where: string, ctx: Context): void {\n const name = `@${decorator.name}`\n let problem: readonly [string, string] | undefined\n if (method.kind !== 'method') problem = [`${name} cannot be applied to the accessor ${where}`, 'Use a regular method']\n else if (method.static) problem = [`${name} cannot be applied to the static method ${where}`, 'Remove `static`']\n else if (method.privateName)\n problem = [`${name} cannot be applied to the #private method ${where}`, 'Use a public method']\n else if (method.visibility !== 'public') {\n problem = [\n `${where} must be public: ${name} methods are called by the generated code`,\n `Remove the '${method.visibility}' modifier`,\n ]\n } else if (method.computed)\n problem = [`${name} cannot be applied to ${where}: computed names are not supported`, 'Use a plain method name']\n else if (method.generator)\n problem = [`${name} cannot be applied to the generator method ${where}`, 'Use a regular (or async) method']\n if (problem !== undefined) report(ctx, INVALID_DECORATOR, decorator.location, problem[0], [problem[1]])\n}\n\n// ---------------------------------------------------------------------------------------- parameters\n\nfunction analyzeParams(\n method: MethodInfo,\n where: string,\n role: 'message' | 'lifecycle',\n ctx: Context,\n): readonly WsParamData[] {\n let payload: DecoratorInfo | undefined\n return Object.freeze(\n method.params.map(param => {\n const data = analyzeParam(param, where, role, ctx)\n if (data.kind === 'payload' || data.kind === 'validated') {\n const decorator = parameterDecorators(param)[0] as DecoratorInfo\n if (payload !== undefined) {\n report(ctx, INVALID_GATEWAY, decorator.location, `${where} has two @Payload parameters`, [\n 'A message has one payload: keep a single @Payload()',\n ])\n }\n payload ??= decorator\n }\n return data\n }),\n )\n}\n\nfunction analyzeParam(param: ParameterInfo, where: string, role: 'message' | 'lifecycle', ctx: Context): WsParamData {\n const absent: WsParamData = { kind: 'undefined', optional: param.optional || param.hasDefault }\n const decorators = parameterDecorators(param)\n const decorator = decorators[0]\n if (decorator === undefined) {\n const foreign = foreignParameterDecorator(param)\n if (foreign !== undefined) {\n report(\n ctx,\n INVALID_DECORATOR,\n foreign.decorator.location,\n `@${foreign.decorator.name} on parameter '${param.name}' of ${where} is imported from '${foreign.module}': gateway handlers use ${foreign.name} from '${RUNTIME_MODULE}'`,\n [`Import it from '${RUNTIME_MODULE}': import { ${foreign.name} } from '${RUNTIME_MODULE}'`],\n )\n return absent\n }\n if (param.optional || param.hasDefault || param.rest) return absent\n report(\n ctx,\n INVALID_GATEWAY,\n param.location,\n `Parameter '${param.name}' of ${where} has no @Payload(), @Conn() or @Ctx() decorator`,\n [\n role === 'message'\n ? 'Every handler parameter is extracted from the message: @Payload(schema?), @Conn() or @Ctx()'\n : '@OnConnect and @OnDisconnect methods receive the connection: @Conn()',\n ],\n )\n return absent\n }\n if (decorators.length > 1) {\n report(\n ctx,\n INVALID_DECORATOR,\n (decorators[1] as DecoratorInfo).location,\n `Parameter '${param.name}' of ${where} has several websocket decorators`,\n ['Keep a single one'],\n )\n }\n if (param.rest) {\n report(\n ctx,\n INVALID_DECORATOR,\n decorator.location,\n `@${decorator.name} cannot be applied to the rest parameter '...${param.name}' of ${where}`,\n )\n return absent\n }\n if (decorator.identity === WsDecorator.Conn) return { kind: 'connection' }\n if (role === 'lifecycle') {\n report(\n ctx,\n INVALID_GATEWAY,\n decorator.location,\n `@${decorator.name} on ${where}: only @OnMessage handlers receive a message`,\n ['@OnConnect and @OnDisconnect methods take @Conn() only'],\n )\n return absent\n }\n if (decorator.identity === WsDecorator.Ctx) return { kind: 'context' }\n return payloadParam(param, decorator, where, ctx)\n}\n\n/** `@Payload()` / `@Payload(schema)`. */\nfunction payloadParam(param: ParameterInfo, decorator: DecoratorInfo, where: string, ctx: Context): WsParamData {\n const arg: ArgInfo | undefined = decorator.args[0]\n if (arg === undefined || (arg.evaluated && arg.value === undefined)) {\n checkUnvalidated(param, decorator, where, ctx)\n return { kind: 'payload' }\n }\n if (arg.ref !== undefined) {\n if (isClassReference(arg.ref)) {\n report(\n ctx,\n INVALID_DECORATOR,\n arg.location,\n `@Payload(${arg.text}) on ${where}: '${arg.ref.name}' is a class, not a Standard Schema`,\n ['Pass a Standard Schema (Zod, Valibot, ArkType...): export const SendMessage = z.object({ ... })'],\n )\n return { kind: 'undefined', optional: false }\n }\n return { kind: 'validated', schema: arg.ref }\n }\n if (!arg.evaluated) return { kind: 'undefined', optional: false }\n report(\n ctx,\n INVALID_DECORATOR,\n arg.location,\n `@Payload on ${where} expects a Standard Schema (Zod, Valibot, ArkType...), got ${describe(arg.value)}`,\n ['Declare the schema with `export const SendMessage = z.object({ ... })` and pass it: @Payload(SendMessage)'],\n )\n return { kind: 'undefined', optional: false }\n}\n\n/** ZNIGHT017: a structured payload injected without schema is trusted blindly. */\nfunction checkUnvalidated(param: ParameterInfo, decorator: DecoratorInfo, where: string, ctx: Context): void {\n const { type } = ctx.types.stripNullish(param.type)\n if (isSafePayloadType(type)) return\n const typed =\n type.kind === 'opaque' && type.reason === 'missing-annotation'\n ? 'has no type annotation'\n : `is typed '${ctx.types.format(param.type)}'`\n ctx.report({\n code: UNVALIDATED_INPUT as never,\n severity: ctx.options.strictValidation ? 'error' : 'warning',\n message: `Unvalidated message payload: parameter '${param.name}' of ${where} ${typed} but @Payload() has no schema`,\n location: decorator.location,\n hints: [\n 'Validate it with a Standard Schema (Zod, Valibot, ArkType...): @Payload(SendMessage)',\n \"Or declare the parameter as 'unknown' (or 'string | Uint8Array') and check it in the handler\",\n ],\n })\n}\n\n/** Parameter decorators of a method that has no websocket role. */\nfunction reportStrayParameters(method: MethodInfo, where: string, ctx: Context): void {\n for (const param of method.params) {\n for (const decorator of parameterDecorators(param)) {\n report(\n ctx,\n INVALID_DECORATOR,\n decorator.location,\n `@${decorator.name} has no effect on parameter '${param.name}' of ${where}: it is not a gateway handler`,\n ['Add @OnMessage(\"event\"), @OnConnect() or @OnDisconnect() to the method, or remove the decorator'],\n )\n }\n }\n}\n\ninterface ForeignDecorator {\n readonly decorator: DecoratorInfo\n readonly module: string\n readonly name: string\n}\n\n/** A parameter decorator named like a websocket one (`Ctx`, `Payload`) imported from another package. */\nfunction foreignParameterDecorator(param: ParameterInfo): ForeignDecorator | undefined {\n for (const decorator of param.decorators) {\n const identity = decorator.identity\n const separator = identity?.lastIndexOf('#') ?? -1\n if (identity === undefined || separator <= 0) continue\n const module = identity.slice(0, separator)\n const name = identity.slice(separator + 1)\n if (module === RUNTIME_MODULE || !module.startsWith('@znight/')) continue\n if (PARAMETER_DECORATORS.has(`${RUNTIME_MODULE}#${name}`)) return { decorator, module, name }\n }\n return undefined\n}\n\n/** Websocket decorators of a parameter, de-duplicated by position. */\nfunction parameterDecorators(param: ParameterInfo): DecoratorInfo[] {\n const seen = new Set<number>()\n return param.decorators.filter(decorator => {\n if (!isParameterDecorator(decorator) || seen.has(decorator.location.start)) return false\n seen.add(decorator.location.start)\n return true\n })\n}\n\nfunction isParameterDecorator(decorator: DecoratorInfo): boolean {\n return decorator.identity !== undefined && PARAMETER_DECORATORS.has(decorator.identity)\n}\n\nfunction isClassReference(ref: ValueRef): boolean {\n const symbol = ref.symbol\n return symbol.kind === 'declaration' && symbol.declaration.kind === 'class'\n}\n\n/** `string`, `Uint8Array`, `string | Uint8Array`, literals and `unknown` need no schema. */\nfunction isSafePayloadType(type: TypeInfo): boolean {\n switch (type.kind) {\n case 'primitive':\n return type.name !== 'any' && type.name !== 'object'\n case 'literal':\n return true\n case 'union':\n return type.types.every(isSafePayloadType)\n case 'reference':\n return BINARY_TYPES.has(type.identity)\n default:\n return false\n }\n}\n","/**\n * `generate` of the websocket extension (RFC 0003 §7): `metadata.extensions.websocket`, gateways\n * sorted by token, handlers in declaration order (bases first), optional fields omitted.\n *\n * ```ts\n * {\n * gateways: [{\n * token: 'src/chat/chat.gateway.ts#ChatGateway',\n * path: '/chat',\n * protocol: 'events',\n * meta: { authenticated: true },\n * handshakeGuards: [],\n * messageGuards: [],\n * onConnect: { method: 'connected', invoke: (g: ChatGateway, c: WsConnection) => g.connected(c as never) },\n * handlers: [{\n * method: 'join', event: 'room.join', meta: {}, guards: [], params: [...],\n * invoke: async (g: ChatGateway, m: WsMessageContext) => g.join(m.connection as never, await validatePayload(JoinRoom, m.data)),\n * }],\n * }],\n * }\n * ```\n */\nimport type { ClassRef, GenerateContext, GenInput, GenNode } from '@znight/compiler'\nimport type { MetaEntry } from '@znight/http/compiler'\nimport type { GatewayData, HandlerData, LifecycleData, WebSocketData, WsParamData } from './data.ts'\n\nimport { compareStrings, RUNTIME_MODULE } from './constants.ts'\n\ntype Context = GenerateContext<WebSocketData>\n\n/** Imports of the runtime helpers, created on first use (no unused import in the module). */\ninterface Helpers {\n connection(): GenNode\n messageContext(): GenNode\n validatePayload(): GenNode\n}\n\n/** Builds the websocket section; `undefined` (no section) without gateways. */\nexport function generateWebSocket(ctx: Context): GenNode | undefined {\n const gateways = ctx.stored\n .filter((data): data is GatewayData => data.kind === 'gateway')\n .sort((a, b) => compareStrings(a.token, b.token))\n if (gateways.length === 0) return undefined\n const helpers = lazyHelpers(ctx)\n const entries: [string, GenInput][] = [\n ['gateways', ctx.arr(gateways.map(gateway => gatewayNode(ctx, gateway, helpers)))],\n ]\n const groups = groupsNode(ctx, gateways)\n if (groups !== undefined) entries.push(['groups', groups])\n return ctx.obj(entries)\n}\n\nfunction gatewayNode(ctx: Context, gateway: GatewayData, helpers: Helpers): GenNode {\n let classType: GenNode | undefined\n const gatewayType = (): GenNode => {\n classType ??= ctx.importType(gateway.identity)\n return classType\n }\n const options = gateway.options\n const entries: [string, GenInput][] = [\n ['token', gateway.token],\n ['path', gateway.path ?? '/'],\n ['protocol', options.protocol],\n ]\n if (options.protocols !== undefined) entries.push(['protocols', ctx.lit([...options.protocols])])\n if (options.maxPayload !== undefined) entries.push(['maxPayload', options.maxPayload])\n if (options.concurrency !== undefined) entries.push(['concurrency', options.concurrency])\n if (options.rateLimit !== undefined) entries.push(['rateLimit', ctx.lit({ ...options.rateLimit })])\n if (options.backpressure !== undefined) entries.push(['backpressure', ctx.lit({ ...options.backpressure })])\n entries.push(\n ['meta', metaNode(ctx, gateway.meta)],\n ['handshakeGuards', tokens(ctx, gateway.handshakeGuards)],\n ['messageGuards', tokens(ctx, gateway.messageGuards)],\n )\n if (gateway.onConnect !== undefined) {\n entries.push(['onConnect', lifecycleNode(ctx, gateway.onConnect, gatewayType, helpers)])\n }\n if (gateway.onDisconnect !== undefined) {\n entries.push(['onDisconnect', lifecycleNode(ctx, gateway.onDisconnect, gatewayType, helpers)])\n }\n entries.push(['handlers', ctx.arr(gateway.handlers.map(handler => handlerNode(ctx, handler, gatewayType, helpers)))])\n return ctx.obj(entries)\n}\n\nfunction metaNode(ctx: Context, meta: readonly MetaEntry[]): GenNode {\n return ctx.obj(meta.map(entry => [entry.key, ctx.lit(entry.value)] as const))\n}\n\nfunction tokens(ctx: Context, refs: readonly ClassRef[]): GenNode {\n return ctx.arr(refs.map(ref => ctx.tokenOf(ref) ?? ref.token))\n}\n\n/** Trailing parameters left `undefined` are not passed. */\nfunction trimmed(params: readonly WsParamData[]): WsParamData[] {\n const list = [...params]\n while (list.length > 0 && list[list.length - 1]?.kind === 'undefined') list.pop()\n return list\n}\n\n/** `{ method, invoke: (g: Gateway, c: WsConnection) => g.method(c as never) }`. */\nfunction lifecycleNode(ctx: Context, lifecycle: LifecycleData, gatewayType: () => GenNode, helpers: Helpers): GenNode {\n const params = trimmed(lifecycle.params)\n const invoke =\n params.length === 0\n ? ctx.arrow([['g', gatewayType()]], g => ctx.call(ctx.member(g, lifecycle.method)))\n : ctx.arrow(\n [\n ['g', gatewayType()],\n ['c', helpers.connection()],\n ],\n (g, c) =>\n ctx.call(\n ctx.member(g, lifecycle.method),\n params.map(param =>\n param.kind === 'connection' ? ctx.code`${c as GenNode} as never` : ctx.lit(undefined),\n ),\n ),\n )\n return ctx.obj([\n ['method', lifecycle.method],\n ['invoke', invoke],\n ])\n}\n\nfunction handlerNode(ctx: Context, handler: HandlerData, gatewayType: () => GenNode, helpers: Helpers): GenNode {\n const entries: [string, GenInput][] = [['method', handler.method]]\n if (handler.event !== undefined) entries.push(['event', handler.event])\n entries.push(\n ['meta', metaNode(ctx, handler.meta)],\n ['guards', tokens(ctx, handler.guards)],\n ['params', ctx.arr(handler.params.flatMap((param, index) => paramNode(ctx, param, index)))],\n ['invoke', invokeNode(ctx, handler, gatewayType, helpers)],\n )\n return ctx.obj(entries)\n}\n\n/** The informational `params` entry of a parameter (none for a parameter left `undefined`). */\nfunction paramNode(ctx: Context, param: WsParamData, index: number): GenNode[] {\n switch (param.kind) {\n case 'payload':\n return [\n ctx.obj([\n ['index', index],\n ['source', 'payload'],\n ]),\n ]\n case 'validated':\n return [\n ctx.obj([\n ['index', index],\n ['source', 'payload'],\n ['schema', true],\n ]),\n ]\n case 'connection':\n return [\n ctx.obj([\n ['index', index],\n ['source', 'connection'],\n ]),\n ]\n case 'context':\n return [\n ctx.obj([\n ['index', index],\n ['source', 'context'],\n ]),\n ]\n case 'undefined':\n return []\n }\n}\n\n/** `(g: Gateway, m: WsMessageContext) => g.method(...args)`, `async` when a payload is validated. */\nfunction invokeNode(ctx: Context, handler: HandlerData, gatewayType: () => GenNode, helpers: Helpers): GenNode {\n const params = trimmed(handler.params)\n if (params.length === 0) {\n return ctx.arrow([['g', gatewayType()]], g => ctx.call(ctx.member(g, handler.method)))\n }\n return ctx.arrow(\n [\n ['g', gatewayType()],\n ['m', helpers.messageContext()],\n ],\n (g, m) =>\n ctx.call(\n ctx.member(g, handler.method),\n params.map(param => argumentNode(ctx, param, m as GenNode, helpers)),\n ),\n { async: params.some(param => param.kind === 'validated') },\n )\n}\n\nfunction argumentNode(ctx: Context, param: WsParamData, m: GenNode, helpers: Helpers): GenNode {\n switch (param.kind) {\n case 'payload':\n return ctx.code`${ctx.member(m, 'data')} as never`\n case 'validated':\n return ctx.code`await ${ctx.call(helpers.validatePayload(), [ctx.importValue(param.schema), ctx.member(m, 'data')])}`\n case 'connection':\n return ctx.code`${ctx.member(m, 'connection')} as never`\n case 'context':\n return m\n case 'undefined':\n return ctx.lit(undefined)\n }\n}\n\n/**\n * `groups`: the route decorator groups the runtime needs (required, holding several keys, or named\n * differently from their key), sorted; `undefined` when there is none (as `extensions.http`).\n */\nfunction groupsNode(ctx: Context, gateways: readonly GatewayData[]): GenNode | undefined {\n const groups = new Map<string, { readonly keys: Set<string>; required: boolean }>()\n const visit = (entries: readonly MetaEntry[]): void => {\n for (const entry of entries) {\n const group = groups.get(entry.group)\n if (group === undefined) groups.set(entry.group, { keys: new Set([entry.key]), required: entry.required })\n else {\n group.keys.add(entry.key)\n group.required ||= entry.required\n }\n }\n }\n for (const gateway of gateways) {\n visit(gateway.meta)\n for (const handler of gateway.handlers) visit(handler.meta)\n }\n const needed = [...groups]\n .filter(([name, group]) => group.required || group.keys.size > 1 || !group.keys.has(name))\n .sort(([a], [b]) => compareStrings(a, b))\n if (needed.length === 0) return undefined\n return ctx.obj(\n needed.map(\n ([name, group]) =>\n [\n name,\n ctx.obj([\n ['keys', ctx.lit([...group.keys].sort(compareStrings))],\n ['required', group.required],\n ]),\n ] as const,\n ),\n )\n}\n\nfunction lazyHelpers(ctx: Context): Helpers {\n const cache = new Map<string, GenNode>()\n const get = (name: string, type: boolean): GenNode => {\n let node = cache.get(name)\n if (node === undefined) {\n node = ctx.importFrom(RUNTIME_MODULE, name, type ? { type: true } : {})\n cache.set(name, node)\n }\n return node\n }\n return {\n connection: () => get('WsConnection', true),\n messageContext: () => get('WsMessageContext', true),\n validatePayload: () => get('validatePayload', false),\n }\n}\n","/**\n * `validate` of the websocket extension (RFC 0003 §6.2): what needs every gateway. Duplicate path\n * shapes (ZNIGHT007), decorators on a class that is neither a gateway nor one of its bases\n * (ZNIGHT005), and the required route decorator groups of RFC 0001 on handshakes (ZNIGHT023).\n */\nimport type { ValidateContext } from '@znight/compiler'\nimport type { MetaEntry } from '@znight/http/compiler'\nimport type { GatewayData, WebSocketData } from './data.ts'\n\nimport { requiredRouteGroups } from '@znight/http/compiler'\nimport { parseRoutePath } from '@znight/http/path'\n\nimport { compareStrings, INVALID_DECORATOR, INVALID_ROUTE, MISSING_ROUTE_DECISION } from './constants.ts'\n\n/** Validates the gateways of the application. */\nexport function validateWebSocket(ctx: ValidateContext<WebSocketData>): void {\n const gateways = ctx.stored\n .filter((data): data is GatewayData => data.kind === 'gateway')\n .sort((a, b) => compareStrings(a.token, b.token))\n\n const byShape = new Map<string, GatewayData>()\n for (const gateway of gateways) {\n if (gateway.path === undefined) continue\n const shape = parseRoutePath(gateway.path).shape\n const first = byShape.get(shape)\n if (first === undefined) {\n byShape.set(shape, gateway)\n continue\n }\n ctx.report({\n code: INVALID_ROUTE,\n severity: 'error',\n message: `${first.displayName} (${first.path}) and ${gateway.displayName} (${gateway.path}) serve the same path`,\n location: gateway.location,\n hints: ['Two gateways cannot match the same handshake: change one of the paths'],\n related: [{ message: `${first.displayName} serves ${first.path}`, location: first.location }],\n })\n }\n\n const bases = new Set(gateways.flatMap(gateway => gateway.chain))\n for (const data of ctx.stored) {\n if (data.kind !== 'members' || data.abstract || bases.has(data.identity)) continue\n for (const decorator of data.decorators) {\n ctx.report({\n code: INVALID_DECORATOR,\n severity: 'error',\n message: `@${decorator.name} has no effect: ${data.displayName} is not a @Gateway`,\n location: decorator.location,\n hints: [\n `Add @Gateway('/path') to ${data.displayName}, or extend it from a @Gateway class`,\n 'Base classes holding shared handlers should be abstract',\n ],\n })\n }\n }\n\n const applied: MetaEntry[] = []\n for (const gateway of gateways) {\n applied.push(...gateway.meta)\n for (const handler of gateway.handlers) applied.push(...handler.meta)\n }\n const required = requiredRouteGroups(ctx, applied)\n if (required.length === 0) return\n for (const gateway of gateways) {\n const decided = new Set(gateway.meta.map(entry => entry.group))\n for (const group of required) {\n if (decided.has(group.group)) continue\n const definition = group.decorators[0] as { readonly definition?: GatewayData['location'] } | undefined\n ctx.report({\n code: MISSING_ROUTE_DECISION,\n severity: 'error',\n message: `Gateway ${gateway.displayName} (${gateway.path ?? '?'}) has no \"${group.group}\" decision`,\n location: gateway.location,\n hints: [`Add ${group.suggestion} to ${gateway.displayName}: the handshake is an HTTP request`],\n ...(definition?.definition === undefined\n ? {}\n : { related: [{ message: `The \"${group.group}\" group is required`, location: definition.definition }] }),\n })\n }\n }\n}\n","/**\n * `@znight/websocket/compiler`: the compiler extension of `@znight/websocket` (RFC 0003 §6, §7).\n *\n * Loaded by `@znight/compiler` through the package manifest (`package.json#znight.compiler`). It\n * reads `@Gateway` classes, their `@OnConnect` / `@OnMessage` / `@OnDisconnect` methods, `@Payload`\n * / `@Conn` / `@Ctx` parameters, guards and route decorators, registers gateways as providers,\n * reports invalid gateways at build time and generates `metadata.extensions.websocket`.\n *\n * This entry only `import type`s from `@znight/compiler`, imports `@znight/http/compiler` and\n * `@znight/http/path` (both runtime-free) and never loads the WebSocket runtime.\n */\nimport type { CompilerExtension, DecoratorSpec } from '@znight/compiler'\nimport type { WebSocketData } from './data.ts'\n\nimport { analyzeWebSocketClass } from './analyze.ts'\nimport { EXTENSION_NAME, WsDecorator } from './constants.ts'\nimport { generateWebSocket } from './generate.ts'\nimport { validateWebSocket } from './validate.ts'\n\nexport type {\n GatewayData,\n GatewayOptionsData,\n HandlerData,\n LifecycleData,\n MemberClassData,\n WebSocketData,\n WsParamData,\n} from './data.ts'\n\n/** Decorators owned by the extension (static / value arguments, spec §4.6). */\nconst decorators: Readonly<Record<string, DecoratorSpec>> = Object.freeze({\n [WsDecorator.Gateway]: { targets: ['class'], params: ['static'] },\n [WsDecorator.OnConnect]: { targets: ['method'], params: [] },\n [WsDecorator.OnDisconnect]: { targets: ['method'], params: [] },\n [WsDecorator.OnMessage]: { targets: ['method'], params: ['static'] },\n [WsDecorator.Payload]: { targets: ['parameter'], params: ['value'] },\n [WsDecorator.Conn]: { targets: ['parameter'], params: [] },\n [WsDecorator.Ctx]: { targets: ['parameter'], params: [] },\n [WsDecorator.UseHandshakeGuard]: { targets: ['class'], params: [], rest: 'value' },\n [WsDecorator.UseMessageGuard]: { targets: ['class', 'method'], params: [], rest: 'value' },\n} satisfies Record<string, DecoratorSpec>)\n\n/** The `@znight/websocket` compiler extension. */\nexport const webSocketCompilerExtension: CompilerExtension<WebSocketData> = Object.freeze({\n apiVersion: 1,\n name: EXTENSION_NAME,\n decorators,\n analyzeClass: analyzeWebSocketClass,\n validate: validateWebSocket,\n generate: generateWebSocket,\n})\n\nexport default webSocketCompilerExtension\n"],"mappings":";;;;AAOA,MAAa,iBAAiB;;AAG9B,MAAa,iBAAiB;;AAG9B,MAAa,cAUT,OAAO,OAAO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