sonic-ws 1.0.0-beta.1 → 1.0.0-beta.2

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.
@@ -0,0 +1 @@
1
+ (()=>{"use strict";function t(t,e){return function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i<o;i++)!n&&i in e||(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))}([],Array(Math.ceil(t.length/e)),!0).map((function(r,n){return t.slice(n*e,n*e+e)}))}var e,r,n,i,o,s=String.fromCharCode(0),a=Math.floor(27647.5),c=a+1,u=[];function h(t){return t.split("").map((function(t){return t.charCodeAt(0)}))}function f(t){return t<a?t:-t+a}function l(t){if(t>=a||t<-a-1)throw new Error("INT_C Numbers must be within range -".concat(a+1," and ").concat(a));return String.fromCharCode(function(t){return t<0?-t+a:t}(t))}function p(t){if(0==t)return 1;for(var e=1,r=c;t>r;)e++,r*=c;return e}function d(t,e){if(0==t)return s;var r=t<0;t=Math.abs(t);for(var n="",i=0;i<e-1;i++){var o=Math.pow(c,e-i-1),u=Math.floor(t/o);n+=String.fromCharCode(u),t-=u*o}return n+=String.fromCharCode(t%c),r?h(n).map((function(t){return String.fromCharCode(t>0?t+a:t)})).join(""):n}function g(t){return h(t).reduce((function(t,e,r,n){return t+f(e)*function(t){var e;return null!==(e=u[t])&&void 0!==e?e:u[t]=Math.pow(c,t)}(n.length-r-1)}),0)}new TextEncoder,(o=i||(i={}))[o.NONE=0]="NONE",o[o.RAW=1]="RAW",o[o.STRING=1]="STRING",o[o.INTS_C=2]="INTS_C",o[o.INTS_D=3]="INTS_D",o[o.DECIMAL=4]="DECIMAL",o[o.BOOLEAN=6]="BOOLEAN";var y=((e={})[i.NONE]=function(t){return""==t},e[i.RAW]=function(){return!0},e[i.INTS_C]=function(t,e){return t.length==e},e[i.INTS_D]=function(t,e){return t.length>0&&h(t).length%t[0].charCodeAt(0)+1<=e},e[i.DECIMAL]=function(t,e){return t.length>0&&h(t).length%t[0].charCodeAt(0)*2+1<=e},e[i.BOOLEAN]=function(t){return t==s||""==t},e),v=((r={})[i.NONE]=function(t){return""},r[i.RAW]=function(t){return t},r[i.INTS_C]=function(t){return h(t).map(f)},r[i.INTS_D]=function(e){return t(h(e.substring(1)),e[0].charCodeAt(0)).map((function(t){return String.fromCharCode.apply(String,t)})).map(g)},r[i.DECIMAL]=function(e){var r=h(e),n=r.shift(),i=t(r,n).map((function(t){return String.fromCharCode.apply(String,t)})).map(g);return parseFloat(i[0]+"."+i[1])},r[i.BOOLEAN]=function(t){return t==s},r),C=((n={})[i.NONE]=function(t){return""},n[i.RAW]=function(t){return t.toString()},n[i.INTS_C]=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return t.map(l).join("")},n[i.INTS_D]=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var r=t.reduce((function(t,e){return Math.max(t,p(e))}),1),n=t.map((function(t){return d(t,r)})).join("");return String.fromCharCode(r)+n},n[i.DECIMAL]=function(t){var e=t.toString().split("."),r=parseFloat(e[0])||0,n=e.length>1&&parseFloat(e[1])||0,i=Math.max(p(r),p(n));return String.fromCharCode(i)+d(r,i)+d(n,i)},n[i.BOOLEAN]=function(t){return t?s:""},n),S=function(){function t(t,e,r,n){this.tag=t,this.type=e,this.dataCap=r,this.dontSpread=n}return t.prototype.serialize=function(){return"".concat(this.dontSpread?1:0).concat(String.fromCharCode(this.dataCap+1)).concat(String.fromCharCode(this.type+1)).concat(String.fromCharCode(this.tag.length+1)).concat(this.tag)},t.deserialize=function(e,r){var n="1"==e[r],i=e.charCodeAt(r+1)-1,o=e.charCodeAt(r+2)-1,s=e.charCodeAt(r+3)-1;return[new t(e.substring(r+4,r+4+s),o,i,n),s]},t.deserializeAll=function(t){for(var e=[],r=0;r<t.length;){var n=this.deserialize(t,r),i=n[0],o=n[1];e.push(i),r+=4+o}return e},t}(),m=function(){function t(t){this.key=1,this.keys={},this.tags={},this.packets=t,this.packetMap={},this.createPackets(t)}return t.prototype.createKey=function(t){t.includes(",")?console.log('Tag "'.concat(t,'" is invalid; keys cannot contain commas.')):(this.keys[t]=this.key,this.tags[this.key]=t,this.key++)},t.prototype.createPackets=function(t){for(var e=0,r=t;e<r.length;e++){var n=r[e];this.createKey(n.tag),this.packetMap[n.tag]=n}},t.prototype.get=function(t){return this.keys[t]},t.prototype.getChar=function(t){return String.fromCharCode(this.get(t))},t.prototype.getPacket=function(t){return this.packetMap[t]},t.prototype.has=function(t){return null!=this.tags[t.charCodeAt(0)]},t.prototype.getKeys=function(){return this.keys},t.prototype.serialize=function(){return this.packets.map((function(t){return t.serialize()})).join(",")},t.empty=function(){return new t([])},t}(),w=function(){function t(t,e){this.processor=v[t.type],this.validifier=y[t.type],this.listener=e,this.dontSpread=t.dontSpread,this.dataCap=t.dataCap}return t.prototype.listen=function(t){try{if(!this.validifier(t,this.dataCap))return!1;var e=this.processor(t);return Array.isArray(e)&&!this.dontSpread?this.listener.apply(this,e):this.listener(e),!0}catch(t){return!1}},t}();function k(t,e,r){for(var n=[],i=3;i<arguments.length;i++)n[i-3]=arguments[i];var o=t.getChar(r);if(null==o)throw new Error('Tag "'.concat(r,'" has not been created!'));var s=t.getPacket(r);if(n.length>s.dataCap)throw new Error('Packet "'.concat(r,'" only allows ').concat(s.dataCap," values!"));e(o+C[s.type].apply(C,n))}var A,E,N=function(){function t(t){var e=this;this.clientPackets=m.empty(),this.serverPackets=m.empty(),this.ws=t,this.listeners={message:[],close:[],event:{}},this.preListen={},this.keyHandler=function(t){return e.serverKeyHandler(t)},this.ws.addEventListener("message",this.keyHandler),this.ws.addEventListener("close",(function(t){e.listeners.close.forEach((function(e){return e(t)}))}))}return t.prototype.serverKeyHandler=function(t){var e=this,r=t.data.toString();if(!r.startsWith("SWS"))throw this.ws.close(),new Error("The server requested is not a Sonic WS server.");var n=r.charCodeAt(3);if(0!=n)throw this.ws.close(),new Error("Version mismatch: ".concat(n>0?"client":"server"," is outdated (server: ").concat(n,", client: ").concat(0,")"));var i=r.substring(4).split(s),o=i[0],a=i[1];this.clientPackets.createPackets(S.deserializeAll(o)),this.serverPackets.createPackets(S.deserializeAll(a)),Object.keys(this.preListen).forEach((function(t){return e.preListen[t].forEach((function(r){var n=e.serverPackets.getPacket(t),i=new w(n,r);e.listen(t,i)}))})),this.ws.removeEventListener("message",this.keyHandler),this.ws.addEventListener("message",(function(t){return e.messageHandler(t)}))},t.prototype.messageHandler=function(t){var e,r=t.data.toString();if(this.listeners.message.forEach((function(t){return t(r)})),!(r.length<1)){var n=r.substring(0,1),i=r.substring(1),o=n.charCodeAt(0);null!=o&&(null===(e=this.listeners.event[o])||void 0===e||e.forEach((function(t){return t.listen(i)})))}},t.prototype.listen=function(t,e){var r=this.serverPackets.get(t);r?(this.listeners.event[r]||(this.listeners.event[r]=[]),this.listeners.event[r].push(e)):console.log("Key is not available on server: "+t)},t.prototype.raw_onmessage=function(t){this.listeners.message.push(t)},t.prototype.raw_send=function(t){this.ws.send(t)},t.prototype.send=function(t){for(var e=this,r=[],n=1;n<arguments.length;n++)r[n-1]=arguments[n];k.apply(void 0,function(t,e,r){if(r||2===arguments.length)for(var n,i=0,o=e.length;i<o;i++)!n&&i in e||(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))}([this.clientPackets,function(t){return e.raw_send(t)},t],r,!1))},t.prototype.on_ready=function(t){this.ws.readyState===WebSocket.OPEN?t():this.ws.addEventListener("open",t)},t.prototype.on_close=function(t){this.listeners.close.push(t)},t.prototype.on=function(t,e){if(this.ws.readyState!==WebSocket.OPEN)return this.preListen[t]||(this.preListen[t]=[]),void this.preListen[t].push(e);var r=this.serverPackets.getPacket(t),n=new w(r,e);this.listen(t,n)},t}(),_=(A=function(t,e){return A=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},A(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}A(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});window.SonicWS=((E=function(t){function e(e,r){var n=new WebSocket(e,r);return t.call(this,n)||this}return _(e,t),e}(N)).PacketType=i,E)})();
package/dist/index.d.ts CHANGED
@@ -2,3 +2,4 @@ export { SonicWS } from './ws/client/node/ClientNode';
2
2
  export { SonicWSConnection } from './ws/server/SonicWSConnection';
3
3
  export { SonicWSServer } from './ws/server/SonicWSServer';
4
4
  export { PacketType } from './ws/packets/PacketType';
5
+ export { CreatePacket } from './ws/util/PacketUtils';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PacketType = exports.SonicWSServer = exports.SonicWSConnection = exports.SonicWS = void 0;
3
+ exports.CreatePacket = exports.PacketType = exports.SonicWSServer = exports.SonicWSConnection = exports.SonicWS = void 0;
4
4
  var ClientNode_1 = require("./ws/client/node/ClientNode");
5
5
  Object.defineProperty(exports, "SonicWS", { enumerable: true, get: function () { return ClientNode_1.SonicWS; } });
6
6
  var SonicWSConnection_1 = require("./ws/server/SonicWSConnection");
@@ -9,3 +9,5 @@ var SonicWSServer_1 = require("./ws/server/SonicWSServer");
9
9
  Object.defineProperty(exports, "SonicWSServer", { enumerable: true, get: function () { return SonicWSServer_1.SonicWSServer; } });
10
10
  var PacketType_1 = require("./ws/packets/PacketType");
11
11
  Object.defineProperty(exports, "PacketType", { enumerable: true, get: function () { return PacketType_1.PacketType; } });
12
+ var PacketUtils_1 = require("./ws/util/PacketUtils");
13
+ Object.defineProperty(exports, "CreatePacket", { enumerable: true, get: function () { return PacketUtils_1.CreatePacket; } });
@@ -0,0 +1 @@
1
+ export declare const VERSION = 0;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSION = void 0;
4
+ exports.VERSION = 0;
@@ -1,9 +1,18 @@
1
- export declare class KeyHolder {
1
+ import { Packet } from "./packets/PacketType";
2
+ export declare class PacketHolder {
2
3
  private key;
3
- keys: Record<string, number>;
4
- constructor(keys: string[]);
4
+ private keys;
5
+ private tags;
6
+ private packetMap;
7
+ private packets;
8
+ constructor(packets: Packet[]);
5
9
  createKey(tag: string): void;
6
- createKeys(tags: string[]): void;
7
- get(key: string): number;
8
- getChar(key: string): string;
10
+ createPackets(packets: Packet[]): void;
11
+ get(tag: string): number;
12
+ getChar(tag: string): string;
13
+ getPacket(tag: string): Packet;
14
+ has(data: string): boolean;
15
+ getKeys(): Record<string, number>;
16
+ serialize(): string;
17
+ static empty(): PacketHolder;
9
18
  }
@@ -1,32 +1,52 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KeyHolder = void 0;
4
- var KeyHolder = /** @class */ (function () {
5
- function KeyHolder(keys) {
3
+ exports.PacketHolder = void 0;
4
+ var PacketHolder = /** @class */ (function () {
5
+ function PacketHolder(packets) {
6
6
  this.key = 1;
7
7
  this.keys = {};
8
- this.createKeys(keys);
8
+ this.tags = {};
9
+ this.packets = packets;
10
+ this.packetMap = {};
11
+ this.createPackets(packets);
9
12
  }
10
- KeyHolder.prototype.createKey = function (tag) {
13
+ PacketHolder.prototype.createKey = function (tag) {
11
14
  if (tag.includes(",")) {
12
15
  console.log("Tag \"".concat(tag, "\" is invalid; keys cannot contain commas."));
13
16
  return;
14
17
  }
15
18
  this.keys[tag] = this.key;
19
+ this.tags[this.key] = tag;
16
20
  this.key++;
17
21
  };
18
- KeyHolder.prototype.createKeys = function (tags) {
19
- for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
20
- var tag = tags_1[_i];
21
- this.createKey(tag);
22
+ PacketHolder.prototype.createPackets = function (packets) {
23
+ for (var _i = 0, packets_1 = packets; _i < packets_1.length; _i++) {
24
+ var packet = packets_1[_i];
25
+ this.createKey(packet.tag);
26
+ this.packetMap[packet.tag] = packet;
22
27
  }
23
28
  };
24
- KeyHolder.prototype.get = function (key) {
25
- return this.keys[key];
29
+ PacketHolder.prototype.get = function (tag) {
30
+ return this.keys[tag];
26
31
  };
27
- KeyHolder.prototype.getChar = function (key) {
28
- return String.fromCharCode(this.get(key));
32
+ PacketHolder.prototype.getChar = function (tag) {
33
+ return String.fromCharCode(this.get(tag));
29
34
  };
30
- return KeyHolder;
35
+ PacketHolder.prototype.getPacket = function (tag) {
36
+ return this.packetMap[tag];
37
+ };
38
+ PacketHolder.prototype.has = function (data) {
39
+ return this.tags[data.charCodeAt(0)] != null;
40
+ };
41
+ PacketHolder.prototype.getKeys = function () {
42
+ return this.keys;
43
+ };
44
+ PacketHolder.prototype.serialize = function () {
45
+ return this.packets.map(function (p) { return p.serialize(); }).join(",");
46
+ };
47
+ PacketHolder.empty = function () {
48
+ return new PacketHolder([]);
49
+ };
50
+ return PacketHolder;
31
51
  }());
32
- exports.KeyHolder = KeyHolder;
52
+ exports.PacketHolder = PacketHolder;
@@ -1,5 +1,4 @@
1
- import { KeyHolder } from '../../KeyHolder';
2
- import { PacketType } from '../../packets/PacketType';
1
+ import { PacketHolder } from '../../KeyHolder';
3
2
  import { PacketListener } from '../../packets/PacketListener';
4
3
  export declare abstract class SonicWSCore {
5
4
  protected ws: WebSocket;
@@ -11,17 +10,19 @@ export declare abstract class SonicWSCore {
11
10
  };
12
11
  };
13
12
  protected preListen: {
14
- [key: string]: Array<PacketListener>;
13
+ [key: string]: Array<(value: string) => void>;
15
14
  };
16
- protected clientKeys: KeyHolder;
17
- protected serverKeys: KeyHolder;
15
+ protected clientPackets: PacketHolder;
16
+ protected serverPackets: PacketHolder;
17
+ private keyHandler;
18
18
  constructor(ws: WebSocket);
19
- protected _finishInit(headers: Record<string, string | string[] | undefined>): void;
19
+ private serverKeyHandler;
20
+ private messageHandler;
20
21
  protected listen(key: string, listener: PacketListener): void;
21
22
  raw_onmessage(listener: (data: string) => void): void;
22
23
  raw_send(data: string): void;
23
- send(key: string, type?: PacketType, ...value: any[]): void;
24
+ send(tag: string, ...values: any[]): void;
24
25
  on_ready(listener: () => void): void;
25
26
  on_close(listener: (event: CloseEvent) => void): void;
26
- on(key: string, type: PacketType, listener: (value: string) => void, dontSpread?: boolean): void;
27
+ on(tag: string, listener: (value: string) => void): void;
27
28
  }
@@ -1,12 +1,26 @@
1
1
  "use strict";
2
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
3
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
4
+ if (ar || !(i in from)) {
5
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
6
+ ar[i] = from[i];
7
+ }
8
+ }
9
+ return to.concat(ar || Array.prototype.slice.call(from));
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.SonicWSCore = void 0;
4
13
  var KeyHolder_1 = require("../../KeyHolder");
5
14
  var PacketType_1 = require("../../packets/PacketType");
6
15
  var PacketListener_1 = require("../../packets/PacketListener");
16
+ var CodePointUtil_1 = require("../../util/CodePointUtil");
17
+ var PacketUtils_1 = require("../../util/PacketUtils");
18
+ var version_1 = require("../../../version");
7
19
  var SonicWSCore = /** @class */ (function () {
8
20
  function SonicWSCore(ws) {
9
21
  var _this = this;
22
+ this.clientPackets = KeyHolder_1.PacketHolder.empty();
23
+ this.serverPackets = KeyHolder_1.PacketHolder.empty();
10
24
  this.ws = ws;
11
25
  this.listeners = {
12
26
  message: [],
@@ -14,43 +28,50 @@ var SonicWSCore = /** @class */ (function () {
14
28
  event: {},
15
29
  };
16
30
  this.preListen = {};
17
- this.clientKeys = new KeyHolder_1.KeyHolder([]);
18
- this.serverKeys = new KeyHolder_1.KeyHolder([]);
19
- this.ws.addEventListener('message', function (event) {
20
- var _a;
21
- var data = event.data.toString();
22
- _this.listeners.message.forEach(function (listener) { return listener(data); });
23
- if (data.length < 1)
24
- return;
25
- var key = data.substring(0, 1);
26
- var value = data.substring(1);
27
- var code = key.charCodeAt(0);
28
- if (code != null) {
29
- (_a = _this.listeners.event[code]) === null || _a === void 0 ? void 0 : _a.forEach(function (l) { return l.listen(value); });
30
- }
31
- });
31
+ this.keyHandler = function (event) { return _this.serverKeyHandler(event); };
32
+ this.ws.addEventListener('message', this.keyHandler); // lambda to persist 'this'
32
33
  this.ws.addEventListener('close', function (event) {
33
34
  _this.listeners.close.forEach(function (listener) { return listener(event); });
34
35
  });
35
36
  }
36
- SonicWSCore.prototype._finishInit = function (headers) {
37
+ SonicWSCore.prototype.serverKeyHandler = function (event) {
37
38
  var _this = this;
38
- var ckData = headers['s-clientkeys'];
39
- var skData = headers['s-serverkeys'];
40
- if (typeof ckData !== 'string' ||
41
- typeof skData !== 'string') {
39
+ var data = event.data.toString();
40
+ if (!data.startsWith("SWS")) {
41
+ this.ws.close();
42
+ throw new Error("The server requested is not a Sonic WS server.");
43
+ }
44
+ var version = data.charCodeAt(3);
45
+ if (version != version_1.VERSION) {
42
46
  this.ws.close();
43
- console.error("The server requested is not a Sonic WS server.");
47
+ throw new Error("Version mismatch: ".concat(version > version_1.VERSION ? "client" : "server", " is outdated (server: ").concat(version, ", client: ").concat(version_1.VERSION, ")"));
48
+ }
49
+ var _a = data.substring(4).split(CodePointUtil_1.NULL), ckData = _a[0], skData = _a[1];
50
+ this.clientPackets.createPackets(PacketType_1.Packet.deserializeAll(ckData));
51
+ this.serverPackets.createPackets(PacketType_1.Packet.deserializeAll(skData));
52
+ Object.keys(this.preListen).forEach(function (tag) { return _this.preListen[tag].forEach(function (listener) {
53
+ var packet = _this.serverPackets.getPacket(tag);
54
+ var packetListener = new PacketListener_1.PacketListener(packet, listener);
55
+ _this.listen(tag, packetListener);
56
+ }); });
57
+ this.ws.removeEventListener('message', this.keyHandler);
58
+ this.ws.addEventListener('message', function (event) { return _this.messageHandler(event); }); // lambda to persist 'this'
59
+ };
60
+ SonicWSCore.prototype.messageHandler = function (event) {
61
+ var _a;
62
+ var data = event.data.toString();
63
+ this.listeners.message.forEach(function (listener) { return listener(data); });
64
+ if (data.length < 1)
44
65
  return;
66
+ var key = data.substring(0, 1);
67
+ var value = data.substring(1);
68
+ var code = key.charCodeAt(0);
69
+ if (code != null) {
70
+ (_a = this.listeners.event[code]) === null || _a === void 0 ? void 0 : _a.forEach(function (l) { return l.listen(value); });
45
71
  }
46
- this.clientKeys.createKeys(ckData.split(","));
47
- this.serverKeys.createKeys(skData.split(","));
48
- Object.keys(this.preListen).forEach(function (key) {
49
- return _this.preListen[key].forEach(function (listener) { return _this.listen(key, listener); });
50
- });
51
72
  };
52
73
  SonicWSCore.prototype.listen = function (key, listener) {
53
- var skey = this.serverKeys.get(key);
74
+ var skey = this.serverPackets.get(key);
54
75
  if (!skey) {
55
76
  console.log("Key is not available on server: " + key);
56
77
  return;
@@ -65,16 +86,13 @@ var SonicWSCore = /** @class */ (function () {
65
86
  SonicWSCore.prototype.raw_send = function (data) {
66
87
  this.ws.send(data);
67
88
  };
68
- SonicWSCore.prototype.send = function (key, type) {
69
- if (type === void 0) { type = PacketType_1.PacketType.NONE; }
70
- var value = [];
71
- for (var _i = 2; _i < arguments.length; _i++) {
72
- value[_i - 2] = arguments[_i];
89
+ SonicWSCore.prototype.send = function (tag) {
90
+ var _this = this;
91
+ var values = [];
92
+ for (var _i = 1; _i < arguments.length; _i++) {
93
+ values[_i - 1] = arguments[_i];
73
94
  }
74
- var code = this.clientKeys.getChar(key);
75
- if (code == null)
76
- throw new Error("Key \"".concat(key, "\" has not been created!"));
77
- this.raw_send(code + PacketType_1.PacketSendProcessors[type].apply(PacketType_1.PacketSendProcessors, value));
95
+ PacketUtils_1.emitPacket.apply(void 0, __spreadArray([this.clientPackets, function (d) { return _this.raw_send(d); }, tag], values, false));
78
96
  };
79
97
  SonicWSCore.prototype.on_ready = function (listener) {
80
98
  if (this.ws.readyState === WebSocket.OPEN) {
@@ -86,18 +104,17 @@ var SonicWSCore = /** @class */ (function () {
86
104
  };
87
105
  SonicWSCore.prototype.on_close = function (listener) {
88
106
  this.listeners.close.push(listener);
89
- this.ws.addEventListener('close', listener);
90
107
  };
91
- SonicWSCore.prototype.on = function (key, type, listener, dontSpread) {
92
- if (dontSpread === void 0) { dontSpread = false; }
93
- var packetListener = new PacketListener_1.PacketListener(type, listener, -1, dontSpread);
108
+ SonicWSCore.prototype.on = function (tag, listener) {
94
109
  if (this.ws.readyState !== WebSocket.OPEN) {
95
- if (!this.preListen[key])
96
- this.preListen[key] = [];
97
- this.preListen[key].push(packetListener);
110
+ if (!this.preListen[tag])
111
+ this.preListen[tag] = [];
112
+ this.preListen[tag].push(listener);
98
113
  return;
99
114
  }
100
- this.listen(key, packetListener);
115
+ var packet = this.serverPackets.getPacket(tag);
116
+ var packetListener = new PacketListener_1.PacketListener(packet, listener);
117
+ this.listen(tag, packetListener);
101
118
  };
102
119
  return SonicWSCore;
103
120
  }());
@@ -24,13 +24,8 @@ var ClientCore_1 = require("../core/ClientCore");
24
24
  var SonicWS = /** @class */ (function (_super) {
25
25
  __extends(SonicWS, _super);
26
26
  function SonicWS(url, options) {
27
- var _this = this;
28
27
  var ws = new ws_1.default.WebSocket(url, options);
29
- _this = _super.call(this, ws) || this; // Cast to match browser WebSocket interface
30
- ws.on('upgrade', function (req) {
31
- _this._finishInit(req.headers);
32
- });
33
- return _this;
28
+ return _super.call(this, ws) || this;
34
29
  }
35
30
  return SonicWS;
36
31
  }(ClientCore_1.SonicWSCore));
@@ -1,10 +1,10 @@
1
- import { PacketType } from "./PacketType";
1
+ import { Packet } from "./PacketType";
2
2
  export declare class PacketListener {
3
3
  private processor;
4
4
  private validifier;
5
5
  private listener;
6
6
  private dontSpread;
7
7
  private dataCap;
8
- constructor(type: PacketType, listener: (data: string) => void, dataCap: number, dontSpread: boolean);
8
+ constructor(packet: Packet, listener: (...data: any[]) => void);
9
9
  listen(value: string): boolean;
10
10
  }
@@ -3,23 +3,27 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PacketListener = void 0;
4
4
  var PacketType_1 = require("./PacketType");
5
5
  var PacketListener = /** @class */ (function () {
6
- function PacketListener(type, listener, dataCap, dontSpread) {
7
- this.processor = PacketType_1.PacketReceiveProcessors[type];
8
- this.validifier = PacketType_1.PacketValidityProcessors[type];
6
+ function PacketListener(packet, listener) {
7
+ this.processor = PacketType_1.PacketReceiveProcessors[packet.type];
8
+ this.validifier = PacketType_1.PacketValidityProcessors[packet.type];
9
9
  this.listener = listener;
10
- this.dontSpread = dontSpread;
11
- this.dataCap = dataCap;
10
+ this.dontSpread = packet.dontSpread;
11
+ this.dataCap = packet.dataCap;
12
12
  }
13
13
  PacketListener.prototype.listen = function (value) {
14
- // -1 if it's the client
15
- if (this.dataCap != -1 && !this.validifier(value, this.dataCap))
14
+ try {
15
+ if (!this.validifier(value, this.dataCap))
16
+ return false;
17
+ var processed = this.processor(value);
18
+ if (Array.isArray(processed) && !this.dontSpread)
19
+ this.listener.apply(this, processed);
20
+ else
21
+ this.listener(processed);
22
+ return true;
23
+ }
24
+ catch (err) {
16
25
  return false;
17
- var processed = this.processor(value);
18
- if (Array.isArray(processed) && !this.dontSpread)
19
- this.listener.apply(this, processed);
20
- else
21
- this.listener(processed);
22
- return true;
26
+ }
23
27
  };
24
28
  return PacketListener;
25
29
  }());
@@ -17,3 +17,13 @@ export declare enum PacketType {
17
17
  export declare const PacketValidityProcessors: Record<PacketType, (data: string, dataCap: number) => boolean>;
18
18
  export declare const PacketReceiveProcessors: Record<PacketType, (data: string) => "" | string | number | number[] | boolean>;
19
19
  export declare const PacketSendProcessors: Record<PacketType, (...data: any) => string>;
20
+ export declare class Packet {
21
+ tag: string;
22
+ type: PacketType;
23
+ dataCap: number;
24
+ dontSpread: boolean;
25
+ constructor(tag: string, type: PacketType, dataCap: number, dontSpread: boolean);
26
+ serialize(): string;
27
+ static deserialize(text: string, offset: number): [packet: Packet, tagLength: number];
28
+ static deserializeAll(text: string): Packet[];
29
+ }
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  var _a, _b, _c;
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.PacketSendProcessors = exports.PacketReceiveProcessors = exports.PacketValidityProcessors = exports.PacketType = void 0;
4
+ exports.Packet = exports.PacketSendProcessors = exports.PacketReceiveProcessors = exports.PacketValidityProcessors = exports.PacketType = void 0;
5
5
  var ArrayUtil_1 = require("../util/ArrayUtil");
6
6
  var CodePointUtil_1 = require("../util/CodePointUtil");
7
7
  var PacketType;
@@ -27,8 +27,8 @@ exports.PacketValidityProcessors = (_a = {},
27
27
  _a[PacketType.NONE] = function (data) { return data == ""; },
28
28
  _a[PacketType.RAW] = function () { return true; },
29
29
  _a[PacketType.INTS_C] = function (data, cap) { return data.length == cap; },
30
- _a[PacketType.INTS_D] = function (data, cap) { return data.length > 0 && (0, CodePointUtil_1.processCharCodes)(data).length == data[0].charCodeAt(0) * cap + 1; },
31
- _a[PacketType.DECIMAL] = function (data, cap) { return data.length > 0 && (0, CodePointUtil_1.processCharCodes)(data).length == data[0].charCodeAt(0) * cap * 2 + 1; },
30
+ _a[PacketType.INTS_D] = function (data, cap) { return data.length > 0 && (0, CodePointUtil_1.processCharCodes)(data).length % data[0].charCodeAt(0) + 1 <= cap; },
31
+ _a[PacketType.DECIMAL] = function (data, cap) { return data.length > 0 && (0, CodePointUtil_1.processCharCodes)(data).length % data[0].charCodeAt(0) * 2 + 1 <= cap; },
32
32
  _a[PacketType.BOOLEAN] = function (data) { return data == CodePointUtil_1.NULL || data == ""; },
33
33
  _a);
34
34
  // todo: code points might make it need to substring(2) but idk if i need to care abt that-
@@ -73,3 +73,34 @@ exports.PacketSendProcessors = (_c = {},
73
73
  },
74
74
  _c[PacketType.BOOLEAN] = function (data) { return data ? CodePointUtil_1.NULL : ""; },
75
75
  _c);
76
+ var Packet = /** @class */ (function () {
77
+ function Packet(tag, type, dataCap, dontSpread) {
78
+ this.tag = tag;
79
+ this.type = type;
80
+ this.dataCap = dataCap;
81
+ this.dontSpread = dontSpread;
82
+ }
83
+ Packet.prototype.serialize = function () {
84
+ return "".concat(this.dontSpread ? 1 : 0).concat(String.fromCharCode(this.dataCap + 1)).concat(String.fromCharCode(this.type + 1)).concat(String.fromCharCode(this.tag.length + 1)).concat(this.tag);
85
+ };
86
+ Packet.deserialize = function (text, offset) {
87
+ var dontSpread = text[offset] == "1";
88
+ var dataCap = text.charCodeAt(offset + 1) - 1;
89
+ var type = (text.charCodeAt(offset + 2) - 1);
90
+ var tagLength = text.charCodeAt(offset + 3) - 1;
91
+ var tag = text.substring(offset + 4, offset + 4 + tagLength);
92
+ return [new Packet(tag, type, dataCap, dontSpread), tagLength];
93
+ };
94
+ Packet.deserializeAll = function (text) {
95
+ var arr = [];
96
+ var offset = 0;
97
+ while (offset < text.length) {
98
+ var _a = this.deserialize(text, offset), packet = _a[0], len = _a[1];
99
+ arr.push(packet);
100
+ offset += 4 + len;
101
+ }
102
+ return arr;
103
+ };
104
+ return Packet;
105
+ }());
106
+ exports.Packet = Packet;
@@ -1,8 +1,5 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  import * as WS from 'ws';
4
2
  import { SonicWSServer } from './SonicWSServer';
5
- import { PacketType } from '../packets/PacketType';
6
3
  export declare class SonicWSConnection {
7
4
  private socket;
8
5
  private host;
@@ -15,14 +12,11 @@ export declare class SonicWSConnection {
15
12
  close(): void;
16
13
  /**
17
14
  * Listens for a packet
18
- * @param key The tag of the key to listen for
19
- * @param type The type of packet to listen for
15
+ * @param tag The tag of the key to listen for
20
16
  * @param listener A function to listen for it
21
- * @param dataCap The amount of values that can pass through the function
22
- * @param dontSpread If the values should be kept in an array instead of spread
23
17
  */
24
- on(key: string, type: PacketType, listener: (value: string) => void, dataCap: number, dontSpread?: boolean): void;
25
- send(key: string, type?: PacketType, ...value: any[]): void;
18
+ on(tag: string, listener: (...values: any) => void): void;
19
+ send(tag: string, ...values: any[]): void;
26
20
  /** Toggles printing all sent and received messages */
27
21
  togglePrint(): void;
28
22
  }
@@ -1,8 +1,18 @@
1
1
  "use strict";
2
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
3
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
4
+ if (ar || !(i in from)) {
5
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
6
+ ar[i] = from[i];
7
+ }
8
+ }
9
+ return to.concat(ar || Array.prototype.slice.call(from));
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.SonicWSConnection = void 0;
4
- var PacketType_1 = require("../packets/PacketType");
5
13
  var PacketListener_1 = require("../packets/PacketListener");
14
+ var CodePointUtil_1 = require("../util/CodePointUtil");
15
+ var PacketUtils_1 = require("../util/PacketUtils");
6
16
  var SonicWSConnection = /** @class */ (function () {
7
17
  function SonicWSConnection(socket, host, id) {
8
18
  var _this = this;
@@ -11,23 +21,23 @@ var SonicWSConnection = /** @class */ (function () {
11
21
  this.host = host;
12
22
  this.id = id;
13
23
  this.listeners = {};
14
- for (var _i = 0, _a = Object.values(host.clientKeys.keys); _i < _a.length; _i++) {
24
+ for (var _i = 0, _a = Object.values(host.clientPackets.getKeys()); _i < _a.length; _i++) {
15
25
  var key = _a[_i];
16
26
  this.listeners[String.fromCharCode(key)] = [];
17
27
  }
18
28
  this.socket.on('message', function (data) {
19
29
  var message = data.toString();
20
30
  if (_this.print)
21
- console.log("\u001B[31m\u2B07\u001B[0m ".concat(_this.id, " ").concat(message));
31
+ console.log("\u001B[31m\u2B07 \u001B[38;5;245m(".concat(_this.id, ",").concat((0, CodePointUtil_1.getStringBytes)(message), ")\u001B[0m ").concat(message));
22
32
  if (message.length < 1) {
23
- _this.socket.close();
33
+ _this.socket.close(4001);
24
34
  return;
25
35
  }
26
36
  var key = message[0];
27
37
  var value = message.substring(1);
28
38
  // not a key, bye bye
29
- if (!_this.listeners[key]) {
30
- _this.socket.close();
39
+ if (!_this.host.clientPackets.has(key)) {
40
+ _this.socket.close(4002);
31
41
  return;
32
42
  }
33
43
  for (var _i = 0, _a = _this.listeners[key]; _i < _a.length; _i++) {
@@ -35,7 +45,7 @@ var SonicWSConnection = /** @class */ (function () {
35
45
  var valid = listener.listen(value);
36
46
  // if invalid then ignore it
37
47
  if (!valid) {
38
- socket.close();
48
+ socket.close(4003);
39
49
  break;
40
50
  }
41
51
  }
@@ -47,39 +57,33 @@ var SonicWSConnection = /** @class */ (function () {
47
57
  };
48
58
  SonicWSConnection.prototype.raw_send = function (data) {
49
59
  if (this.print)
50
- console.log("\u001B[32m\u2B06\u001B[0m ".concat(this.id, " ").concat(data));
60
+ console.log("\u001B[32m\u2B06 \u001B[38;5;245m(".concat(this.id, ",").concat((0, CodePointUtil_1.getStringBytes)(data), ")\u001B[0m ").concat(data));
51
61
  this.socket.send(data);
52
62
  };
53
63
  SonicWSConnection.prototype.close = function () {
54
- this.socket.close();
64
+ this.socket.close(1000);
55
65
  };
56
66
  /**
57
67
  * Listens for a packet
58
- * @param key The tag of the key to listen for
59
- * @param type The type of packet to listen for
68
+ * @param tag The tag of the key to listen for
60
69
  * @param listener A function to listen for it
61
- * @param dataCap The amount of values that can pass through the function
62
- * @param dontSpread If the values should be kept in an array instead of spread
63
70
  */
64
- SonicWSConnection.prototype.on = function (key, type, listener, dataCap, dontSpread) {
65
- if (dontSpread === void 0) { dontSpread = false; }
66
- var code = this.host.clientKeys.getChar(key);
71
+ SonicWSConnection.prototype.on = function (tag, listener) {
72
+ var code = this.host.clientPackets.getChar(tag);
67
73
  if (code == null)
68
- throw new Error("Key \"".concat(key, "\" has not been created!"));
74
+ throw new Error("Tag \"".concat(tag, "\" has not been created!"));
75
+ var packet = this.host.clientPackets.getPacket(tag);
69
76
  if (!this.listeners[code])
70
77
  this.listeners[code] = [];
71
- this.listeners[code].push(new PacketListener_1.PacketListener(type, listener, dataCap, dontSpread));
78
+ this.listeners[code].push(new PacketListener_1.PacketListener(packet, listener));
72
79
  };
73
- SonicWSConnection.prototype.send = function (key, type) {
74
- if (type === void 0) { type = PacketType_1.PacketType.NONE; }
75
- var value = [];
76
- for (var _i = 2; _i < arguments.length; _i++) {
77
- value[_i - 2] = arguments[_i];
80
+ SonicWSConnection.prototype.send = function (tag) {
81
+ var _this = this;
82
+ var values = [];
83
+ for (var _i = 1; _i < arguments.length; _i++) {
84
+ values[_i - 1] = arguments[_i];
78
85
  }
79
- var code = this.host.serverKeys.getChar(key);
80
- if (code == null)
81
- throw new Error("Key \"".concat(key, "\" has not been created!"));
82
- this.raw_send(code + PacketType_1.PacketSendProcessors[type].apply(PacketType_1.PacketSendProcessors, value));
86
+ PacketUtils_1.emitPacket.apply(void 0, __spreadArray([this.host.serverPackets, function (d) { return _this.raw_send(d); }, tag], values, false));
83
87
  };
84
88
  /** Toggles printing all sent and received messages */
85
89
  SonicWSConnection.prototype.togglePrint = function () {
@@ -1,14 +1,15 @@
1
1
  import * as WS from 'ws';
2
2
  import { SonicWSConnection } from './SonicWSConnection';
3
- import { KeyHolder } from '../KeyHolder';
3
+ import { PacketHolder } from '../KeyHolder';
4
+ import { Packet } from '../packets/PacketType';
4
5
  export declare class SonicWSServer {
5
6
  private wss;
6
7
  private socketIDs;
7
8
  private connectListeners;
8
- clientKeys: KeyHolder;
9
- serverKeys: KeyHolder;
9
+ clientPackets: PacketHolder;
10
+ serverPackets: PacketHolder;
10
11
  connections: SonicWSConnection[];
11
- constructor(ck: string[], sk: string[], options?: WS.ServerOptions);
12
+ constructor(clientPackets: Packet[], serverPackets: Packet[], options?: WS.ServerOptions);
12
13
  private generateSocketID;
13
14
  on_connect(runner: (client: SonicWSConnection) => void): void;
14
15
  on_ready(runner: () => void): void;
@@ -15,35 +15,44 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
36
  exports.SonicWSServer = void 0;
27
37
  var WS = __importStar(require("ws"));
28
38
  var SonicWSConnection_1 = require("./SonicWSConnection");
29
39
  var KeyHolder_1 = require("../KeyHolder");
40
+ var CodePointUtil_1 = require("../util/CodePointUtil");
41
+ var version_1 = require("../../version");
30
42
  var SonicWSServer = /** @class */ (function () {
31
- function SonicWSServer(ck, sk, options) {
43
+ function SonicWSServer(clientPackets, serverPackets, options) {
32
44
  if (options === void 0) { options = {}; }
33
45
  var _this = this;
34
46
  this.socketIDs = [];
35
47
  this.connectListeners = [];
36
48
  this.connections = [];
37
49
  this.wss = new WS.WebSocketServer(options);
38
- this.clientKeys = new KeyHolder_1.KeyHolder(ck);
39
- this.serverKeys = new KeyHolder_1.KeyHolder(sk);
40
- // send tags to the client so it doesn't have to hard code them in
41
- this.wss.on('headers', function (headers) {
42
- headers.push('S-ClientKeys: ' + ck.join(","));
43
- headers.push('S-ServerKeys: ' + sk.join(","));
44
- });
50
+ this.clientPackets = new KeyHolder_1.PacketHolder(clientPackets);
51
+ this.serverPackets = new KeyHolder_1.PacketHolder(serverPackets);
45
52
  this.wss.on('connection', function (socket) {
46
53
  var sonicConnection = new SonicWSConnection_1.SonicWSConnection(socket, _this, _this.generateSocketID());
54
+ // send tags to the client so it doesn't have to hard code them in
55
+ socket.send("SWS" + String.fromCharCode(version_1.VERSION) + _this.clientPackets.serialize() + CodePointUtil_1.NULL + _this.serverPackets.serialize());
47
56
  _this.connections.push(sonicConnection);
48
57
  _this.connectListeners.forEach(function (l) { return l(sonicConnection); });
49
58
  socket.on('close', function () {
@@ -9,8 +9,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
9
9
  return to.concat(ar || Array.prototype.slice.call(from));
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.splitArray = void 0;
12
+ exports.splitArray = splitArray;
13
13
  function splitArray(arr, size) {
14
14
  return __spreadArray([], Array(Math.ceil(arr.length / size)), true).map(function (_, i) { return arr.slice(i * size, i * size + size); });
15
15
  }
16
- exports.splitArray = splitArray;
@@ -2,7 +2,6 @@ export declare const NULL: string;
2
2
  export declare const MAX_C = 55295;
3
3
  export declare const NEGATIVE_C: number;
4
4
  export declare const OVERFLOW: number;
5
- export declare const LOG_OVERFLOW: number;
6
5
  export declare function processCharCodes(text: string): number[];
7
6
  export declare function fromSignedINT_C(point: number): number;
8
7
  export declare function toSignedINT_C(number: number): number;
@@ -10,3 +9,5 @@ export declare function stringedINT_C(number: number): string;
10
9
  export declare function sectorSize(number: number): number;
11
10
  export declare function convertINT_D(number: number, chars: number): string;
12
11
  export declare function deconvertINT_D(string: string): number;
12
+ export declare function getCharBytes(char: string): number;
13
+ export declare function getStringBytes(str: string): number;
@@ -1,7 +1,16 @@
1
1
  "use strict";
2
2
  // this shit is so complex so i commented it...
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.deconvertINT_D = exports.convertINT_D = exports.sectorSize = exports.stringedINT_C = exports.toSignedINT_C = exports.fromSignedINT_C = exports.processCharCodes = exports.LOG_OVERFLOW = exports.OVERFLOW = exports.NEGATIVE_C = exports.MAX_C = exports.NULL = void 0;
4
+ exports.OVERFLOW = exports.NEGATIVE_C = exports.MAX_C = exports.NULL = void 0;
5
+ exports.processCharCodes = processCharCodes;
6
+ exports.fromSignedINT_C = fromSignedINT_C;
7
+ exports.toSignedINT_C = toSignedINT_C;
8
+ exports.stringedINT_C = stringedINT_C;
9
+ exports.sectorSize = sectorSize;
10
+ exports.convertINT_D = convertINT_D;
11
+ exports.deconvertINT_D = deconvertINT_D;
12
+ exports.getCharBytes = getCharBytes;
13
+ exports.getStringBytes = getStringBytes;
5
14
  // null char so it's easy
6
15
  exports.NULL = String.fromCharCode(0);
7
16
  // the highest usable character in utf8
@@ -11,42 +20,46 @@ exports.NEGATIVE_C = Math.floor(exports.MAX_C / 2);
11
20
  // overflow is used as our "base" in a positional number system (like base 10, but very large)
12
21
  // we use this to reduce the number of characters needed to represent large numbers
13
22
  exports.OVERFLOW = exports.NEGATIVE_C + 1;
14
- // precomputed log(OVERFLOW) lets us calculate how many digits (characters) we need
15
- exports.LOG_OVERFLOW = Math.log(exports.OVERFLOW);
23
+ var OVERFLOW_POWS = [];
24
+ function overflowPow(num) {
25
+ var _a;
26
+ return (_a = OVERFLOW_POWS[num]) !== null && _a !== void 0 ? _a : (OVERFLOW_POWS[num] = Math.pow(exports.OVERFLOW, num));
27
+ }
16
28
  function processCharCodes(text) {
17
29
  return text.split("").map(function (v) { return v.charCodeAt(0); });
18
30
  }
19
- exports.processCharCodes = processCharCodes;
20
31
  // this converts an encoded code point back to a signed number
21
32
  function fromSignedINT_C(point) {
22
33
  // if the code point is below NEGATIVE_C, it's a positive number and can be returned directly
23
34
  // if it's above or equal to NEGATIVE_C, it was originally negative, so we reverse the offset
24
35
  return point < exports.NEGATIVE_C ? point : -point + exports.NEGATIVE_C;
25
36
  }
26
- exports.fromSignedINT_C = fromSignedINT_C;
27
37
  // this converts a signed number into a non-negative integer that fits in a code point
28
38
  function toSignedINT_C(number) {
29
39
  // positive numbers are returned as-is
30
40
  // negative numbers are made positive and offset above NEGATIVE_C to mark them
31
41
  return number < 0 ? -number + exports.NEGATIVE_C : number;
32
42
  }
33
- exports.toSignedINT_C = toSignedINT_C;
34
43
  // just conversion and checks lol
35
44
  function stringedINT_C(number) {
36
45
  if (number >= exports.NEGATIVE_C || number < -exports.NEGATIVE_C - 1)
37
46
  throw new Error("INT_C Numbers must be within range -".concat(exports.NEGATIVE_C + 1, " and ").concat(exports.NEGATIVE_C));
38
47
  return String.fromCharCode(toSignedINT_C(number));
39
48
  }
40
- exports.stringedINT_C = stringedINT_C;
41
49
  // calculate how many characters (digits) are needed to store this number in OVERFLOW base
42
50
  function sectorSize(number) {
43
51
  // 0 would make -Infinity;
44
52
  if (number == 0)
45
53
  return 1;
46
- // we add 1 because log gives us a fractional digit count that needs to be rounded up
47
- return Math.floor(Math.log(Math.abs(number)) / exports.LOG_OVERFLOW) + 1;
54
+ // iterative system because it's faster than log
55
+ var count = 1;
56
+ var num = exports.OVERFLOW;
57
+ while (number > num) {
58
+ count++;
59
+ num *= exports.OVERFLOW;
60
+ }
61
+ return count;
48
62
  }
49
- exports.sectorSize = sectorSize;
50
63
  // encodes a signed integer into a unicode-safe string using a large base (OVERFLOW)
51
64
  function convertINT_D(number, chars) {
52
65
  // special case: zero is always encoded as a single null character
@@ -75,14 +88,19 @@ function convertINT_D(number, chars) {
75
88
  : string;
76
89
  return stringified;
77
90
  }
78
- exports.convertINT_D = convertINT_D;
79
91
  // decodes a string created by convertINT_D back into the original signed integer
80
92
  function deconvertINT_D(string) {
81
93
  // for each code point in the string, reverse the sign encoding if necessary,
82
94
  // then multiply by the appropriate base power based on its position
83
95
  return processCharCodes(string).reduce(function (c, n, i, arr) {
84
96
  // multiply by the positional weight based on its place (most-significant-digit first)
85
- return c + fromSignedINT_C(n) * Math.pow(exports.OVERFLOW, arr.length - i - 1);
97
+ return c + fromSignedINT_C(n) * overflowPow(arr.length - i - 1);
86
98
  }, 0);
87
99
  }
88
- exports.deconvertINT_D = deconvertINT_D;
100
+ var encoder = new TextEncoder();
101
+ function getCharBytes(char) {
102
+ return encoder.encode(char).length;
103
+ }
104
+ function getStringBytes(str) {
105
+ return str.split("").reduce(function (c, n) { return c + getCharBytes(n); }, 0);
106
+ }
@@ -0,0 +1,4 @@
1
+ import { PacketHolder } from "../KeyHolder";
2
+ import { Packet, PacketType } from "../packets/PacketType";
3
+ export declare function CreatePacket(tag: string, type?: PacketType, dataCap?: number, dontSpread?: boolean): Packet;
4
+ export declare function emitPacket(packets: PacketHolder, send: (data: string) => void, tag: string, ...values: any[]): void;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CreatePacket = CreatePacket;
4
+ exports.emitPacket = emitPacket;
5
+ var PacketType_1 = require("../packets/PacketType");
6
+ function CreatePacket(tag, type, dataCap, dontSpread) {
7
+ if (type === void 0) { type = PacketType_1.PacketType.NONE; }
8
+ if (dataCap === void 0) { dataCap = 1; }
9
+ if (dontSpread === void 0) { dontSpread = false; }
10
+ return new PacketType_1.Packet(tag, type, dataCap, dontSpread);
11
+ }
12
+ function emitPacket(packets, send, tag) {
13
+ var values = [];
14
+ for (var _i = 3; _i < arguments.length; _i++) {
15
+ values[_i - 3] = arguments[_i];
16
+ }
17
+ var code = packets.getChar(tag);
18
+ if (code == null)
19
+ throw new Error("Tag \"".concat(tag, "\" has not been created!"));
20
+ var packet = packets.getPacket(tag);
21
+ if (values.length > packet.dataCap)
22
+ throw new Error("Packet \"".concat(tag, "\" only allows ").concat(packet.dataCap, " values!"));
23
+ send(code + PacketType_1.PacketSendProcessors[packet.type].apply(PacketType_1.PacketSendProcessors, values));
24
+ }
package/package.json CHANGED
@@ -1,12 +1,17 @@
1
1
  {
2
2
  "name": "sonic-ws",
3
- "version": "1.0.0-beta.1",
3
+ "version": "1.0.0-beta.2",
4
4
  "description": "A bandwidth efficient websocket library",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "scripts": {
8
- "build": "tsc -d",
9
- "test": "rimraf ./dist && npm run build && node test.mjs"
8
+ "webpack": "webpack --mode production",
9
+ "build_web": "rimraf ./html && tsc --target ES5 --module ES6 --outdir ./html src/ws/client/browser/ClientBrowser.ts && npm run webpack",
10
+ "build_node": "rimraf ./dist && tsc -d",
11
+ "build": "npm run build_node && npm run build_web",
12
+
13
+ "test_web": "npm run build && node test-site/server.mjs",
14
+ "test_node": "npm run build_node && node test.mjs"
10
15
  },
11
16
  "repository": {
12
17
  "type": "git",
@@ -22,6 +27,14 @@
22
27
  "ws": "^8.18.2"
23
28
  },
24
29
  "devDependencies": {
25
- "@types/ws": "^8.18.1"
30
+ "@types/node": "^22.15.17",
31
+ "@types/ws": "^8.18.1",
32
+ "ts-loader": "^9.5.2",
33
+ "typescript": "^5.8.3",
34
+ "undici": "^7.8.0",
35
+ "undici-types": "^7.8.0",
36
+ "webpack": "^5.99.8",
37
+ "webpack-cli": "^6.0.1",
38
+ "webpack-dev-server": "^5.2.1"
26
39
  }
27
40
  }
@@ -0,0 +1,17 @@
1
+ const path = require('path');
2
+
3
+ module.exports = {
4
+ entry: './html/ws/client/browser/ClientBrowser.js',
5
+ output: {
6
+ filename: 'SonicWS_bundle.js',
7
+ path: path.resolve(__dirname, 'bundled'),
8
+ },
9
+ resolve: {
10
+ extensions: ['.js'],
11
+ },
12
+ module: {
13
+ rules: [
14
+ ],
15
+ },
16
+ mode: 'production',
17
+ };
@@ -1,4 +0,0 @@
1
- import { SonicWSCore } from "../core/ClientCore";
2
- export declare class SonicWS extends SonicWSCore {
3
- constructor(url: string, protocols: string | string[]);
4
- }
@@ -1,28 +0,0 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.SonicWS = void 0;
19
- var ClientCore_1 = require("../core/ClientCore");
20
- var SonicWS = /** @class */ (function (_super) {
21
- __extends(SonicWS, _super);
22
- function SonicWS(url, protocols) {
23
- var ws = new WebSocket(url, protocols);
24
- return _super.call(this, ws) || this;
25
- }
26
- return SonicWS;
27
- }(ClientCore_1.SonicWSCore));
28
- exports.SonicWS = SonicWS;