typenative 0.3.1 → 0.4.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.
Files changed (147) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +17 -1
  3. package/bin/cli.js +25 -11
  4. package/bin/go/convert.js +11 -1
  5. package/bin/index.js +221 -47
  6. package/bin/main.js +35 -14
  7. package/bin/node/assert.js +2 -2
  8. package/bin/node/buffer.js +9 -0
  9. package/bin/node/dns.js +1 -1
  10. package/bin/node/events.js +1 -1
  11. package/bin/node/fs.js +1 -1
  12. package/bin/node/fs_watch.js +407 -0
  13. package/bin/node/http2.js +33 -6
  14. package/bin/node/readline.js +1 -1
  15. package/bin/node/registry.js +2 -1
  16. package/bin/node/stream.js +6 -3
  17. package/bin/node/timers.js +1 -1
  18. package/bin/node/typed_arrays.js +608 -0
  19. package/bin/node/util.js +3 -0
  20. package/bin/node/zlib.js +131 -16
  21. package/bin/transpiler.js +635 -44
  22. package/bin/version.js +1 -1
  23. package/conformance.md +16 -4
  24. package/examples/README.md +54 -0
  25. package/examples/fibonacci/README.md +89 -0
  26. package/examples/fibonacci/bench.mjs +87 -0
  27. package/examples/fibonacci/main.ts +21 -0
  28. package/examples/hello-world/README.md +62 -0
  29. package/examples/hello-world/bench.mjs +66 -0
  30. package/examples/hello-world/main.ts +7 -0
  31. package/examples/json-server/README.md +125 -0
  32. package/examples/json-server/bench.mjs +171 -0
  33. package/examples/json-server/main.ts +67 -0
  34. package/govendor/github.com/andybalholm/brotli/LICENSE +19 -0
  35. package/govendor/github.com/andybalholm/brotli/README.md +19 -0
  36. package/govendor/github.com/andybalholm/brotli/backward_references.go +185 -0
  37. package/govendor/github.com/andybalholm/brotli/backward_references_hq.go +796 -0
  38. package/govendor/github.com/andybalholm/brotli/bit_cost.go +436 -0
  39. package/govendor/github.com/andybalholm/brotli/bit_reader.go +266 -0
  40. package/govendor/github.com/andybalholm/brotli/bitwriter.go +56 -0
  41. package/govendor/github.com/andybalholm/brotli/block_splitter.go +144 -0
  42. package/govendor/github.com/andybalholm/brotli/block_splitter_command.go +434 -0
  43. package/govendor/github.com/andybalholm/brotli/block_splitter_distance.go +433 -0
  44. package/govendor/github.com/andybalholm/brotli/block_splitter_literal.go +433 -0
  45. package/govendor/github.com/andybalholm/brotli/brotli_bit_stream.go +1435 -0
  46. package/govendor/github.com/andybalholm/brotli/cluster.go +30 -0
  47. package/govendor/github.com/andybalholm/brotli/cluster_command.go +164 -0
  48. package/govendor/github.com/andybalholm/brotli/cluster_distance.go +326 -0
  49. package/govendor/github.com/andybalholm/brotli/cluster_literal.go +326 -0
  50. package/govendor/github.com/andybalholm/brotli/command.go +254 -0
  51. package/govendor/github.com/andybalholm/brotli/compress_fragment.go +834 -0
  52. package/govendor/github.com/andybalholm/brotli/compress_fragment_two_pass.go +775 -0
  53. package/govendor/github.com/andybalholm/brotli/constants.go +77 -0
  54. package/govendor/github.com/andybalholm/brotli/context.go +2176 -0
  55. package/govendor/github.com/andybalholm/brotli/decode.go +2570 -0
  56. package/govendor/github.com/andybalholm/brotli/dictionary.go +122890 -0
  57. package/govendor/github.com/andybalholm/brotli/dictionary_hash.go +32779 -0
  58. package/govendor/github.com/andybalholm/brotli/encode.go +1220 -0
  59. package/govendor/github.com/andybalholm/brotli/encoder.go +177 -0
  60. package/govendor/github.com/andybalholm/brotli/encoder_dict.go +22 -0
  61. package/govendor/github.com/andybalholm/brotli/encoder_fast.go +201 -0
  62. package/govendor/github.com/andybalholm/brotli/entropy_encode.go +592 -0
  63. package/govendor/github.com/andybalholm/brotli/entropy_encode_static.go +4399 -0
  64. package/govendor/github.com/andybalholm/brotli/fast_log.go +290 -0
  65. package/govendor/github.com/andybalholm/brotli/find_match_length.go +45 -0
  66. package/govendor/github.com/andybalholm/brotli/go.mod +3 -0
  67. package/govendor/github.com/andybalholm/brotli/h10.go +287 -0
  68. package/govendor/github.com/andybalholm/brotli/h5.go +214 -0
  69. package/govendor/github.com/andybalholm/brotli/h6.go +216 -0
  70. package/govendor/github.com/andybalholm/brotli/hash.go +342 -0
  71. package/govendor/github.com/andybalholm/brotli/hash_composite.go +93 -0
  72. package/govendor/github.com/andybalholm/brotli/hash_forgetful_chain.go +252 -0
  73. package/govendor/github.com/andybalholm/brotli/hash_longest_match_quickly.go +214 -0
  74. package/govendor/github.com/andybalholm/brotli/hash_rolling.go +168 -0
  75. package/govendor/github.com/andybalholm/brotli/histogram.go +226 -0
  76. package/govendor/github.com/andybalholm/brotli/http.go +201 -0
  77. package/govendor/github.com/andybalholm/brotli/huffman.go +653 -0
  78. package/govendor/github.com/andybalholm/brotli/literal_cost.go +182 -0
  79. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain1.go +212 -0
  80. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain2.go +248 -0
  81. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain3.go +278 -0
  82. package/govendor/github.com/andybalholm/brotli/matchfinder/emitter.go +34 -0
  83. package/govendor/github.com/andybalholm/brotli/matchfinder/m0.go +175 -0
  84. package/govendor/github.com/andybalholm/brotli/matchfinder/m4.go +339 -0
  85. package/govendor/github.com/andybalholm/brotli/matchfinder/matchfinder.go +103 -0
  86. package/govendor/github.com/andybalholm/brotli/matchfinder/pathfinder.go +328 -0
  87. package/govendor/github.com/andybalholm/brotli/matchfinder/textencoder.go +53 -0
  88. package/govendor/github.com/andybalholm/brotli/matchfinder/trio.go +327 -0
  89. package/govendor/github.com/andybalholm/brotli/matchfinder/zdfast.go +258 -0
  90. package/govendor/github.com/andybalholm/brotli/matchfinder/zfast.go +206 -0
  91. package/govendor/github.com/andybalholm/brotli/matchfinder/zm.go +302 -0
  92. package/govendor/github.com/andybalholm/brotli/memory.go +66 -0
  93. package/govendor/github.com/andybalholm/brotli/metablock.go +574 -0
  94. package/govendor/github.com/andybalholm/brotli/metablock_command.go +165 -0
  95. package/govendor/github.com/andybalholm/brotli/metablock_distance.go +165 -0
  96. package/govendor/github.com/andybalholm/brotli/metablock_literal.go +165 -0
  97. package/govendor/github.com/andybalholm/brotli/params.go +37 -0
  98. package/govendor/github.com/andybalholm/brotli/platform.go +103 -0
  99. package/govendor/github.com/andybalholm/brotli/prefix.go +30 -0
  100. package/govendor/github.com/andybalholm/brotli/prefix_dec.go +723 -0
  101. package/govendor/github.com/andybalholm/brotli/quality.go +196 -0
  102. package/govendor/github.com/andybalholm/brotli/reader.go +127 -0
  103. package/govendor/github.com/andybalholm/brotli/ringbuffer.go +134 -0
  104. package/govendor/github.com/andybalholm/brotli/state.go +313 -0
  105. package/govendor/github.com/andybalholm/brotli/static_dict.go +662 -0
  106. package/govendor/github.com/andybalholm/brotli/static_dict_lut.go +75094 -0
  107. package/govendor/github.com/andybalholm/brotli/symbol_list.go +22 -0
  108. package/govendor/github.com/andybalholm/brotli/transform.go +641 -0
  109. package/govendor/github.com/andybalholm/brotli/utf8_util.go +70 -0
  110. package/govendor/github.com/andybalholm/brotli/util.go +7 -0
  111. package/govendor/github.com/andybalholm/brotli/write_bits.go +52 -0
  112. package/govendor/github.com/andybalholm/brotli/writer.go +162 -0
  113. package/govendor/github.com/fsnotify/fsnotify/.mailmap +2 -0
  114. package/govendor/github.com/fsnotify/fsnotify/CHANGELOG.md +651 -0
  115. package/govendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md +147 -0
  116. package/govendor/github.com/fsnotify/fsnotify/LICENSE +25 -0
  117. package/govendor/github.com/fsnotify/fsnotify/README.md +214 -0
  118. package/govendor/github.com/fsnotify/fsnotify/backend_fen.go +469 -0
  119. package/govendor/github.com/fsnotify/fsnotify/backend_inotify.go +597 -0
  120. package/govendor/github.com/fsnotify/fsnotify/backend_kqueue.go +735 -0
  121. package/govendor/github.com/fsnotify/fsnotify/backend_other.go +22 -0
  122. package/govendor/github.com/fsnotify/fsnotify/backend_windows.go +702 -0
  123. package/govendor/github.com/fsnotify/fsnotify/fsnotify.go +526 -0
  124. package/govendor/github.com/fsnotify/fsnotify/go.mod +3 -0
  125. package/govendor/github.com/fsnotify/fsnotify/internal/darwin.go +20 -0
  126. package/govendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go +15 -0
  127. package/govendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go +15 -0
  128. package/govendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go +20 -0
  129. package/govendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go +32 -0
  130. package/govendor/github.com/fsnotify/fsnotify/internal/debug_linux.go +56 -0
  131. package/govendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go +15 -0
  132. package/govendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go +16 -0
  133. package/govendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go +45 -0
  134. package/govendor/github.com/fsnotify/fsnotify/internal/debug_windows.go +40 -0
  135. package/govendor/github.com/fsnotify/fsnotify/internal/freebsd.go +20 -0
  136. package/govendor/github.com/fsnotify/fsnotify/internal/internal.go +2 -0
  137. package/govendor/github.com/fsnotify/fsnotify/internal/unix.go +20 -0
  138. package/govendor/github.com/fsnotify/fsnotify/internal/unix2.go +25 -0
  139. package/govendor/github.com/fsnotify/fsnotify/internal/windows.go +40 -0
  140. package/govendor/github.com/fsnotify/fsnotify/shared.go +64 -0
  141. package/govendor/github.com/fsnotify/fsnotify/staticcheck.conf +3 -0
  142. package/govendor/github.com/fsnotify/fsnotify/system_bsd.go +7 -0
  143. package/govendor/github.com/fsnotify/fsnotify/system_darwin.go +8 -0
  144. package/govendor/manifest.txt +3 -1
  145. package/package.json +1 -1
  146. package/types/typenative-npm.d.ts +72 -0
  147. package/types/typenative.d.ts +117 -1
@@ -690,6 +690,15 @@ export function registerBuffer(r) {
690
690
  const type = call.types[0];
691
691
  if (call.args.length === 0)
692
692
  return '[]byte{}';
693
+ // new Uint8Array(arrayBuffer, byteOffset?, length?): a view sharing its memory
694
+ if (r.isArrayBuffer(call.nodes[0])) {
695
+ if (call.args.length === 1)
696
+ return call.args[0];
697
+ const start = `int(${call.args[1]})`;
698
+ if (call.args.length === 2)
699
+ return `${call.args[0]}[${start}:]`;
700
+ return `${call.args[0]}[${start}:${start}+int(${call.args[2]})]`;
701
+ }
693
702
  if (type === 'float64')
694
703
  return `make([]byte, int(${call.args[0]}))`;
695
704
  use();
package/bin/node/dns.js CHANGED
@@ -113,7 +113,7 @@ func tnDnsPromise[T any](work func() (T, error)) chan T {
113
113
  TnReject(ch, err)
114
114
  return
115
115
  }
116
- ch <- v
116
+ TnAsyncSend(ch, v)
117
117
  }()
118
118
  return ch
119
119
  }
@@ -339,7 +339,7 @@ func TnEventsOnce(target tnEmitterLike, event string, options ...interface{}) ch
339
339
  if event != "error" {
340
340
  e.removeListener("error", errorListener)
341
341
  }
342
- ch <- args
342
+ TnAsyncSend(ch, args)
343
343
  }
344
344
  errorListener = func(args ...interface{}) {
345
345
  e.removeListener(event, listener)
package/bin/node/fs.js CHANGED
@@ -787,7 +787,7 @@ func TnFsPromise[T any](work func() T) chan T {
787
787
  TnReject(ch, err)
788
788
  return
789
789
  }
790
- ch <- result
790
+ TnAsyncSend(ch, result)
791
791
  }()
792
792
  return ch
793
793
  }
@@ -0,0 +1,407 @@
1
+ // node:fs watch / watchFile / unwatchFile and fs/promises watch.
2
+ //
3
+ // fs.watch runs on the vendored github.com/fsnotify/fsnotify (inotify, kqueue,
4
+ // ReadDirectoryChangesW; linked only into programs that call fs.watch): a
5
+ // goroutine reads its events and emits 'change' on the event loop. Recursive
6
+ // watches add every subdirectory, and directories created later.
7
+ // fs.watchFile polls stat() like Node does.
8
+ import { defineClass, defineHelper, setResults } from './registry.js';
9
+ const fsWatchHelper = `// node:fs watch (fsnotify)
10
+ type TnFSWatcher struct {
11
+ TnEventEmitter
12
+ asyncCtx TnAsyncContext
13
+ watcher *fsnotify.Watcher
14
+ root string
15
+ isDir bool
16
+ recursive bool
17
+ closed bool
18
+ refd bool
19
+ // fs/promises watch: events go to a channel instead of 'change'
20
+ events chan *TnFsWatchEvent
21
+ }
22
+
23
+ // One change, as fs/promises watch yields it
24
+ type TnFsWatchEvent struct {
25
+ eventType string
26
+ filename string
27
+ }
28
+
29
+ func tnFsWatchIsFunc(v interface{}) bool {
30
+ return v != nil && reflect.ValueOf(v).Kind() == reflect.Func && !reflect.ValueOf(v).IsNil()
31
+ }
32
+
33
+ // rename for entries appearing / disappearing, change for writes and
34
+ // attribute changes (Node's two event types)
35
+ func tnFsWatchType(op fsnotify.Op) string {
36
+ if op.Has(fsnotify.Create) || op.Has(fsnotify.Remove) || op.Has(fsnotify.Rename) {
37
+ return "rename"
38
+ }
39
+ return "change"
40
+ }
41
+
42
+ // options: an encoding string or { persistent, recursive, encoding, signal }
43
+ // events: fs/promises watch's channel (nil for fs.watch)
44
+ func tnFsWatchStart(path string, options interface{}, events chan *TnFsWatchEvent) *TnFSWatcher {
45
+ w := &TnFSWatcher{asyncCtx: TnAsyncSnapshot(), root: filepath.Clean(path), events: events}
46
+ persistent := true
47
+ if _, isString := options.(string); options != nil && !isString {
48
+ if p, ok := TnGet(options, "persistent").(bool); ok {
49
+ persistent = p
50
+ }
51
+ w.recursive, _ = TnGet(options, "recursive").(bool)
52
+ }
53
+ info, err := os.Stat(path)
54
+ if err != nil {
55
+ panic(TnSysError(err, "watch", path))
56
+ }
57
+ w.isDir = info.IsDir()
58
+ watcher, err := fsnotify.NewWatcher()
59
+ if err != nil {
60
+ panic(TnSysError(err, "watch", path))
61
+ }
62
+ w.watcher = watcher
63
+ if err := w.add(w.root); err != nil {
64
+ watcher.Close()
65
+ panic(TnSysError(err, "watch", path))
66
+ }
67
+ if persistent {
68
+ w.refd = true
69
+ TnLoopRef()
70
+ }
71
+ if options != nil {
72
+ if signal, ok := TnGet(options, "signal").(*TnAbortSignal); ok && signal != nil {
73
+ if signal.aborted {
74
+ TnLoopPost(func() { w.close() })
75
+ } else {
76
+ signal.addEventListener("abort", func(ev *TnEvent) { w.close() })
77
+ }
78
+ }
79
+ }
80
+ return w
81
+ }
82
+
83
+ // Adds a directory (and, for recursive watches, its subdirectories)
84
+ func (w *TnFSWatcher) add(dir string) error {
85
+ if !w.recursive || !w.isDir {
86
+ return w.watcher.Add(dir)
87
+ }
88
+ return filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
89
+ if err != nil {
90
+ if p == dir {
91
+ return err
92
+ }
93
+ return nil
94
+ }
95
+ if d.IsDir() {
96
+ return w.watcher.Add(p)
97
+ }
98
+ return nil
99
+ })
100
+ }
101
+
102
+ // The filename Node reports: relative to a watched directory, the file's own
103
+ // name for a watched file
104
+ func (w *TnFSWatcher) filename(name string) string {
105
+ if !w.isDir {
106
+ return filepath.Base(w.root)
107
+ }
108
+ if rel, err := filepath.Rel(w.root, name); err == nil {
109
+ return rel
110
+ }
111
+ return filepath.Base(name)
112
+ }
113
+
114
+ // Reads fsnotify's channels until close(); handle runs on the loop
115
+ func (w *TnFSWatcher) run(handle func(eventType string, filename string), fail func(err error)) {
116
+ go func() {
117
+ for {
118
+ select {
119
+ case ev, ok := <-w.watcher.Events:
120
+ if !ok {
121
+ return
122
+ }
123
+ if w.recursive && ev.Op.Has(fsnotify.Create) {
124
+ if info, err := os.Stat(ev.Name); err == nil && info.IsDir() {
125
+ w.add(ev.Name)
126
+ }
127
+ }
128
+ eventType := tnFsWatchType(ev.Op)
129
+ filename := w.filename(ev.Name)
130
+ TnLoopPost(func() {
131
+ if !w.closed {
132
+ TnAsyncRun(w.asyncCtx, func() { handle(eventType, filename) })
133
+ }
134
+ })
135
+ case err, ok := <-w.watcher.Errors:
136
+ if !ok {
137
+ return
138
+ }
139
+ failure := err
140
+ TnLoopPost(func() {
141
+ if !w.closed {
142
+ TnAsyncRun(w.asyncCtx, func() { fail(failure) })
143
+ }
144
+ })
145
+ }
146
+ }
147
+ }()
148
+ }
149
+
150
+ // fs.watch(filename[, options][, listener])
151
+ func TnFsWatch(path string, rest ...interface{}) *TnFSWatcher {
152
+ var options interface{}
153
+ for _, a := range rest {
154
+ if tnFsWatchIsFunc(a) {
155
+ continue
156
+ }
157
+ options = a
158
+ }
159
+ w := tnFsWatchStart(path, options, nil)
160
+ for _, a := range rest {
161
+ if tnFsWatchIsFunc(a) {
162
+ w.on("change", a)
163
+ }
164
+ }
165
+ w.run(func(eventType string, filename string) {
166
+ w.emit("change", eventType, filename)
167
+ }, func(err error) {
168
+ w.emit("error", TnSysError(err, "watch", path))
169
+ })
170
+ return w
171
+ }
172
+
173
+ func (w *TnFSWatcher) close() {
174
+ w.stop(tnAbortError("The operation was aborted", "AbortError"))
175
+ }
176
+
177
+ // Stops watching; fs/promises watch's iterator rejects with reason
178
+ func (w *TnFSWatcher) stop(reason interface{}) {
179
+ if w.closed {
180
+ return
181
+ }
182
+ w.closed = true
183
+ w.watcher.Close()
184
+ if w.refd {
185
+ w.refd = false
186
+ TnLoopUnref()
187
+ }
188
+ if w.events != nil {
189
+ TnReject(w.events, reason)
190
+ return
191
+ }
192
+ TnLoopPost(func() { w.emit("close") })
193
+ }
194
+
195
+ func (w *TnFSWatcher) ref() *TnFSWatcher {
196
+ if !w.refd && !w.closed {
197
+ w.refd = true
198
+ TnLoopRef()
199
+ }
200
+ return w
201
+ }
202
+
203
+ func (w *TnFSWatcher) unref() *TnFSWatcher {
204
+ if w.refd {
205
+ w.refd = false
206
+ TnLoopUnref()
207
+ }
208
+ return w
209
+ }
210
+
211
+ // fs/promises watch(filename[, options]): an async iterator of
212
+ // { eventType, filename }; aborting the signal rejects it with an AbortError
213
+ func TnFsWatchIterator(path string, options ...interface{}) chan *TnFsWatchEvent {
214
+ var opts interface{}
215
+ if len(options) > 0 {
216
+ opts = options[0]
217
+ }
218
+ ch := make(chan *TnFsWatchEvent, 1024)
219
+ w := tnFsWatchStart(path, opts, ch)
220
+ // The consumer's await keeps the program alive
221
+ w.unref()
222
+ w.run(func(eventType string, filename string) {
223
+ select {
224
+ case ch <- &TnFsWatchEvent{eventType: eventType, filename: filename}:
225
+ default:
226
+ }
227
+ }, func(err error) {
228
+ w.stop(TnSysError(err, "watch", path))
229
+ })
230
+ return ch
231
+ }
232
+
233
+ // fs.watchFile: polls stat() every interval (Node's default 5007 ms) and calls
234
+ // listener(curr, prev) when the file changes; a missing file has zeroed Stats
235
+ type TnStatWatcher struct {
236
+ TnEventEmitter
237
+ asyncCtx TnAsyncContext
238
+ path string
239
+ stop chan struct{}
240
+ stopped bool
241
+ refd bool
242
+ }
243
+
244
+ var tnStatWatchers = map[string]*TnStatWatcher{}
245
+
246
+ func tnStatOrZero(path string) *TnStats {
247
+ info, err := os.Stat(path)
248
+ if err != nil {
249
+ zero := time.UnixMilli(0)
250
+ return &TnStats{atime: zero, mtime: zero, ctime: zero, birthtime: zero}
251
+ }
252
+ return tnStatsOf(info)
253
+ }
254
+
255
+ func tnStatsChanged(a *TnStats, b *TnStats) bool {
256
+ return a.mtimeMs != b.mtimeMs || a.size != b.size || a.mode != b.mode
257
+ }
258
+
259
+ // fs.watchFile(filename[, options], listener)
260
+ func TnWatchFile(path string, rest ...interface{}) *TnStatWatcher {
261
+ interval := 5007.0
262
+ persistent := true
263
+ var listener interface{}
264
+ for _, a := range rest {
265
+ if tnFsWatchIsFunc(a) {
266
+ listener = a
267
+ continue
268
+ }
269
+ if a != nil {
270
+ if n, ok := TnGet(a, "interval").(float64); ok && n > 0 {
271
+ interval = n
272
+ }
273
+ if p, ok := TnGet(a, "persistent").(bool); ok {
274
+ persistent = p
275
+ }
276
+ }
277
+ }
278
+ key := filepath.Clean(path)
279
+ if existing, ok := tnStatWatchers[key]; ok {
280
+ if listener != nil {
281
+ existing.on("change", listener)
282
+ }
283
+ return existing
284
+ }
285
+ s := &TnStatWatcher{asyncCtx: TnAsyncSnapshot(), path: path, stop: make(chan struct{})}
286
+ tnStatWatchers[key] = s
287
+ if listener != nil {
288
+ s.on("change", listener)
289
+ }
290
+ if persistent {
291
+ s.refd = true
292
+ TnLoopRef()
293
+ }
294
+ prev := tnStatOrZero(path)
295
+ go func() {
296
+ ticker := time.NewTicker(max(time.Duration(interval*float64(time.Millisecond)), time.Millisecond))
297
+ defer ticker.Stop()
298
+ for {
299
+ select {
300
+ case <-s.stop:
301
+ return
302
+ case <-ticker.C:
303
+ }
304
+ curr := tnStatOrZero(path)
305
+ if !tnStatsChanged(curr, prev) {
306
+ continue
307
+ }
308
+ before := prev
309
+ prev = curr
310
+ TnLoopPost(func() {
311
+ if !s.stopped {
312
+ TnAsyncRun(s.asyncCtx, func() { s.emit("change", curr, before) })
313
+ }
314
+ })
315
+ }
316
+ }()
317
+ return s
318
+ }
319
+
320
+ func (s *TnStatWatcher) halt() {
321
+ if s.stopped {
322
+ return
323
+ }
324
+ s.stopped = true
325
+ close(s.stop)
326
+ s.unref()
327
+ delete(tnStatWatchers, filepath.Clean(s.path))
328
+ }
329
+
330
+ // fs.unwatchFile(filename[, listener]): removes one listener, or all of them;
331
+ // polling stops once none is left
332
+ func TnUnwatchFile(path string, listener ...interface{}) {
333
+ s, ok := tnStatWatchers[filepath.Clean(path)]
334
+ if !ok {
335
+ return
336
+ }
337
+ if len(listener) > 0 && listener[0] != nil {
338
+ s.removeListener("change", listener[0])
339
+ if s.listenerCount("change") > 0 {
340
+ return
341
+ }
342
+ }
343
+ s.halt()
344
+ }
345
+
346
+ func (s *TnStatWatcher) ref() *TnStatWatcher {
347
+ if !s.refd && !s.stopped {
348
+ s.refd = true
349
+ TnLoopRef()
350
+ }
351
+ return s
352
+ }
353
+
354
+ func (s *TnStatWatcher) unref() *TnStatWatcher {
355
+ if s.refd {
356
+ s.refd = false
357
+ TnLoopUnref()
358
+ }
359
+ return s
360
+ }`;
361
+ const EMITTER_METHODS = 'on=*TnEventEmitter; once=*TnEventEmitter; addListener=*TnEventEmitter; off=*TnEventEmitter; removeListener=*TnEventEmitter; removeAllListeners=*TnEventEmitter; emit=bool; listenerCount=float64';
362
+ export function registerFsWatch(r) {
363
+ defineHelper(r, 'nodeFsWatch', ['github.com/fsnotify/fsnotify', 'io/fs', 'os', 'path/filepath', 'reflect', 'time'], ['nodeFs', 'nodeEvents', 'eventLoop', 'promise', 'dynamic', 'nodeInvoke'], fsWatchHelper);
364
+ const use = () => r.helper('nodeFsWatch');
365
+ defineClass(r, 'fs.FSWatcher', '*TnFSWatcher', 'class', `${EMITTER_METHODS}; close=; ref=*TnFSWatcher; unref=*TnFSWatcher`, '', '', '');
366
+ defineClass(r, 'fs.StatWatcher', '*TnStatWatcher', 'class', `${EMITTER_METHODS}; ref=*TnStatWatcher; unref=*TnStatWatcher`, '', '', '');
367
+ defineClass(r, 'fs/promises.FileChangeInfo', '*TnFsWatchEvent', 'class', '', 'eventType=string; filename=string', '', '');
368
+ // Listener parameters: change(eventType, filename) / error(err) / watchFile's (curr, prev)
369
+ const watchListener = (nodes) => {
370
+ const event = nodes[0];
371
+ const name = event && event.kind === 'StringLiteral' ? String(event.text) : '';
372
+ if (name === 'change')
373
+ return ['string', 'string'];
374
+ if (name === 'error')
375
+ return ['interface{}'];
376
+ return [];
377
+ };
378
+ const statListener = (nodes) => {
379
+ const event = nodes[0];
380
+ const name = event && event.kind === 'StringLiteral' ? String(event.text) : '';
381
+ return name === 'change' ? ['*TnStats', '*TnStats'] : [];
382
+ };
383
+ for (const method of ['on', 'once', 'addListener']) {
384
+ r.paramTypers[`fs.FSWatcher#${method}`] = watchListener;
385
+ r.paramTypers[`fs.StatWatcher#${method}`] = statListener;
386
+ }
387
+ r.functions['fs.watch'] = (c) => {
388
+ use();
389
+ return `TnFsWatch(${c.args.join(', ')})`;
390
+ };
391
+ r.paramTypers['fs.watch'] = (_n) => ['string', 'string'];
392
+ r.functions['fs.watchFile'] = (c) => {
393
+ use();
394
+ return `TnWatchFile(${c.args.join(', ')})`;
395
+ };
396
+ r.paramTypers['fs.watchFile'] = (_n) => ['*TnStats', '*TnStats'];
397
+ r.functions['fs.unwatchFile'] = (c) => {
398
+ use();
399
+ return `TnUnwatchFile(${c.args.join(', ')})`;
400
+ };
401
+ setResults(r, 'fs', 'watch=*TnFSWatcher; watchFile=*TnStatWatcher; unwatchFile=');
402
+ r.functions['fs/promises.watch'] = (c) => {
403
+ use();
404
+ return `TnFsWatchIterator(${c.args.join(', ')})`;
405
+ };
406
+ r.results['fs/promises.watch'] = 'chan *TnFsWatchEvent';
407
+ }
package/bin/node/http2.js CHANGED
@@ -25,6 +25,8 @@ type TnHttp2Session struct {
25
25
  active int
26
26
  nextID float64
27
27
  socket *TnSocket
28
+
29
+ connectEmitted bool
28
30
  }
29
31
 
30
32
  func (s *TnHttp2Session) Get_closed() bool { return s.closed }
@@ -51,6 +53,21 @@ func (s *TnHttp2Session) unref() *TnHttp2Session {
51
53
 
52
54
  func (s *TnHttp2Session) setTimeout(ms float64, cb ...interface{}) *TnHttp2Session { return s }
53
55
 
56
+ // 'connect' fires once, when the session's first connection is up; guarded on
57
+ // the loop so the eager probe dial and the transport's own dials can both call
58
+ // it without racing
59
+ func (s *TnHttp2Session) emitConnect(conn net.Conn) {
60
+ TnLoopPost(func() {
61
+ if s.connectEmitted || s.destroyed {
62
+ return
63
+ }
64
+ s.connectEmitted = true
65
+ s.socket = tnInfoSocket(conn.LocalAddr(), conn.RemoteAddr().String())
66
+ s.socket.encrypted = s.encrypted
67
+ s.emit("connect", s, s.socket)
68
+ })
69
+ }
70
+
54
71
  func (s *TnHttp2Session) maybeFinish() {
55
72
  if !s.closed || s.active > 0 || s.finished {
56
73
  return
@@ -140,6 +157,17 @@ func TnHttp2Connect(authority interface{}, args ...interface{}) *TnHttp2Session
140
157
  t.Protocols = protocols
141
158
  s.transport = t
142
159
  s.client = &http.Client{Transport: t, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
160
+ // The transport dials through here (https too, there is no custom DialTLS),
161
+ // so 'connect' is posted before that request's response can be
162
+ dialer := &net.Dialer{Timeout: 10 * time.Second}
163
+ t.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
164
+ conn, err := dialer.DialContext(ctx, network, addr)
165
+ if err != nil {
166
+ return nil, err
167
+ }
168
+ s.emitConnect(conn)
169
+ return conn, nil
170
+ }
143
171
  if listener != nil {
144
172
  s.TnEventEmitter.once("connect", listener)
145
173
  }
@@ -149,6 +177,9 @@ func TnHttp2Connect(authority interface{}, args ...interface{}) *TnHttp2Session
149
177
  conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), 10*time.Second)
150
178
  TnLoopPost(func() {
151
179
  if err != nil {
180
+ if s.connectEmitted || s.destroyed {
181
+ return
182
+ }
152
183
  p, _ := strconv.ParseFloat(port, 64)
153
184
  target := host
154
185
  if ip := tnDialedIP(err); ip != "" {
@@ -157,12 +188,8 @@ func TnHttp2Connect(authority interface{}, args ...interface{}) *TnHttp2Session
157
188
  s.destroy(TnNetError(err, "connect", target, p))
158
189
  return
159
190
  }
160
- s.socket = tnInfoSocket(conn.LocalAddr(), conn.RemoteAddr().String())
161
- s.socket.encrypted = s.encrypted
191
+ s.emitConnect(conn)
162
192
  conn.Close()
163
- if !s.destroyed {
164
- s.emit("connect", s, s.socket)
165
- }
166
193
  })
167
194
  }()
168
195
  return s
@@ -617,7 +644,7 @@ const HTTP2_NUMBERS = {
617
644
  };
618
645
  export function registerHttp2(r) {
619
646
  defineModule(r, 'http2');
620
- defineHelper(r, 'nodeHttp2', ['bytes', 'crypto/tls', 'fmt', 'io', 'net', 'net/http', 'net/url', 'os', 'sort', 'strconv', 'strings', 'time'], ['nodeHttp', 'nodeNet', 'netErrors', 'nodeStream', 'nodeEvents', 'eventLoop', 'nodeInvoke', 'dynamic', 'orderedMap', 'tlsConfig', 'fsErrors'], http2Helper);
647
+ defineHelper(r, 'nodeHttp2', ['bytes', 'context', 'crypto/tls', 'fmt', 'io', 'net', 'net/http', 'net/url', 'os', 'sort', 'strconv', 'strings', 'time'], ['nodeHttp', 'nodeNet', 'netErrors', 'nodeStream', 'nodeEvents', 'eventLoop', 'nodeInvoke', 'dynamic', 'orderedMap', 'tlsConfig', 'fsErrors'], http2Helper);
621
648
  const use = () => r.helper('nodeHttp2');
622
649
  defineClass(r, 'http2.Http2Stream', '*TnHttp2Stream', 'class', STREAM_METHODS + '; respond=; respondWithFile=; close=; pushStream=; additionalHeaders=', '', STREAM_GETTERS + '; id=float64; session=*TnHttp2Session; sentHeaders=*TnMap[string, interface{}]; headersSent=bool; pushAllowed=bool; endAfterHeaders=bool; rstCode=float64; aborted=bool', '');
623
650
  for (const name of ['ServerHttp2Stream', 'ClientHttp2Stream'])
@@ -104,7 +104,7 @@ func (rl *TnReadline) questionAsync(query string, options ...interface{}) chan s
104
104
  rl.writeOut(query)
105
105
  rl.pendingQuestion = func(answer string) {
106
106
  TnLoopUnref()
107
- ch <- answer
107
+ TnAsyncSend(ch, answer)
108
108
  }
109
109
  return ch
110
110
  }
@@ -39,7 +39,8 @@ export function createNodeRegistry() {
39
39
  temp: (prefix) => prefix,
40
40
  typeOf: (_node) => '',
41
41
  visit: (_node) => '',
42
- categoryOf: (_node) => ''
42
+ categoryOf: (_node) => '',
43
+ isArrayBuffer: (_node) => false
43
44
  };
44
45
  return registry;
45
46
  }
@@ -1027,14 +1027,13 @@ func TnCreateWriteStream(path string, options ...interface{}) *TnStream {
1027
1027
  const zlibStreamHelper = `// zlib streams: Transforms buffering the input, (de)compressed at the end
1028
1028
  func TnZlibStream(format string, decompress bool, options ...interface{}) *TnStream {
1029
1029
  s := TnNewTransform()
1030
- level := tnZlibLevel(options)
1031
1030
  input := []byte{}
1032
1031
  s.goTransform = func(chunk []byte) { input = append(input, chunk...) }
1033
1032
  s.goFlush = func() []byte {
1034
1033
  if decompress {
1035
1034
  return tnDecompress(format, input)
1036
1035
  }
1037
- return tnCompress(format, input, level)
1036
+ return tnCompress(format, input, options)
1038
1037
  }
1039
1038
  return s
1040
1039
  }`;
@@ -1185,12 +1184,16 @@ func tnStdin() *bufio.Reader {
1185
1184
  createInflate: 'inflate:true',
1186
1185
  createDeflateRaw: 'deflateRaw:false',
1187
1186
  createInflateRaw: 'inflateRaw:true',
1188
- createUnzip: 'unzip:true'
1187
+ createUnzip: 'unzip:true',
1188
+ createBrotliCompress: 'brotli:false',
1189
+ createBrotliDecompress: 'brotli:true'
1189
1190
  };
1190
1191
  for (const name of Object.keys(zlibStreams)) {
1191
1192
  const parts = zlibStreams[name].split(':');
1192
1193
  r.functions[`zlib.${name}`] = (call) => {
1193
1194
  r.helper('zlibStreams');
1195
+ if (parts[0] === 'brotli')
1196
+ r.helper('nodeBrotli');
1194
1197
  const options = call.args.length > 0 ? `, ${call.args[0]}` : '';
1195
1198
  return `TnZlibStream(${JSON.stringify(parts[0])}, ${parts[1]}${options})`;
1196
1199
  };
@@ -144,7 +144,7 @@ func TnTimeoutPromise[T any](ms float64, value T, options ...interface{}) chan T
144
144
  timer = TnSetTimeout(ms, func() {
145
145
  if !settled {
146
146
  settled = true
147
- ch <- value
147
+ TnAsyncSend(ch, value)
148
148
  }
149
149
  })
150
150
  if signal != nil {