UNPKG

zod-sockets

Version:

Socket.IO solution with I/O validation and the ability to generate AsyncAPI specification and a contract for consumers

17 lines (14 loc) 24.7 kB
"use strict";var Ye=Object.create;var te=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var et=(e,t)=>{for(var o in t)te(e,o,{get:t[o],enumerable:!0})},Ce=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Qe(t))!Xe.call(e,r)&&r!==o&&te(e,r,{get:()=>t[r],enumerable:!(n=Je(t,r))||n.enumerable});return e};var P=(e,t,o)=>(o=e!=null?Ye(Ge(e)):{},Ce(t||!e||!e.__esModule?te(o,"default",{value:e,enumerable:!0}):o,e)),tt=e=>Ce(te({},"__esModule",{value:!0}),e);var io={};et(io,{AbstractAction:()=>Q,ActionsFactory:()=>de,Config:()=>J,Documentation:()=>fe,InputValidationError:()=>L,Integration:()=>me,OutputValidationError:()=>V,attachSockets:()=>ve,createSimpleConfig:()=>Ke});module.exports=tt(io);var Me=require("zod"),oe=(e,t)=>{try{return typeof e.parse(t)}catch{return}},Y=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,ot=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),D=e=>e.charAt(0).toLowerCase()+e.slice(1),l=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,o=>`/${o}`).split("/")).map(ot).join(""),je=e=>e instanceof Error?e:new Error(String(e)),ge=e=>e instanceof Me.z.ZodError?e.issues.map(({path:t,message:o})=>(t.length?[t.join("/")]:[]).concat(o).join(": ")).join("; "):e.message;var ne=e=>({join:async t=>e.join(t),leave:async t=>typeof t=="string"?e.leave(t):Promise.all(t.map(o=>e.leave(o))).then(()=>{})});var De=P(require("node:assert/strict"),1);var re=({sockets:e,...t})=>e.map(o=>({id:o.id,handshake:o.handshake,rooms:Array.from(o.rooms),getData:()=>o.data||{},emit:U({subject:o,...t}),...ne(o)}));function U({subject:e,emission:t,timeout:o}){return async(n,...r)=>{let i="id"in e;(0,De.default)(n in t,new Error(`Unsupported event ${n}`));let{schema:a,ack:s}=t[n],d=a.parse(r);if(!s)return e.emit(String(n),...d)||!0;let f=await e.timeout(o).emitWithAck(String(n),...d);return(i?s:s.array()).parse(f)}}var xe=({subject:e,...t})=>o=>({getClients:async()=>re({sockets:await e.in(o).fetchSockets(),...t}),broadcast:U({...t,subject:e.to(o)})});var Ie={onConnection:({client:{id:e,getData:t},logger:o})=>o.debug("Client connected",{...t(),id:e}),onDisconnect:({client:{id:e,getData:t},logger:o})=>o.debug("Client disconnected",{...t(),id:e}),onAnyIncoming:({event:e,client:{id:t,getData:o},logger:n})=>n.debug(`${e} from ${t}`,o()),onAnyOutgoing:({event:e,logger:t,payload:o})=>t.debug(`Sending ${e}`,o),onStartup:({logger:e})=>e.debug("Ready"),onError:({logger:e,event:t,error:o})=>e.error(t?`${t} handling error`:"Error",o)};var ie="/",B=e=>{let t=e.trim();return t.startsWith("/")?t:`/${t}`};var $=require("ansis"),E=require("ramda"),nt=(0,$.italic)("for River".padEnd(20)),rt="Proudly supports non-binary community.".padStart(77),it=` ,, MMM"""AMV \u1FEF7MM .M"""bgd \u1FEF7MM mm M\u2019 AMV MM ,MI "Y MM MM \u1FEF AMV ,pW"Wq. ,M""bMM \u1FEFMMb. ,pW"Wq. ,p6"bo MM ,MP\u2019 .gP"Ya mmMMmm ,pP"Ybd AMV 6W\u2019 \u1FEFWb ,AP MM \u1FEFYMMNq. 6W\u2019 \u1FEFWb 6M\u2019 OO MM ;Y ,M\u2019 Yb MM 8I \u1FEF" AMV , 8M M8 8MI MM . \u1FEFMM 8M M8 8M MM;Mm 8M"""""" MM \u1FEFYMMMa. AMV ,M YA. ,A9 \u1FEFMb MM Mb dM YA. ,A9 YM. , MM \u1FEFMb. YM. , MM L. I8 AMVmmmmMM \u1FEFYbmd9\u2019 \u1FEFWbmd"MML. P"Ybmmd" \u1FEFYbmd9\u2019 YMbmd\u2019 .JMML. YA. \u1FEFMbmmd\u2019 \u1FEFMbmo M9mmmP\u2019 ${nt}${rt} `,st=(0,E.cond)([[(0,E.gt)(4),(0,E.always)((0,$.hex)("#FCF434"))],[(0,E.gt)(5),(0,E.always)((0,$.hex)("#FFF"))],[(0,E.gt)(8),(0,E.always)((0,$.hex)("#9C59D1"))],[E.T,(0,E.always)((0,$.hex)("#2C2C2C"))]]),we=()=>it.split(` `).map((e,t)=>st(t)(e)).join(` `);var ve=async({io:e,actions:t,target:o,config:{namespaces:n,timeout:r,startupLogo:i=!0},logger:a=console})=>{for(let s in n){let d=e.of(B(s)),{emission:f,hooks:A,metadata:x}=n[s],{onConnection:j,onDisconnect:Z,onAnyIncoming:N,onAnyOutgoing:S,onStartup:H,onError:T}={...Ie,...A},b={emission:f,timeout:r},w={logger:a,withRooms:xe({subject:e,metadata:x,...b}),all:{getClients:async()=>re({sockets:await d.fetchSockets(),metadata:x,...b}),getRooms:()=>Array.from(d.adapter.rooms.keys()),broadcast:U({subject:e,...b})}};d.on("connection",async g=>{let u=U({subject:g,...b}),z=U({subject:g.broadcast,...b}),C={emit:u,broadcast:z,id:g.id,handshake:g.handshake,getRequest:()=>g.request,isConnected:()=>g.connected,getRooms:()=>Array.from(g.rooms),getData:()=>g.data||{},setData:h=>{x.parse(h),g.data=h},...ne(g)},O={...w,client:C,withRooms:xe({subject:g,metadata:x,...b})};await j(O),g.onAny((h,..._)=>N({event:h,payload:_,...O})),g.onAnyOutgoing((h,..._)=>S({event:h,payload:_,...O}));for(let h of t)if(h.getNamespace()===s){let _=h.getEvent();g.on(_,async(...ke)=>{try{return await h.execute({params:ke,...O})}catch(qe){return T({...O,event:_,payload:ke,error:je(qe)})}})}g.on("disconnect",()=>Z(O))}),await H(w)}return(i?console.log:()=>{})(we()),a.debug("Running","v2.2.0 (CJS)"),a.info("Listening",o.address()),e.attach(o)};var Re=require("zod");var J=class e{timeout;startupLogo;security;namespaces;constructor({timeout:t=2e3,startupLogo:o=!0,namespaces:n={},security:r=[]}={}){this.timeout=t,this.startupLogo=o,this.namespaces=n,this.security=r}addNamespace({path:t=ie,emission:o={},metadata:n=Re.z.object({}),hooks:r={},examples:i={},security:a=[]}){let{namespaces:s,...d}=this,f={emission:o,examples:i,hooks:r,metadata:n,security:a};return new e({...d,namespaces:{...s,[t]:f}})}},Ke=({startupLogo:e,timeout:t,security:o,emission:n,examples:r,hooks:i,metadata:a}={})=>new J({startupLogo:e,timeout:t,security:o}).addNamespace({emission:n,examples:r,metadata:a,hooks:i});var ce=require("ramda"),W=require("zod");var se=class extends Error{name="IOSchemaError"},L=class extends se{constructor(o){super(ge(o));this.originalError=o}name="InputValidationError"},V=class extends se{constructor(o){super(ge(o));this.originalError=o}name="OutputValidationError"};var Q=class{},ae=class extends Q{#t;#r;#o;#e;#n;#i;constructor(t){super(),this.#t=t.event,this.#r=t.ns||ie,this.#o=t.input,this.#e="output"in t?t.output:void 0,this.#n=[],this.#i=t.handler}getEvent(){return this.#t}getNamespace(){return this.#r}getSchema(t){return t==="input"?this.#o:this.#e}#s(t){let o=this.#e?(0,ce.init)(t):t;try{return this.#o.parse(o)}catch(n){throw n instanceof W.z.ZodError?new L(n):n}}#a(t){if(this.#e)try{return W.z.function(this.#e,W.z.void()).parse((0,ce.last)(t),{path:[Math.max(0,t.length-1)]})}catch(o){throw o instanceof W.z.ZodError?new L(o):o}}#c(t){if(this.#e)try{return this.#e.parse(t)}catch(o){throw o instanceof W.z.ZodError?new V(o):o}}async execute({params:t,logger:o,...n}){let r=this.#s(t);o.debug(`${this.#t}: parsed input (${this.#e?"excl.":"no"} ack)`,r);let i=this.#a(t),a=await this.#i({input:r,logger:o,...n}),s=this.#c(a);i&&s&&(o.debug(`${this.#t}: parsed output`,s),i(...s))}example(t,o){return this.#n.push({variant:t,payload:o}),this}getExamples(t){return this.#n.filter(o=>o.variant===t).map(({payload:o})=>o)}};var de=class{constructor(t){this.config=t}build(t){return new ae(t)}};var Ne=P(require("typescript"),1);var be=require("ramda"),he=P(require("typescript"),1),k=require("zod"),p=he.default.factory,G=[p.createModifier(he.default.SyntaxKind.ExportKeyword)],Se=(e,t,o=3)=>{if(!t)return k.z.function(e,k.z.void());let n=k.z.function(t,k.z.void()),r=e._def.rest;if(!r||o<=0)return k.z.function(k.z.tuple([...e.items,n]),k.z.void());let i=(0,be.range)(0,o).map(a=>{let s=[...e.items].concat((0,be.range)(1,a+1).map(d=>r.describe(`${r.description||"rest"}${d}`))).concat(n);return k.z.function(k.z.tuple(s),k.z.void())});return k.z.union(i)};var m=P(require("typescript"),1),X=require("zod");var v=(e,{onEach:t,rules:o,onMissing:n,ctx:r={}})=>{let i=o[e._def.typeName],s=i?i(e,{...r,next:f=>v(f,{ctx:r,onEach:t,rules:o,onMissing:n})}):n(e,r),d=t&&t(e,{prev:s,...r});return d?{...s,...d}:s};var I=P(require("typescript"),1),{factory:pe}=I.default,q=(e,t)=>{I.default.addSyntheticLeadingComment(e,I.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Te=(e,t,o)=>{let n=pe.createTypeAliasDeclaration(void 0,pe.createIdentifier(t),void 0,e);return o&&q(n,o),n},Pe=(e,t)=>{let o=I.default.createSourceFile("print.ts","",I.default.ScriptTarget.Latest,!1,I.default.ScriptKind.TS);return I.default.createPrinter(t).printNode(I.default.EmitHint.Unspecified,e,o)},at=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ue=e=>at.test(e)?pe.createIdentifier(e):pe.createStringLiteral(e);var{factory:c}=m.default,ct={[m.default.SyntaxKind.AnyKeyword]:"",[m.default.SyntaxKind.BigIntKeyword]:BigInt(0),[m.default.SyntaxKind.BooleanKeyword]:!1,[m.default.SyntaxKind.NumberKeyword]:0,[m.default.SyntaxKind.ObjectKeyword]:{},[m.default.SyntaxKind.StringKeyword]:"",[m.default.SyntaxKind.UndefinedKeyword]:void 0,[m.default.SyntaxKind.UnknownKeyword]:void 0},dt=({value:e})=>c.createLiteralTypeNode(typeof e=="number"?c.createNumericLiteral(e):typeof e=="boolean"?e?c.createTrue():c.createFalse():c.createStringLiteral(e)),pt=({shape:e},{direction:t,next:o,optionalPropStyle:{withQuestionMark:n}})=>{let r=Object.entries(e).map(([i,a])=>{let s=t==="out"&&Y(a)?a instanceof X.z.ZodOptional:a.isOptional(),d=c.createPropertySignature(void 0,Ue(i),s&&n?c.createToken(m.default.SyntaxKind.QuestionToken):void 0,o(a));return a.description&&q(d,a.description),d});return c.createTypeLiteralNode(r)},mt=({element:e},{next:t})=>c.createArrayTypeNode(t(e)),ut=({options:e})=>c.createUnionTypeNode(e.map(t=>c.createLiteralTypeNode(c.createStringLiteral(t)))),$e=(e,{next:t})=>c.createUnionTypeNode(e.options.map(t)),lt=(e,t)=>t instanceof X.z.ZodDate?new Date:ct?.[e.kind],yt=(e,{next:t,direction:o})=>{let n=e.innerType(),r=t(n),i=e._def.effect;if(o==="out"&&i.type==="transform"){let a=oe(e,lt(r,n)),s={number:m.default.SyntaxKind.NumberKeyword,bigint:m.default.SyntaxKind.BigIntKeyword,boolean:m.default.SyntaxKind.BooleanKeyword,string:m.default.SyntaxKind.StringKeyword,undefined:m.default.SyntaxKind.UndefinedKeyword,object:m.default.SyntaxKind.ObjectKeyword};return c.createKeywordTypeNode(a&&s[a]||m.default.SyntaxKind.AnyKeyword)}return r},ft=e=>c.createUnionTypeNode(Object.values(e.enum).map(t=>c.createLiteralTypeNode(typeof t=="number"?c.createNumericLiteral(t):c.createStringLiteral(t)))),gt=(e,{next:t,optionalPropStyle:{withUndefined:o}})=>{let n=t(e.unwrap());return o?c.createUnionTypeNode([n,c.createKeywordTypeNode(m.default.SyntaxKind.UndefinedKeyword)]):n},xt=(e,{next:t})=>c.createUnionTypeNode([t(e.unwrap()),c.createLiteralTypeNode(c.createNull())]),bt=({items:e,_def:{rest:t}},{next:o})=>c.createTupleTypeNode(e.map(o).concat(t===null?[]:c.createRestTypeNode(o(t)))),ht=({keySchema:e,valueSchema:t},{next:o})=>c.createExpressionWithTypeArguments(c.createIdentifier("Record"),[e,t].map(o)),St=(e,{next:t})=>c.createIntersectionTypeNode([e._def.left,e._def.right].map(t)),Tt=(e,{next:t})=>t(e._def.innerType),F=e=>()=>c.createKeywordTypeNode(e),Zt=(e,{next:t})=>t(e.unwrap()),Nt=(e,{next:t})=>t(e._def.innerType),At=(e,{next:t})=>t(e._def.innerType),Et=(e,{next:t,direction:o})=>t(e._def[o]),zt=()=>c.createLiteralTypeNode(c.createNull()),Ot=()=>c.createTypeReferenceNode(c.createIdentifier("Date")),kt=(e,{makeAlias:t,next:o})=>t(e,()=>o(e.schema)),Ct=(e,{next:t})=>{let o=e.parameters().items.map((r,i)=>c.createParameterDeclaration(void 0,void 0,c.createIdentifier(r.description?D(l(r.description)):`${r instanceof X.z.ZodFunction?"cb":"p"}${i+1}`),void 0,t(r))),{rest:n}=e.parameters()._def;return n&&o.push(c.createParameterDeclaration(void 0,c.createToken(m.default.SyntaxKind.DotDotDotToken),c.createIdentifier(n.description?D(l(n.description)):"rest"),void 0,t(X.z.array(n)))),c.createFunctionTypeNode(void 0,o,t(e.returnType()))},Mt={ZodString:F(m.default.SyntaxKind.StringKeyword),ZodNumber:F(m.default.SyntaxKind.NumberKeyword),ZodBigInt:F(m.default.SyntaxKind.BigIntKeyword),ZodBoolean:F(m.default.SyntaxKind.BooleanKeyword),ZodAny:F(m.default.SyntaxKind.AnyKeyword),ZodVoid:F(m.default.SyntaxKind.VoidKeyword),ZodUnknown:F(m.default.SyntaxKind.UnknownKeyword),ZodDate:Ot,ZodNull:zt,ZodArray:mt,ZodTuple:bt,ZodRecord:ht,ZodObject:pt,ZodLiteral:dt,ZodIntersection:St,ZodUnion:$e,ZodDefault:Tt,ZodEnum:ut,ZodNativeEnum:ft,ZodEffects:yt,ZodOptional:gt,ZodNullable:xt,ZodDiscriminatedUnion:$e,ZodBranded:Zt,ZodCatch:At,ZodPipeline:Et,ZodLazy:kt,ZodReadonly:Nt,ZodFunction:Ct},Ze=(e,t)=>v(e,{rules:Mt,onMissing:()=>c.createKeywordTypeNode(m.default.SyntaxKind.AnyKeyword),ctx:t});var jt="root",Le=["emission","actions"],me=class{program=[];aliases={};ids={path:p.createIdentifier("path"),socket:p.createIdentifier("Socket"),socketBase:p.createIdentifier("SocketBase"),ioClient:p.createStringLiteral("socket.io-client"),emission:p.createIdentifier(l(Le[0])),actions:p.createIdentifier(l(Le[1]))};registry={};makeAlias(t,o,n){let r=this.aliases[t].get(o)?.name?.text;if(!r){r=`Type${this.aliases[t].size+1}`;let i=p.createLiteralTypeNode(p.createNull());this.aliases[t].set(o,Te(i,r)),this.aliases[t].set(o,Te(n(),r))}return p.createTypeReferenceNode(r)}constructor({config:{namespaces:t},actions:o,optionalPropStyle:n={withQuestionMark:!0,withUndefined:!0},maxOverloads:r=3}){this.program.push(p.createImportDeclaration(void 0,p.createImportClause(!0,void 0,p.createNamedImports([p.createImportSpecifier(!1,this.ids.socket,this.ids.socketBase)])),this.ids.ioClient));for(let[i,{emission:a}]of Object.entries(t)){this.aliases[i]=new Map,this.registry[i]={emission:[],actions:[]};let s={makeAlias:this.makeAlias.bind(this,i),optionalPropStyle:n};for(let[d,{schema:f,ack:A}]of Object.entries(a)){let x=Ze(Se(f,A,r),{direction:"out",...s});this.registry[i].emission.push({event:d,node:x})}for(let d of o)if(d.getNamespace()===i){let f=d.getEvent(),A=d.getSchema("input"),x=d.getSchema("output"),j=Ze(Se(A,x,r),{direction:"in",...s});this.registry[i].actions.push({event:f,node:j})}}for(let i in this.registry){let a=l(i)||l(jt),s=p.createVariableStatement(G,p.createVariableDeclarationList([p.createVariableDeclaration(this.ids.path,void 0,void 0,p.createStringLiteral(B(i)))],Ne.default.NodeFlags.Const));q(s,`@desc The actual path of the ${a} namespace`);let d=Object.entries(this.registry[i]).map(([A,x])=>p.createInterfaceDeclaration(G,l(A),void 0,void 0,x.map(({event:j,node:Z})=>p.createPropertySignature(void 0,j,void 0,Z)))),f=p.createTypeAliasDeclaration(G,this.ids.socket,void 0,p.createTypeReferenceNode(this.ids.socketBase,[p.createTypeReferenceNode(this.ids.emission),p.createTypeReferenceNode(this.ids.actions)]));q(f,`@example const socket: ${a}.${this.ids.socket.text} = io(${a}.${this.ids.path.text})`),this.program.push(p.createModuleDeclaration(G,p.createIdentifier(a),p.createModuleBlock([s,...this.aliases[i].values(),...d,f]),Ne.default.NodeFlags.Namespace))}}print(t){return this.program.map((o,n)=>Pe(o,n<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(` `)}};var K=require("zod");var Fe=P(require("yaml"),1),ue=class{document;constructor(t){this.document={asyncapi:"3.0.0",...t,servers:{},channels:{},components:{}}}addServer(t,o){return this.document.servers={...this.document.servers,[t]:o},this}addChannel(t,o){return this.document.channels={...this.document.channels,[t]:o},this}addOperation(t,o){return this.document.operations={...this.document.operations,[t]:o},this}addSecurityScheme(t,o){return this.document.components={...this.document.components,securitySchemes:{...this.document.components?.securitySchemes,[t]:o}},this}getSpec(){return this.document}getSpecAsJson(t,o){return JSON.stringify(this.document,t,o)}getSpecAsYaml(){return Fe.default.stringify(this.document)}};var ye=P(require("node:assert/strict"),1),y=require("ramda"),M=require("zod");function R(e){return"$ref"in e}var Dt={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},It=({_def:{innerType:e,defaultValue:t}},{next:o})=>({...o(e),default:t()}),wt=({_def:{innerType:e}},{next:t})=>t(e),He=()=>({format:"any"}),vt=({options:e},{next:t})=>({oneOf:e.map(t)}),Rt=({options:e,discriminator:t},{next:o})=>({discriminator:t,oneOf:Array.from(e.values()).map(o)}),Kt=e=>{let[t,o]=e.filter(r=>!R(r)&&r.type==="object"&&Object.keys(r).every(i=>["type","properties","required","examples"].includes(i)));(0,ye.default)(t&&o,"Can not flatten objects");let n={type:"object"};return(t.properties||o.properties)&&(n.properties=(0,y.mergeDeepWith)((r,i)=>Array.isArray(r)&&Array.isArray(i)?(0,y.concat)(r,i):r===i?i:ye.default.fail("Can not flatten properties"),t.properties||{},o.properties||{})),(t.required||o.required)&&(n.required=(0,y.union)(t.required||[],o.required||[])),n},Pt=({_def:{left:e,right:t}},{next:o})=>{let n=[e,t].map(o);try{return Kt(n)}catch{}return{allOf:n}},Ut=(e,{next:t})=>t(e.unwrap()),$t=(e,{next:t})=>t(e._def.innerType),Lt=(e,{next:t})=>{let o=t(e.unwrap());return R(o)||(o.type=Ve(o)),o},Be=e=>{let t=(0,y.toLower)((0,y.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},_e=e=>({type:Be(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Ft=({value:e})=>({type:Be(e),const:e}),Ht=(e,{direction:t,next:o})=>{let n=Object.keys(e.shape),r=s=>t==="out"&&Y(s)?s instanceof M.z.ZodOptional:s.isOptional(),i=n.filter(s=>!r(e.shape[s])),a={type:"object"};return n.length&&(a.properties=le(e,o)),i.length&&(a.required=i),a},_t=()=>({type:"null"}),Bt=()=>({type:"boolean"}),Vt=()=>({type:"integer",format:"bigint"}),Wt=e=>e.every(t=>t instanceof M.z.ZodLiteral),qt=({keySchema:e,valueSchema:t},{next:o})=>{if(e instanceof M.z.ZodEnum||e instanceof M.z.ZodNativeEnum){let n=Object.values(e.enum),r={type:"object"};return n.length&&(r.properties=le(M.z.object((0,y.fromPairs)((0,y.xprod)(n,[t]))),o),r.required=n),r}if(e instanceof M.z.ZodLiteral)return{type:"object",properties:le(M.z.object({[e.value]:t}),o),required:[e.value]};if(e instanceof M.z.ZodUnion&&Wt(e.options)){let n=(0,y.map)(i=>`${i.value}`,e.options),r=(0,y.fromPairs)((0,y.xprod)(n,[t]));return{type:"object",properties:le(M.z.object(r),o),required:n}}return{type:"object",additionalProperties:o(t)}},Yt=({_def:e,element:t},{next:o})=>{let n={type:"array",items:o(t)};return e.minLength&&(n.minItems=e.minLength.value),e.maxLength&&(n.maxItems=e.maxLength.value),n},Jt=({items:e,_def:{rest:t}},{next:o})=>({type:"array",items:e.length?e.map(o):void 0,additionalItems:t===null?!1:o(t)}),Qt=({isEmail:e,isURL:t,minLength:o,maxLength:n,isUUID:r,isCUID:i,isCUID2:a,isULID:s,isIP:d,isEmoji:f,isDatetime:A,_def:{checks:x}})=>{let j=x.find(T=>T.kind==="regex"),Z=x.find(T=>T.kind==="datetime"),N=j?j.regex:Z?Z.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,S={type:"string"},H={"date-time":A,email:e,url:t,uuid:r,cuid:i,cuid2:a,ulid:s,ip:d,emoji:f};for(let T in H)if(H[T]){S.format=T;break}return o!==null&&(S.minLength=o),n!==null&&(S.maxLength=n),N&&(S.pattern=N.source),S},Gt=e=>{let t=e._def.checks.find(({kind:d})=>d==="min"),o=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,n=t?t.inclusive:!0,r=e._def.checks.find(({kind:d})=>d==="max"),i=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=r?r.inclusive:!0,s={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return n?s.minimum=o:s.exclusiveMinimum=o,a?s.maximum=i:s.exclusiveMaximum=i,s},le=({shape:e},t)=>(0,y.map)(t,e),Xt=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return e.format==="date"?new Date:Dt?.[t]},Ve=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},eo=(e,{direction:t,next:o})=>{let n=o(e.innerType()),{effect:r}=e._def;if(t==="out"&&r.type==="transform"&&!R(n)){let i=oe(e,Xt(n));return i&&["number","string","boolean"].includes(i)?{type:i}:o(M.z.any())}if(t==="in"&&r.type==="preprocess"&&!R(n)){let{type:i,...a}=n;return{...a,format:`${a.format||i} (preprocessed)`}}return n},to=(e,{direction:t,next:o})=>o(e._def[t]),oo=(e,{next:t})=>t(e.unwrap()),no=()=>({format:"date"}),Ae={ZodString:Qt,ZodNumber:Gt,ZodBigInt:Vt,ZodBoolean:Bt,ZodNull:_t,ZodArray:Yt,ZodTuple:Jt,ZodRecord:qt,ZodObject:Ht,ZodLiteral:Ft,ZodIntersection:Pt,ZodUnion:vt,ZodAny:He,ZodDefault:It,ZodEnum:_e,ZodNativeEnum:_e,ZodEffects:eo,ZodOptional:Ut,ZodNullable:Lt,ZodDiscriminatedUnion:Rt,ZodBranded:oo,ZodCatch:wt,ZodPipeline:to,ZodReadonly:$t,ZodDate:no,ZodUnknown:He},Ee=(e,{direction:t,prev:o})=>{if(R(o))return{};let{description:n}=e,r=o.type!==void 0,i=t==="out"&&Y(e),a=r&&!i&&e.isNullable(),s={};return n&&(s.description=n),a&&(s.type=Ve(o)),s},ze=e=>ye.default.fail(`Zod type ${e.constructor.name} is unsupported.`),ro=(e,t)=>{if(R(e)||!t)return e;if(e.type==="array"&&e.items&&Array.isArray(e.items))for(let o of t)for(let n=0;n<o.length;n++){let r=e.items[n];r&&!R(r)&&(r.examples=[...r.examples||[],o[n]])}return e},ee=({event:e,schema:t,examples:o,direction:n,isAck:r})=>({name:r?void 0:e,title:r?`Acknowledgement for ${e}`:e,payload:ro(v(t,{ctx:{direction:n},onMissing:ze,onEach:Ee,rules:Ae}),o),examples:o&&o.length?o.map(i=>({payload:i})):void 0}),Oe=({direction:e,channelId:t,messageId:o,ackId:n,event:r,ns:i,securityIds:a})=>({action:e==="out"?"send":"receive",channel:{$ref:`#/channels/${t}`},messages:[{$ref:`#/channels/${t}/messages/${o}`}],title:r,summary:`${e==="out"?"Outgoing":"Incoming"} event ${r}`,description:`The message ${e==="out"?"produced":"consumed"} by the application within the ${i} namespace`,security:a&&a.length?a.map(s=>({$ref:`#/components/securitySchemes/${s}`})):void 0,reply:n?{address:{location:"$message.payload#",description:"Last argument: acknowledgement handler"},channel:{$ref:`#/channels/${t}`},messages:[{$ref:`#/channels/${t}/messages/${n}`}]}:void 0});var We=(e,t)=>t&&(Array.isArray(t)?t:[t]).map(o=>o[e]).filter(o=>!!o),fe=class extends ue{#t(){let t={onEach:Ee,onMissing:ze,rules:Ae,ctx:{direction:"in"}};return{bindingVersion:"0.1.0",method:"GET",headers:v(K.z.object({connection:K.z.literal("Upgrade").optional(),upgrade:K.z.literal("websocket").optional()}),t),query:{...v(K.z.object({EIO:K.z.literal("4").describe("The version of the protocol"),transport:K.z.enum(["polling","websocket"]).describe("The name of the transport"),sid:K.z.string().optional().describe("The session identifier")}),t),externalDocs:{description:"Engine.IO Protocol",url:"https://socket.io/docs/v4/engine-io-protocol/"}}}}constructor({actions:t,config:{namespaces:o,security:n},title:r,version:i,documentId:a,description:s,contact:d,license:f,servers:A={}}){super({info:{title:r,version:i,contact:d,license:f,description:s},id:a,defaultContentType:"text/plain"});let x=[];for(let[Z,N]of Object.entries(n)){let S=D(l(`server security ${Z}`));this.addSecurityScheme(S,N),x.push(S)}for(let Z in A){let N=new URL(A[Z].url);this.addServer(Z,{description:A[Z].description,host:N.host,pathname:N.pathname,protocol:N.protocol.slice(0,-1),security:x.length?x.map(S=>({$ref:`#/components/securitySchemes/${S}`})):void 0}),this.document.id||(this.document.id=`urn:${N.host.split(".").concat(N.pathname.slice(1).split("/")).join(":")}`)}let j=this.#t();for(let[Z,{emission:N,examples:S,security:H}]of Object.entries(o)){let T=B(Z),b=l(T)||"Root",w={},g=[];for(let[u,z]of Object.entries(H)){let C=D(l(`${b} security ${u}`));this.addSecurityScheme(C,z),g.push(C)}for(let[u,{schema:z,ack:C}]of Object.entries(N)){let O=D(l(`${b} outgoing ${u}`)),h=D(l(`${b} ack for outgoing ${u}`));w[O]=ee({event:u,schema:z,direction:"out",examples:We("payload",S[u])}),C&&(w[h]=ee({event:u,schema:C,examples:We("ack",S[u]),direction:"in",isAck:!0})),this.addOperation(l(`${b} send operation ${u}`),Oe({direction:"out",event:u,channelId:b,messageId:O,ackId:C&&h,ns:T}))}for(let u of t)if(u.getNamespace()===T){let z=u.getEvent(),C=D(l(`${b} incoming ${z}`)),O=D(l(`${b} ack for incoming ${z}`)),h=u.getSchema("output");w[C]=ee({event:z,schema:u.getSchema("input"),examples:u.getExamples("input"),direction:"in"}),h&&(w[O]=ee({event:z,schema:h,examples:u.getExamples("output"),direction:"out",isAck:!0})),this.addOperation(l(`${b} recv operation ${z}`),Oe({direction:"in",channelId:b,messageId:C,event:z,ns:T,ackId:h&&O,securityIds:g}))}this.addChannel(b,{address:T,title:`Namespace ${T}`,bindings:{ws:j},messages:w})}}};0&&(module.exports={AbstractAction,ActionsFactory,Config,Documentation,InputValidationError,Integration,OutputValidationError,attachSockets,createSimpleConfig});