iosignal 9.12.0 → 9.13.0

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.
@@ -16,7 +16,7 @@ import fs, { readFileSync } from 'fs';
16
16
  import { memoryUsage } from 'process';
17
17
  import path from 'path';
18
18
 
19
- var version$1 = "9.12.0";
19
+ var version$1 = "9.13.0";
20
20
  var pkg = {
21
21
  version: version$1};
22
22
 
@@ -594,12 +594,12 @@ const STATUS$1 = {
594
594
  ERROR: 255
595
595
  };
596
596
 
597
- const encoder$2 = new TextEncoder();
597
+ const encoder$3 = new TextEncoder();
598
598
 
599
599
 
600
600
  function getSignalPack(tag, ...args) {
601
601
  if (typeof tag !== 'string') throw TypeError('tag should be string.')
602
- let tagEncoded = encoder$2.encode(tag);
602
+ let tagEncoded = encoder$3.encode(tag);
603
603
  if (tagEncoded.byteLength > SIZE_LIMIT.TAG_LEN1) throw TypeError('tag UTF-8 byte length exceeds 255')
604
604
  let payload = parsePayload(args);
605
605
 
@@ -641,7 +641,7 @@ function parsePayload(args) {
641
641
  } else if (args.length == 1) {
642
642
  if (typeof args[0] === 'string' || typeof args[0] === 'number') {
643
643
  type = PAYLOAD_TYPE.TEXT;
644
- pack = encoder$2.encode(args[0] + "."); // add null byte area.
644
+ pack = encoder$3.encode(args[0] + "."); // add null byte area.
645
645
  pack[pack.byteLength - 1] = 0; // set byte-zero : '\0' in C/C++
646
646
 
647
647
  } else if (ArrayBuffer.isView(args[0]) || args[0] instanceof ArrayBuffer) {
@@ -649,7 +649,7 @@ function parsePayload(args) {
649
649
  pack = $$1.B8(args[0]);
650
650
  } else if (typeof args[0] === 'object') {
651
651
  type = PAYLOAD_TYPE.OBJECT;
652
- pack = encoder$2.encode(JSON.stringify(args[0]));
652
+ pack = encoder$3.encode(JSON.stringify(args[0]));
653
653
  } else {
654
654
  throw new Error('unknown payload arguments')
655
655
  }
@@ -663,7 +663,7 @@ function parsePayload(args) {
663
663
  type = PAYLOAD_TYPE.MBA;
664
664
  } else {
665
665
  type = PAYLOAD_TYPE.MJSON;
666
- pack = encoder$2.encode(JSON.stringify(args));
666
+ pack = encoder$3.encode(JSON.stringify(args));
667
667
  }
668
668
 
669
669
  }
@@ -675,6 +675,42 @@ function getPayloadFromSignalPack(signalPack) {
675
675
  let tagLen = signalPack.readUint8(1);
676
676
  return signalPack.subarray(3 + tagLen)
677
677
  }
678
+ const decoder$5 = new TextDecoder();
679
+
680
+ /**
681
+ * Arguments of a SIGNAL payload, as IO emits them after the tag: EMPTY [], TEXT [string] (the
682
+ * trailing NUL that C/C++ senders add is removed), BINARY [the buffer itself], OBJECT [value],
683
+ * MJSON [...values], MBA [...args]. null for an unknown payload type. Throws on malformed JSON/MBA.
684
+ * @param {number} payloadType
685
+ * @param {Uint8Array} payloadBuffer
686
+ * @returns {any[] | null}
687
+ */
688
+ function decodeSignalArgs(payloadType, payloadBuffer) {
689
+ switch (payloadType) {
690
+ case PAYLOAD_TYPE.EMPTY:
691
+ return []
692
+ case PAYLOAD_TYPE.TEXT: {
693
+ const end = payloadBuffer[payloadBuffer.byteLength - 1] === 0 ? payloadBuffer.byteLength - 1 : payloadBuffer.byteLength;
694
+ return [decoder$5.decode(payloadBuffer.subarray(0, end))]
695
+ }
696
+ case PAYLOAD_TYPE.BINARY:
697
+ return [payloadBuffer]
698
+ case PAYLOAD_TYPE.OBJECT:
699
+ return [JSON.parse(decoder$5.decode(payloadBuffer))]
700
+ case PAYLOAD_TYPE.MJSON: {
701
+ const values = JSON.parse(decoder$5.decode(payloadBuffer));
702
+ if (!Array.isArray(values)) throw new TypeError('MJSON payload is not an array')
703
+ return values
704
+ }
705
+ case PAYLOAD_TYPE.MBA: {
706
+ const mba = $$1.unpack(payloadBuffer);
707
+ if (!mba) throw new TypeError('malformed MBA payload')
708
+ return mba.args
709
+ }
710
+ default:
711
+ return null
712
+ }
713
+ }
678
714
 
679
715
  const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function e(e,r,n,i,o){let f,s,u,h,a,c,l,p,y,g,d,b,w;for(;o>=64;){for(f=r[0],s=r[1],u=r[2],h=r[3],a=r[4],c=r[5],l=r[6],p=r[7],g=0;g<16;g++)d=i+4*g,e[g]=(255&n[d])<<24|(255&n[d+1])<<16|(255&n[d+2])<<8|255&n[d+3];for(g=16;g<64;g++)y=e[g-2],b=(y>>>17|y<<15)^(y>>>19|y<<13)^y>>>10,y=e[g-15],w=(y>>>7|y<<25)^(y>>>18|y<<14)^y>>>3,e[g]=(b+e[g-7]|0)+(w+e[g-16]|0);for(g=0;g<64;g++)b=(((a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7))+(a&c^~a&l)|0)+(p+(t[g]+e[g]|0)|0)|0,w=((f>>>2|f<<30)^(f>>>13|f<<19)^(f>>>22|f<<10))+(f&s^f&u^s&u)|0,p=l,l=c,c=a,a=h+b|0,h=u,u=s,s=f,f=b+w|0;r[0]+=f,r[1]+=s,r[2]+=u,r[3]+=h,r[4]+=a,r[5]+=c,r[6]+=l,r[7]+=p,i+=64,o-=64;}return i}const r=function(){function t(){this.digestLength=32,this.blockSize=64,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=false,this.reset();}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=false,this},t.prototype.clean=function(){for(var t=0;t<this.buffer.length;t++)this.buffer[t]=0;for(t=0;t<this.temp.length;t++)this.temp[t]=0;this.reset();},t.prototype.update=function(t,r){if(void 0===r&&(r=t.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");let n=0;if(this.bytesHashed+=r,this.bufferLength>0){for(;this.bufferLength<64&&r>0;)this.buffer[this.bufferLength++]=t[n++],r--;64===this.bufferLength&&(e(this.temp,this.state,this.buffer,0,64),this.bufferLength=0);}for(r>=64&&(n=e(this.temp,this.state,t,n,r),r%=64);r>0;)this.buffer[this.bufferLength++]=t[n++],r--;return this},t.prototype.finish=function(t){if(!this.finished){const t=this.bytesHashed,n=this.bufferLength,i=t/536870912|0,o=t<<3,f=t%64<56?64:128;this.buffer[n]=128;for(var r=n+1;r<f-8;r++)this.buffer[r]=0;this.buffer[f-8]=i>>>24&255,this.buffer[f-7]=i>>>16&255,this.buffer[f-6]=i>>>8&255,this.buffer[f-5]=i>>>0&255,this.buffer[f-4]=o>>>24&255,this.buffer[f-3]=o>>>16&255,this.buffer[f-2]=o>>>8&255,this.buffer[f-1]=o>>>0&255,e(this.temp,this.state,this.buffer,0,f),this.finished=true;}for(r=0;r<8;r++)t[4*r+0]=this.state[r]>>>24&255,t[4*r+1]=this.state[r]>>>16&255,t[4*r+2]=this.state[r]>>>8&255,t[4*r+3]=this.state[r]>>>0&255;return this},t.prototype.digest=function(){const t=new Uint8Array(this.digestLength);return this.finish(t),t},t.prototype._saveState=function(t){for(let e=0;e<this.state.length;e++)t[e]=this.state[e];},t.prototype._restoreState=function(t,e){for(let e=0;e<this.state.length;e++)this.state[e]=t[e];this.bytesHashed=e,this.finished=false,this.bufferLength=0;},t}(),n=function(){function t(t){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;const e=new Uint8Array(this.blockSize);if(t.length>this.blockSize)(new r).update(t).finish(e).clean();else for(var n=0;n<t.length;n++)e[n]=t[n];for(n=0;n<e.length;n++)e[n]^=54;this.inner.update(e);for(n=0;n<e.length;n++)e[n]^=106;this.outer.update(e),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(n=0;n<e.length;n++)e[n]=0;}return t.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},t.prototype.clean=function(){for(let t=0;t<this.istate.length;t++)this.ostate[t]=this.istate[t]=0;this.inner.clean(),this.outer.clean();},t.prototype.update=function(t){return this.inner.update(t),this},t.prototype.finish=function(t){return this.outer.finished?this.outer.finish(t):(this.inner.finish(t),this.outer.update(t,this.digestLength).finish(t)),this},t.prototype.digest=function(){const t=new Uint8Array(this.digestLength);return this.finish(t),t},t}();function i(t){const e=(new r).update(t),n=e.digest();return e.clean(),n}var o,f,s,u={},h={},a={};
680
716
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */function c(){return f||(f=1,a.read=function(t,e,r,n,i){var o,f,s=8*i-n-1,u=(1<<s)-1,h=u>>1,a=-7,c=r?i-1:0,l=r?-1:1,p=t[e+c];for(c+=l,o=p&(1<<-a)-1,p>>=-a,a+=s;a>0;o=256*o+t[e+c],c+=l,a-=8);for(f=o&(1<<-a)-1,o>>=-a,a+=n;a>0;f=256*f+t[e+c],c+=l,a-=8);if(0===o)o=1-h;else {if(o===u)return f?NaN:1/0*(p?-1:1);f+=Math.pow(2,n),o-=h;}return (p?-1:1)*f*Math.pow(2,o-n)},a.write=function(t,e,r,n,i,o){var f,s,u,h=8*o-i-1,a=(1<<h)-1,c=a>>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,y=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,f=a):(f=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-f))<1&&(f--,u*=2),(e+=f+c>=1?l/u:l*Math.pow(2,1-c))*u>=2&&(f++,u/=2),f+c>=a?(s=0,f=a):f+c>=1?(s=(e*u-1)*Math.pow(2,i),f+=c):(s=e*Math.pow(2,c-1)*Math.pow(2,i),f=0));i>=8;t[r+p]=255&s,p+=y,s/=256,i-=8);for(f=f<<i|s,h+=i;h>0;t[r+p]=255&f,p+=y,f/=256,h-=8);t[r+p-y]|=128*g;}),a}
@@ -703,13 +739,13 @@ const t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1
703
739
  */
704
740
 
705
741
  const Buffer$1 = $$1.Buffer;
706
- const encoder$1 = new TextEncoder();
742
+ const encoder$2 = new TextEncoder();
707
743
  const decoder$4 = new TextDecoder();
708
744
 
709
745
  // Wire tag lengths use one byte, regardless of JavaScript string length.
710
746
  function encodeTag(tag, allowEmpty = true) {
711
747
  if (typeof tag !== 'string') throw TypeError('tag should be string.')
712
- const encoded = encoder$1.encode(tag);
748
+ const encoded = encoder$2.encode(tag);
713
749
  if ((!allowEmpty && encoded.byteLength === 0) || encoded.byteLength > SIZE_LIMIT.TAG_LEN1) {
714
750
  throw TypeError('tag UTF-8 byte length must be ' + (allowEmpty ? '0' : '1') + '~255')
715
751
  }
@@ -1289,83 +1325,15 @@ class IOCore extends EventEmitter {
1289
1325
  > cid_sub message: tag includes cid and @ both : 'cid@*'
1290
1326
  > ch_sub message: else.
1291
1327
  */
1292
- // console.log('payloadType', payloadType )
1293
- switch (payloadType) {
1294
-
1295
- case PAYLOAD_TYPE.EMPTY:
1296
- if (tag.indexOf('@') === 0) {
1297
- this.emit('@', tag);
1298
- if (tag !== '@') this.emit(tag, tag);
1299
- } else {
1300
- this.emit(tag, tag);
1301
- this.emit('message', tag);
1302
- }
1303
- break;
1304
-
1305
- case PAYLOAD_TYPE.TEXT:
1306
- // !! Must remove null char before decode in JS.
1307
- // string payload contains null char for the c/cpp devices.
1308
- let payloadStringWithoutNull = payloadBuffer;
1309
- if (payloadBuffer[payloadBuffer.byteLength - 1] === 0) {
1310
- payloadStringWithoutNull = payloadBuffer.subarray(0, payloadBuffer.byteLength - 1);
1311
- }
1312
- let oneString = decoder$4.decode(payloadStringWithoutNull);
1313
- if (tag.indexOf('@') === 0) {
1314
- this.emit('@', tag, oneString);
1315
- if (tag !== '@') this.emit(tag, tag, oneString);
1316
- } else {
1317
- this.emit(tag, tag, oneString);
1318
- this.emit('message', tag, oneString);
1319
- }
1320
- break;
1321
-
1322
- case PAYLOAD_TYPE.BINARY:
1323
- if (tag.indexOf('@') === 0) {
1324
- this.emit('@', tag, payloadBuffer);
1325
- if (tag !== '@') this.emit(tag, tag, payloadBuffer);
1326
- } else {
1327
- this.emit(tag, tag, payloadBuffer);
1328
- this.emit('message', tag, payloadBuffer);
1329
- }
1330
- break;
1331
-
1332
- case PAYLOAD_TYPE.OBJECT:
1333
- let oneObjectBuffer = decoder$4.decode(payloadBuffer);
1334
- let oneJSONObject = JSON.parse(oneObjectBuffer);
1335
- if (tag.indexOf('@') === 0) {
1336
- this.emit('@', tag, oneJSONObject);
1337
- if (tag !== '@') this.emit(tag, tag, oneJSONObject);
1338
- } else {
1339
- this.emit(tag, tag, oneJSONObject);
1340
- this.emit('message', tag, oneJSONObject);
1341
- }
1342
- break;
1343
-
1344
- case PAYLOAD_TYPE.MJSON:
1345
- let mjsonBuffer = decoder$4.decode(payloadBuffer);
1346
- let mjson = JSON.parse(mjsonBuffer);
1347
- if (tag.indexOf('@') === 0) {
1348
- this.emit('@', tag, ...mjson);
1349
- if (tag !== '@') this.emit(tag, tag, ...mjson);
1350
- } else {
1351
- this.emit(tag, tag, ...mjson);
1352
- this.emit('message', tag, ...mjson);
1353
- }
1354
- break;
1355
-
1356
- case PAYLOAD_TYPE.MBA:
1357
- let mbaObject = $$1.unpack(payloadBuffer);
1358
- if (tag.indexOf('@') === 0) {
1359
- this.emit('@', tag, ...mbaObject.args);
1360
- if (tag !== '@') this.emit(tag, tag, ...mbaObject.args);
1361
- } else {
1362
- this.emit(tag, tag, ...mbaObject.args);
1363
- this.emit('message', tag, ...mbaObject.args);
1364
- }
1365
- break;
1366
-
1367
- default:
1368
- // console.log('## Unkown payloadtype', payloadType)
1328
+ const args = decodeSignalArgs(payloadType, payloadBuffer);
1329
+ if (args) {
1330
+ if (tag.indexOf('@') === 0) {
1331
+ this.emit('@', tag, ...args);
1332
+ if (tag !== '@') this.emit(tag, tag, ...args);
1333
+ } else {
1334
+ this.emit(tag, tag, ...args);
1335
+ this.emit('message', tag, ...args);
1336
+ }
1369
1337
  }
1370
1338
 
1371
1339
  } catch (err) {
@@ -8743,6 +8711,264 @@ function deliveryAllowed(target, sender) {
8743
8711
  return policy.defaultAllow
8744
8712
  }
8745
8713
 
8714
+ const encoder$1 = new TextEncoder();
8715
+ const NAME = /^[A-Za-z0-9_.-]{1,64}$/;
8716
+
8717
+ /**
8718
+ * Validates one tag pattern of a host. A trailing '*' makes it a prefix; '*' is allowed nowhere else.
8719
+ * Channel patterns (inbound, and own without '@'): global channel tags, so no '@' and no leading
8720
+ * '#' (home channels belong to one network) or '$'. Unicast patterns (own, leading '@'): the topic
8721
+ * of '<cid>@topic' messages.
8722
+ * @returns {{ pattern: string, text: string, prefix: boolean, unicast: boolean }}
8723
+ */
8724
+ function parsePattern(pattern, allowUnicast) {
8725
+ if (typeof pattern !== 'string' || pattern.length === 0) throw new TypeError('host tag must be a non-empty string')
8726
+ const prefix = pattern.endsWith('*');
8727
+ const text = prefix ? pattern.slice(0, -1) : pattern;
8728
+ if (text.includes('*')) throw new TypeError(`host tag ${pattern}: '*' is allowed only at the end`)
8729
+ if (text.includes(',')) throw new TypeError(`host tag ${pattern}: ',' separates tags`)
8730
+ if (encoder$1.encode(text).byteLength > SIZE_LIMIT.TAG_LEN1) throw new TypeError(`host tag ${pattern} exceeds 255 UTF-8 bytes`)
8731
+ const unicast = text.startsWith('@');
8732
+ if (unicast) {
8733
+ if (!allowUnicast) throw new TypeError(`host tag ${pattern}: inbound tags are channel tags (no '@')`)
8734
+ if (text.indexOf('@', 1) !== -1) throw new TypeError(`host tag ${pattern}: a unicast topic has one '@'`)
8735
+ if (text.length === 1) throw new TypeError(`host tag ${pattern}: empty topic`)
8736
+ } else {
8737
+ if (text.includes('@')) throw new TypeError(`host tag ${pattern}: channel tags have no '@'`)
8738
+ if (text.startsWith('#')) throw new TypeError(`host tag ${pattern}: home channel tags ('#...') cannot be hosted`)
8739
+ if (text.startsWith('$')) throw new TypeError(`host tag ${pattern}: '$' prefix is reserved`)
8740
+ if (text.length === 0) throw new TypeError(`host tag ${pattern}: empty tag`)
8741
+ }
8742
+ return { pattern, text, prefix, unicast }
8743
+ }
8744
+
8745
+ function overlaps(a, b) {
8746
+ if (a.prefix && b.text.startsWith(a.text)) return true
8747
+ if (b.prefix && a.text.startsWith(b.text)) return true
8748
+ return a.text === b.text
8749
+ }
8750
+
8751
+ /**
8752
+ * The tags all hosts of one server have claimed. Patterns never overlap, so a tag matches at most one.
8753
+ */
8754
+ class HostTable {
8755
+ constructor() {
8756
+ this.exact = new Map(); // text -> entry
8757
+ this.prefixes = []; // entries
8758
+ this.hosts = new Map(); // name -> Host
8759
+ }
8760
+
8761
+ get size() {
8762
+ return this.hosts.size
8763
+ }
8764
+
8765
+ add(host, entries) {
8766
+ if (this.hosts.has(host.name)) throw new Error(`host ${host.name} already exists`)
8767
+ const all = [...this.exact.values(), ...this.prefixes];
8768
+ entries.forEach((entry, i) => {
8769
+ for (const other of [...all, ...entries.slice(0, i)]) {
8770
+ if (overlaps(entry, other)) {
8771
+ throw new Error(`host tag ${entry.pattern} overlaps ${other.pattern}` +
8772
+ (other.host === host ? '' : ` of host ${other.host.name}`))
8773
+ }
8774
+ }
8775
+ });
8776
+ for (const entry of entries) {
8777
+ if (entry.prefix) this.prefixes.push(entry);
8778
+ else this.exact.set(entry.text, entry);
8779
+ }
8780
+ this.hosts.set(host.name, host);
8781
+ }
8782
+
8783
+ remove(host) {
8784
+ if (this.hosts.get(host.name) !== host) return
8785
+ this.hosts.delete(host.name);
8786
+ for (const [text, entry] of this.exact) if (entry.host === host) this.exact.delete(text);
8787
+ this.prefixes = this.prefixes.filter(entry => entry.host !== host);
8788
+ }
8789
+
8790
+ // tag: a client channel tag, or '@topic' of a unicast. Returns the entry or undefined.
8791
+ match(tag) {
8792
+ const entry = this.exact.get(tag);
8793
+ if (entry) return entry
8794
+ for (const p of this.prefixes) if (tag.startsWith(p.text)) return p
8795
+ return undefined
8796
+ }
8797
+
8798
+ // A connection closed. ownsCid: it still owned its CID (no newer connection took it over).
8799
+ remoteClosed(remote, ownsCid) {
8800
+ if (!ownsCid || !remote.cid) return
8801
+ for (const host of this.hosts.values()) host._remoteClosed(remote);
8802
+ }
8803
+ }
8804
+
8805
+ /**
8806
+ * Game logic (or any server-side logic) inside the server process. Created by server.host().
8807
+ *
8808
+ * Events:
8809
+ * 'message' (from, tag, ...args) a client signal to one of the inbound tags. from is the
8810
+ * server's view of the sender (never anything in the payload).
8811
+ * 'leave' (from, reason) a participant's connection closed (it no longer has its CID)
8812
+ * 'error' (error) a 'message' or 'leave' handler threw
8813
+ * 'close' () the host was closed
8814
+ */
8815
+ class Host extends require$$0$3 {
8816
+
8817
+ constructor(manager, name, options = {}) {
8818
+ super();
8819
+ if (typeof name !== 'string' || !NAME.test(name)) {
8820
+ throw new TypeError('host name: 1-64 characters of A-Z a-z 0-9 _ . -')
8821
+ }
8822
+ if (options === null || typeof options !== 'object') throw new TypeError('host options must be an object')
8823
+ for (const key of Object.keys(options)) {
8824
+ if (!['inbound', 'own', 'fanout', 'retain'].includes(key)) throw new TypeError(`unknown host option: ${key}`)
8825
+ }
8826
+ const list = (key) => {
8827
+ const value = options[key] ?? [];
8828
+ if (!Array.isArray(value)) throw new TypeError(`host option ${key} must be an array of tags`)
8829
+ return value
8830
+ };
8831
+ /** @type {Host} */
8832
+ const host = this;
8833
+ const inbound = list('inbound').map(p => ({ ...parsePattern(p, false), kind: 'inbound', host }));
8834
+ const own = list('own').map(p => ({ ...parsePattern(p, true), kind: 'own', host }));
8835
+ if (inbound.length === 0) throw new TypeError('host needs at least one inbound tag')
8836
+
8837
+ const fanout = options.fanout ?? null;
8838
+ if (fanout !== null && !(Number.isSafeInteger(fanout) && fanout > 0)) {
8839
+ throw new RangeError('host fanout must be null or a positive integer')
8840
+ }
8841
+ const retain = options.retain ?? {};
8842
+ for (const key of ['tags', 'bytes']) {
8843
+ if (retain[key] !== undefined && !(Number.isSafeInteger(retain[key]) && retain[key] > 0)) {
8844
+ throw new RangeError(`host retain.${key} must be a positive integer`)
8845
+ }
8846
+ }
8847
+
8848
+ this.name = name;
8849
+ this.manager = manager;
8850
+ this.fanout = fanout;
8851
+ this.retainTags = retain.tags ?? null; // null: the server's retain.tagsPerOwner
8852
+ this.retainBytes = retain.bytes ?? null; // null: the server's retain.bytesPerOwner
8853
+ this.retainOwnerKey = 'host:' + name;
8854
+ this.ownChannels = own.filter(e => !e.unicast);
8855
+ this.closed = false;
8856
+ /** @type {Map<string, Readonly<object>>} cid -> from, connections that sent to this host */
8857
+ this._participants = new Map();
8858
+
8859
+ manager.hosts.add(this, [...inbound, ...own]);
8860
+ // Values a client retained on these tags before the host claimed them are not the host's.
8861
+ for (const tag of [...manager.retain_messages.keys()]) {
8862
+ if (!tag.startsWith(manager.CHANNEL_PREFIX)) continue
8863
+ const entry = manager.hosts.match(tag.slice(manager.CHANNEL_PREFIX.length));
8864
+ if (entry?.host === this) manager.dropChannelRetain(tag);
8865
+ }
8866
+ }
8867
+
8868
+ /** Connections that have sent to this host and are still online: cid -> from. */
8869
+ get participants() {
8870
+ return this._participants
8871
+ }
8872
+
8873
+ /** Stop tracking a participant; no 'leave' is emitted for it (until it sends again). */
8874
+ forget(cid) {
8875
+ return this._participants.delete(cid)
8876
+ }
8877
+
8878
+ /**
8879
+ * Publish to one of the host's own channel tags. A tag with '$' is also retained, owned by the
8880
+ * host. Returns the number of connections it was delivered to.
8881
+ */
8882
+ publish(tag, ...args) {
8883
+ this._open();
8884
+ if (typeof tag !== 'string') throw new TypeError('tag should be string.')
8885
+ const entry = this.manager.hosts.match(tag);
8886
+ if (tag.startsWith('@') || entry?.host !== this || entry.kind !== 'own') {
8887
+ throw new Error(`host ${this.name} does not own channel tag ${tag}`)
8888
+ }
8889
+ const message = getSignalPack(tag, ...args);
8890
+ return this.manager.hostPublish(this, this.manager.CHANNEL_PREFIX + tag, message)
8891
+ }
8892
+
8893
+ /**
8894
+ * Send to one connection. It receives '@' + topic. Returns false when the CID is not online
8895
+ * or its receive buffer is too small for the message.
8896
+ */
8897
+ to(cid, topic, ...args) {
8898
+ this._open();
8899
+ if (typeof topic !== 'string' || topic.length === 0 || topic.includes('@')) {
8900
+ throw new TypeError('topic must be a non-empty string without @')
8901
+ }
8902
+ const remote = this.manager.cid2remote.get(cid);
8903
+ const message = getSignalPack('@' + topic, ...args);
8904
+ if (!remote || remote._closing) return false
8905
+ const skipped = remote.peerRxLimitSkipped;
8906
+ remote.send_enc_mode(message);
8907
+ return remote.peerRxLimitSkipped === skipped
8908
+ }
8909
+
8910
+ /** Release the tags (they become ordinary channels again) and the host's retained values. */
8911
+ close() {
8912
+ if (this.closed) return
8913
+ this.closed = true;
8914
+ this.manager.hosts.remove(this);
8915
+ const owner = this.manager.retainOwners.get(this.retainOwnerKey);
8916
+ if (owner) for (const tag of [...owner.tags]) this.manager.dropChannelRetain(tag);
8917
+ this._participants.clear();
8918
+ this.emit('close');
8919
+ }
8920
+
8921
+ _open() {
8922
+ if (this.closed) throw new Error(`host ${this.name} is closed`)
8923
+ }
8924
+
8925
+ // The server's view of a sender; reused while nothing in it changes.
8926
+ static from(remote) {
8927
+ const authorized = remote.boho?.isAuthorized === true;
8928
+ const f = remote._hostFrom;
8929
+ if (f && f.cid === remote.cid && f.uid === remote.uid && f.role === remote.role &&
8930
+ f.nick === remote.nick && f.authorized === authorized) return f
8931
+ return remote._hostFrom = Object.freeze({
8932
+ cid: remote.cid, uid: remote.uid || null, role: remote.role, authorized,
8933
+ nick: remote.nick || '', ssid: remote.ssid
8934
+ })
8935
+ }
8936
+
8937
+ // A SIGNAL from a client to one of the inbound tags. Returns false if it was not delivered.
8938
+ _receive(remote, tag, message) {
8939
+ if (message[0] !== IOMsg.SIGNAL || !remote.cid) return false
8940
+ const tagLen = message[1];
8941
+ if (message.byteLength < tagLen + 3) return false
8942
+ let args;
8943
+ try {
8944
+ args = decodeSignalArgs(message[2 + tagLen], message.subarray(3 + tagLen));
8945
+ } catch {
8946
+ return false
8947
+ }
8948
+ if (!args) return false
8949
+ const from = Host.from(remote);
8950
+ this._participants.set(from.cid, from);
8951
+ this._emitSafely('message', from, tag, ...args);
8952
+ return true
8953
+ }
8954
+
8955
+ _remoteClosed(remote) {
8956
+ const from = this._participants.get(remote.cid);
8957
+ if (!from) return
8958
+ this._participants.delete(remote.cid);
8959
+ this._emitSafely('leave', Host.from(remote), remote.closeReason ?? 'close');
8960
+ }
8961
+
8962
+ _emitSafely(name, ...args) {
8963
+ try {
8964
+ this.emit(name, ...args);
8965
+ } catch (error) {
8966
+ if (this.listenerCount('error')) this.emit('error', error);
8967
+ else console.error(`host ${this.name} ${name} handler error:`, error);
8968
+ }
8969
+ }
8970
+ }
8971
+
8746
8972
  // Characters of an anonymous CID after its '?': lowercase Crockford base32, easy to read aloud and type.
8747
8973
  const ANONYMOUS_CID_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz';
8748
8974
 
@@ -8764,7 +8990,10 @@ class Manager {
8764
8990
  this.counters = { rxMessages: 0, rxBytes: 0, txMessages: 0, txBytes: 0,
8765
8991
  publishes: 0, deliveryAttempts: 0, quotaExcluded: 0, oversizeRejected: 0, rateLimited: 0,
8766
8992
  peerRxLimitSkipped: 0, // messages not sent: larger than the peer's advertised RX buffer
8767
- policyDenied: 0 }; // unicasts and CID publications a device's delivery policy kept back
8993
+ policyDenied: 0, // unicasts and CID publications a device's delivery policy kept back
8994
+ hostInbound: 0, // client signals handed to a host (server.host)
8995
+ hostRejected: 0, // signals to a host tag that were not handed over (E2E, malformed payload)
8996
+ hostDenied: 0 }; // client signals to a tag a host owns, dropped
8768
8997
 
8769
8998
  this.authManager = authManager;
8770
8999
 
@@ -8789,6 +9018,7 @@ class Manager {
8789
9018
  this.retainExpiry = new Map(); // key: channel retain tag in a grace pool -> expiry time
8790
9019
  this.retainBytes = 0; // all retained messages, channel and CID
8791
9020
  this.channel_map = new Map(); // key: channelName -> value: < remote : Set >
9021
+ this.hosts = new HostTable(); // tags claimed by server.host() hosts
8792
9022
  this.CHANNEL_PREFIX = 'CH:';
8793
9023
  this.CID_PREFIX = 'CID:';
8794
9024
  this.metrics = new Metrics(this);
@@ -8934,10 +9164,12 @@ class Manager {
8934
9164
  if (this.connectionLogger) this.connectionLogger.log(remoteInfo);
8935
9165
  // A replaced duplicate login no longer owns its CID; the new connection is still online.
8936
9166
  const cidOwner = this.cid2remote.get(remote.cid);
8937
- if (!remote.cid || !cidOwner || cidOwner === remote) {
9167
+ const ownsCid = !remote.cid || !cidOwner || cidOwner === remote;
9168
+ if (ownsCid) {
8938
9169
  this.deligateSignal(remote, '@state', 'close');
8939
9170
  this.deligateSignal(remote, '@$state', 'close');
8940
9171
  }
9172
+ if (this.hosts.size) this.hosts.remoteClosed(remote, ownsCid);
8941
9173
 
8942
9174
  // remove subscriber
8943
9175
  for (let ch of remote.channels.keys()) {
@@ -9060,6 +9292,26 @@ class Manager {
9060
9292
  if (tag.indexOf('$') == 0) return ['err', 'prefix $ is reserved for userSet tag.']
9061
9293
 
9062
9294
  let cidIndex = tag.indexOf('@');
9295
+
9296
+ // Hosts (server.host): a signal to an inbound tag goes to the host only, with its sender; a
9297
+ // client may not send to a tag a host owns. CID publications ('@topic') name their sender and
9298
+ // are never hosted.
9299
+ if (this.hosts.size && cidIndex !== 0) {
9300
+ const entry = this.hosts.match(cidIndex > 0 ? tag.slice(cidIndex) : tag);
9301
+ if (entry?.kind === 'inbound') {
9302
+ if (entry.host._receive(remote, tag, message)) {
9303
+ this.counters.hostInbound++;
9304
+ return ['ok', 1]
9305
+ }
9306
+ this.counters.hostRejected++;
9307
+ return ['err', 'Not accepted by the host']
9308
+ }
9309
+ if (entry) {
9310
+ this.counters.hostDenied++;
9311
+ if (this.server?.listenerCount?.('host:denied')) this.server.emit('host:denied', remote, tag, entry.host.name);
9312
+ return ['err', 'Tag is reserved by a host']
9313
+ }
9314
+ }
9063
9315
  // A device whose policy also covers its publications: each subscriber is checked (see deliveryPolicy.js).
9064
9316
  const publisher = cidIndex === 0 && remote.rxPolicy?.filterPublish ? remote : null;
9065
9317
  if (cidIndex === 0) {
@@ -9124,36 +9376,39 @@ class Manager {
9124
9376
  }
9125
9377
 
9126
9378
  this.counters.publishes++;
9379
+ const sent = this.deliver(tag, message, remote.quota.fanout, publisher);
9380
+ if (sent === null) return ['err', 'No subscriber.']
9381
+ return ['ok', sent]
9382
+ }
9383
+
9384
+ // Sends a SIGNAL to the subscribers of a full channel key ('CH:…', 'CID:…', home channel), at
9385
+ // most fanout (null: all). publisher: a device whose delivery policy filters its publications.
9386
+ // Returns the number sent, or null when the channel has no subscribers.
9387
+ deliver(tag, message, fanout, publisher = null) {
9388
+ const remotes = this.channel_map.get(tag);
9389
+ if (!remotes || remotes.size === 0) return null
9390
+ const limit = fanout === null ? remotes.size : Math.min(fanout, remotes.size);
9391
+ this.counters.quotaExcluded += remotes.size - limit;
9127
9392
  let sentCounter = 0;
9128
- if (this.channel_map.has(tag)) {
9129
- // console.log('raw channel_map matched tag:', tag)
9130
- let remotes = this.channel_map.get(tag);
9131
- if (remotes.size >= 1) {
9132
- const fanout = remote.quota.fanout;
9133
- const limit = fanout === null ? remotes.size : Math.min(fanout, remotes.size);
9134
- this.counters.quotaExcluded += remotes.size - limit;
9135
- let peers = remotes.values();
9136
- while (sentCounter < limit) {
9137
- let c = peers.next().value;
9138
- if (!c) {
9139
- // console.log('## null remote' )
9140
- break;
9141
- }
9142
- if (publisher && !deliveryAllowed(publisher, c)) {
9143
- this.deliveryDenied(publisher, c, 'publish');
9144
- continue
9145
- }
9146
- // change: from v4.x allow receiveSelfMessages.
9147
- c.send_enc_mode(message);
9148
- sentCounter++;
9149
- }
9150
-
9151
- this.counters.deliveryAttempts += sentCounter;
9152
- return ['ok', sentCounter]
9393
+ for (const c of remotes) {
9394
+ if (sentCounter >= limit) break;
9395
+ if (publisher && !deliveryAllowed(publisher, c)) {
9396
+ this.deliveryDenied(publisher, c, 'publish');
9397
+ continue
9153
9398
  }
9399
+ // change: from v4.x allow receiveSelfMessages.
9400
+ c.send_enc_mode(message);
9401
+ sentCounter++;
9154
9402
  }
9155
- // console.log('-- No subscriber. ch: ' , tag )
9156
- return ['err', 'No subscriber.']
9403
+ this.counters.deliveryAttempts += sentCounter;
9404
+ return sentCounter
9405
+ }
9406
+
9407
+ // A host's publication (Host.publish): full channel key, already packed.
9408
+ hostPublish(host, tag, message) {
9409
+ if (tag.includes('$') && this.retainOptions.enabled) this.storeChannelRetain(tag, message, null, host);
9410
+ this.counters.publishes++;
9411
+ return this.deliver(tag, message, host.fanout) ?? 0
9157
9412
  }
9158
9413
 
9159
9414
 
@@ -9201,14 +9456,18 @@ class Manager {
9201
9456
  return owner
9202
9457
  }
9203
9458
 
9204
- storeChannelRetain(tag, message, remote) {
9205
- const owner = this.retainOwner(remote.boho.isAuthorized ? 'cid:' + remote.cid : 'conn:' + remote.ssid);
9459
+ // host: a Host (server.host) writing its own tag, with its own budget; remote is then null.
9460
+ storeChannelRetain(tag, message, remote, host = null) {
9461
+ const owner = this.retainOwner(host ? host.retainOwnerKey
9462
+ : remote.boho.isAuthorized ? 'cid:' + remote.cid : 'conn:' + remote.ssid);
9463
+ const tagsPerOwner = host?.retainTags ?? this.retainOptions.tagsPerOwner;
9464
+ const bytesPerOwner = host?.retainBytes ?? this.retainOptions.bytesPerOwner;
9206
9465
  const old = this.retain_messages.get(tag);
9207
9466
  const freed = old?.byteLength ?? 0;
9208
9467
  const room = old || (this.retain_messages.size < this.retainOptions.limitCounter &&
9209
- owner.tags.size < this.retainOptions.tagsPerOwner);
9468
+ owner.tags.size < tagsPerOwner);
9210
9469
  const ownerBytes = owner.bytes - (this.retain_owner.get(tag) === owner ? freed : 0);
9211
- if (room && this.retainFits(message, freed, ownerBytes, this.retainOptions.bytesPerOwner)) {
9470
+ if (room && this.retainFits(message, freed, ownerBytes, bytesPerOwner)) {
9212
9471
  if (old) this.releaseChannelRetain(tag, freed);
9213
9472
  this.retain_messages.set(tag, this.retainCopy(message));
9214
9473
  owner.bytes += message.byteLength;
@@ -9943,6 +10202,7 @@ class Server extends require$$0$3 {
9943
10202
  this.membersOnly = boolean('membersOnly', options.membersOnly ?? serverOption.membersOnly);
9944
10203
  this.serviceNames = new Set();
9945
10204
  this.services = new Map(); // name -> service module (for lifecycle hooks)
10205
+ this.hosts = new Set(); // open hosts (server.host)
9946
10206
  // Stays null for a CongSocket-only server, so close() does not wait on a WebSocket server.
9947
10207
  this.wss = null;
9948
10208
  this.port = null;
@@ -10068,6 +10328,25 @@ class Server extends require$$0$3 {
10068
10328
  return this.manager.metrics.snapshot()
10069
10329
  }
10070
10330
 
10331
+ /**
10332
+ * Server-side logic (a game, a room) in this process. Signals clients send to the inbound tags go
10333
+ * to the host only, with the server's view of the sender; clients cannot send to the tags it owns.
10334
+ * @param {string} name 1-64 characters of A-Z a-z 0-9 _ . -
10335
+ * @param {{ inbound: string[], own?: string[], fanout?: number|null,
10336
+ * retain?: { tags?: number, bytes?: number } }} options
10337
+ * inbound: channel tags clients send to the host (a trailing '*' is a prefix). Not relayed.
10338
+ * own: channel tags only the host publishes, and '@topic' unicast topics only the host sends.
10339
+ * fanout: most subscribers one publish reaches (default null: all).
10340
+ * retain: budget of the host's retained ('$') values (default: retain.tagsPerOwner/bytesPerOwner).
10341
+ * @returns {Host}
10342
+ */
10343
+ host(name, options) {
10344
+ const host = new Host(this.manager, name, options);
10345
+ host.once('close', () => this.hosts.delete(host));
10346
+ this.hosts.add(host);
10347
+ return host
10348
+ }
10349
+
10071
10350
  /**
10072
10351
  * RPC service register.
10073
10352
  * service: service_name <string>
@@ -10127,6 +10406,7 @@ class Server extends require$$0$3 {
10127
10406
  */
10128
10407
  close(callback) {
10129
10408
  console.log('closing iosignal server...');
10409
+ for (const host of [...this.hosts]) host.close();
10130
10410
  if (this.manager) {
10131
10411
  this.manager.close();
10132
10412
  }
@@ -4,3 +4,12 @@ export function parsePayload(args: any): {
4
4
  buffer: Uint8Array<ArrayBuffer> | import("buffer").Buffer | null | undefined;
5
5
  };
6
6
  export function getPayloadFromSignalPack(signalPack: any): any;
7
+ /**
8
+ * Arguments of a SIGNAL payload, as IO emits them after the tag: EMPTY [], TEXT [string] (the
9
+ * trailing NUL that C/C++ senders add is removed), BINARY [the buffer itself], OBJECT [value],
10
+ * MJSON [...values], MBA [...args]. null for an unknown payload type. Throws on malformed JSON/MBA.
11
+ * @param {number} payloadType
12
+ * @param {Uint8Array} payloadBuffer
13
+ * @returns {any[] | null}
14
+ */
15
+ export function decodeSignalArgs(payloadType: number, payloadBuffer: Uint8Array): any[] | null;