@primitiv/network-common 0.19.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.
- package/LICENSE.txt +190 -0
- package/README.md +9 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +1002 -0
- package/dist/index.mjs +1 -0
- package/package.json +52 -0
package/LICENSE.txt
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding any notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 Thomas Piquet (THP Software)
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# @primitiv/network-common
|
|
2
|
+
|
|
3
|
+
> **Internal package** - This is an internal module of the [Primitiv Engine](https://primitivengine.com/).
|
|
4
|
+
|
|
5
|
+
For documentation, examples, and guides, visit **[primitivengine.com](https://primitivengine.com/)**.
|
|
6
|
+
|
|
7
|
+
## 📄 License
|
|
8
|
+
|
|
9
|
+
Apache-2.0 - See [LICENSE.txt](./LICENSE.txt).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var B=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var X=(n,t)=>{for(var e in t)B(n,e,{get:t[e],enumerable:!0})},ee=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Y(t))!J.call(n,a)&&a!==e&&B(n,a,{get:()=>t[a],enumerable:!(i=G(t,a))||i.enumerable});return n};var te=n=>ee(B({},"__esModule",{value:!0}),n);var se={};X(se,{CallbackSectionType:()=>m,DC_RELIABLE:()=>Z,DC_UNRELIABLE:()=>z,FragmentAssembler:()=>w,HEADER_SIZE_FRAG:()=>g,HEADER_SIZE_SINGLE:()=>h,HandshakeState:()=>L,HandshakeStatus:()=>O,InterleavingManager:()=>R,LoopbackTransport:()=>M,MTU:()=>k,Marker:()=>l,Tick:()=>y,TransportState:()=>F,calculateFragmentCount:()=>D,createPacket:()=>T,decodeClientCallback:()=>K,decodeHeader:()=>A,encodeClientCallback:()=>N,encodeHeader:()=>P,extractPayload:()=>S,fragmentPacket:()=>U,isFragMarker:()=>x,isReliableMarker:()=>I,toFragMarker:()=>v,willFragment:()=>_});module.exports=te(se);var h=9,g=13,k=1200,l={HandshakeRequest:1,HandshakeResponse:2,HandshakeStateClient:3,HandshakeStateServer:4,Ping:5,Pong:6,LoadBundle:16,LoadBundleFrag:17,UpdateReliable:32,UpdateReliableFrag:33,UpdateVolatile:34,UpdateVolatileFrag:35,EmptyUpdate:36,InputReliable:48,InputReliableFrag:49,InputVolatile:50,InputVolatileFrag:51,AudioOrder:64,HapticOrder:65,PostProcessOrder:66,MacroOrder:67,BridgeToServer:80,BridgeToServerFrag:81,BridgeToClient:82,BridgeToClientFrag:83,ClientCallback:96,ClientCallbackFrag:97};function x(n){return n===l.LoadBundleFrag||n===l.UpdateReliableFrag||n===l.UpdateVolatileFrag||n===l.InputReliableFrag||n===l.InputVolatileFrag||n===l.BridgeToServerFrag||n===l.BridgeToClientFrag||n===l.ClientCallbackFrag}function v(n){switch(n){case l.LoadBundle:return l.LoadBundleFrag;case l.UpdateReliable:return l.UpdateReliableFrag;case l.UpdateVolatile:return l.UpdateVolatileFrag;case l.InputReliable:return l.InputReliableFrag;case l.InputVolatile:return l.InputVolatileFrag;case l.BridgeToServer:return l.BridgeToServerFrag;case l.BridgeToClient:return l.BridgeToClientFrag;case l.ClientCallback:return l.ClientCallbackFrag;default:return n}}function I(n){return n<=15||n===l.LoadBundle||n===l.LoadBundleFrag||n===l.UpdateReliable||n===l.UpdateReliableFrag||n===l.InputReliable||n===l.InputReliableFrag||n>=80}var O=(a=>(a[a.OK=0]="OK",a[a.VersionMismatch=1]="VersionMismatch",a[a.ServerFull=2]="ServerFull",a[a.AuthFailed=3]="AuthFailed",a))(O||{}),L=(o=>(o[o.Connected=0]="Connected",o[o.WaitingForResponse=1]="WaitingForResponse",o[o.Authenticating=2]="Authenticating",o[o.LoadingAssets=3]="LoadingAssets",o[o.Ready=4]="Ready",o[o.InSimulation=5]="InSimulation",o[o.Disconnected=255]="Disconnected",o))(L||{});var y=class n{high;low;constructor(t,e){this.high=t>>>0,this.low=e>>>0}static ZERO=new n(0,0);static from(t){let e=Number(t>>32n&0xffffffffn),i=Number(t&0xffffffffn);return new n(e,i)}static fromNumber(t){if(t<0)throw new Error("Tick must be positive");let e=Math.floor(t/4294967296),i=t>>>0;return new n(e,i)}static fromBuffer(t,e=0){let i=(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0,a=(t[e+4]<<24|t[e+5]<<16|t[e+6]<<8|t[e+7])>>>0;return new n(i,a)}toBigInt(){return BigInt(this.high)<<32n|BigInt(this.low)}toNumber(){return this.high*4294967296+this.low}toBuffer(){let t=new Uint8Array(8);return this.writeToBuffer(t,0),t}writeToBuffer(t,e=0){t[e]=this.high>>>24&255,t[e+1]=this.high>>>16&255,t[e+2]=this.high>>>8&255,t[e+3]=this.high&255,t[e+4]=this.low>>>24&255,t[e+5]=this.low>>>16&255,t[e+6]=this.low>>>8&255,t[e+7]=this.low&255}increment(){let t=this.low+1,e=this.high;return t>4294967295&&(t=0,e++),new n(e,t)}compare(t){return this.high!==t.high?this.high-t.high:this.low-t.low}equals(t){return this.high===t.high&&this.low===t.low}isZero(){return this.high===0&&this.low===0}toString(){return`Tick(${this.toBigInt()})`}getHigh(){return this.high}getLow(){return this.low}};function P(n){let e=n.fragInfo!==void 0?13:9,i=new Uint8Array(e);return E(n,i,0),i}function E(n,t,e){let i=n.fragInfo!==void 0;return t[e]=n.marker,i&&n.fragInfo?(t[e+1]=n.fragInfo.totalChunks>>>8&255,t[e+2]=n.fragInfo.totalChunks&255,t[e+3]=n.fragInfo.chunkIndex>>>8&255,t[e+4]=n.fragInfo.chunkIndex&255,n.tick.writeToBuffer(t,e+5),13):(n.tick.writeToBuffer(t,e+1),9)}function A(n){if(n.length<9)throw new Error(`Buffer too small for header: ${n.length} < ${9}`);let t=n[0];if(x(t)){if(n.length<13)throw new Error(`Buffer too small for frag header: ${n.length} < ${13}`);let a=n[1]<<8|n[2],r=n[3]<<8|n[4],s=y.fromBuffer(n,5);return{header:{marker:t,tick:s,fragInfo:{totalChunks:a,chunkIndex:r}},payloadOffset:13}}let i=y.fromBuffer(n,1);return{header:{marker:t,tick:i},payloadOffset:9}}function T(n,t){let i=n.fragInfo!==void 0?13:9,a=t?t.length:0,r=new Uint8Array(i+a);return E(n,r,0),a>0&&r.set(t,i),r}function S(n){let{header:t,payloadOffset:e}=A(n),i=n.slice(e);return{header:t,payload:i}}function U(n,t,e,i){let a=i?.mtu??1200,r=a-13;if(e.length+9<=a)return[T({marker:n,tick:t},e)];let s=v(n);if(s===n)throw new Error(`Packet with marker 0x${n.toString(16)} exceeds MTU (${a}) but has no fragmentation variant.`);let o=Math.ceil(e.length/r),c=[];for(let d=0;d<o;d++){let p=d*r,b=Math.min(p+r,e.length),j=e.subarray(p,b),q={marker:s,tick:t,fragInfo:{totalChunks:o,chunkIndex:d}};c.push(T(q,j))}return c}function D(n,t=1200){if(n+9<=t)return 1;let e=t-13;return Math.ceil(n/e)}function _(n,t=1200){return n+9>t}function ne(n,t){return`${n}:${t.getHigh()}:${t.getLow()}`}var w=class{buckets=new Map;ttlMs;maxPendingBuckets;maxTotalChunks;lastRejection=null;constructor(t){this.ttlMs=t?.ttlMs??1e4,this.maxPendingBuckets=t?.maxPendingBuckets??0,this.maxTotalChunks=t?.maxTotalChunks??0}receive(t){this.lastRejection=null;let{header:e,payloadOffset:i}=A(t),a=t.subarray(i);return!x(e.marker)||!e.fragInfo?{marker:e.marker,tick:e.tick,payload:a}:this.handleFragment(e,a)}handleFragment(t,e){let{marker:i,tick:a,fragInfo:r}=t;if(!r)return null;let s=ne(i,a),o=this.buckets.get(s);if(!o){if(this.maxTotalChunks>0&&r.totalChunks>this.maxTotalChunks)return this.lastRejection=`Fragment totalChunks (${r.totalChunks}) exceeds limit (${this.maxTotalChunks})`,null;if(this.maxPendingBuckets>0&&this.buckets.size>=this.maxPendingBuckets)return this.lastRejection=`Pending transfers (${this.buckets.size}) reached limit (${this.maxPendingBuckets})`,null;o={marker:i,tick:a,totalChunks:r.totalChunks,receivedCount:0,chunks:new Array(r.totalChunks).fill(null),createdAt:Date.now()},this.buckets.set(s,o)}if(r.chunkIndex>=o.totalChunks)return null;if(o.chunks[r.chunkIndex]===null&&(o.chunks[r.chunkIndex]=e,o.receivedCount++),o.receivedCount===o.totalChunks){let c=0;for(let b=0;b<o.chunks.length;b++)o.chunks[b]&&(c+=o.chunks[b].length);let d=new Uint8Array(c),p=0;for(let b of o.chunks)b&&(d.set(b,p),p+=b.length);return this.buckets.delete(s),{marker:i,tick:a,payload:d}}return null}cleanup(){let t=Date.now(),e=0;for(let[i,a]of this.buckets)t-a.createdAt>this.ttlMs&&(this.buckets.delete(i),e++);return e}getPendingCount(){return this.buckets.size}clearTick(t){for(let[e,i]of this.buckets)i.tick.equals(t)&&this.buckets.delete(e)}destroy(){this.buckets.clear()}};var R=class{transport;backgroundQueue=[];immediateQueue=[];bgCursor=0;imCursor=0;options;constructor(t,e={}){this.transport=t,this.options={fragmentsPerTick:e.fragmentsPerTick??5,bufferedThreshold:e.bufferedThreshold??16384,maxBackgroundQueue:e.maxBackgroundQueue??4096}}enqueue(t,e,i){let a=I(t),r=U(t,e,i);for(let s of r)this.backgroundQueue.push({data:s,reliable:a});this.enforceBackgroundLimit()}enqueueImmediate(t,e,i){let a=I(t),r=U(t,e,i);for(let s of r)this.immediateQueue.push({data:s,reliable:a})}enqueueRawImmediate(t,e){this.immediateQueue.push({data:t,reliable:e})}flush(){if(!this.transport.isReady())return;for(;this.imCursor<this.immediateQueue.length;){let i=this.immediateQueue[this.imCursor++];this.transport.send(i.data,i.reliable)}this.imCursor>0&&(this.immediateQueue.length=0,this.imCursor=0);let t=0,e=this.options.fragmentsPerTick;for(;this.bgCursor<this.backgroundQueue.length&&t<e&&this.transport.getBufferedAmount()<this.options.bufferedThreshold;){let i=this.backgroundQueue[this.bgCursor++];this.transport.send(i.data,i.reliable),t++}this.bgCursor>0&&this.bgCursor>=this.backgroundQueue.length?(this.backgroundQueue.length=0,this.bgCursor=0):this.bgCursor>256&&(this.backgroundQueue.splice(0,this.bgCursor),this.bgCursor=0)}clear(){this.backgroundQueue.length=0,this.immediateQueue.length=0,this.bgCursor=0,this.imCursor=0}enforceBackgroundLimit(){let t=this.backgroundQueue.length-this.bgCursor;if(this.options.maxBackgroundQueue>0&&t>this.options.maxBackgroundQueue){let e=t-this.options.maxBackgroundQueue;this.bgCursor+=e}}getPendingCount(){return this.backgroundQueue.length-this.bgCursor}hasImmediatePending(){return this.imCursor<this.immediateQueue.length}};var m={AudioAck:1,MacroFeedback:2},Q=1,W=2,$=3,V=4,H=5,C=new TextEncoder,f=new TextDecoder;function N(n){let t=[];if(n.audioAcks.length>0&&t.push({type:m.AudioAck,payload:re(n.audioAcks)}),n.macroFeedbacks.length>0&&t.push({type:m.MacroFeedback,payload:ie(n.macroFeedbacks)}),t.length===0)return new Uint8Array(0);let e=1;for(let r of t)e+=2+r.payload.byteLength;let i=new Uint8Array(e),a=0;i[a++]=t.length;for(let r of t)i[a++]=r.type,r.type===m.AudioAck?i[a++]=n.audioAcks.length:r.type===m.MacroFeedback?i[a++]=n.macroFeedbacks.length:i[a++]=0,i.set(r.payload,a),a+=r.payload.byteLength;return i}function re(n){let t=0,e=[];for(let s of n)switch(s.type){case"sound-loaded":{let o=C.encode(s.name);e.push({name:o}),t+=4+o.byteLength;break}case"sound-error":{let o=C.encode(s.name),c=C.encode(s.error);e.push({name:o,error:c}),t+=4+o.byteLength+1+c.byteLength;break}case"playback-started":e.push({}),t+=7;break;case"playback-ended":e.push({}),t+=7;break;case"playback-error":{let o=C.encode(s.error);e.push({error:o}),t+=2+(s.instanceId!=null?4:0)+2+1+o.byteLength;break}}let i=new Uint8Array(t),a=new DataView(i.buffer),r=0;for(let s=0;s<n.length;s++){let o=n[s],c=e[s];switch(o.type){case"sound-loaded":i[r++]=Q,a.setUint16(r,o.soundId,!1),r+=2,i[r++]=c.name.byteLength,i.set(c.name,r),r+=c.name.byteLength;break;case"sound-error":i[r++]=W,a.setUint16(r,o.soundId,!1),r+=2,i[r++]=c.name.byteLength,i.set(c.name,r),r+=c.name.byteLength,i[r++]=c.error.byteLength,i.set(c.error,r),r+=c.error.byteLength;break;case"playback-started":i[r++]=$,a.setUint32(r,o.instanceId,!1),r+=4,a.setUint16(r,o.soundId,!1),r+=2;break;case"playback-ended":i[r++]=V,a.setUint32(r,o.instanceId,!1),r+=4,a.setUint16(r,o.soundId,!1),r+=2;break;case"playback-error":{i[r++]=H;let d=o.instanceId!=null?1:0;i[r++]=d,d&&(a.setUint32(r,o.instanceId,!1),r+=4);let p=typeof o.sound=="number"?o.sound:0;a.setUint16(r,p,!1),r+=2,i[r++]=c.error.byteLength,i.set(c.error,r),r+=c.error.byteLength;break}}}return i}function ie(n){let t=0,e=[];for(let s of n)switch(t+=3,s.cmd){case 1:e.push(null);break;case 2:e.push(null),t+=1+(s.valueType==="number"?2:1);break;case 3:{let o=C.encode(s.text);e.push(o),t+=2+o.byteLength;break}case 4:e.push(null),t+=2;break;case 5:{let o=C.encode(s.data);e.push(o),t+=2+o.byteLength;break}}let i=new Uint8Array(t),a=new DataView(i.buffer),r=0;for(let s=0;s<n.length;s++){let o=n[s];switch(i[r++]=o.cmd,a.setUint16(r,o.instanceId,!1),r+=2,o.cmd){case 1:break;case 2:o.valueType==="number"?(i[r++]=0,a.setUint16(r,o.value,!1),r+=2):(i[r++]=1,i[r++]=o.value?1:0);break;case 3:{let c=e[s];a.setUint16(r,c.byteLength,!1),r+=2,i.set(c,r),r+=c.byteLength;break}case 4:a.setUint16(r,o.index,!1),r+=2;break;case 5:{let c=e[s];a.setUint16(r,c.byteLength,!1),r+=2,i.set(c,r),r+=c.byteLength;break}}}return i}function u(n,t,e){if(t+e>n.byteLength)throw new RangeError(`ClientCallback: truncated payload \u2014 need ${e} bytes at offset ${t}, but only ${n.byteLength-t} remain (total ${n.byteLength})`)}function K(n){let t={audioAcks:[],macroFeedbacks:[]};if(n.byteLength===0)return t;let e=new DataView(n.buffer,n.byteOffset,n.byteLength),i=0;u(n,i,1);let a=n[i++];for(let r=0;r<a;r++){u(n,i,2);let s=n[i++],o=n[i++];switch(s){case m.AudioAck:for(let c=0;c<o;c++){let{ack:d,newOffset:p}=ae(n,e,i);t.audioAcks.push(d),i=p}break;case m.MacroFeedback:for(let c=0;c<o;c++){let{feedback:d,newOffset:p}=oe(n,e,i);t.macroFeedbacks.push(d),i=p}break;default:return t}}return t}function ae(n,t,e){u(n,e,1);let i=n[e++];switch(i){case Q:{u(n,e,3);let a=t.getUint16(e,!1);e+=2;let r=n[e++];u(n,e,r);let s=f.decode(n.subarray(e,e+r));return e+=r,{ack:{type:"sound-loaded",soundId:a,name:s},newOffset:e}}case W:{u(n,e,3);let a=t.getUint16(e,!1);e+=2;let r=n[e++];u(n,e,r);let s=f.decode(n.subarray(e,e+r));e+=r,u(n,e,1);let o=n[e++];u(n,e,o);let c=f.decode(n.subarray(e,e+o));return e+=o,{ack:{type:"sound-error",soundId:a,name:s,error:c},newOffset:e}}case $:{u(n,e,6);let a=t.getUint32(e,!1);e+=4;let r=t.getUint16(e,!1);return e+=2,{ack:{type:"playback-started",instanceId:a,soundId:r},newOffset:e}}case V:{u(n,e,6);let a=t.getUint32(e,!1);e+=4;let r=t.getUint16(e,!1);return e+=2,{ack:{type:"playback-ended",instanceId:a,soundId:r},newOffset:e}}case H:{u(n,e,1);let a=n[e++];a&&u(n,e,4);let r=a?t.getUint32(e,!1):void 0;a&&(e+=4),u(n,e,3);let s=t.getUint16(e,!1);e+=2;let o=n[e++];u(n,e,o);let c=f.decode(n.subarray(e,e+o));return e+=o,{ack:{type:"playback-error",instanceId:r,sound:s,error:c},newOffset:e}}default:throw new Error(`Unknown AudioAck sub-type: 0x${i.toString(16)}`)}}function oe(n,t,e){u(n,e,3);let i=n[e++],a=t.getUint16(e,!1);switch(e+=2,i){case 1:return{feedback:{cmd:1,instanceId:a},newOffset:e};case 2:{u(n,e,1);let r=n[e++]===0?"number":"boolean",s;return r==="number"?(u(n,e,2),s=t.getUint16(e,!1),e+=2):(u(n,e,1),s=n[e++]!==0),{feedback:{cmd:2,instanceId:a,valueType:r,value:s},newOffset:e}}case 3:{u(n,e,2);let r=t.getUint16(e,!1);e+=2,u(n,e,r);let s=f.decode(n.subarray(e,e+r));return e+=r,{feedback:{cmd:3,instanceId:a,text:s},newOffset:e}}case 4:{u(n,e,2);let r=t.getUint16(e,!1);return e+=2,{feedback:{cmd:4,instanceId:a,index:r},newOffset:e}}case 5:{u(n,e,2);let r=t.getUint16(e,!1);e+=2,u(n,e,r);let s=f.decode(n.subarray(e,e+r));return e+=r,{feedback:{cmd:5,instanceId:a,data:s},newOffset:e}}default:throw new Error(`Unknown MacroFeedback cmd: 0x${i.toString(16)}`)}}var F=(a=>(a[a.Connecting=0]="Connecting",a[a.Open=1]="Open",a[a.Closing=2]="Closing",a[a.Closed=3]="Closed",a))(F||{});var M=class{onMessage=null;onInputMessage=null;onStateChange=null;onError=null;send(t,e){this.onMessage?.(t)}sendInput(t,e){this.onInputMessage?.(t)}getState(){return 1}getBufferedAmount(){return 0}isReady(){return!0}close(t,e){}};var Z="reliable",z="unreliable";
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,1002 @@
|
|
|
1
|
+
import { AudioAck, MacroFeedback } from '@primitiv/types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Primitiv V6 Protocol Constants and Types
|
|
5
|
+
* @packageDocumentation
|
|
6
|
+
*/
|
|
7
|
+
/** Standard header: Marker(1) + Tick(8) */
|
|
8
|
+
declare const HEADER_SIZE_SINGLE = 9;
|
|
9
|
+
/** Fragmented header: Marker(1) + FragBlock(4) + Tick(8) */
|
|
10
|
+
declare const HEADER_SIZE_FRAG = 13;
|
|
11
|
+
/** Maximum packet size before fragmentation */
|
|
12
|
+
declare const MTU = 1200;
|
|
13
|
+
/**
|
|
14
|
+
* Super-Marker registry for Primitiv V6 protocol
|
|
15
|
+
*/
|
|
16
|
+
declare const Marker: {
|
|
17
|
+
readonly HandshakeRequest: 1;
|
|
18
|
+
readonly HandshakeResponse: 2;
|
|
19
|
+
readonly HandshakeStateClient: 3;
|
|
20
|
+
readonly HandshakeStateServer: 4;
|
|
21
|
+
/** Client sends Ping to measure latency */
|
|
22
|
+
readonly Ping: 5;
|
|
23
|
+
/** Server responds with Pong */
|
|
24
|
+
readonly Pong: 6;
|
|
25
|
+
readonly LoadBundle: 16;
|
|
26
|
+
readonly LoadBundleFrag: 17;
|
|
27
|
+
readonly UpdateReliable: 32;
|
|
28
|
+
readonly UpdateReliableFrag: 33;
|
|
29
|
+
readonly UpdateVolatile: 34;
|
|
30
|
+
readonly UpdateVolatileFrag: 35;
|
|
31
|
+
readonly EmptyUpdate: 36;
|
|
32
|
+
readonly InputReliable: 48;
|
|
33
|
+
readonly InputReliableFrag: 49;
|
|
34
|
+
readonly InputVolatile: 50;
|
|
35
|
+
readonly InputVolatileFrag: 51;
|
|
36
|
+
readonly AudioOrder: 64;
|
|
37
|
+
readonly HapticOrder: 65;
|
|
38
|
+
readonly PostProcessOrder: 66;
|
|
39
|
+
readonly MacroOrder: 67;
|
|
40
|
+
/** App -> Server tunnel message */
|
|
41
|
+
readonly BridgeToServer: 80;
|
|
42
|
+
/** App -> Server tunnel message (Fragmented) */
|
|
43
|
+
readonly BridgeToServerFrag: 81;
|
|
44
|
+
/** Server -> App tunnel message */
|
|
45
|
+
readonly BridgeToClient: 82;
|
|
46
|
+
/** Server -> App tunnel message (Fragmented) */
|
|
47
|
+
readonly BridgeToClientFrag: 83;
|
|
48
|
+
readonly ClientCallback: 96;
|
|
49
|
+
readonly ClientCallbackFrag: 97;
|
|
50
|
+
};
|
|
51
|
+
type MarkerType = (typeof Marker)[keyof typeof Marker];
|
|
52
|
+
/**
|
|
53
|
+
* Check if a marker is a fragmented type
|
|
54
|
+
*/
|
|
55
|
+
declare function isFragMarker(marker: number): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Get the fragmented version of a marker
|
|
58
|
+
*/
|
|
59
|
+
declare function toFragMarker(marker: number): number;
|
|
60
|
+
/**
|
|
61
|
+
* Check if a marker requires reliable transport
|
|
62
|
+
*/
|
|
63
|
+
declare function isReliableMarker(marker: number): boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Handshake response status codes
|
|
66
|
+
*/
|
|
67
|
+
declare enum HandshakeStatus {
|
|
68
|
+
OK = 0,
|
|
69
|
+
VersionMismatch = 1,
|
|
70
|
+
ServerFull = 2,
|
|
71
|
+
AuthFailed = 3
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Handshake state machine states
|
|
75
|
+
*/
|
|
76
|
+
declare enum HandshakeState {
|
|
77
|
+
/** Initial state */
|
|
78
|
+
Connected = 0,
|
|
79
|
+
/** Waiting for version check response */
|
|
80
|
+
WaitingForResponse = 1,
|
|
81
|
+
/** Client sending credentials */
|
|
82
|
+
Authenticating = 2,
|
|
83
|
+
/** Loading assets */
|
|
84
|
+
LoadingAssets = 3,
|
|
85
|
+
/** Ready to start simulation */
|
|
86
|
+
Ready = 4,
|
|
87
|
+
/** In active simulation */
|
|
88
|
+
InSimulation = 5,
|
|
89
|
+
/** Disconnected or error */
|
|
90
|
+
Disconnected = 255
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Tick - 64-bit simulation timestamp wrapper for browser compatibility
|
|
95
|
+
*
|
|
96
|
+
* The Tick is the core timing primitive in Primitiv V6 protocol.
|
|
97
|
+
* It's a uint64 encoded as Big-Endian in the wire format.
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* ```ts
|
|
101
|
+
* const tick = Tick.from(12345n);
|
|
102
|
+
* const buffer = tick.toBuffer();
|
|
103
|
+
* const restored = Tick.fromBuffer(buffer);
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
declare class Tick {
|
|
107
|
+
private readonly high;
|
|
108
|
+
private readonly low;
|
|
109
|
+
private constructor();
|
|
110
|
+
/** Zero tick (used for handshake) */
|
|
111
|
+
static readonly ZERO: Tick;
|
|
112
|
+
/** Create from BigInt */
|
|
113
|
+
static from(value: bigint): Tick;
|
|
114
|
+
/** Create from number (safe for values < 2^53) */
|
|
115
|
+
static fromNumber(value: number): Tick;
|
|
116
|
+
/** Create from 8-byte Big-Endian buffer */
|
|
117
|
+
static fromBuffer(buffer: Uint8Array, offset?: number): Tick;
|
|
118
|
+
/** Convert to BigInt */
|
|
119
|
+
toBigInt(): bigint;
|
|
120
|
+
/** Convert to number (precision loss for large values) */
|
|
121
|
+
toNumber(): number;
|
|
122
|
+
/** Write to 8-byte Big-Endian buffer */
|
|
123
|
+
toBuffer(): Uint8Array;
|
|
124
|
+
/** Write to existing buffer at offset */
|
|
125
|
+
writeToBuffer(buffer: Uint8Array, offset?: number): void;
|
|
126
|
+
/** Increment by 1 */
|
|
127
|
+
increment(): Tick;
|
|
128
|
+
/** Compare with another tick */
|
|
129
|
+
compare(other: Tick): number;
|
|
130
|
+
/** Check equality */
|
|
131
|
+
equals(other: Tick): boolean;
|
|
132
|
+
/** Check if this tick is zero */
|
|
133
|
+
isZero(): boolean;
|
|
134
|
+
toString(): string;
|
|
135
|
+
/** Get high 32 bits */
|
|
136
|
+
getHigh(): number;
|
|
137
|
+
/** Get low 32 bits */
|
|
138
|
+
getLow(): number;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Primitiv V6 Header Encoding/Decoding
|
|
143
|
+
*/
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Fragment information for large packets
|
|
147
|
+
*/
|
|
148
|
+
interface FragInfo {
|
|
149
|
+
/** Total number of chunks */
|
|
150
|
+
totalChunks: number;
|
|
151
|
+
/** Index of this chunk (0-based) */
|
|
152
|
+
chunkIndex: number;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Primitiv packet header
|
|
156
|
+
*/
|
|
157
|
+
interface PrimitivHeader {
|
|
158
|
+
/** Message marker (type identifier) */
|
|
159
|
+
marker: number;
|
|
160
|
+
/** Simulation tick */
|
|
161
|
+
tick: Tick;
|
|
162
|
+
/** Fragment info (only for Frag markers) */
|
|
163
|
+
fragInfo?: FragInfo;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Result of decoding a header
|
|
167
|
+
*/
|
|
168
|
+
interface DecodeResult {
|
|
169
|
+
header: PrimitivHeader;
|
|
170
|
+
/** Offset where payload starts */
|
|
171
|
+
payloadOffset: number;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Encode a Primitiv header to binary
|
|
175
|
+
*
|
|
176
|
+
* Single packet: [Marker(1) + Tick(8)] = 9 bytes
|
|
177
|
+
* Frag packet: [Marker(1) + TotalChunks(2) + ChunkIndex(2) + Tick(8)] = 13 bytes
|
|
178
|
+
*/
|
|
179
|
+
declare function encodeHeader(header: PrimitivHeader): Uint8Array;
|
|
180
|
+
/**
|
|
181
|
+
* Decode a Primitiv header from binary
|
|
182
|
+
*/
|
|
183
|
+
declare function decodeHeader(buffer: Uint8Array): DecodeResult;
|
|
184
|
+
/**
|
|
185
|
+
* Create a complete packet with header + payload.
|
|
186
|
+
* Writes header directly into the final buffer (single allocation).
|
|
187
|
+
*/
|
|
188
|
+
declare function createPacket(header: PrimitivHeader, payload?: Uint8Array): Uint8Array;
|
|
189
|
+
/**
|
|
190
|
+
* Extract payload from a packet
|
|
191
|
+
*/
|
|
192
|
+
declare function extractPayload(packet: Uint8Array): {
|
|
193
|
+
header: PrimitivHeader;
|
|
194
|
+
payload: Uint8Array;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Primitiv V6 Packet Fragmenter
|
|
199
|
+
*
|
|
200
|
+
* Splits large payloads into MTU-sized chunks with proper headers.
|
|
201
|
+
*/
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Fragment options
|
|
205
|
+
*/
|
|
206
|
+
interface FragmentOptions {
|
|
207
|
+
/** Custom MTU (default: 1200) */
|
|
208
|
+
mtu?: number;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Fragment a packet if it exceeds MTU
|
|
212
|
+
*
|
|
213
|
+
* @param marker - Base marker (will be converted to Frag version if needed)
|
|
214
|
+
* @param tick - Simulation tick
|
|
215
|
+
* @param payload - Payload to send
|
|
216
|
+
* @param options - Optional fragmentation options
|
|
217
|
+
* @returns Array of complete packets ready to send
|
|
218
|
+
*/
|
|
219
|
+
declare function fragmentPacket(marker: number, tick: Tick, payload: Uint8Array, options?: FragmentOptions): Uint8Array[];
|
|
220
|
+
/**
|
|
221
|
+
* Calculate the number of fragments needed for a payload
|
|
222
|
+
*/
|
|
223
|
+
declare function calculateFragmentCount(payloadSize: number, mtu?: number): number;
|
|
224
|
+
/**
|
|
225
|
+
* Check if a payload will require fragmentation
|
|
226
|
+
*/
|
|
227
|
+
declare function willFragment(payloadSize: number, mtu?: number): boolean;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Primitiv V6 Fragment Assembler
|
|
231
|
+
*
|
|
232
|
+
* Reassembles fragmented packets using composite key (Marker, Tick).
|
|
233
|
+
* Note: Cleanup must be triggered externally (no internal timers).
|
|
234
|
+
*/
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Completed packet result
|
|
238
|
+
*/
|
|
239
|
+
interface CompletePacket {
|
|
240
|
+
marker: number;
|
|
241
|
+
tick: Tick;
|
|
242
|
+
payload: Uint8Array;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Assembler options
|
|
246
|
+
*/
|
|
247
|
+
interface AssemblerOptions {
|
|
248
|
+
/** Time-to-live for pending transfers in ms (default: 10000) */
|
|
249
|
+
ttlMs?: number;
|
|
250
|
+
/** Maximum number of concurrent pending transfers (default: unlimited) */
|
|
251
|
+
maxPendingBuckets?: number;
|
|
252
|
+
/** Maximum totalChunks value accepted per transfer (default: unlimited) */
|
|
253
|
+
maxTotalChunks?: number;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Fragment Assembler
|
|
257
|
+
*
|
|
258
|
+
* Handles both single packets (pass-through) and fragmented packets.
|
|
259
|
+
* Uses composite key (Marker, Tick) for isolation.
|
|
260
|
+
*
|
|
261
|
+
* @example
|
|
262
|
+
* ```ts
|
|
263
|
+
* const assembler = new FragmentAssembler();
|
|
264
|
+
*
|
|
265
|
+
* // In your tick loop or periodic cleanup:
|
|
266
|
+
* assembler.cleanup();
|
|
267
|
+
* ```
|
|
268
|
+
*/
|
|
269
|
+
declare class FragmentAssembler {
|
|
270
|
+
private readonly buckets;
|
|
271
|
+
private readonly ttlMs;
|
|
272
|
+
private readonly maxPendingBuckets;
|
|
273
|
+
private readonly maxTotalChunks;
|
|
274
|
+
/**
|
|
275
|
+
* Set after `receive()` returns `null` due to a security limit.
|
|
276
|
+
* Contains a human-readable reason, or `null` if the last
|
|
277
|
+
* rejection was simply "more fragments needed".
|
|
278
|
+
* Reset on every `receive()` call.
|
|
279
|
+
*/
|
|
280
|
+
lastRejection: string | null;
|
|
281
|
+
constructor(options?: AssemblerOptions);
|
|
282
|
+
/**
|
|
283
|
+
* Process an incoming packet
|
|
284
|
+
*
|
|
285
|
+
* @param packet - Raw packet bytes
|
|
286
|
+
* @returns Complete packet if ready, null if more fragments needed
|
|
287
|
+
*/
|
|
288
|
+
receive(packet: Uint8Array): CompletePacket | null;
|
|
289
|
+
/**
|
|
290
|
+
* Handle a fragmented packet
|
|
291
|
+
*/
|
|
292
|
+
private handleFragment;
|
|
293
|
+
/**
|
|
294
|
+
* Cleanup stale transfers (call this periodically from external tick loop)
|
|
295
|
+
*/
|
|
296
|
+
cleanup(): number;
|
|
297
|
+
/**
|
|
298
|
+
* Get pending transfer count (for debugging/monitoring)
|
|
299
|
+
*/
|
|
300
|
+
getPendingCount(): number;
|
|
301
|
+
/**
|
|
302
|
+
* Force cleanup of all pending transfers for a tick
|
|
303
|
+
*/
|
|
304
|
+
clearTick(tick: Tick): void;
|
|
305
|
+
/**
|
|
306
|
+
* Clear all pending transfers
|
|
307
|
+
*/
|
|
308
|
+
destroy(): void;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Transport Abstraction Layer
|
|
313
|
+
*
|
|
314
|
+
* Defines interfaces for network transport (WebSocket, WebRTC, TCP, etc.)
|
|
315
|
+
* without implementation dependencies.
|
|
316
|
+
*/
|
|
317
|
+
/**
|
|
318
|
+
* Transport connection state
|
|
319
|
+
*/
|
|
320
|
+
declare enum TransportState {
|
|
321
|
+
Connecting = 0,
|
|
322
|
+
Open = 1,
|
|
323
|
+
Closing = 2,
|
|
324
|
+
Closed = 3
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Message received callback
|
|
328
|
+
*/
|
|
329
|
+
type OnMessageCallback = (data: Uint8Array) => void;
|
|
330
|
+
/**
|
|
331
|
+
* Connection state change callback
|
|
332
|
+
*/
|
|
333
|
+
type OnStateChangeCallback = (state: TransportState) => void;
|
|
334
|
+
/**
|
|
335
|
+
* Error callback
|
|
336
|
+
*/
|
|
337
|
+
type OnErrorCallback = (error: Error) => void;
|
|
338
|
+
/**
|
|
339
|
+
* Transport interface
|
|
340
|
+
*
|
|
341
|
+
* Abstraction over different transport mechanisms.
|
|
342
|
+
* Implementations should handle their specific protocol details.
|
|
343
|
+
*/
|
|
344
|
+
interface ITransport {
|
|
345
|
+
/**
|
|
346
|
+
* Send binary data
|
|
347
|
+
* @param data - Data to send
|
|
348
|
+
* @param reliable - If true, use reliable channel (TCP/Reliable DataChannel)
|
|
349
|
+
*/
|
|
350
|
+
send(data: Uint8Array, reliable: boolean): void;
|
|
351
|
+
/**
|
|
352
|
+
* Close the transport connection
|
|
353
|
+
* @param code - Optional close code
|
|
354
|
+
* @param reason - Optional close reason
|
|
355
|
+
*/
|
|
356
|
+
close(code?: number, reason?: string): void;
|
|
357
|
+
/**
|
|
358
|
+
* Get current connection state
|
|
359
|
+
*/
|
|
360
|
+
getState(): TransportState;
|
|
361
|
+
/**
|
|
362
|
+
* Get amount of data buffered for sending (bytes)
|
|
363
|
+
* Used for backpressure/pacing
|
|
364
|
+
*/
|
|
365
|
+
getBufferedAmount(): number;
|
|
366
|
+
/**
|
|
367
|
+
* Check if transport is ready to send
|
|
368
|
+
*/
|
|
369
|
+
isReady(): boolean;
|
|
370
|
+
/**
|
|
371
|
+
* Set message handler
|
|
372
|
+
*/
|
|
373
|
+
onMessage: OnMessageCallback | null;
|
|
374
|
+
/**
|
|
375
|
+
* Set state change handler
|
|
376
|
+
*/
|
|
377
|
+
onStateChange: OnStateChangeCallback | null;
|
|
378
|
+
/**
|
|
379
|
+
* Set error handler
|
|
380
|
+
*/
|
|
381
|
+
onError: OnErrorCallback | null;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Client transport interface
|
|
385
|
+
*
|
|
386
|
+
* Extended transport interface for client-side use.
|
|
387
|
+
* Adds connection initiation capability.
|
|
388
|
+
*/
|
|
389
|
+
interface IClientTransport extends ITransport {
|
|
390
|
+
/**
|
|
391
|
+
* Connect to a server
|
|
392
|
+
* @param url - Server URL to connect to
|
|
393
|
+
*/
|
|
394
|
+
connect(url: string): Promise<void>;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Server transport interface
|
|
398
|
+
*
|
|
399
|
+
* Extended transport interface for server-side use.
|
|
400
|
+
*/
|
|
401
|
+
interface IServerTransport {
|
|
402
|
+
/**
|
|
403
|
+
* Start accepting connections
|
|
404
|
+
* @param port - Port to listen on
|
|
405
|
+
* @param host - Host to bind to (default: 0.0.0.0)
|
|
406
|
+
*/
|
|
407
|
+
listen(port: number, host?: string): Promise<void>;
|
|
408
|
+
/**
|
|
409
|
+
* Stop accepting connections
|
|
410
|
+
*/
|
|
411
|
+
stop(): Promise<void>;
|
|
412
|
+
/**
|
|
413
|
+
* Called when a new client connects
|
|
414
|
+
*/
|
|
415
|
+
onConnection: ((clientId: string, transport: ITransport) => void) | null;
|
|
416
|
+
/**
|
|
417
|
+
* Called when a client disconnects
|
|
418
|
+
*/
|
|
419
|
+
onDisconnection: ((clientId: string, reason?: string) => void) | null;
|
|
420
|
+
/**
|
|
421
|
+
* Get all connected client IDs
|
|
422
|
+
*/
|
|
423
|
+
getConnectedClients(): string[];
|
|
424
|
+
/**
|
|
425
|
+
* Get transport for a specific client
|
|
426
|
+
*/
|
|
427
|
+
getClientTransport(clientId: string): ITransport | null;
|
|
428
|
+
/**
|
|
429
|
+
* Disconnect a specific client
|
|
430
|
+
*/
|
|
431
|
+
disconnectClient(clientId: string, reason?: string): void;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Primitiv Interleaving Manager
|
|
436
|
+
*
|
|
437
|
+
* Manages prioritized message queuing and paced fragmentation for the network stack.
|
|
438
|
+
* Ensures that large data transfers (background) don't block real-time updates (immediate).
|
|
439
|
+
*/
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Interleaving Manager configuration
|
|
443
|
+
*/
|
|
444
|
+
interface InterleavingOptions {
|
|
445
|
+
/** Max fragments sent per flush call (background stream) */
|
|
446
|
+
fragmentsPerTick?: number;
|
|
447
|
+
/** Transport buffered amount threshold (pacing) */
|
|
448
|
+
bufferedThreshold?: number;
|
|
449
|
+
/**
|
|
450
|
+
* Maximum number of packets allowed in the background queue.
|
|
451
|
+
* When exceeded, the oldest undelivered packets are dropped.
|
|
452
|
+
* Prevents unbounded memory growth from slow/stalled clients.
|
|
453
|
+
* @default 4096
|
|
454
|
+
*/
|
|
455
|
+
maxBackgroundQueue?: number;
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Manages interleaving of fragments and real-time packets
|
|
459
|
+
*/
|
|
460
|
+
declare class InterleavingManager {
|
|
461
|
+
private readonly transport;
|
|
462
|
+
private readonly backgroundQueue;
|
|
463
|
+
private readonly immediateQueue;
|
|
464
|
+
private bgCursor;
|
|
465
|
+
private imCursor;
|
|
466
|
+
private readonly options;
|
|
467
|
+
constructor(transport: ITransport, options?: InterleavingOptions);
|
|
468
|
+
/**
|
|
469
|
+
* Enqueue a payload for interleaved (background) delivery.
|
|
470
|
+
* Large payloads will be automatically fragmented.
|
|
471
|
+
*/
|
|
472
|
+
enqueue(marker: number, tick: Tick, payload: Uint8Array): void;
|
|
473
|
+
/**
|
|
474
|
+
* Enqueue a payload for prioritized immediate delivery.
|
|
475
|
+
* Large payloads will be automatically fragmented.
|
|
476
|
+
*/
|
|
477
|
+
enqueueImmediate(marker: number, tick: Tick, payload: Uint8Array): void;
|
|
478
|
+
/**
|
|
479
|
+
* Enqueue a pre-built packet for immediate delivery.
|
|
480
|
+
* Skipping all queues and fragmentation logic.
|
|
481
|
+
*/
|
|
482
|
+
enqueueRawImmediate(data: Uint8Array, reliable: boolean): void;
|
|
483
|
+
/**
|
|
484
|
+
* Flush queues to the transport
|
|
485
|
+
* Respects budget and bufferedAmount thresholds.
|
|
486
|
+
*/
|
|
487
|
+
flush(): void;
|
|
488
|
+
/**
|
|
489
|
+
* Clear all pending messages
|
|
490
|
+
*/
|
|
491
|
+
clear(): void;
|
|
492
|
+
/**
|
|
493
|
+
* Drop oldest undelivered background packets when the queue exceeds the limit.
|
|
494
|
+
* This prevents unbounded memory growth from slow or stalled clients.
|
|
495
|
+
*/
|
|
496
|
+
private enforceBackgroundLimit;
|
|
497
|
+
/**
|
|
498
|
+
* Get number of pending background fragments
|
|
499
|
+
*/
|
|
500
|
+
getPendingCount(): number;
|
|
501
|
+
/**
|
|
502
|
+
* Check if there are any pending immediate messages
|
|
503
|
+
*/
|
|
504
|
+
hasImmediatePending(): boolean;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* ClientCallback - Batched client->server feedback codec.
|
|
509
|
+
*
|
|
510
|
+
* Wire format:
|
|
511
|
+
* ┌────────────────┬───────────────────────────────────────────────────┐
|
|
512
|
+
* │ numSections: 1 │ Section[] │
|
|
513
|
+
* └────────────────┴───────────────────────────────────────────────────┘
|
|
514
|
+
*
|
|
515
|
+
* Each Section:
|
|
516
|
+
* ┌──────────┬──────────┬──────────────────────────────────────────────┐
|
|
517
|
+
* │ type: 1 │ count: 1 │ entries (type-specific encoding) │
|
|
518
|
+
* └──────────┴──────────┴──────────────────────────────────────────────┘
|
|
519
|
+
*
|
|
520
|
+
* Callback types:
|
|
521
|
+
* 0x01 = AudioAck
|
|
522
|
+
*
|
|
523
|
+
* AudioAck entry encoding:
|
|
524
|
+
* ┌─────────────────┬─────────────────────────────────────────────┐
|
|
525
|
+
* │ ackType: 1 │ fields (varies by ackType) │
|
|
526
|
+
* └─────────────────┴─────────────────────────────────────────────┘
|
|
527
|
+
*
|
|
528
|
+
* ackType 0x01 sound-loaded: soundId:u16, nameLen:u8, name:utf8
|
|
529
|
+
* ackType 0x02 sound-error: soundId:u16, nameLen:u8, name:utf8, errLen:u8, err:utf8
|
|
530
|
+
* ackType 0x03 playback-started: instanceId:u32, soundId:u16
|
|
531
|
+
* ackType 0x04 playback-ended: instanceId:u32, soundId:u16
|
|
532
|
+
* ackType 0x05 playback-error: hasInstance:u8, instanceId?:u32, soundRef:u16, errLen:u8, err:utf8
|
|
533
|
+
*
|
|
534
|
+
* MacroFeedback entry encoding:
|
|
535
|
+
* ┌─────────────────┬─────────────────────────────────────────────┐
|
|
536
|
+
* │ cmd: 1 │ instanceId: 2 │ fields (varies by cmd) │
|
|
537
|
+
* └─────────────────┴─────────────────────────────────────────────┘
|
|
538
|
+
*
|
|
539
|
+
* cmd 0x01 click: (no extra fields)
|
|
540
|
+
* cmd 0x02 change: valueType:u8 (0=number,1=bool), value:u16|u8
|
|
541
|
+
* cmd 0x03 submit: textLen:u16, text:utf8
|
|
542
|
+
* cmd 0x04 select: index:u16
|
|
543
|
+
* cmd 0x05 custom: dataLen:u16, data:utf8
|
|
544
|
+
*/
|
|
545
|
+
|
|
546
|
+
declare const CallbackSectionType: {
|
|
547
|
+
readonly AudioAck: 1;
|
|
548
|
+
readonly MacroFeedback: 2;
|
|
549
|
+
};
|
|
550
|
+
/**
|
|
551
|
+
* Decoded client callback payload - one section per callback type.
|
|
552
|
+
*/
|
|
553
|
+
interface DecodedClientCallback {
|
|
554
|
+
audioAcks: AudioAck[];
|
|
555
|
+
macroFeedbacks: MacroFeedback[];
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Encode batched client callbacks into a compact binary payload.
|
|
559
|
+
*
|
|
560
|
+
* Only non-empty sections are written. Returns an empty Uint8Array
|
|
561
|
+
* if there is nothing to send.
|
|
562
|
+
*/
|
|
563
|
+
declare function encodeClientCallback(data: DecodedClientCallback): Uint8Array;
|
|
564
|
+
/**
|
|
565
|
+
* Decode a ClientCallback binary payload into structured sections.
|
|
566
|
+
*
|
|
567
|
+
* Throws `RangeError` if the payload is truncated or malformed.
|
|
568
|
+
*/
|
|
569
|
+
declare function decodeClientCallback(data: Uint8Array): DecodedClientCallback;
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* LoopbackTransport - Synchronous in-process transport for standalone mode.
|
|
573
|
+
*
|
|
574
|
+
* Implements ITransport without fragmentation, without copying, without interleaving.
|
|
575
|
+
* Passes Uint8Array buffers directly to the onMessage callback synchronously.
|
|
576
|
+
*
|
|
577
|
+
* Bidirectional:
|
|
578
|
+
* - send() → onMessage (server→client direction, for tick updates)
|
|
579
|
+
* - sendInput() → onInputMessage (client→server direction, for input)
|
|
580
|
+
*/
|
|
581
|
+
|
|
582
|
+
declare class LoopbackTransport implements ITransport {
|
|
583
|
+
/** Callback for server→client messages (tick updates) */
|
|
584
|
+
onMessage: OnMessageCallback | null;
|
|
585
|
+
/** Callback for client→server messages (input) */
|
|
586
|
+
onInputMessage: OnMessageCallback | null;
|
|
587
|
+
onStateChange: OnStateChangeCallback | null;
|
|
588
|
+
onError: OnErrorCallback | null;
|
|
589
|
+
/**
|
|
590
|
+
* Send data synchronously (server→client direction).
|
|
591
|
+
* Used for tick updates from engine to renderer.
|
|
592
|
+
*/
|
|
593
|
+
send(data: Uint8Array, _reliable: boolean): void;
|
|
594
|
+
/**
|
|
595
|
+
* Send input data synchronously (client→server direction).
|
|
596
|
+
* Used for input from client to engine.
|
|
597
|
+
*/
|
|
598
|
+
sendInput(data: Uint8Array, _reliable: boolean): void;
|
|
599
|
+
/**
|
|
600
|
+
* Always open.
|
|
601
|
+
*/
|
|
602
|
+
getState(): TransportState;
|
|
603
|
+
/**
|
|
604
|
+
* No buffering in loopback.
|
|
605
|
+
*/
|
|
606
|
+
getBufferedAmount(): number;
|
|
607
|
+
/**
|
|
608
|
+
* Always ready.
|
|
609
|
+
*/
|
|
610
|
+
isReady(): boolean;
|
|
611
|
+
/**
|
|
612
|
+
* No-op for loopback.
|
|
613
|
+
*/
|
|
614
|
+
close(_code?: number, _reason?: string): void;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* WebRTC Signaling Protocol Types
|
|
619
|
+
*
|
|
620
|
+
* Defines JSON messages exchanged over the WebSocket signaling channel
|
|
621
|
+
* to establish WebRTC DataChannel connections.
|
|
622
|
+
*
|
|
623
|
+
* ## Server Transport Modes
|
|
624
|
+
*
|
|
625
|
+
* The server supports three distinct WebRTC transport modes:
|
|
626
|
+
*
|
|
627
|
+
* - **`webrtc-direct`** — Full ICE with local signaling. The game server runs
|
|
628
|
+
* its own signaling WebSocket endpoint. Requires the server to be directly
|
|
629
|
+
* reachable by clients (public IP or port forwarding). Best for dedicated
|
|
630
|
+
* servers with known addresses.
|
|
631
|
+
*
|
|
632
|
+
* - **`webrtc-relay`** — Full ICE with external relay signaling. The game
|
|
633
|
+
* server connects to a public signaling relay and registers under a
|
|
634
|
+
* `sessionId`. Clients connect to the same relay with the matching
|
|
635
|
+
* `sessionId`. Enables "zero-config" networking where neither server nor
|
|
636
|
+
* clients need public IPs. Best for peer-hosted games or NAT traversal.
|
|
637
|
+
*
|
|
638
|
+
* - **`webrtc-lite`** — ICE-lite mode. The server opens a single multiplexed
|
|
639
|
+
* UDP port and announces its address directly. Requires port forwarding but
|
|
640
|
+
* guarantees ~100% connectivity. Best for maximum reliability with known
|
|
641
|
+
* server infrastructure.
|
|
642
|
+
*
|
|
643
|
+
* ## Client Transport Modes
|
|
644
|
+
*
|
|
645
|
+
* The client supports two WebRTC modes:
|
|
646
|
+
*
|
|
647
|
+
* - **`webrtc-full`** — Full ICE negotiation with STUN. Works with both
|
|
648
|
+
* `webrtc-direct` and `webrtc-relay` servers. When `sessionId` is provided,
|
|
649
|
+
* connects via relay; otherwise connects directly to the server URL.
|
|
650
|
+
*
|
|
651
|
+
* - **`webrtc-lite`** — ICE-lite mode. Connects to a `webrtc-lite` server.
|
|
652
|
+
* No STUN required on the client side.
|
|
653
|
+
*
|
|
654
|
+
* ## Signaling Flow
|
|
655
|
+
*
|
|
656
|
+
* 1. Client opens signaling WebSocket (direct to server or via relay)
|
|
657
|
+
* 2. Client creates RTCPeerConnection + 2 DataChannels (reliable, unreliable)
|
|
658
|
+
* 3. Client sends `rtc-offer` with SDP
|
|
659
|
+
* 4. Server creates PeerConnection, sets remote offer, creates answer
|
|
660
|
+
* 5. Server sends `rtc-answer` with SDP
|
|
661
|
+
* 6. Both sides exchange `rtc-candidate` messages (ICE candidates)
|
|
662
|
+
* 7. DataChannels open → game protocol flows over DataChannels
|
|
663
|
+
* 8. Signaling WebSocket stays alive as a health-check channel
|
|
664
|
+
*/
|
|
665
|
+
/**
|
|
666
|
+
* Messages the client sends to the server during WebRTC signaling.
|
|
667
|
+
* Used in direct mode (client connects to server's signaling endpoint).
|
|
668
|
+
*/
|
|
669
|
+
type ClientSignalingMessage = {
|
|
670
|
+
type: 'rtc-offer';
|
|
671
|
+
sdp: string;
|
|
672
|
+
} | {
|
|
673
|
+
type: 'rtc-candidate';
|
|
674
|
+
candidate: string;
|
|
675
|
+
mid: string;
|
|
676
|
+
};
|
|
677
|
+
/**
|
|
678
|
+
* Messages the server sends to the client during WebRTC signaling.
|
|
679
|
+
* Used in direct mode and relayed in relay mode.
|
|
680
|
+
*/
|
|
681
|
+
type ServerSignalingMessage = {
|
|
682
|
+
type: 'rtc-answer';
|
|
683
|
+
sdp: string;
|
|
684
|
+
} | {
|
|
685
|
+
type: 'rtc-candidate';
|
|
686
|
+
candidate: string;
|
|
687
|
+
mid: string;
|
|
688
|
+
} | {
|
|
689
|
+
type: 'rtc-error';
|
|
690
|
+
message: string;
|
|
691
|
+
};
|
|
692
|
+
/**
|
|
693
|
+
* Shared configuration options for all WebRTC server modes.
|
|
694
|
+
*/
|
|
695
|
+
interface BaseWebRTCServerConfig {
|
|
696
|
+
/**
|
|
697
|
+
* Maximum number of concurrent WebRTC peer connections.
|
|
698
|
+
* @default 64
|
|
699
|
+
*/
|
|
700
|
+
maxPeers?: number;
|
|
701
|
+
/**
|
|
702
|
+
* List of allowed origins for the signaling WebSocket.
|
|
703
|
+
* If set, only connections with a matching `Origin` header are accepted.
|
|
704
|
+
* If omitted or empty, all origins are allowed.
|
|
705
|
+
*
|
|
706
|
+
* @example ['https://mygame.com', 'http://localhost:5173']
|
|
707
|
+
*/
|
|
708
|
+
allowedOrigins?: string[];
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Configuration for `webrtc-direct` server mode.
|
|
712
|
+
*
|
|
713
|
+
* The server runs its own signaling WebSocket endpoint and uses full ICE
|
|
714
|
+
* with STUN servers for NAT traversal. Requires the server to be directly
|
|
715
|
+
* reachable by clients.
|
|
716
|
+
*
|
|
717
|
+
* @example
|
|
718
|
+
* ```ts
|
|
719
|
+
* {
|
|
720
|
+
* mode: 'direct',
|
|
721
|
+
* stunServers: ['stun:stun.l.google.com:19302'],
|
|
722
|
+
* }
|
|
723
|
+
* ```
|
|
724
|
+
*/
|
|
725
|
+
interface WebRTCDirectServerConfig extends BaseWebRTCServerConfig {
|
|
726
|
+
/** Discriminant for direct mode. */
|
|
727
|
+
mode: 'direct';
|
|
728
|
+
/**
|
|
729
|
+
* STUN server URIs for ICE candidate gathering.
|
|
730
|
+
* Required for NAT traversal in direct mode.
|
|
731
|
+
*
|
|
732
|
+
* @example ['stun:stun.l.google.com:19302']
|
|
733
|
+
*/
|
|
734
|
+
stunServers?: string[];
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Configuration for `webrtc-relay` server mode.
|
|
738
|
+
*
|
|
739
|
+
* The server connects to an external signaling relay as a WebSocket client
|
|
740
|
+
* and registers under a `sessionId`. Clients connect to the same relay
|
|
741
|
+
* with the matching `sessionId` and are routed to this server.
|
|
742
|
+
*
|
|
743
|
+
* This enables "zero-config" networking where both server and clients only
|
|
744
|
+
* need to know the relay URL and a shared session ID — no port forwarding
|
|
745
|
+
* or public IP required on the server.
|
|
746
|
+
*
|
|
747
|
+
* @example
|
|
748
|
+
* ```ts
|
|
749
|
+
* {
|
|
750
|
+
* mode: 'relay',
|
|
751
|
+
* signalingUrl: 'wss://signal.example.com',
|
|
752
|
+
* sessionId: 'my-game-abc123',
|
|
753
|
+
* stunServers: ['stun:stun.l.google.com:19302'],
|
|
754
|
+
* }
|
|
755
|
+
* ```
|
|
756
|
+
*/
|
|
757
|
+
interface WebRTCRelayServerConfig extends BaseWebRTCServerConfig {
|
|
758
|
+
/** Discriminant for relay mode. */
|
|
759
|
+
mode: 'relay';
|
|
760
|
+
/**
|
|
761
|
+
* URL of the external signaling relay server.
|
|
762
|
+
* The game server connects to this relay as a WebSocket client.
|
|
763
|
+
*
|
|
764
|
+
* @example 'wss://signal.example.com'
|
|
765
|
+
*/
|
|
766
|
+
signalingUrl: string;
|
|
767
|
+
/**
|
|
768
|
+
* Session identifier for relay registration.
|
|
769
|
+
*
|
|
770
|
+
* The server registers under this ID. Clients connect to the same relay
|
|
771
|
+
* with the matching `sessionId` to be routed to this server.
|
|
772
|
+
*
|
|
773
|
+
* @example 'my-game-abc123'
|
|
774
|
+
*/
|
|
775
|
+
sessionId: string;
|
|
776
|
+
/**
|
|
777
|
+
* STUN server URIs for ICE candidate gathering.
|
|
778
|
+
* Required for NAT traversal.
|
|
779
|
+
*
|
|
780
|
+
* @example ['stun:stun.l.google.com:19302']
|
|
781
|
+
*/
|
|
782
|
+
stunServers?: string[];
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Configuration for `webrtc-lite` server mode.
|
|
786
|
+
*
|
|
787
|
+
* ICE-lite mode: the server opens a single multiplexed UDP port and
|
|
788
|
+
* announces its address directly to clients. Requires port forwarding
|
|
789
|
+
* on the server side but guarantees ~100% connectivity.
|
|
790
|
+
*
|
|
791
|
+
* @example
|
|
792
|
+
* ```ts
|
|
793
|
+
* {
|
|
794
|
+
* mode: 'lite',
|
|
795
|
+
* dataPort: 9000,
|
|
796
|
+
* }
|
|
797
|
+
* ```
|
|
798
|
+
*/
|
|
799
|
+
interface WebRTCLiteServerConfig extends BaseWebRTCServerConfig {
|
|
800
|
+
/** Discriminant for ICE-lite mode. */
|
|
801
|
+
mode: 'lite';
|
|
802
|
+
/**
|
|
803
|
+
* UDP port for WebRTC data.
|
|
804
|
+
* All clients are multiplexed on this single port.
|
|
805
|
+
* @default port + 1 (where port is the signaling/HTTP port)
|
|
806
|
+
*/
|
|
807
|
+
dataPort?: number;
|
|
808
|
+
/**
|
|
809
|
+
* Bind address for the UDP socket.
|
|
810
|
+
* @default '0.0.0.0'
|
|
811
|
+
*/
|
|
812
|
+
bindAddress?: string;
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Union of all WebRTC server configurations.
|
|
816
|
+
* Discriminated on the `mode` field.
|
|
817
|
+
*/
|
|
818
|
+
type WebRTCServerConfig = WebRTCDirectServerConfig | WebRTCRelayServerConfig | WebRTCLiteServerConfig;
|
|
819
|
+
/**
|
|
820
|
+
* Configuration for `webrtc-full` client mode.
|
|
821
|
+
*
|
|
822
|
+
* Uses full ICE negotiation with STUN servers. Can connect to either:
|
|
823
|
+
* - A `webrtc-direct` server (via `signalingUrl` pointing to the server)
|
|
824
|
+
* - A `webrtc-relay` server (via `signalingUrl` pointing to relay + `sessionId`)
|
|
825
|
+
*
|
|
826
|
+
* The presence of `sessionId` determines whether to use relay mode.
|
|
827
|
+
*
|
|
828
|
+
* @example Direct mode (connect to server directly)
|
|
829
|
+
* ```ts
|
|
830
|
+
* {
|
|
831
|
+
* mode: 'full',
|
|
832
|
+
* signalingUrl: 'ws://gameserver.example.com:3000',
|
|
833
|
+
* stunServers: ['stun:stun.l.google.com:19302'],
|
|
834
|
+
* }
|
|
835
|
+
* ```
|
|
836
|
+
*
|
|
837
|
+
* @example Relay mode (connect via signaling relay)
|
|
838
|
+
* ```ts
|
|
839
|
+
* {
|
|
840
|
+
* mode: 'full',
|
|
841
|
+
* signalingUrl: 'wss://signal.example.com',
|
|
842
|
+
* sessionId: 'my-game-abc123',
|
|
843
|
+
* stunServers: ['stun:stun.l.google.com:19302'],
|
|
844
|
+
* }
|
|
845
|
+
* ```
|
|
846
|
+
*/
|
|
847
|
+
interface WebRTCFullClientConfig {
|
|
848
|
+
/** Discriminant for full ICE mode. */
|
|
849
|
+
mode: 'full';
|
|
850
|
+
/**
|
|
851
|
+
* URL of the signaling endpoint.
|
|
852
|
+
*
|
|
853
|
+
* - In direct mode: WebSocket URL of the game server's signaling endpoint.
|
|
854
|
+
* - In relay mode: WebSocket URL of the external signaling relay.
|
|
855
|
+
*
|
|
856
|
+
* @example 'ws://gameserver:3000' or 'wss://signal.example.com'
|
|
857
|
+
*/
|
|
858
|
+
signalingUrl?: string;
|
|
859
|
+
/**
|
|
860
|
+
* Session identifier for relay mode.
|
|
861
|
+
*
|
|
862
|
+
* When set, the client connects to the relay and requests to join the
|
|
863
|
+
* session with this ID. The relay routes the client to the game server
|
|
864
|
+
* that registered with the same `sessionId`.
|
|
865
|
+
*
|
|
866
|
+
* When omitted, the client connects directly to the server (direct mode).
|
|
867
|
+
*
|
|
868
|
+
* @example 'my-game-abc123'
|
|
869
|
+
*/
|
|
870
|
+
sessionId?: string;
|
|
871
|
+
/**
|
|
872
|
+
* STUN server URIs for ICE candidate gathering.
|
|
873
|
+
*
|
|
874
|
+
* @example ['stun:stun.l.google.com:19302']
|
|
875
|
+
*/
|
|
876
|
+
stunServers?: string[];
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* Configuration for `webrtc-lite` client mode.
|
|
880
|
+
*
|
|
881
|
+
* Connects to a `webrtc-lite` server. No STUN required on the client side
|
|
882
|
+
* since the server announces its address directly.
|
|
883
|
+
*
|
|
884
|
+
* @example
|
|
885
|
+
* ```ts
|
|
886
|
+
* {
|
|
887
|
+
* mode: 'lite',
|
|
888
|
+
* signalingUrl: 'ws://gameserver.example.com:3000',
|
|
889
|
+
* }
|
|
890
|
+
* ```
|
|
891
|
+
*/
|
|
892
|
+
interface WebRTCLiteClientConfig {
|
|
893
|
+
/** Discriminant for ICE-lite mode. */
|
|
894
|
+
mode: 'lite';
|
|
895
|
+
/**
|
|
896
|
+
* WebSocket URL of the game server's signaling endpoint.
|
|
897
|
+
*
|
|
898
|
+
* @example 'ws://gameserver.example.com:3000'
|
|
899
|
+
*/
|
|
900
|
+
signalingUrl?: string;
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Union of all WebRTC client configurations.
|
|
904
|
+
* Discriminated on the `mode` field.
|
|
905
|
+
*/
|
|
906
|
+
type WebRTCClientConfig = WebRTCFullClientConfig | WebRTCLiteClientConfig;
|
|
907
|
+
/**
|
|
908
|
+
* Messages the game server sends TO the signaling relay.
|
|
909
|
+
*
|
|
910
|
+
* The relay is a lightweight WebSocket router. The game server connects as a
|
|
911
|
+
* WS client, registers with `'register-server'`, then receives client
|
|
912
|
+
* signaling messages and responds with SDP answers / ICE candidates - each
|
|
913
|
+
* tagged with `clientId` so the relay can route them.
|
|
914
|
+
*/
|
|
915
|
+
type ServerToRelayMessage = {
|
|
916
|
+
type: 'register-server';
|
|
917
|
+
sessionId: string;
|
|
918
|
+
} | {
|
|
919
|
+
type: 'rtc-answer';
|
|
920
|
+
clientId: string;
|
|
921
|
+
sdp: string;
|
|
922
|
+
} | {
|
|
923
|
+
type: 'rtc-candidate';
|
|
924
|
+
clientId: string;
|
|
925
|
+
candidate: string;
|
|
926
|
+
mid: string;
|
|
927
|
+
} | {
|
|
928
|
+
type: 'rtc-error';
|
|
929
|
+
clientId: string;
|
|
930
|
+
message: string;
|
|
931
|
+
};
|
|
932
|
+
/**
|
|
933
|
+
* Messages the signaling relay sends TO the game server.
|
|
934
|
+
*
|
|
935
|
+
* Each message from a client is tagged with `clientId` so the server knows
|
|
936
|
+
* which PeerConnection it belongs to.
|
|
937
|
+
*/
|
|
938
|
+
type RelayToServerMessage = {
|
|
939
|
+
type: 'server-registered';
|
|
940
|
+
serverId: string;
|
|
941
|
+
} | {
|
|
942
|
+
type: 'client-joined';
|
|
943
|
+
clientId: string;
|
|
944
|
+
} | {
|
|
945
|
+
type: 'client-left';
|
|
946
|
+
clientId: string;
|
|
947
|
+
} | {
|
|
948
|
+
type: 'rtc-offer';
|
|
949
|
+
clientId: string;
|
|
950
|
+
sdp: string;
|
|
951
|
+
} | {
|
|
952
|
+
type: 'rtc-candidate';
|
|
953
|
+
clientId: string;
|
|
954
|
+
candidate: string;
|
|
955
|
+
mid: string;
|
|
956
|
+
};
|
|
957
|
+
/**
|
|
958
|
+
* Messages the client sends TO the signaling relay.
|
|
959
|
+
*
|
|
960
|
+
* The client connects to the relay, sends `'join-session'` with a `sessionId`
|
|
961
|
+
* to be routed to the game server that registered with that ID.
|
|
962
|
+
*/
|
|
963
|
+
type ClientToRelayMessage = {
|
|
964
|
+
type: 'join-session';
|
|
965
|
+
sessionId: string;
|
|
966
|
+
} | {
|
|
967
|
+
type: 'rtc-offer';
|
|
968
|
+
sdp: string;
|
|
969
|
+
} | {
|
|
970
|
+
type: 'rtc-candidate';
|
|
971
|
+
candidate: string;
|
|
972
|
+
mid: string;
|
|
973
|
+
};
|
|
974
|
+
/**
|
|
975
|
+
* Messages the signaling relay sends TO the client.
|
|
976
|
+
*
|
|
977
|
+
* The relay routes these messages from the game server to the client.
|
|
978
|
+
*/
|
|
979
|
+
type RelayToClientMessage = {
|
|
980
|
+
type: 'session-joined';
|
|
981
|
+
serverId: string;
|
|
982
|
+
} | {
|
|
983
|
+
type: 'session-not-found';
|
|
984
|
+
sessionId: string;
|
|
985
|
+
} | {
|
|
986
|
+
type: 'rtc-answer';
|
|
987
|
+
sdp: string;
|
|
988
|
+
} | {
|
|
989
|
+
type: 'rtc-candidate';
|
|
990
|
+
candidate: string;
|
|
991
|
+
mid: string;
|
|
992
|
+
} | {
|
|
993
|
+
type: 'rtc-error';
|
|
994
|
+
message: string;
|
|
995
|
+
};
|
|
996
|
+
/** Label for the ordered, reliable DataChannel */
|
|
997
|
+
declare const DC_RELIABLE = "reliable";
|
|
998
|
+
/** Label for the unordered, unreliable DataChannel (maxRetransmits = 0) */
|
|
999
|
+
declare const DC_UNRELIABLE = "unreliable";
|
|
1000
|
+
|
|
1001
|
+
export { CallbackSectionType, DC_RELIABLE, DC_UNRELIABLE, FragmentAssembler, HEADER_SIZE_FRAG, HEADER_SIZE_SINGLE, HandshakeState, HandshakeStatus, InterleavingManager, LoopbackTransport, MTU, Marker, Tick, TransportState, calculateFragmentCount, createPacket, decodeClientCallback, decodeHeader, encodeClientCallback, encodeHeader, extractPayload, fragmentPacket, isFragMarker, isReliableMarker, toFragMarker, willFragment };
|
|
1002
|
+
export type { AssemblerOptions, ClientSignalingMessage, ClientToRelayMessage, CompletePacket, DecodeResult, DecodedClientCallback, FragInfo, FragmentOptions, IClientTransport, IServerTransport, ITransport, InterleavingOptions, MarkerType, OnErrorCallback, OnMessageCallback, OnStateChangeCallback, PrimitivHeader, RelayToClientMessage, RelayToServerMessage, ServerSignalingMessage, ServerToRelayMessage, WebRTCClientConfig, WebRTCDirectServerConfig, WebRTCFullClientConfig, WebRTCLiteClientConfig, WebRTCLiteServerConfig, WebRTCRelayServerConfig, WebRTCServerConfig };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var h=9,p=13,C=1200,l={HandshakeRequest:1,HandshakeResponse:2,HandshakeStateClient:3,HandshakeStateServer:4,Ping:5,Pong:6,LoadBundle:16,LoadBundleFrag:17,UpdateReliable:32,UpdateReliableFrag:33,UpdateVolatile:34,UpdateVolatileFrag:35,EmptyUpdate:36,InputReliable:48,InputReliableFrag:49,InputVolatile:50,InputVolatileFrag:51,AudioOrder:64,HapticOrder:65,PostProcessOrder:66,MacroOrder:67,BridgeToServer:80,BridgeToServerFrag:81,BridgeToClient:82,BridgeToClientFrag:83,ClientCallback:96,ClientCallbackFrag:97};function f(n){return n===l.LoadBundleFrag||n===l.UpdateReliableFrag||n===l.UpdateVolatileFrag||n===l.InputReliableFrag||n===l.InputVolatileFrag||n===l.BridgeToServerFrag||n===l.BridgeToClientFrag||n===l.ClientCallbackFrag}function v(n){switch(n){case l.LoadBundle:return l.LoadBundleFrag;case l.UpdateReliable:return l.UpdateReliableFrag;case l.UpdateVolatile:return l.UpdateVolatileFrag;case l.InputReliable:return l.InputReliableFrag;case l.InputVolatile:return l.InputVolatileFrag;case l.BridgeToServer:return l.BridgeToServerFrag;case l.BridgeToClient:return l.BridgeToClientFrag;case l.ClientCallback:return l.ClientCallbackFrag;default:return n}}function I(n){return n<=15||n===l.LoadBundle||n===l.LoadBundleFrag||n===l.UpdateReliable||n===l.UpdateReliableFrag||n===l.InputReliable||n===l.InputReliableFrag||n>=80}var B=(a=>(a[a.OK=0]="OK",a[a.VersionMismatch=1]="VersionMismatch",a[a.ServerFull=2]="ServerFull",a[a.AuthFailed=3]="AuthFailed",a))(B||{}),O=(o=>(o[o.Connected=0]="Connected",o[o.WaitingForResponse=1]="WaitingForResponse",o[o.Authenticating=2]="Authenticating",o[o.LoadingAssets=3]="LoadingAssets",o[o.Ready=4]="Ready",o[o.InSimulation=5]="InSimulation",o[o.Disconnected=255]="Disconnected",o))(O||{});var y=class n{high;low;constructor(t,e){this.high=t>>>0,this.low=e>>>0}static ZERO=new n(0,0);static from(t){let e=Number(t>>32n&0xffffffffn),i=Number(t&0xffffffffn);return new n(e,i)}static fromNumber(t){if(t<0)throw new Error("Tick must be positive");let e=Math.floor(t/4294967296),i=t>>>0;return new n(e,i)}static fromBuffer(t,e=0){let i=(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0,a=(t[e+4]<<24|t[e+5]<<16|t[e+6]<<8|t[e+7])>>>0;return new n(i,a)}toBigInt(){return BigInt(this.high)<<32n|BigInt(this.low)}toNumber(){return this.high*4294967296+this.low}toBuffer(){let t=new Uint8Array(8);return this.writeToBuffer(t,0),t}writeToBuffer(t,e=0){t[e]=this.high>>>24&255,t[e+1]=this.high>>>16&255,t[e+2]=this.high>>>8&255,t[e+3]=this.high&255,t[e+4]=this.low>>>24&255,t[e+5]=this.low>>>16&255,t[e+6]=this.low>>>8&255,t[e+7]=this.low&255}increment(){let t=this.low+1,e=this.high;return t>4294967295&&(t=0,e++),new n(e,t)}compare(t){return this.high!==t.high?this.high-t.high:this.low-t.low}equals(t){return this.high===t.high&&this.low===t.low}isZero(){return this.high===0&&this.low===0}toString(){return`Tick(${this.toBigInt()})`}getHigh(){return this.high}getLow(){return this.low}};function $(n){let e=n.fragInfo!==void 0?13:9,i=new Uint8Array(e);return L(n,i,0),i}function L(n,t,e){let i=n.fragInfo!==void 0;return t[e]=n.marker,i&&n.fragInfo?(t[e+1]=n.fragInfo.totalChunks>>>8&255,t[e+2]=n.fragInfo.totalChunks&255,t[e+3]=n.fragInfo.chunkIndex>>>8&255,t[e+4]=n.fragInfo.chunkIndex&255,n.tick.writeToBuffer(t,e+5),13):(n.tick.writeToBuffer(t,e+1),9)}function A(n){if(n.length<9)throw new Error(`Buffer too small for header: ${n.length} < ${9}`);let t=n[0];if(f(t)){if(n.length<13)throw new Error(`Buffer too small for frag header: ${n.length} < ${13}`);let a=n[1]<<8|n[2],r=n[3]<<8|n[4],s=y.fromBuffer(n,5);return{header:{marker:t,tick:s,fragInfo:{totalChunks:a,chunkIndex:r}},payloadOffset:13}}let i=y.fromBuffer(n,1);return{header:{marker:t,tick:i},payloadOffset:9}}function T(n,t){let i=n.fragInfo!==void 0?13:9,a=t?t.length:0,r=new Uint8Array(i+a);return L(n,r,0),a>0&&r.set(t,i),r}function V(n){let{header:t,payloadOffset:e}=A(n),i=n.slice(e);return{header:t,payload:i}}function U(n,t,e,i){let a=i?.mtu??1200,r=a-13;if(e.length+9<=a)return[T({marker:n,tick:t},e)];let s=v(n);if(s===n)throw new Error(`Packet with marker 0x${n.toString(16)} exceeds MTU (${a}) but has no fragmentation variant.`);let o=Math.ceil(e.length/r),c=[];for(let d=0;d<o;d++){let g=d*r,b=Math.min(g+r,e.length),Q=e.subarray(g,b),W={marker:s,tick:t,fragInfo:{totalChunks:o,chunkIndex:d}};c.push(T(W,Q))}return c}function H(n,t=1200){if(n+9<=t)return 1;let e=t-13;return Math.ceil(n/e)}function N(n,t=1200){return n+9>t}function K(n,t){return`${n}:${t.getHigh()}:${t.getLow()}`}var w=class{buckets=new Map;ttlMs;maxPendingBuckets;maxTotalChunks;lastRejection=null;constructor(t){this.ttlMs=t?.ttlMs??1e4,this.maxPendingBuckets=t?.maxPendingBuckets??0,this.maxTotalChunks=t?.maxTotalChunks??0}receive(t){this.lastRejection=null;let{header:e,payloadOffset:i}=A(t),a=t.subarray(i);return!f(e.marker)||!e.fragInfo?{marker:e.marker,tick:e.tick,payload:a}:this.handleFragment(e,a)}handleFragment(t,e){let{marker:i,tick:a,fragInfo:r}=t;if(!r)return null;let s=K(i,a),o=this.buckets.get(s);if(!o){if(this.maxTotalChunks>0&&r.totalChunks>this.maxTotalChunks)return this.lastRejection=`Fragment totalChunks (${r.totalChunks}) exceeds limit (${this.maxTotalChunks})`,null;if(this.maxPendingBuckets>0&&this.buckets.size>=this.maxPendingBuckets)return this.lastRejection=`Pending transfers (${this.buckets.size}) reached limit (${this.maxPendingBuckets})`,null;o={marker:i,tick:a,totalChunks:r.totalChunks,receivedCount:0,chunks:new Array(r.totalChunks).fill(null),createdAt:Date.now()},this.buckets.set(s,o)}if(r.chunkIndex>=o.totalChunks)return null;if(o.chunks[r.chunkIndex]===null&&(o.chunks[r.chunkIndex]=e,o.receivedCount++),o.receivedCount===o.totalChunks){let c=0;for(let b=0;b<o.chunks.length;b++)o.chunks[b]&&(c+=o.chunks[b].length);let d=new Uint8Array(c),g=0;for(let b of o.chunks)b&&(d.set(b,g),g+=b.length);return this.buckets.delete(s),{marker:i,tick:a,payload:d}}return null}cleanup(){let t=Date.now(),e=0;for(let[i,a]of this.buckets)t-a.createdAt>this.ttlMs&&(this.buckets.delete(i),e++);return e}getPendingCount(){return this.buckets.size}clearTick(t){for(let[e,i]of this.buckets)i.tick.equals(t)&&this.buckets.delete(e)}destroy(){this.buckets.clear()}};var R=class{transport;backgroundQueue=[];immediateQueue=[];bgCursor=0;imCursor=0;options;constructor(t,e={}){this.transport=t,this.options={fragmentsPerTick:e.fragmentsPerTick??5,bufferedThreshold:e.bufferedThreshold??16384,maxBackgroundQueue:e.maxBackgroundQueue??4096}}enqueue(t,e,i){let a=I(t),r=U(t,e,i);for(let s of r)this.backgroundQueue.push({data:s,reliable:a});this.enforceBackgroundLimit()}enqueueImmediate(t,e,i){let a=I(t),r=U(t,e,i);for(let s of r)this.immediateQueue.push({data:s,reliable:a})}enqueueRawImmediate(t,e){this.immediateQueue.push({data:t,reliable:e})}flush(){if(!this.transport.isReady())return;for(;this.imCursor<this.immediateQueue.length;){let i=this.immediateQueue[this.imCursor++];this.transport.send(i.data,i.reliable)}this.imCursor>0&&(this.immediateQueue.length=0,this.imCursor=0);let t=0,e=this.options.fragmentsPerTick;for(;this.bgCursor<this.backgroundQueue.length&&t<e&&this.transport.getBufferedAmount()<this.options.bufferedThreshold;){let i=this.backgroundQueue[this.bgCursor++];this.transport.send(i.data,i.reliable),t++}this.bgCursor>0&&this.bgCursor>=this.backgroundQueue.length?(this.backgroundQueue.length=0,this.bgCursor=0):this.bgCursor>256&&(this.backgroundQueue.splice(0,this.bgCursor),this.bgCursor=0)}clear(){this.backgroundQueue.length=0,this.immediateQueue.length=0,this.bgCursor=0,this.imCursor=0}enforceBackgroundLimit(){let t=this.backgroundQueue.length-this.bgCursor;if(this.options.maxBackgroundQueue>0&&t>this.options.maxBackgroundQueue){let e=t-this.options.maxBackgroundQueue;this.bgCursor+=e}}getPendingCount(){return this.backgroundQueue.length-this.bgCursor}hasImmediatePending(){return this.imCursor<this.immediateQueue.length}};var m={AudioAck:1,MacroFeedback:2},P=1,E=2,S=3,D=4,_=5,k=new TextEncoder,x=new TextDecoder;function Z(n){let t=[];if(n.audioAcks.length>0&&t.push({type:m.AudioAck,payload:z(n.audioAcks)}),n.macroFeedbacks.length>0&&t.push({type:m.MacroFeedback,payload:j(n.macroFeedbacks)}),t.length===0)return new Uint8Array(0);let e=1;for(let r of t)e+=2+r.payload.byteLength;let i=new Uint8Array(e),a=0;i[a++]=t.length;for(let r of t)i[a++]=r.type,r.type===m.AudioAck?i[a++]=n.audioAcks.length:r.type===m.MacroFeedback?i[a++]=n.macroFeedbacks.length:i[a++]=0,i.set(r.payload,a),a+=r.payload.byteLength;return i}function z(n){let t=0,e=[];for(let s of n)switch(s.type){case"sound-loaded":{let o=k.encode(s.name);e.push({name:o}),t+=4+o.byteLength;break}case"sound-error":{let o=k.encode(s.name),c=k.encode(s.error);e.push({name:o,error:c}),t+=4+o.byteLength+1+c.byteLength;break}case"playback-started":e.push({}),t+=7;break;case"playback-ended":e.push({}),t+=7;break;case"playback-error":{let o=k.encode(s.error);e.push({error:o}),t+=2+(s.instanceId!=null?4:0)+2+1+o.byteLength;break}}let i=new Uint8Array(t),a=new DataView(i.buffer),r=0;for(let s=0;s<n.length;s++){let o=n[s],c=e[s];switch(o.type){case"sound-loaded":i[r++]=P,a.setUint16(r,o.soundId,!1),r+=2,i[r++]=c.name.byteLength,i.set(c.name,r),r+=c.name.byteLength;break;case"sound-error":i[r++]=E,a.setUint16(r,o.soundId,!1),r+=2,i[r++]=c.name.byteLength,i.set(c.name,r),r+=c.name.byteLength,i[r++]=c.error.byteLength,i.set(c.error,r),r+=c.error.byteLength;break;case"playback-started":i[r++]=S,a.setUint32(r,o.instanceId,!1),r+=4,a.setUint16(r,o.soundId,!1),r+=2;break;case"playback-ended":i[r++]=D,a.setUint32(r,o.instanceId,!1),r+=4,a.setUint16(r,o.soundId,!1),r+=2;break;case"playback-error":{i[r++]=_;let d=o.instanceId!=null?1:0;i[r++]=d,d&&(a.setUint32(r,o.instanceId,!1),r+=4);let g=typeof o.sound=="number"?o.sound:0;a.setUint16(r,g,!1),r+=2,i[r++]=c.error.byteLength,i.set(c.error,r),r+=c.error.byteLength;break}}}return i}function j(n){let t=0,e=[];for(let s of n)switch(t+=3,s.cmd){case 1:e.push(null);break;case 2:e.push(null),t+=1+(s.valueType==="number"?2:1);break;case 3:{let o=k.encode(s.text);e.push(o),t+=2+o.byteLength;break}case 4:e.push(null),t+=2;break;case 5:{let o=k.encode(s.data);e.push(o),t+=2+o.byteLength;break}}let i=new Uint8Array(t),a=new DataView(i.buffer),r=0;for(let s=0;s<n.length;s++){let o=n[s];switch(i[r++]=o.cmd,a.setUint16(r,o.instanceId,!1),r+=2,o.cmd){case 1:break;case 2:o.valueType==="number"?(i[r++]=0,a.setUint16(r,o.value,!1),r+=2):(i[r++]=1,i[r++]=o.value?1:0);break;case 3:{let c=e[s];a.setUint16(r,c.byteLength,!1),r+=2,i.set(c,r),r+=c.byteLength;break}case 4:a.setUint16(r,o.index,!1),r+=2;break;case 5:{let c=e[s];a.setUint16(r,c.byteLength,!1),r+=2,i.set(c,r),r+=c.byteLength;break}}}return i}function u(n,t,e){if(t+e>n.byteLength)throw new RangeError(`ClientCallback: truncated payload \u2014 need ${e} bytes at offset ${t}, but only ${n.byteLength-t} remain (total ${n.byteLength})`)}function q(n){let t={audioAcks:[],macroFeedbacks:[]};if(n.byteLength===0)return t;let e=new DataView(n.buffer,n.byteOffset,n.byteLength),i=0;u(n,i,1);let a=n[i++];for(let r=0;r<a;r++){u(n,i,2);let s=n[i++],o=n[i++];switch(s){case m.AudioAck:for(let c=0;c<o;c++){let{ack:d,newOffset:g}=G(n,e,i);t.audioAcks.push(d),i=g}break;case m.MacroFeedback:for(let c=0;c<o;c++){let{feedback:d,newOffset:g}=Y(n,e,i);t.macroFeedbacks.push(d),i=g}break;default:return t}}return t}function G(n,t,e){u(n,e,1);let i=n[e++];switch(i){case P:{u(n,e,3);let a=t.getUint16(e,!1);e+=2;let r=n[e++];u(n,e,r);let s=x.decode(n.subarray(e,e+r));return e+=r,{ack:{type:"sound-loaded",soundId:a,name:s},newOffset:e}}case E:{u(n,e,3);let a=t.getUint16(e,!1);e+=2;let r=n[e++];u(n,e,r);let s=x.decode(n.subarray(e,e+r));e+=r,u(n,e,1);let o=n[e++];u(n,e,o);let c=x.decode(n.subarray(e,e+o));return e+=o,{ack:{type:"sound-error",soundId:a,name:s,error:c},newOffset:e}}case S:{u(n,e,6);let a=t.getUint32(e,!1);e+=4;let r=t.getUint16(e,!1);return e+=2,{ack:{type:"playback-started",instanceId:a,soundId:r},newOffset:e}}case D:{u(n,e,6);let a=t.getUint32(e,!1);e+=4;let r=t.getUint16(e,!1);return e+=2,{ack:{type:"playback-ended",instanceId:a,soundId:r},newOffset:e}}case _:{u(n,e,1);let a=n[e++];a&&u(n,e,4);let r=a?t.getUint32(e,!1):void 0;a&&(e+=4),u(n,e,3);let s=t.getUint16(e,!1);e+=2;let o=n[e++];u(n,e,o);let c=x.decode(n.subarray(e,e+o));return e+=o,{ack:{type:"playback-error",instanceId:r,sound:s,error:c},newOffset:e}}default:throw new Error(`Unknown AudioAck sub-type: 0x${i.toString(16)}`)}}function Y(n,t,e){u(n,e,3);let i=n[e++],a=t.getUint16(e,!1);switch(e+=2,i){case 1:return{feedback:{cmd:1,instanceId:a},newOffset:e};case 2:{u(n,e,1);let r=n[e++]===0?"number":"boolean",s;return r==="number"?(u(n,e,2),s=t.getUint16(e,!1),e+=2):(u(n,e,1),s=n[e++]!==0),{feedback:{cmd:2,instanceId:a,valueType:r,value:s},newOffset:e}}case 3:{u(n,e,2);let r=t.getUint16(e,!1);e+=2,u(n,e,r);let s=x.decode(n.subarray(e,e+r));return e+=r,{feedback:{cmd:3,instanceId:a,text:s},newOffset:e}}case 4:{u(n,e,2);let r=t.getUint16(e,!1);return e+=2,{feedback:{cmd:4,instanceId:a,index:r},newOffset:e}}case 5:{u(n,e,2);let r=t.getUint16(e,!1);e+=2,u(n,e,r);let s=x.decode(n.subarray(e,e+r));return e+=r,{feedback:{cmd:5,instanceId:a,data:s},newOffset:e}}default:throw new Error(`Unknown MacroFeedback cmd: 0x${i.toString(16)}`)}}var F=(a=>(a[a.Connecting=0]="Connecting",a[a.Open=1]="Open",a[a.Closing=2]="Closing",a[a.Closed=3]="Closed",a))(F||{});var M=class{onMessage=null;onInputMessage=null;onStateChange=null;onError=null;send(t,e){this.onMessage?.(t)}sendInput(t,e){this.onInputMessage?.(t)}getState(){return 1}getBufferedAmount(){return 0}isReady(){return!0}close(t,e){}};var J="reliable",X="unreliable";export{m as CallbackSectionType,J as DC_RELIABLE,X as DC_UNRELIABLE,w as FragmentAssembler,p as HEADER_SIZE_FRAG,h as HEADER_SIZE_SINGLE,O as HandshakeState,B as HandshakeStatus,R as InterleavingManager,M as LoopbackTransport,C as MTU,l as Marker,y as Tick,F as TransportState,H as calculateFragmentCount,T as createPacket,q as decodeClientCallback,A as decodeHeader,Z as encodeClientCallback,$ as encodeHeader,V as extractPayload,U as fragmentPacket,f as isFragMarker,I as isReliableMarker,v as toFragMarker,N as willFragment};
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@primitiv/network-common",
|
|
3
|
+
"version": "0.19.0",
|
|
4
|
+
"description": "Primitiv network common module",
|
|
5
|
+
"author": "THP Software",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/thp-software/primitiv",
|
|
9
|
+
"directory": "packages/network-common"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://primitivengine.com",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/thp-software/primitiv/issues"
|
|
14
|
+
},
|
|
15
|
+
"license": "Apache-2.0",
|
|
16
|
+
"type": "module",
|
|
17
|
+
"main": "./dist/index.cjs",
|
|
18
|
+
"module": "./dist/index.mjs",
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"import": "./dist/index.mjs",
|
|
24
|
+
"require": "./dist/index.cjs"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18.0.0"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"README.md",
|
|
33
|
+
"LICENSE.txt"
|
|
34
|
+
],
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@primitiv/types": "0.19.0"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"typescript": "^5.6.3"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "rimraf dist && node ../../scripts/build-package.mjs packages/network-common",
|
|
46
|
+
"dev": "tsc --watch",
|
|
47
|
+
"clean": "rimraf dist",
|
|
48
|
+
"lint": "eslint \"src/**/*.ts\" --max-warnings 0",
|
|
49
|
+
"typecheck": "tsc --noEmit",
|
|
50
|
+
"test": "node --test --import tsx src/**/*.test.ts"
|
|
51
|
+
}
|
|
52
|
+
}
|