sfml.js 1.0.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (313) hide show
  1. package/README.ja.md +10 -9
  2. package/README.ko.md +10 -9
  3. package/README.md +10 -9
  4. package/README.zh-CN.md +10 -9
  5. package/binding.gyp +23 -16
  6. package/dist/audio/effect-processor.js +9 -3
  7. package/dist/audio/input-sound-file.js +41 -15
  8. package/dist/audio/listener.js +33 -11
  9. package/dist/audio/music.js +41 -18
  10. package/dist/audio/output-sound-file.js +4 -2
  11. package/dist/audio/playback-device.js +11 -3
  12. package/dist/audio/sound-buffer-recorder.js +8 -5
  13. package/dist/audio/sound-buffer.js +40 -17
  14. package/dist/audio/sound-file-factory.js +21 -9
  15. package/dist/audio/sound-file-reader.js +21 -7
  16. package/dist/audio/sound-recorder.js +36 -15
  17. package/dist/audio/sound-source.js +117 -40
  18. package/dist/audio/sound-stream.js +14 -5
  19. package/dist/audio/sound.js +9 -4
  20. package/dist/audio/value.js +42 -16
  21. package/dist/graphics/blend-mode.js +2 -1
  22. package/dist/graphics/boolean-vector.d.ts +1 -2
  23. package/dist/graphics/boolean-vector.js +19 -9
  24. package/dist/graphics/color.js +2 -1
  25. package/dist/graphics/convex-shape.js +7 -3
  26. package/dist/graphics/font.js +52 -23
  27. package/dist/graphics/glsl-matrix.js +8 -3
  28. package/dist/graphics/glsl.js +47 -16
  29. package/dist/graphics/glyph.js +27 -10
  30. package/dist/graphics/image.js +30 -14
  31. package/dist/graphics/rect.js +15 -8
  32. package/dist/graphics/render-states.js +18 -9
  33. package/dist/graphics/render-target.js +49 -23
  34. package/dist/graphics/render-texture.js +24 -12
  35. package/dist/graphics/render-window.js +6 -3
  36. package/dist/graphics/shader.js +67 -32
  37. package/dist/graphics/shape.js +25 -13
  38. package/dist/graphics/sprite.js +19 -9
  39. package/dist/graphics/stencil-mode.js +10 -6
  40. package/dist/graphics/swap.js +2 -1
  41. package/dist/graphics/text.js +123 -48
  42. package/dist/graphics/texture.js +48 -24
  43. package/dist/graphics/transform.js +29 -13
  44. package/dist/graphics/transformable.js +2 -1
  45. package/dist/graphics/vertex-array.js +40 -18
  46. package/dist/graphics/vertex-buffer.js +39 -19
  47. package/dist/graphics/vertex.js +6 -3
  48. package/dist/graphics/view.js +30 -14
  49. package/dist/index.d.ts +4 -4
  50. package/dist/internal/audio-codec-registry.js +12 -6
  51. package/dist/internal/audio-input-stream.js +2 -1
  52. package/dist/internal/audio-music-pump.js +58 -24
  53. package/dist/internal/audio-recorder-session.js +17 -7
  54. package/dist/internal/audio-worker-session.js +28 -10
  55. package/dist/internal/audio-worker.js +40 -21
  56. package/dist/internal/glsl-value.d.ts +3 -1
  57. package/dist/internal/glsl-value.js +18 -8
  58. package/dist/internal/graphics-state.js +29 -15
  59. package/dist/internal/input-stream.d.ts +3 -1
  60. package/dist/internal/input-stream.js +16 -7
  61. package/dist/internal/numeric-properties.js +2 -1
  62. package/dist/internal/render-states.js +2 -1
  63. package/dist/internal/scalar.js +22 -13
  64. package/dist/internal/shaped-glyph.d.ts +3 -1
  65. package/dist/internal/shaped-glyph.js +12 -4
  66. package/dist/internal/struct-view.d.ts +3 -1
  67. package/dist/internal/struct-view.js +3 -1
  68. package/dist/internal/transformable.js +2 -1
  69. package/dist/network/common.js +23 -11
  70. package/dist/network/dns.js +25 -17
  71. package/dist/network/ftp.js +43 -18
  72. package/dist/network/http.js +126 -56
  73. package/dist/network/ip-address.js +50 -25
  74. package/dist/network/packet.js +63 -25
  75. package/dist/network/sftp.js +175 -74
  76. package/dist/network/socket-selector.js +28 -14
  77. package/dist/network/socket.js +71 -30
  78. package/dist/network/tcp-listener.js +42 -19
  79. package/dist/network/tcp-socket.js +111 -53
  80. package/dist/network/tls-material.js +2 -1
  81. package/dist/network/udp-socket.js +68 -33
  82. package/dist/system/angle.js +2 -1
  83. package/dist/system/clock.js +4 -2
  84. package/dist/system/err.js +5 -2
  85. package/dist/system/file-input-stream.js +8 -4
  86. package/dist/system/input-stream.js +6 -3
  87. package/dist/system/operators.d.ts +1 -1
  88. package/dist/system/operators.js +90 -50
  89. package/dist/system/sleep.js +4 -2
  90. package/dist/system/time.js +12 -6
  91. package/dist/system/vector2.js +6 -7
  92. package/dist/system/vector3.js +11 -6
  93. package/dist/window/clipboard.js +2 -1
  94. package/dist/window/context.js +10 -5
  95. package/dist/window/cursor.js +2 -1
  96. package/dist/window/event.js +9 -5
  97. package/dist/window/mouse.js +4 -2
  98. package/dist/window/video-mode.js +2 -1
  99. package/dist/window/window.js +19 -12
  100. package/native/addon.cc +25 -12
  101. package/native/audio-binding.cc +266 -126
  102. package/native/audio-codec-binding.cc +147 -77
  103. package/native/audio-device-binding.cc +76 -49
  104. package/native/audio-file-binding.cc +116 -67
  105. package/native/audio-recorder-binding.cc +147 -98
  106. package/native/audio-recorder.h +1 -1
  107. package/native/audio-state.h +53 -30
  108. package/native/audio-stream-binding.cc +148 -94
  109. package/native/audio-stream.h +5 -4
  110. package/native/audio-worker-binding.cc +163 -81
  111. package/native/audio-worker.h +35 -19
  112. package/native/batch-drawable.cc +29 -16
  113. package/native/batch-drawable.h +11 -8
  114. package/native/context-binding.cc +40 -27
  115. package/native/context-settings.h +15 -8
  116. package/native/deferred-delete.cc +9 -6
  117. package/native/deferred-delete.h +7 -8
  118. package/native/error-stream-binding.cc +42 -28
  119. package/native/font-binding.cc +89 -48
  120. package/native/graphics-binding.cc +122 -72
  121. package/native/graphics-state.h +50 -36
  122. package/native/image-binding.cc +38 -24
  123. package/native/image-state.h +26 -18
  124. package/native/input-binding.cc +42 -27
  125. package/native/render-window-binding.cc +38 -23
  126. package/native/shader-binding.cc +115 -50
  127. package/native/shape-binding.cc +94 -49
  128. package/native/shape-state.h +18 -9
  129. package/native/shaped-glyph-storage.h +9 -5
  130. package/native/stream-binding.cc +143 -117
  131. package/native/system-binding.cc +17 -12
  132. package/native/text-binding.cc +68 -35
  133. package/native/text-state.h +25 -18
  134. package/native/texture-binding.cc +42 -33
  135. package/native/texture-resource.h +20 -12
  136. package/native/time-value.h +3 -1
  137. package/native/transformable-binding.cc +12 -6
  138. package/native/transformable-state.h +6 -6
  139. package/native/value-binding.h +46 -28
  140. package/native/value-layout.h +10 -10
  141. package/native/values-binding.cc +29 -23
  142. package/native/vertex-binding.cc +18 -12
  143. package/native/vertex-buffer-binding.cc +38 -24
  144. package/native/vertex-storage.h +2 -2
  145. package/native/view-data.h +4 -3
  146. package/native/window-binding.cc +75 -45
  147. package/native/window-event.h +20 -11
  148. package/native/window-owner.h +15 -12
  149. package/package.json +44 -51
  150. package/src/audio/effect-processor.ts +9 -3
  151. package/src/audio/input-sound-file.ts +108 -36
  152. package/src/audio/listener.ts +39 -13
  153. package/src/audio/music.ts +112 -47
  154. package/src/audio/output-sound-file.ts +40 -11
  155. package/src/audio/playback-device.ts +23 -8
  156. package/src/audio/sound-buffer-recorder.ts +35 -13
  157. package/src/audio/sound-buffer.ts +166 -58
  158. package/src/audio/sound-file-factory.ts +127 -49
  159. package/src/audio/sound-file-reader.ts +49 -15
  160. package/src/audio/sound-recorder.ts +100 -34
  161. package/src/audio/sound-source.ts +142 -45
  162. package/src/audio/sound-stream.ts +15 -5
  163. package/src/audio/sound.ts +12 -4
  164. package/src/audio/value.ts +89 -26
  165. package/src/graphics/blend-mode.ts +3 -1
  166. package/src/graphics/boolean-vector.ts +56 -26
  167. package/src/graphics/color.ts +3 -1
  168. package/src/graphics/convex-shape.ts +10 -3
  169. package/src/graphics/font.ts +171 -50
  170. package/src/graphics/glsl-matrix.ts +9 -3
  171. package/src/graphics/glsl.ts +81 -35
  172. package/src/graphics/glyph.ts +67 -26
  173. package/src/graphics/image.ts +119 -45
  174. package/src/graphics/rect.ts +56 -24
  175. package/src/graphics/render-states.ts +31 -14
  176. package/src/graphics/render-target.ts +197 -81
  177. package/src/graphics/render-texture.ts +36 -12
  178. package/src/graphics/render-window.ts +9 -3
  179. package/src/graphics/shader.ts +186 -61
  180. package/src/graphics/shape.ts +93 -35
  181. package/src/graphics/sprite.ts +64 -25
  182. package/src/graphics/stencil-mode.ts +12 -6
  183. package/src/graphics/swap.ts +3 -2
  184. package/src/graphics/text.ts +229 -74
  185. package/src/graphics/texture.ts +180 -61
  186. package/src/graphics/transform.ts +132 -47
  187. package/src/graphics/transformable.ts +3 -1
  188. package/src/graphics/vertex-array.ts +87 -35
  189. package/src/graphics/vertex-buffer.ts +97 -33
  190. package/src/graphics/vertex.ts +9 -3
  191. package/src/graphics/view.ts +59 -21
  192. package/src/index.ts +101 -23
  193. package/src/internal/audio-codec-registry.ts +18 -6
  194. package/src/internal/audio-input-stream.ts +6 -2
  195. package/src/internal/audio-music-pump.ts +116 -41
  196. package/src/internal/audio-native.ts +249 -96
  197. package/src/internal/audio-recorder-session.ts +68 -24
  198. package/src/internal/audio-worker-session.ts +65 -21
  199. package/src/internal/audio-worker.ts +85 -41
  200. package/src/internal/glsl-value.ts +26 -11
  201. package/src/internal/graphics-state.ts +57 -20
  202. package/src/internal/input-stream.ts +23 -10
  203. package/src/internal/native.ts +252 -99
  204. package/src/internal/numeric-properties.ts +2 -1
  205. package/src/internal/render-states.ts +3 -1
  206. package/src/internal/scalar.ts +33 -14
  207. package/src/internal/shaped-glyph.ts +25 -12
  208. package/src/internal/struct-view.ts +40 -13
  209. package/src/internal/transformable.ts +3 -1
  210. package/src/network/common.ts +35 -11
  211. package/src/network/dns.ts +95 -38
  212. package/src/network/ftp.ts +129 -47
  213. package/src/network/http.ts +232 -77
  214. package/src/network/ip-address.ts +118 -48
  215. package/src/network/packet.ts +161 -54
  216. package/src/network/sftp.ts +498 -168
  217. package/src/network/socket-selector.ts +66 -26
  218. package/src/network/socket.ts +133 -46
  219. package/src/network/tcp-listener.ts +78 -29
  220. package/src/network/tcp-socket.ts +240 -95
  221. package/src/network/tls-material.ts +6 -2
  222. package/src/network/udp-socket.ts +147 -53
  223. package/src/system/angle.ts +3 -1
  224. package/src/system/clock.ts +12 -4
  225. package/src/system/err.ts +5 -2
  226. package/src/system/file-input-stream.ts +12 -4
  227. package/src/system/input-stream.ts +9 -3
  228. package/src/system/operators.ts +290 -115
  229. package/src/system/sleep.ts +6 -2
  230. package/src/system/time.ts +18 -6
  231. package/src/system/timeout-with-predicate.ts +19 -8
  232. package/src/system/vector2.ts +101 -49
  233. package/src/system/vector3.ts +85 -36
  234. package/src/window/clipboard.ts +3 -1
  235. package/src/window/context.ts +15 -5
  236. package/src/window/cursor.ts +3 -1
  237. package/src/window/event.ts +26 -12
  238. package/src/window/mouse.ts +6 -2
  239. package/src/window/video-mode.ts +3 -1
  240. package/src/window/window.ts +119 -37
  241. package/test/native/audio-probes.cc +74 -36
  242. package/test/native/deferred-delete-probes.cc +17 -11
  243. package/test/native/drawable-probes.cc +70 -36
  244. package/test/native/exception-probes.cc +14 -9
  245. package/test/native/image-probes.cc +20 -10
  246. package/test/native/matrix-probes.cc +8 -4
  247. package/test/native/network-oracle.cc +17 -11
  248. package/test/native/render-texture-probes.cc +33 -24
  249. package/test/native/shader-probes.cc +9 -9
  250. package/test/native/shape-probes.cc +37 -23
  251. package/test/native/sprite-probes.cc +41 -25
  252. package/test/native/system-probes.cc +58 -35
  253. package/test/native/text-probes.cc +77 -44
  254. package/test/native/texture-probes.cc +43 -26
  255. package/test/native/time-probes.cc +18 -12
  256. package/test/native/transform-probes.cc +15 -10
  257. package/test/native/transformable-probes.cc +23 -17
  258. package/test/native/value-oracle.h +9 -4
  259. package/test/native/value-probes.cc +31 -23
  260. package/test/native/vertex-array-probes.cc +22 -14
  261. package/test/native/vertex-buffer-probes.cc +28 -17
  262. package/test/native/view-probes.cc +29 -17
  263. package/test/native/window-probes.cc +66 -33
  264. package/tools/ensure-sfml.cjs +9 -0
  265. package/tools/generate-network-constants.cjs +11 -6
  266. package/tools/generate-window-constants.cjs +31 -12
  267. package/docs/README.ja.md +0 -30
  268. package/docs/README.ko.md +0 -30
  269. package/docs/README.md +0 -30
  270. package/docs/README.zh-CN.md +0 -30
  271. package/docs/api.ja.md +0 -84
  272. package/docs/api.ko.md +0 -84
  273. package/docs/api.md +0 -81
  274. package/docs/api.zh-CN.md +0 -81
  275. package/docs/audio.ja.md +0 -249
  276. package/docs/audio.ko.md +0 -251
  277. package/docs/audio.md +0 -252
  278. package/docs/audio.zh-CN.md +0 -252
  279. package/docs/concepts.ja.md +0 -130
  280. package/docs/concepts.ko.md +0 -130
  281. package/docs/concepts.md +0 -131
  282. package/docs/concepts.zh-CN.md +0 -131
  283. package/docs/development.ja.md +0 -144
  284. package/docs/development.ko.md +0 -144
  285. package/docs/development.md +0 -146
  286. package/docs/development.zh-CN.md +0 -146
  287. package/docs/getting-started.ja.md +0 -154
  288. package/docs/getting-started.ko.md +0 -154
  289. package/docs/getting-started.md +0 -156
  290. package/docs/getting-started.zh-CN.md +0 -156
  291. package/docs/graphics.ja.md +0 -256
  292. package/docs/graphics.ko.md +0 -254
  293. package/docs/graphics.md +0 -255
  294. package/docs/graphics.zh-CN.md +0 -257
  295. package/docs/network.ja.md +0 -214
  296. package/docs/network.ko.md +0 -216
  297. package/docs/network.md +0 -218
  298. package/docs/network.zh-CN.md +0 -218
  299. package/docs/system.ja.md +0 -169
  300. package/docs/system.ko.md +0 -171
  301. package/docs/system.md +0 -173
  302. package/docs/system.zh-CN.md +0 -173
  303. package/docs/window.ja.md +0 -138
  304. package/docs/window.ko.md +0 -140
  305. package/docs/window.md +0 -141
  306. package/docs/window.zh-CN.md +0 -141
  307. package/native/exception-boundary.h +0 -97
  308. package/native/numeric-fields.h +0 -96
  309. package/native/shared-handle.h +0 -107
  310. package/test/tsconfig.json +0 -8
  311. package/tools/configure-lsp.cjs +0 -23
  312. package/tools/lib_downloader.cjs +0 -92
  313. package/tools/lib_downloader_urls.cjs +0 -23
@@ -1,216 +0,0 @@
1
- # Network
2
-
3
- [English](network.md) / [简体中文](network.zh-CN.md) / [日本語](network.ja.md) / **한국어**
4
-
5
- > Packet으로 메시지를 정의하고 TCP/UDP로 전송하거나, HTTP, FTP, SFTP로 프로토콜 작업을 수행합니다. 네트워크 I/O는 Promise를 반환하며, 호출자는 작업 상태도 확인해야 합니다.
6
-
7
- [API 안내](api.ko.md) · [핵심 개념](concepts.ko.md) · [루프백 예제](../examples/network.cjs)
8
-
9
- 실제 Network 구현은 Node.js 전송 계층으로 SFML 스타일 인터페이스를 제공합니다. FTP는 basic-ftp, SFTP는 ssh2, IPv6 파싱은 ipaddr.js를 사용합니다. SFML C++ 네트워크 모듈을 호출하지 않으며, Packet 형식과 일부 값의 의미는 독립적인 C++ 프로그램으로 대조합니다.
10
-
11
- ## 인터페이스와 호출 방식
12
-
13
- | 인터페이스 | 구현 및 조정 |
14
- |------|------------|
15
- | IpAddress | IPv4 정수/4바이트 생성, IPv6 16바이트 생성, 복사, fromString, toString, toInteger, toBytes, getType, isV4/isV6. 정적 resolve, getLocalAddress, getPublicAddress는 Promise 반환 |
16
- | Dns | resolve, queryNs, queryMx, querySrv, queryTxt, getPublicAddress. 독립 Resolver와 서버 지정 지원 |
17
- | Socket | setBlocking, isBlocking, AnyPort, Status. getLastError는 가장 최근의 하위 계층 오류 반환 |
18
- | TcpSocket | connect, disconnect, send, receive, 포트/원격 주소 조회; setupTlsClient, setupTlsServer, getCurrentCiphersuiteName |
19
- | TcpListener | listen, close, accept, getLocalPort |
20
- | UdpSocket | bind, unbind, send, receive, getLocalPort, MaxDatagramSize |
21
- | SocketSelector | add, remove, clear, wait, isReady, dispatchReadyCallbacks, 복사 생성자, assign; Receive/Send 비트 플래그 |
22
- | Packet | append, clear, getData, getDataSize, getReadPosition, endOfPacket, isValid, 복사 생성자; 타입이 명확한 write/read; onSend/onReceive 재정의 가능 |
23
- | Http | setHost, sendRequest, Request, Response; 명시적인 HTTP 요청 버전 |
24
- | Ftp | connect, disconnect, login, keepAlive, 작업 디렉터리, 디렉터리 목록, 디렉터리 이동/생성/삭제, 파일 이름 변경/삭제, 업로드/이어 쓰기/다운로드, sendCommand |
25
- | Sftp | connect와 login 분리, 비밀번호/키 인증, getSessionInfo, 경로 해석, 디렉터리 및 속성, 이름 변경/삭제, 스트리밍 업로드와 다운로드, TimeoutWithPredicate |
26
-
27
- I/O나 대기가 있는 메서드는 Promise를 반환하고, 단순 상태 조회와 설정은 동기식입니다. TcpSocket의 `disconnect()`, listener.close, udp.unbind는 로컬 전송을 동기식으로 종료합니다. FTP/SFTP의 disconnect는 Promise를 반환하며, 진행 중인 작업을 중단하는 동기식 close도 제공합니다.
28
-
29
- C++ 출력 참조는 반환 객체로 표현합니다.
30
-
31
- | 작업 | 반환값 |
32
- |------|--------|
33
- | TCP send(Uint8Array) | `{ status, sent }` |
34
- | TCP receive(Uint8Array) | `{ status, received }` |
35
- | TCP send/receive(Packet) | `SocketStatus` |
36
- | UDP send(Uint8Array 또는 Packet, address, port) | `SocketStatus` |
37
- | UDP receive(Uint8Array 또는 Packet) | `{ status, received, remoteAddress?, remotePort }` |
38
-
39
- SocketHandle은 Node transport 객체의 타입 별칭이며, protected getNativeHandle에서만 사용합니다. 플랫폼 간에 전달할 수 있는 운영체제 fd/SOCKET 숫자가 아닙니다.
40
-
41
- ## TCP, UDP, Selector
42
-
43
- ```js
44
- const sf = require('sfml.js');
45
-
46
- function check(status) {
47
- if (status !== sf.SocketStatus.Done) {
48
- throw new Error(`Socket operation failed: ${status}`);
49
- }
50
- }
51
-
52
- async function exchange() {
53
- const listener = new sf.TcpListener();
54
- const client = new sf.TcpSocket();
55
- const peer = new sf.TcpSocket();
56
- try {
57
- check(await listener.listen(0, sf.IpAddress.LocalHost));
58
- const accepting = listener.accept(peer);
59
- check(await client.connect(sf.IpAddress.LocalHost,
60
- listener.getLocalPort(), sf.seconds(1)));
61
- check(await accepting);
62
-
63
- const received = new sf.Packet();
64
- const waiting = peer.receive(received);
65
- check(await client.send(
66
- new sf.Packet().write('string', '你好').write('u64', 42n)));
67
- check(await waiting);
68
- console.log(received.read('string'), received.read('u64'));
69
- } finally {
70
- listener.close();
71
- client.disconnect();
72
- peer.disconnect();
73
- }
74
- }
75
- exchange().catch(error => {
76
- console.error(error);
77
- process.exitCode = 1;
78
- });
79
- ```
80
-
81
- `setBlocking(true)`는 필요한 데이터나 쓰기 완료를 Promise가 기다린다는 뜻이며, 이벤트 루프를 차단하지 않습니다. `setBlocking(false)`는 현재 래퍼 계층의 상태에 따라 반환한다는 뜻입니다. TCP connect는 연결을 시작하고 NotReady를 반환하며, Selector.Send로 연결 준비를 기다릴 수 있습니다. TLS 초기화가 HandshakeStarted를 반환한 뒤에는 같은 setup 메서드를 반복 호출하여 핸드셰이크 상태를 확인할 수 있습니다. UDP bind/send와 TCP listen은 실제 포트와 작업 결과를 제공하기 위해 여전히 Node의 완료 알림을 기다립니다.
82
-
83
- TCP 원시 바이트 전송의 sent는 이번에 래퍼 계층이 받아들인 바이트 수입니다. 논블로킹 모드에서는 현재 Node writable highWaterMark의 남은 용량까지만 제출합니다. 일부만 수락하면 Partial, 공간이 없으면 NotReady를 반환합니다. 이어서 보낼 때는 아직 보내지 않은 뒷부분을 전달하세요. Node write가 false를 반환하는 것은 백프레셔만 뜻하며, 이번에 이미 큐에 들어간 바이트를 호출자에게 다시 보내라고 요구하지 않습니다. Done은 상대 애플리케이션이 데이터를 이미 소비하거나 영구 저장했다는 뜻이 아닙니다.
84
-
85
- TCP Packet은 빅 엔디언 uint32 길이 접두사를 사용합니다. Partial 이후에는 같은 Packet을 계속 전달하세요. 래퍼 계층이 첫 전송의 스냅샷과 오프셋을 유지합니다. 완료되기 전에 다른 전송을 시도하면 NotReady를 반환하여 패킷 내용이 섞이지 않도록 합니다. 수신은 헤더와 본문이 임의로 분할되어 도착하는 경우를 지원하며, 논블로킹 NotReady에서도 이미 받은 부분을 유지합니다. 수신 중인 Packet이 완료되기 전에는 원시 바이트 수신으로 전환할 수 없습니다.
86
-
87
- TCP 수신은 Node readable 큐와 백프레셔를 사용하며, 무한히 늘어나는 별도 데이터 복사본을 만들지 않습니다. UDP는 데이터그램 경계를 유지합니다. 대상 배열이 데이터그램보다 작으면 해당 데이터그램을 버리고 Error를 반환합니다. UDP 수신 큐는 최대 4096개 데이터그램 또는 8 MiB를 담으며, 초과하면 새 데이터그램을 버립니다. 단일 데이터그램의 최대 크기는 65507바이트입니다. TCP Packet 수신 한도는 64 MiB이며, 초과하면 연결을 닫고 Error를 반환합니다.
88
-
89
- Selector는 래퍼 계층의 읽기/쓰기 준비 상태를 관찰하며, 원시 시스템 select와 동일하다고 보장하지 않습니다. wait 한 번마다 준비 상태 스냅샷을 저장하고, isReady는 그 스냅샷을 조회하며, dispatchReadyCallbacks는 명시적으로 콜백을 전달합니다. wait는 타임아웃 시 false를 반환합니다. 멤버 집합을 변경하거나 모든 멤버를 닫으면 대기가 깨어납니다. 하나의 selector에서는 동시에 하나의 wait만 허용하며, 변경 후 다시 wait할 수 있습니다. selector 복사는 멤버 참조와 준비 상태 스냅샷을 복사할 뿐 socket을 복사하지 않습니다.
90
-
91
- 연결을 닫으면 대기 중인 읽기, accept, Selector 대기가 깨어납니다. 새 연결은 새 세대 번호를 사용하므로 이전 작업은 새 연결의 데이터를 읽을 수 없습니다. 사용을 마치면 네트워크 객체를 명시적으로 닫으세요. 활성 Node 연결은 프로세스를 계속 실행 상태로 유지합니다.
92
-
93
- ## Packet
94
-
95
- 이후 코드의 `sf`는 모두 `require('sfml.js')`를 뜻합니다. 쓰기와 읽기에서 필드 순서와 타입이 일치해야 합니다.
96
-
97
- ```js
98
- const packet = new sf.Packet()
99
- .write('bool', true)
100
- .write('i32', -100)
101
- .write('u64', 18446744073709551615n)
102
- .write('f32', 1.5)
103
- .write('string', '音频🌟')
104
- .write('bytes', new Uint8Array([ 255, 0, 254 ]));
105
- ```
106
-
107
- | 타입 매개변수 | JS 타입 | SFML 바이트 형식 |
108
- |----------|---------|---------------|
109
- | bool | boolean | 1바이트 |
110
- | i8/u8, i16/u16, i32/u32 | number | 해당 비트 폭의 정수, 빅 엔디언 |
111
- | i64/u64 | bigint | 64비트 정수, 빅 엔디언 |
112
- | f32/f64 | number | IEEE 부동소수점. 실행 호스트의 바이트 순서를 사용하며 SFML memcpy와 동일 |
113
- | string | string | sf::String에 대응: uint32 문자 수 + UTF-32 빅 엔디언 코드 포인트 |
114
- | utf8 | string | UTF-8로 인코딩한 std::string: uint32 바이트 수 + 바이트 |
115
- | bytes | Uint8Array | 이진 std::string: uint32 바이트 수 + 원본 바이트 |
116
-
117
- `read(type)`은 해당 타입을 반환하며, 데이터가 부족하면 undefined를 반환하고 clear할 때까지 isValid를 false로 만듭니다. 실패해도 누락된 필드를 건너뛰지 않습니다. 문자열 길이를 성공적으로 읽은 상태라면 커서는 문자열 본문 시작에 멈춥니다. 정수 쓰기는 비트 폭에 맞게 변환하며, 64비트 값은 number를 거치지 않습니다. 엔디언이 다른 플랫폼 간의 부동소수점 Packet은 원본 SFML과 마찬가지로 양측에서 변환 방식을 합의해야 합니다.
118
-
119
- 내부에서는 확장 가능한 Buffer를 사용하며, 정수와 부동소수점을 읽을 때 같은 메모리에 직접 접근합니다. getData는 유효 영역의 뷰를 반환하고, 빈 패킷은 undefined를 반환합니다. 이 뷰는 읽기 전용으로 사용해야 합니다. 용량 확장이나 clear 후에도 이전 뷰는 이전 할당의 수명을 유지합니다. append는 입력을 복사하며, 전송은 입력을 받아들일 때 스냅샷을 생성하므로 이후 호출자가 입력을 수정해도 이미 제출한 바이트는 바뀌지 않습니다. 추가 NAN 매핑이나 바이트별 언어 경계 호출은 없습니다.
120
-
121
- onSend는 전송할 바이트를 반환하고, onReceive는 완전한 메시지를 받습니다. 하위 클래스에서 압축이나 사용자 정의 인코딩을 구현할 수 있습니다. 네트워크 수신은 onReceive 호출 전에 기존 패킷을 clear합니다. 두 훅은 동기식으로 실행되므로 비동기 작업은 send/receive 밖에서 수행해야 합니다.
122
-
123
- ## 주소, DNS, TLS
124
-
125
- IpAddress는 불변 값입니다. toBytes는 독립적인 IPv6 바이트 복사본을 반환하고, toInteger는 IPv4에만 적용됩니다. fromString은 DNS 조회를 하지 않으며 축약 IPv4, 8진수 형식, zone ID가 있는 IPv6를 받지 않습니다. equal, notEqual, less, lessEqual, greater, greaterEqual은 주소를 지원합니다. 정렬은 먼저 IPv4/IPv6 순서, 그다음 바이트 순서로 수행합니다.
126
-
127
- Dns.resolve는 서버를 지정하지 않으면 hosts 파일을 포함한 시스템 lookup을 사용합니다. 이 경로의 완료 시간은 시스템 리졸버가 결정합니다. 서버를 지정하면 A/AAAA를 병렬 조회합니다. queryNs/Mx/Srv/Txt는 독립적인 Resolver를 사용하며, 타임아웃되면 해당 조회만 취소하고 다른 조회에는 영향을 주지 않습니다. MX의 priority는 preference로, SRV의 name은 target으로 매핑됩니다. 기본 서버 조회가 실패하면 undefined나 빈 배열을 반환합니다.
128
-
129
- getLocalAddress는 UDP 라우팅 선택으로 로컬 주소를 구하며, 애플리케이션 데이터를 전송하지 않습니다. 공인 주소 조회에는 외부 DNS/HTTP 서비스가 필요하므로 오프라인 테스트에서는 실제 공인 주소를 조회하지 않습니다. Time.Zero는 타임아웃을 설정하지 않는다는 뜻입니다.
130
-
131
- TLS는 연결된 TCP를 클라이언트나 서버로 업그레이드하는 기능을 지원합니다. 클라이언트는 기본적으로 시스템 CA와 hostname을 검증합니다. 인증서 문자열/바이트를 CA로 전달하거나, 명시적으로 false를 전달하여 검증을 끌 수 있습니다. 서버는 인증서, 개인 키, 선택적인 암호문구를 받습니다. 업그레이드 전에 plaintext 읽기/쓰기 큐를 비워야 합니다. 인증서와 암호 스위트는 Node/OpenSSL에서 제공하며, 그 집합이 SFML의 Mbed TLS와 동일하다고 보장하지 않습니다.
132
-
133
- ## HTTP
134
-
135
- ```javascript
136
- const sf = require('sfml.js');
137
-
138
- async function fetchText(host, uri) {
139
- const http = new sf.Http(host);
140
- const request = new sf.Http.Request(uri);
141
- const response = await http.sendRequest(request, sf.seconds(5));
142
- if (response.getStatus() !== sf.HttpStatus.Ok) {
143
- throw new Error(`HTTP status: ${response.getStatus()}`);
144
- }
145
- return response.getBody();
146
- }
147
- ```
148
-
149
- Request는 setField, setMethod, setUri, setHttpVersion, setBody를 지원합니다. Response는 상태, HTTP 버전, 필드, 본문 조회를 지원합니다. getBody는 UTF-8로 디코딩하고, getBodyBytes는 독립적인 원시 바이트를 가져옵니다. setBody에는 Uint8Array를 직접 전달할 수 있습니다.
150
-
151
- SFML에서 HTTP/1.0/1.1 요청 줄을 명시적으로 지정하는 기능을 지원하기 위해 Node TCP/TLS로 요청을 보내고 응답을 점진적으로 파싱합니다. 파서는 Content-Length, chunked, trailer, 중간 1xx 응답, HEAD/본문 없는 상태, 연결 종료로 구분하는 본문을 지원합니다. 요청 본문은 Content-Length를 사용하며, 충돌하는 길이와 Transfer-Encoding은 금지합니다. 리디렉션을 자동으로 따르거나 본문을 압축 해제하거나 HTTP/2로 업그레이드하지 않습니다.
152
-
153
- sendRequest의 Time은 요청 전체를 제한하며, 네 번째 인수로 AbortSignal을 전달하여 취소할 수 있습니다. 잘못되거나 잘린 응답은 InvalidResponse로, 연결/TLS 실패와 취소는 ConnectionFailed로 매핑됩니다. 응답 본문의 상한은 64 MiB이고, 미완성 헤더나 chunk framing의 상한은 64 KiB입니다. setHost는 주소를 동기식으로 파싱하며, 실제 DNS와 연결은 sendRequest에서 수행합니다.
154
-
155
- ## FTP
156
-
157
- FTP는 basic-ftp의 제어 연결, 수동 데이터 채널, 스트리밍 파일 전송을 사용합니다. connect는 로그인하지 않으며, login의 기본값은 anonymous입니다. 열거형과 응답 타입은 패키지에 포함된 SFML 헤더에서 생성하며, 원본 FTP 상태 코드는 그대로 유지합니다. 디렉터리 목록 조회에는 NLST를 보냅니다.
158
-
159
- download(remoteFile, localDirectory, mode)는 로컬 디렉터리에 원격 파일 이름으로 저장합니다. upload(localFile, remoteDirectory, mode, append)는 원격 디렉터리에 로컬 파일 이름으로 씁니다. Binary/Ascii/Ebcdic은 각각 TYPE I/A/E를 보내며, 모드 지원 여부는 서버 응답에 따라 결정됩니다. renameFile, deleteDirectory 등은 해당 작업만 수행하고 암묵적으로 재귀 삭제하지 않습니다. sendCommand로 다른 FTP 명령을 보낼 수 있으며, 인수의 줄바꿈과 NUL은 거부합니다.
160
-
161
- 같은 Ftp 객체의 작업은 직렬 실행합니다. connect의 Time은 연결 수립만 제한하며, 다른 명령은 close로 직접 중단할 수 있습니다. close는 제어 연결과 데이터 연결을 닫습니다. 연결 실패, 연결 종료, 로컬 파일 오류는 해당 SFML 응답으로 매핑하며, 서버 오류는 상태 코드를 유지합니다.
162
-
163
- <a id="sftp"></a>
164
- ## SFTP
165
-
166
- SFTP는 ssh2를 사용합니다. connect는 SSH 협상을 마치고 인증 직전에서 멈춥니다. getSessionInfo로 호스트 공개 키, SHA-1/SHA-256 지문, 협상된 알고리즘을 읽을 수 있습니다. login은 비밀번호 또는 일치하는 공개 키와 개인 키 및 암호문구를 지원하며, 인증 실패 후 재시도할 수 있습니다.
167
-
168
- 호스트 키를 known_hosts와 자동 비교하지 않습니다. SFML처럼 SessionInfo를 공개하여 호출자가 판단하도록 합니다. 서버 신원을 검증해야 한다면 login 전에 hostKey.sha256을 신뢰할 수 있는 지문과 비교하세요.
169
-
170
- 아래 함수에는 애플리케이션이 IpAddress, 인증 정보, 이미 신뢰할 수 있는 지문, 소비 콜백을 전달합니다.
171
-
172
- ```javascript
173
- async function download(address, username, password, trustedFingerprint, consume) {
174
- const client = new sf.Sftp();
175
- try {
176
- const connection = await client.connect(address, 22, sf.seconds(5));
177
- if (!connection.isOk()) throw new Error(connection.getMessage());
178
- const info = client.getSessionInfo();
179
- if (!info || info.hostKey.sha256 !== trustedFingerprint) {
180
- throw new Error('Unexpected SFTP host key');
181
- }
182
- const authentication = await client.login(username, password, sf.seconds(5));
183
- if (!authentication.isOk()) throw new Error(authentication.getMessage());
184
- const result = await client.download('/file', async bytes => {
185
- await consume(bytes);
186
- return true;
187
- });
188
- if (!result.isOk()) throw new Error(result.getMessage());
189
- } finally {
190
- client.close();
191
- }
192
- }
193
- ```
194
-
195
- download 콜백은 최대 65536바이트의 Buffer 뷰를 받습니다. false를 반환하면 중단하고, EOF에서는 0바이트 콜백으로 끝납니다. upload 콜백은 `{ data, size }`를 받아 Buffer를 채우고 size를 유효 바이트 수로 설정합니다. false를 반환해도 이번 유효 데이터를 쓴 뒤 중단합니다. 콜백은 Promise를 반환할 수 있습니다. 매번 독립적인 Buffer를 할당하므로 콜백이 이전 뷰를 보관해도 이후 블록에 덮어써지지 않습니다. 업로드 콜백이 완료된 뒤에는 호출자가 제출된 블록을 계속 수정해서는 안 됩니다.
196
-
197
- 속성에는 경로, FileType, 권한, bigint 크기/UID/GID, Date 시간이 포함됩니다. ssh2의 오프셋 및 속성 수치 인터페이스는 number를 사용하므로, 이 바인딩은 정밀도를 잃지 않도록 0~2⁵³−1 범위의 정확한 오프셋만 받으며 범위를 초과하면 거부합니다. 시간 정밀도는 프로토콜이 제공하는 초 단위입니다. rename(overwrite=true)는 OpenSSH POSIX rename 확장을 사용하며, 지원하지 않는 서버는 오류를 반환합니다.
198
-
199
- Time은 한 번의 무진행 대기 주기로 변환됩니다. TimeoutWithPredicate는 연결에 들어오는 데이터나 작업 완료 알림 없이 한 주기가 지나면 조건 함수를 호출합니다. true면 계속 기다리고, false면 Timeout을 반환한 뒤 세션을 닫습니다. Time.Zero는 타이머를 설정하지 않습니다. 이 메커니즘은 Node 이벤트 계층의 대기이므로, libssh2의 EAGAIN/커널 준비 상태 세부 동작과 동일하게 볼 수 없습니다.
200
-
201
- close는 진행 중인 대기를 중단합니다. 사용자 콜백의 Promise를 강제 종료할 수는 없지만, 이후 완료되더라도 다시 수립된 세션에서 계속 읽거나 쓰지 않습니다. SFTP 프로토콜 상태는 해당 Result.Value로 매핑합니다. 하위 계층 오류를 libssh2 전용 값과 일대일로 대응할 수 없으면 Error와 원본 메시지를 반환하며, 전용 오류를 임의로 만들어 내지 않습니다.
202
-
203
- ## 검증과 데모
204
-
205
- `npm run demo:network`는 로컬 루프백 주소에서 TCP, Packet, UDP, Selector 예제를 실행하며, 끝나면 모든 연결을 닫습니다.
206
-
207
- `npm run test:runtime`에는 네트워크 테스트가 포함됩니다. 로컬 TCP/UDP/DNS/FTP/SSH 서버를 시작하여 실제 소켓, 분할된 메시지, 전송 백프레셔, TLS 신뢰 및 hostname 실패, 비밀번호 및 공개 키 인증, 디렉터리와 스트리밍 파일 작업, 타임아웃, 취소를 테스트합니다. `network-oracle.test.cjs`는 임시 디렉터리에서 SFML C++ 프로그램을 컴파일하여 Packet 각 필드의 바이트와 IPv4/IPv6 문자열을 대조합니다. Windows에서는 이 Unix 컴파일 명령을 건너뜁니다.
208
-
209
- 의존성 버전은 [package.json](../package.json)과 잠금 파일을 기준으로 합니다. 로컬 루프백 테스트는 공용 인터넷 서비스의 가용성을 검증하지 않습니다. 플랫폼 구성과 실행 방법은 [개발 가이드](development.ko.md#testing)를 참고하세요.
210
-
211
- <a id="sfml-cpp-reference"></a>
212
- ## SFML C++ 레퍼런스
213
-
214
- 원본 클래스 문서: [Packet](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1Packet.html), [TcpSocket](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1TcpSocket.html), [UdpSocket](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1UdpSocket.html), [Http](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1Http.html), [Ftp](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1Ftp.html), [Sftp](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1Sftp.html).
215
-
216
- 패킷 형식과 프로토콜 개념은 업스트림 문서를 참고하세요. 이 바인딩은 Node.js 전송 계층과 Promise I/O를 사용하므로, 상태값과 제한은 JS 문서의 설명을 우선합니다.
package/docs/network.md DELETED
@@ -1,218 +0,0 @@
1
- # Network
2
-
3
- **English** · [简体中文](network.zh-CN.md) · [日本語](network.ja.md) · [한국어](network.ko.md)
4
-
5
- > Define messages with Packet and send them over TCP/UDP, or use HTTP, FTP and SFTP for protocol operations. Network I/O returns promises; callers must also check operation statuses.
6
-
7
- [API guide](api.md) · [Core concepts](concepts.md) · [Loopback example](../examples/network.cjs)
8
-
9
- Production Network code implements SFML-style APIs with Node.js transports, using basic-ftp for FTP, ssh2 for SFTP and ipaddr.js for IPv6 parsing. It does not call the SFML C++ network module; Packet formats and selected value semantics are compared against independent C++ programs.
10
-
11
- ## APIs and calling conventions
12
-
13
- | API | Implementation and adaptations |
14
- |------|------------|
15
- | IpAddress | IPv4 integer/four-byte construction, IPv6 16-byte construction, copying, fromString, toString, toInteger, toBytes, getType, isV4/isV6; static resolve, getLocalAddress and getPublicAddress return promises |
16
- | Dns | resolve, queryNs, queryMx, querySrv, queryTxt, getPublicAddress; supports independent Resolvers and custom servers |
17
- | Socket | setBlocking, isBlocking, AnyPort, Status; getLastError returns the most recent underlying error |
18
- | TcpSocket | connect, disconnect, send, receive, port/remote-address queries; setupTlsClient, setupTlsServer, getCurrentCiphersuiteName |
19
- | TcpListener | listen, close, accept, getLocalPort |
20
- | UdpSocket | bind, unbind, send, receive, getLocalPort, MaxDatagramSize |
21
- | SocketSelector | add, remove, clear, wait, isReady, dispatchReadyCallbacks, copy construction and assign; Receive/Send bit flags |
22
- | Packet | append, clear, getData, getDataSize, getReadPosition, endOfPacket, isValid, copy construction; explicitly typed write/read; overridable onSend/onReceive |
23
- | Http | setHost, sendRequest, Request and Response; explicit HTTP request version |
24
- | Ftp | connect, disconnect, login, keepAlive, working directory, directory listings, change/create/delete directories, rename/delete files, upload/append/download, sendCommand |
25
- | Sftp | Separate connect and login, password/key authentication, getSessionInfo, path resolution, directories and attributes, rename/delete, streaming uploads/downloads, TimeoutWithPredicate |
26
-
27
- Methods involving I/O or waiting return promises; pure state queries and configuration remain synchronous. TcpSocket's `disconnect()`, listener.close and udp.unbind synchronously end local transports. FTP/SFTP disconnect returns a promise; a separate synchronous close interrupts unfinished operations.
28
-
29
- C++ output references are represented by returned objects:
30
-
31
- | Operation | Return value |
32
- |------|--------|
33
- | TCP send(Uint8Array) | `{ status, sent }` |
34
- | TCP receive(Uint8Array) | `{ status, received }` |
35
- | TCP send/receive(Packet) | `SocketStatus` |
36
- | UDP send(Uint8Array or Packet, address, port) | `SocketStatus` |
37
- | UDP receive(Uint8Array or Packet) | `{ status, received, remoteAddress?, remotePort }` |
38
-
39
- SocketHandle is a type alias for a Node transport object, used only by protected getNativeHandle; it is not a portable numeric operating-system fd/SOCKET.
40
-
41
- ## TCP, UDP and Selector
42
-
43
- ```js
44
- const sf = require('sfml.js');
45
-
46
- function check(status) {
47
- if (status !== sf.SocketStatus.Done) {
48
- throw new Error(`Socket operation failed: ${status}`);
49
- }
50
- }
51
-
52
- async function exchange() {
53
- const listener = new sf.TcpListener();
54
- const client = new sf.TcpSocket();
55
- const peer = new sf.TcpSocket();
56
- try {
57
- check(await listener.listen(0, sf.IpAddress.LocalHost));
58
- const accepting = listener.accept(peer);
59
- check(await client.connect(sf.IpAddress.LocalHost,
60
- listener.getLocalPort(), sf.seconds(1)));
61
- check(await accepting);
62
-
63
- const received = new sf.Packet();
64
- const waiting = peer.receive(received);
65
- check(await client.send(
66
- new sf.Packet().write('string', '你好').write('u64', 42n)));
67
- check(await waiting);
68
- console.log(received.read('string'), received.read('u64'));
69
- } finally {
70
- listener.close();
71
- client.disconnect();
72
- peer.disconnect();
73
- }
74
- }
75
- exchange().catch(error => {
76
- console.error(error);
77
- process.exitCode = 1;
78
- });
79
- ```
80
-
81
- `setBlocking(true)` makes the promise wait for required data/write completion without blocking the event loop. `setBlocking(false)` returns according to the wrapper's current state; TCP connect starts a connection and returns NotReady, and Selector.Send can wait for connection readiness. After TLS setup returns HandshakeStarted, repeat the same setup method to obtain handshake status. UDP bind/send and TCP listen still wait for Node completion notifications to provide actual ports and operation results.
82
-
83
- For raw TCP byte sends, sent is the number of bytes accepted by the wrapper in this call. Nonblocking mode submits at most the remaining capacity under the current Node writable highWaterMark; partial acceptance returns Partial, and no space returns NotReady. Pass the unsent suffix when continuing. A false result from Node write indicates only backpressure; bytes already queued in that call do not need resending. Done does not mean the peer application has consumed or persisted the data.
84
-
85
- TCP Packet uses a big-endian uint32 length prefix. After Partial, continue passing the same Packet; the wrapper retains the first send's snapshot and offset. Other sends return NotReady until it completes, preventing packet contents from interleaving. Receiving supports arbitrarily segmented headers and bodies; nonblocking NotReady retains received portions. Do not switch to raw-byte receiving until an in-progress Packet receive completes.
86
-
87
- TCP receive uses the Node readable queue and backpressure, without an additional unbounded copy of the data. UDP preserves datagram boundaries; if the destination array is smaller than the datagram, that datagram is discarded and Error is returned. The UDP receive queue holds at most 4096 datagrams or 8 MiB, discarding new datagrams beyond the limit. A single datagram is limited to 65507 bytes. TCP Packet receive is limited to 64 MiB; exceeding the limit closes the connection and returns Error.
88
-
89
- Selector observes wrapper-level readable/writable state and does not claim equivalence to raw system select. Each wait saves a readiness snapshot; isReady queries it, and dispatchReadyCallbacks explicitly dispatches callbacks. wait returns false on timeout. Changing the member set or closing all members wakes the wait. A selector allows only one simultaneous wait; after modifications, you can wait again. Copying a selector copies member references and the readiness snapshot, not sockets.
90
-
91
- Closing connections wakes pending reads, accept and Selector waits. New connections use a new generation, so old operations cannot read data from a new connection. Explicitly close network objects when finished; active Node connections keep the process alive.
92
-
93
- ## Packet
94
-
95
- In the following snippets, `sf` means `require('sfml.js')`. Writes and reads must use the same field order and types:
96
-
97
- ```js
98
- const packet = new sf.Packet()
99
- .write('bool', true)
100
- .write('i32', -100)
101
- .write('u64', 18446744073709551615n)
102
- .write('f32', 1.5)
103
- .write('string', '音频🌟')
104
- .write('bytes', new Uint8Array([ 255, 0, 254 ]));
105
- ```
106
-
107
- | Type argument | JS type | SFML byte format |
108
- |----------|---------|---------------|
109
- | bool | boolean | One byte |
110
- | i8/u8, i16/u16, i32/u32 | number | Integer of the corresponding bit width, big-endian |
111
- | i64/u64 | bigint | 64-bit integer, big-endian |
112
- | f32/f64 | number | IEEE floating point in host byte order, matching SFML memcpy |
113
- | string | string | Corresponds to sf::String: uint32 character count + UTF-32 big-endian code points |
114
- | utf8 | string | UTF-8 encoded as std::string: uint32 byte count + bytes |
115
- | bytes | Uint8Array | Binary std::string: uint32 byte count + original bytes |
116
-
117
- `read(type)` returns the corresponding type, or undefined when data is insufficient, leaving isValid false until clear. Failure does not skip the missing field; if a string length has been read successfully, the cursor stays at the start of the string body. Integer writes convert to the specified bit width; 64-bit values do not pass through number. As with original SFML, floating-point Packets exchanged across endianness boundaries require both sides to agree on conversion.
118
-
119
- The implementation uses a growable Buffer, with integer and floating-point reads accessing the same memory directly. getData returns a view of the valid region, or undefined for an empty packet; treat the view as read-only. Old views keep old allocations alive after capacity growth or clear. append copies input; sending takes a snapshot when input is accepted, so later caller modifications cannot change submitted bytes. There is no extra NAN mapping or per-byte cross-language call.
120
-
121
- onSend returns bytes to send, and onReceive receives a complete message; subclasses can implement compression or custom encoding. Network receive clears the original packet before calling onReceive. Both hooks run synchronously; perform asynchronous work outside send/receive.
122
-
123
- ## Addresses, DNS and TLS
124
-
125
- IpAddress is immutable; toBytes returns an independent copy of IPv6 bytes, and toInteger applies only to IPv4. fromString does not perform DNS and rejects abbreviated IPv4, octal forms and IPv6 with a zone ID. equal, notEqual, less, lessEqual, greater and greaterEqual support addresses; ordering compares IPv4/IPv6 first, then bytes.
126
-
127
- Without custom servers, Dns.resolve uses system lookup, including the hosts file; completion timing on this path is controlled by the system resolver. With custom servers, it queries A/AAAA in parallel. queryNs/Mx/Srv/Txt use independent Resolvers; timeout cancels only that query, without affecting others. MX priority maps to preference, and SRV name maps to target. Failed default-server queries return undefined or an empty array.
128
-
129
- getLocalAddress obtains the local address through UDP route selection without sending application data. Public-address queries require external DNS/HTTP services; offline tests do not make real public-network queries. Time.Zero means no timeout.
130
-
131
- TLS supports client and server upgrades of connected TCP sockets. Clients verify against system CAs and the hostname by default; pass certificate strings/bytes as a CA, or explicitly pass false to disable verification. Servers accept a certificate, private key and optional passphrase. Drain plaintext read/write queues before upgrading. Certificates and cipher suites are provided by Node/OpenSSL; their set is not guaranteed to match SFML's Mbed TLS.
132
-
133
- ## HTTP
134
-
135
- ```javascript
136
- const sf = require('sfml.js');
137
-
138
- async function fetchText(host, uri) {
139
- const http = new sf.Http(host);
140
- const request = new sf.Http.Request(uri);
141
- const response = await http.sendRequest(request, sf.seconds(5));
142
- if (response.getStatus() !== sf.HttpStatus.Ok) {
143
- throw new Error(`HTTP status: ${response.getStatus()}`);
144
- }
145
- return response.getBody();
146
- }
147
- ```
148
-
149
- Request supports setField, setMethod, setUri, setHttpVersion and setBody; Response provides status, HTTP version, field and body queries. getBody decodes UTF-8; getBodyBytes returns independent raw bytes. setBody accepts Uint8Array directly.
150
-
151
- To support SFML's explicit HTTP/1.0/1.1 request lines, the implementation sends requests over Node TCP/TLS and parses responses incrementally. Parsing supports Content-Length, chunked encoding, trailers, interim 1xx responses, HEAD/bodyless statuses and connection-close delimiting. Request bodies use Content-Length; conflicting lengths and Transfer-Encoding are forbidden. Redirects are not followed automatically, bodies are not decompressed, and connections are not upgraded to HTTP/2.
152
-
153
- The Time passed to sendRequest limits the whole request; a fourth AbortSignal argument can cancel it. Invalid or truncated responses map to InvalidResponse; connection/TLS failures and cancellation map to ConnectionFailed. Response bodies are limited to 64 MiB, and incomplete headers or chunk framing to 64 KiB. setHost parses the address synchronously; actual DNS resolution and connection happen in sendRequest.
154
-
155
- ## FTP
156
-
157
- FTP uses basic-ftp's control connection, passive data channels and streaming file transfers. connect does not log in; login defaults to anonymous. Enums and response types are generated from the bundled SFML headers, preserving raw FTP status codes. Directory listings send NLST.
158
-
159
- download(remoteFile, localDirectory, mode) writes under the remote filename in the local directory; upload(localFile, remoteDirectory, mode, append) writes under the local filename in the remote directory. Binary/Ascii/Ebcdic send TYPE I/A/E respectively; server responses determine mode support. renameFile, deleteDirectory and similar methods perform only their corresponding operations, without implicit recursive deletion. sendCommand sends other FTP commands; newlines and NUL in arguments are rejected.
160
-
161
- Operations on the same Ftp object are serialized. connect's Time limits only connection establishment; use close to interrupt other commands explicitly. close shuts down both control and data connections. Connection failures, closed connections and local file errors map to corresponding SFML responses; server errors preserve their status codes.
162
-
163
- <a id="sftp"></a>
164
-
165
- ## SFTP
166
-
167
- SFTP uses ssh2. connect completes SSH negotiation and stops before authentication; getSessionInfo provides the host public key, SHA-1/SHA-256 fingerprints and negotiated algorithms. login supports a password or matching public/private keys and a passphrase; failed authentication can be retried.
168
-
169
- Host keys are not automatically matched against known_hosts. As in SFML, SessionInfo is exposed for the caller to evaluate. To verify server identity, compare hostKey.sha256 with a trusted fingerprint before login.
170
-
171
- The application supplies an IpAddress, credentials, a known trusted fingerprint and a consumer callback to this function:
172
-
173
- ```javascript
174
- async function download(address, username, password, trustedFingerprint, consume) {
175
- const client = new sf.Sftp();
176
- try {
177
- const connection = await client.connect(address, 22, sf.seconds(5));
178
- if (!connection.isOk()) throw new Error(connection.getMessage());
179
- const info = client.getSessionInfo();
180
- if (!info || info.hostKey.sha256 !== trustedFingerprint) {
181
- throw new Error('Unexpected SFTP host key');
182
- }
183
- const authentication = await client.login(username, password, sf.seconds(5));
184
- if (!authentication.isOk()) throw new Error(authentication.getMessage());
185
- const result = await client.download('/file', async bytes => {
186
- await consume(bytes);
187
- return true;
188
- });
189
- if (!result.isOk()) throw new Error(result.getMessage());
190
- } finally {
191
- client.close();
192
- }
193
- }
194
- ```
195
-
196
- The download callback receives a Buffer view of at most 65536 bytes; return false to stop, and EOF ends with a zero-byte callback. The upload callback receives `{ data, size }`: fill the Buffer and set size to the valid byte count. Returning false still writes this call's valid data before stopping. Callbacks may return promises. Each call allocates an independent Buffer, so retained old views are not overwritten by later blocks; after an upload callback completes, the caller must not modify the submitted block.
197
-
198
- Attributes include paths, FileType, permissions, bigint size/UID/GID and Date timestamps. ssh2's numeric offset and attribute APIs use number, so this binding accepts only exact offsets from 0 to 2^53 - 1, rejecting larger values to avoid silent precision loss. Timestamp precision is the protocol's seconds. rename(overwrite=true) uses the OpenSSH POSIX rename extension; servers without that extension return an error.
199
-
200
- Time becomes the period for a single wait without progress. TimeoutWithPredicate calls its predicate when a full period passes with no inbound connection data or operation-completion notification: true continues waiting; false returns Timeout and closes the session. Time.Zero sets no timer. This is waiting at the Node event layer, not equivalent to libssh2 EAGAIN or kernel-readiness details.
201
-
202
- close interrupts active waits. User callback promises cannot be forcibly terminated, but their later completion cannot continue reads or writes on a reestablished session. SFTP protocol statuses map to corresponding Result.Value values; when underlying errors cannot be mapped one-to-one to libssh2-specific values, the result is Error with the original message, without inventing a specific error.
203
-
204
- ## Verification and demos
205
-
206
- `npm run demo:network` runs TCP, Packet, UDP and Selector examples on the local loopback address, closing all connections when finished.
207
-
208
- `npm run test:runtime` includes network tests that start local TCP/UDP/DNS/FTP/SSH services and exercise real sockets, segmented messages, send backpressure, TLS trust and hostname failures, password and public-key authentication, directory and streaming file operations, timeouts and cancellation. `network-oracle.test.cjs` compiles an SFML C++ program in a temporary directory to compare bytes for every Packet field and IPv4/IPv6 strings; Windows skips this Unix compilation command.
209
-
210
- Dependency versions are defined by [package.json](../package.json) and the lockfile. Local loopback tests do not verify public-service availability; see the [development guide](development.md#testing) for platform configuration and execution.
211
-
212
- <a id="sfml-cpp-reference"></a>
213
-
214
- ## SFML C++ reference
215
-
216
- The original [Packet](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1Packet.html), [TcpSocket](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1TcpSocket.html), [UdpSocket](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1UdpSocket.html), [Http](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1Http.html), [Ftp](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1Ftp.html) and [Sftp](https://www.sfml-dev.org/documentation/3.1.0/classsf_1_1Sftp.html) references explain upstream packet formats and protocol concepts.
217
-
218
- This binding uses Node.js transports and promise-based I/O rather than SFML C++ Network. The statuses, limits, timeouts and lifecycle rules in this JavaScript guide take precedence for sfml.js applications.