typenative 0.4.0 → 0.5.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 (167) hide show
  1. package/.github/workflows/ci.yml +2 -0
  2. package/CHANGELOG.md +372 -0
  3. package/CONTRIBUTION.md +1 -1
  4. package/README.md +62 -22
  5. package/ROUND2-HANDOFF.md +200 -0
  6. package/bin/cli.js +2 -0
  7. package/bin/go/bridge.js +74 -14
  8. package/bin/go/convert.js +48 -0
  9. package/bin/go/metadata.js +13 -4
  10. package/bin/go/overrides.js +4 -6
  11. package/bin/go/stdlib.generated.js +2 -0
  12. package/bin/index.js +130 -2
  13. package/bin/main.js +2 -0
  14. package/bin/node/assert.js +2 -2
  15. package/bin/node/async_hooks.js +1 -1
  16. package/bin/node/buffer.js +16 -5
  17. package/bin/node/child_process.js +57 -9
  18. package/bin/node/cluster.js +44 -6
  19. package/bin/node/core.js +1 -1
  20. package/bin/node/crypto.js +205 -4
  21. package/bin/node/crypto_keys.js +21 -21
  22. package/bin/node/dgram.js +231 -7
  23. package/bin/node/diagnostics_channel.js +3 -3
  24. package/bin/node/dns.js +472 -9
  25. package/bin/node/errno_tables.js +445 -0
  26. package/bin/node/events.js +3 -3
  27. package/bin/node/fetch.js +2 -2
  28. package/bin/node/fs.js +24 -17
  29. package/bin/node/fs_watch.js +5 -5
  30. package/bin/node/http.js +131 -33
  31. package/bin/node/http2.js +7 -4
  32. package/bin/node/module_v8.js +142 -0
  33. package/bin/node/net.js +17 -14
  34. package/bin/node/path.js +17 -3
  35. package/bin/node/process.js +274 -9
  36. package/bin/node/readline.js +272 -1
  37. package/bin/node/registry.js +5 -1
  38. package/bin/node/sqlite.js +65 -17
  39. package/bin/node/stream.js +220 -22
  40. package/bin/node/stream_web.js +10 -10
  41. package/bin/node/system_extra.js +3 -3
  42. package/bin/node/test.js +834 -234
  43. package/bin/node/test_coverage.js +187 -0
  44. package/bin/node/test_report.js +1392 -0
  45. package/bin/node/test_run.js +575 -0
  46. package/bin/node/timers.js +4 -4
  47. package/bin/node/tls.js +5 -5
  48. package/bin/node/url.js +23 -5
  49. package/bin/node/util.js +49 -8
  50. package/bin/node/util_extra.js +13 -37
  51. package/bin/node/webview.js +654 -0
  52. package/bin/node/worker_threads.js +80 -20
  53. package/bin/node/zlib.js +3 -3
  54. package/bin/parse-node.js +4 -0
  55. package/bin/transpiler.js +14457 -1723
  56. package/bin/typecheck-node.js +1 -0
  57. package/bin/version.js +1 -1
  58. package/conformance.md +1153 -884
  59. package/examples/README.md +47 -10
  60. package/examples/desktop-notes/README.md +108 -0
  61. package/examples/desktop-notes/bench.mjs +125 -0
  62. package/examples/desktop-notes/main.ts +131 -0
  63. package/examples/desktop-notes/package-lock.json +726 -0
  64. package/examples/desktop-notes/package.json +9 -0
  65. package/examples/desktop-notes/ui.ts +176 -0
  66. package/examples/dupe-finder/README.md +76 -0
  67. package/examples/dupe-finder/bench.mjs +120 -0
  68. package/examples/dupe-finder/main.ts +87 -0
  69. package/examples/json-server/README.md +31 -29
  70. package/examples/json-server/bench.mjs +130 -38
  71. package/examples/mandelbrot-png/README.md +65 -0
  72. package/examples/mandelbrot-png/bench.mjs +95 -0
  73. package/examples/mandelbrot-png/main.ts +98 -0
  74. package/examples/mandelbrot-png/preview.png +0 -0
  75. package/examples/marked-cli/README.md +159 -0
  76. package/examples/marked-cli/bench.mjs +178 -0
  77. package/examples/marked-cli/main.ts +292 -0
  78. package/examples/marked-cli/parity.mjs +185 -0
  79. package/examples/marked-cli/vendor/marked/LICENSE +44 -0
  80. package/examples/marked-cli/vendor/marked/VENDOR.md +26 -0
  81. package/examples/todo-cli/README.md +69 -0
  82. package/examples/todo-cli/bench.mjs +89 -0
  83. package/examples/todo-cli/main.ts +92 -0
  84. package/examples/yaml-cli/README.md +136 -0
  85. package/examples/yaml-cli/bench.mjs +265 -0
  86. package/examples/yaml-cli/main.ts +29 -0
  87. package/examples/yaml-cli/parity.mjs +156 -0
  88. package/examples/yaml-cli/vendor/yaml/LICENSE +13 -0
  89. package/examples/yaml-cli/vendor/yaml/VENDOR.md +25 -0
  90. package/govendor/github.com/jchv/go-webview2/LICENSE +22 -0
  91. package/govendor/github.com/jchv/go-webview2/README.md +21 -0
  92. package/govendor/github.com/jchv/go-webview2/common.go +84 -0
  93. package/govendor/github.com/jchv/go-webview2/go.mod +3 -0
  94. package/govendor/github.com/jchv/go-webview2/internal/w32/w32.go +194 -0
  95. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_386.go +14 -0
  96. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_64bit.go +15 -0
  97. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_COLOR.go +8 -0
  98. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND.go +9 -0
  99. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_KEY_EVENT_KIND.go +10 -0
  100. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_MOVE_FOCUS_REASON.go +9 -0
  101. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_PHYSICAL_KEY_STATUS.go +10 -0
  102. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_WEB_RESOURCE_CONTEXT.go +23 -0
  103. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventArgs.go +78 -0
  104. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventHandler.go +52 -0
  105. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller.go +132 -0
  106. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller2.go +74 -0
  107. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2CreateCoreWebView2ControllerCompletedHandler.go +48 -0
  108. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventArgs.go +17 -0
  109. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventHandler.go +48 -0
  110. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Settings.go +270 -0
  111. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequest.go +43 -0
  112. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventArgs.go +51 -0
  113. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventHandler.go +48 -0
  114. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceResponse.go +21 -0
  115. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_2.go +21 -0
  116. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_3.go +60 -0
  117. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebViewSettings.go +396 -0
  118. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium.go +361 -0
  119. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_386.go +24 -0
  120. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_amd64.go +22 -0
  121. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_arm64.go +26 -0
  122. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc.go +13 -0
  123. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go17.go +51 -0
  124. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go18.go +16 -0
  125. package/govendor/github.com/jchv/go-webview2/pkg/edge/corewebview2.go +411 -0
  126. package/govendor/github.com/jchv/go-webview2/pkg/edge/guid.go +223 -0
  127. package/govendor/github.com/jchv/go-webview2/webview.go +482 -0
  128. package/govendor/github.com/jchv/go-webview2/webviewloader/README.md +3 -0
  129. package/govendor/github.com/jchv/go-webview2/webviewloader/module.go +153 -0
  130. package/govendor/github.com/jchv/go-webview2/webviewloader/module_386.go +6 -0
  131. package/govendor/github.com/jchv/go-webview2/webviewloader/module_amd64.go +6 -0
  132. package/govendor/github.com/jchv/go-webview2/webviewloader/module_arm64.go +6 -0
  133. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/arm64/WebView2Loader.dll +0 -0
  134. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x64/WebView2Loader.dll +0 -0
  135. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x86/WebView2Loader.dll +0 -0
  136. package/govendor/github.com/jchv/go-winloader/LICENSE.md +7 -0
  137. package/govendor/github.com/jchv/go-winloader/README.md +124 -0
  138. package/govendor/github.com/jchv/go-winloader/common.go +11 -0
  139. package/govendor/github.com/jchv/go-winloader/go.mod +3 -0
  140. package/govendor/github.com/jchv/go-winloader/internal/loader/loader.go +25 -0
  141. package/govendor/github.com/jchv/go-winloader/internal/loader/machine.go +53 -0
  142. package/govendor/github.com/jchv/go-winloader/internal/memloader/cache.go +42 -0
  143. package/govendor/github.com/jchv/go-winloader/internal/memloader/loader.go +253 -0
  144. package/govendor/github.com/jchv/go-winloader/internal/pe/export.go +76 -0
  145. package/govendor/github.com/jchv/go-winloader/internal/pe/format.go +522 -0
  146. package/govendor/github.com/jchv/go-winloader/internal/pe/import.go +106 -0
  147. package/govendor/github.com/jchv/go-winloader/internal/pe/module.go +91 -0
  148. package/govendor/github.com/jchv/go-winloader/internal/pe/reloc.go +177 -0
  149. package/govendor/github.com/jchv/go-winloader/internal/pe/util.go +40 -0
  150. package/govendor/github.com/jchv/go-winloader/internal/vmem/common.go +55 -0
  151. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_other.go +71 -0
  152. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_windows.go +179 -0
  153. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_other.go +17 -0
  154. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_windows.go +73 -0
  155. package/govendor/github.com/jchv/go-winloader/internal/winloader/loader_windows.go +64 -0
  156. package/govendor/github.com/jchv/go-winloader/internal/winloader/machine_windows.go +32 -0
  157. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_386.go +9 -0
  158. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_amd64.go +9 -0
  159. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_arm64.go +9 -0
  160. package/govendor/github.com/jchv/go-winloader/loader_other.go +24 -0
  161. package/govendor/github.com/jchv/go-winloader/loader_windows.go +33 -0
  162. package/govendor/manifest.txt +3 -1
  163. package/package.json +1 -1
  164. package/tsparser/main.go +4 -0
  165. package/types/typenative-go.d.ts +23 -0
  166. package/types/typenative-npm.d.ts +359 -7
  167. package/types/typenative.d.ts +283 -42
@@ -0,0 +1,654 @@
1
+ // @webviewjs/webview: native app windows that render a web page. Programs use
2
+ // the npm package's API, so they run unchanged under Node.js (the real package)
3
+ // and compiled (this subset). Windows embeds the system WebView2 through the
4
+ // pure-Go go-webview2 (govendor/); other platforms, and Windows without the
5
+ // WebView2 runtime, open Chrome, Edge or Chromium as an app window (no cgo).
6
+ //
7
+ // A window's UI loop never runs JS: it lives on its own goroutine, which reaches
8
+ // the program through TnLoopPost. A close is therefore reported as the window
9
+ // goes away, so the 'close' event can't be cancelled.
10
+ import { defineClass, defineHelper, defineModule } from './registry.js';
11
+ const webviewHelper = `// @webviewjs/webview: application, windows and webviews
12
+ type TnWebviewEvent struct {
13
+ event string
14
+ }
15
+
16
+ type TnWebviewContext struct {
17
+ dir string
18
+ }
19
+
20
+ // What a window runs on: an embedded webview, or a browser app window
21
+ type tnWebviewBackend interface {
22
+ navigate(url string)
23
+ setHtml(html string)
24
+ eval(js string)
25
+ reload()
26
+ setTitle(title string)
27
+ close()
28
+ }
29
+
30
+ // The ref a running app holds keeps the process alive until its last window closes
31
+ type TnWebviewApp struct {
32
+ TnEventEmitter
33
+ windows []*TnWebviewWindow
34
+ running bool
35
+ ready bool
36
+ exited bool
37
+ held bool
38
+ waiters []chan struct{}
39
+ }
40
+
41
+ type TnWebviewWindow struct {
42
+ TnEventEmitter
43
+ app *TnWebviewApp
44
+ title string
45
+ width uint
46
+ height uint
47
+ logical bool
48
+ resizable bool
49
+ webview *TnWebview
50
+ backend tnWebviewBackend
51
+ scripted bool
52
+ closed bool
53
+ }
54
+
55
+ type TnWebview struct {
56
+ window *TnWebviewWindow
57
+ url string
58
+ html string
59
+ dir string
60
+ devtools bool
61
+ }
62
+
63
+ func tnWebviewString(options interface{}, key string) string {
64
+ switch v := TnGetValue(options, key).(type) {
65
+ case string:
66
+ return v
67
+ case *string:
68
+ if v != nil {
69
+ return *v
70
+ }
71
+ }
72
+ return ""
73
+ }
74
+
75
+ func tnWebviewBool(options interface{}, key string, def bool) bool {
76
+ switch v := TnGetValue(options, key).(type) {
77
+ case bool:
78
+ return v
79
+ case *bool:
80
+ if v != nil {
81
+ return *v
82
+ }
83
+ }
84
+ return def
85
+ }
86
+
87
+ func tnWebviewSize(options interface{}, key string, def uint) uint {
88
+ switch v := TnGetValue(options, key).(type) {
89
+ case float64:
90
+ return uint(v)
91
+ case *float64:
92
+ if v != nil {
93
+ return uint(*v)
94
+ }
95
+ }
96
+ return def
97
+ }
98
+
99
+ func TnNewWebviewApp() *TnWebviewApp {
100
+ return &TnWebviewApp{}
101
+ }
102
+
103
+ func (a *TnWebviewApp) createWebContext(options ...interface{}) *TnWebviewContext {
104
+ c := &TnWebviewContext{}
105
+ if len(options) > 0 && options[0] != nil {
106
+ c.dir = tnWebviewString(options[0], "dataDirectory")
107
+ }
108
+ return c
109
+ }
110
+
111
+ func (a *TnWebviewApp) createBrowserWindow(options ...interface{}) *TnWebviewWindow {
112
+ w := &TnWebviewWindow{app: a, width: 800, height: 600, resizable: true}
113
+ if len(options) > 0 && options[0] != nil {
114
+ w.title = tnWebviewString(options[0], "title")
115
+ w.width = tnWebviewSize(options[0], "width", w.width)
116
+ w.height = tnWebviewSize(options[0], "height", w.height)
117
+ w.logical = tnWebviewBool(options[0], "logical", false)
118
+ w.resizable = tnWebviewBool(options[0], "resizable", true)
119
+ }
120
+ a.windows = append(a.windows, w)
121
+ return w
122
+ }
123
+
124
+ func (a *TnWebviewApp) isReady() bool {
125
+ return a.ready
126
+ }
127
+
128
+ // Starts the app: windows open now, or as soon as they get a webview
129
+ func (a *TnWebviewApp) run() {
130
+ if a.running {
131
+ return
132
+ }
133
+ a.running = true
134
+ a.held = true
135
+ TnLoopRef()
136
+ TnLoopPost(func() {
137
+ a.ready = true
138
+ a.emit("ready", &TnWebviewEvent{event: "ready"})
139
+ for _, ch := range a.waiters {
140
+ TnAsyncClose(ch)
141
+ }
142
+ a.waiters = nil
143
+ })
144
+ for _, w := range a.windows {
145
+ w.open()
146
+ }
147
+ }
148
+
149
+ func (a *TnWebviewApp) whenReady() chan struct{} {
150
+ ch := make(chan struct{})
151
+ if a.ready {
152
+ close(ch)
153
+ return ch
154
+ }
155
+ a.waiters = append(a.waiters, ch)
156
+ a.run()
157
+ return ch
158
+ }
159
+
160
+ // Closes every window; unlike a last window closing, this emits nothing
161
+ func (a *TnWebviewApp) exit() {
162
+ a.exited = true
163
+ for _, w := range a.windows {
164
+ w.close()
165
+ }
166
+ a.release()
167
+ }
168
+
169
+ func (a *TnWebviewApp) release() {
170
+ if a.held {
171
+ a.held = false
172
+ TnLoopUnref()
173
+ }
174
+ }
175
+
176
+ func (a *TnWebviewApp) anyOpen() bool {
177
+ for _, w := range a.windows {
178
+ if w.backend != nil && !w.closed {
179
+ return true
180
+ }
181
+ }
182
+ return false
183
+ }
184
+
185
+ func (w *TnWebviewWindow) createWebview(options ...interface{}) *TnWebview {
186
+ if w.webview != nil {
187
+ panic(TnNodeError("Error", "ERR_WEBVIEW_MULTIPLE", "A window holds one webview"))
188
+ }
189
+ v := &TnWebview{window: w}
190
+ if len(options) > 0 && options[0] != nil {
191
+ v.url = tnWebviewString(options[0], "url")
192
+ v.html = tnWebviewString(options[0], "html")
193
+ v.devtools = tnWebviewBool(options[0], "enableDevtools", false)
194
+ if c, ok := TnGetValue(options[0], "webContext").(*TnWebviewContext); ok && c != nil {
195
+ v.dir = c.dir
196
+ }
197
+ }
198
+ w.webview = v
199
+ if w.app.running {
200
+ w.open()
201
+ }
202
+ return v
203
+ }
204
+
205
+ func (w *TnWebviewWindow) open() {
206
+ if w.webview == nil || w.backend != nil || w.closed {
207
+ return
208
+ }
209
+ w.backend = tnWebviewOpen(w, func() { TnLoopPost(w.finished) })
210
+ }
211
+
212
+ func (w *TnWebviewWindow) setTitle(title string) {
213
+ w.title = title
214
+ if w.backend != nil && !w.closed {
215
+ w.backend.setTitle(title)
216
+ }
217
+ }
218
+
219
+ func (w *TnWebviewWindow) close() {
220
+ if w.closed {
221
+ return
222
+ }
223
+ if w.backend == nil {
224
+ w.closed = true
225
+ return
226
+ }
227
+ w.scripted = true
228
+ w.backend.close()
229
+ }
230
+
231
+ // (loop task) The window is gone. As in the npm package, only a close the user
232
+ // asked for emits the first two events.
233
+ func (w *TnWebviewWindow) finished() {
234
+ w.closed = true
235
+ a := w.app
236
+ if !w.scripted {
237
+ w.emit("close", &TnWebviewEvent{event: "close"})
238
+ a.emit("window-close-requested", &TnWebviewEvent{event: "window-close-requested"})
239
+ }
240
+ if a.anyOpen() {
241
+ return
242
+ }
243
+ if !a.exited {
244
+ a.emit("application-close-requested", &TnWebviewEvent{event: "application-close-requested"})
245
+ }
246
+ a.release()
247
+ }
248
+
249
+ func (v *TnWebview) live() bool {
250
+ return v.window.backend != nil && !v.window.closed
251
+ }
252
+
253
+ func (v *TnWebview) loadUrl(url string) {
254
+ v.url, v.html = url, ""
255
+ if v.live() {
256
+ v.window.backend.navigate(url)
257
+ }
258
+ }
259
+
260
+ func (v *TnWebview) loadHtml(html string) {
261
+ v.url, v.html = "", html
262
+ if v.live() {
263
+ v.window.backend.setHtml(html)
264
+ }
265
+ }
266
+
267
+ func (v *TnWebview) evaluateScript(js string) {
268
+ if v.live() {
269
+ v.window.backend.eval(js)
270
+ }
271
+ }
272
+
273
+ func (v *TnWebview) reload() {
274
+ if v.live() {
275
+ v.window.backend.reload()
276
+ }
277
+ }
278
+
279
+ // The browser app window: the program can't reach into it, so only its own
280
+ // page and its closing are available
281
+ type tnWebviewBrowser struct {
282
+ kill func()
283
+ }
284
+
285
+ func tnWebviewUnsupported(call string) *TnError {
286
+ return TnNodeError("Error", "ERR_WEBVIEW_UNSUPPORTED", call+" needs an embedded webview, and this window is a browser app window")
287
+ }
288
+
289
+ func (b *tnWebviewBrowser) navigate(url string) { panic(tnWebviewUnsupported("loadUrl")) }
290
+ func (b *tnWebviewBrowser) setHtml(html string) { panic(tnWebviewUnsupported("loadHtml")) }
291
+ func (b *tnWebviewBrowser) eval(js string) { panic(tnWebviewUnsupported("evaluateScript")) }
292
+ func (b *tnWebviewBrowser) reload() { panic(tnWebviewUnsupported("reload")) }
293
+ func (b *tnWebviewBrowser) setTitle(title string) {}
294
+ func (b *tnWebviewBrowser) close() { b.kill() }
295
+
296
+ func tnWebviewFindBrowser() string {
297
+ var candidates []string
298
+ switch runtime.GOOS {
299
+ case "windows":
300
+ for _, root := range []string{os.Getenv("ProgramFiles(x86)"), os.Getenv("ProgramFiles"), os.Getenv("LocalAppData")} {
301
+ candidates = append(candidates, filepath.Join(root, "Microsoft", "Edge", "Application", "msedge.exe"))
302
+ candidates = append(candidates, filepath.Join(root, "Google", "Chrome", "Application", "chrome.exe"))
303
+ }
304
+ case "darwin":
305
+ home, _ := os.UserHomeDir()
306
+ for _, root := range []string{"/Applications", filepath.Join(home, "Applications")} {
307
+ candidates = append(candidates, filepath.Join(root, "Google Chrome.app", "Contents", "MacOS", "Google Chrome"))
308
+ candidates = append(candidates, filepath.Join(root, "Microsoft Edge.app", "Contents", "MacOS", "Microsoft Edge"))
309
+ candidates = append(candidates, filepath.Join(root, "Chromium.app", "Contents", "MacOS", "Chromium"))
310
+ }
311
+ default:
312
+ for _, name := range []string{"google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge", "microsoft-edge-stable"} {
313
+ if found, err := exec.LookPath(name); err == nil {
314
+ return found
315
+ }
316
+ }
317
+ }
318
+ for _, path := range candidates {
319
+ if info, err := os.Stat(path); err == nil && !info.IsDir() {
320
+ return path
321
+ }
322
+ }
323
+ return ""
324
+ }
325
+
326
+ func tnWebviewOpenBrowser(w *TnWebviewWindow, closed func()) tnWebviewBackend {
327
+ browser := tnWebviewFindBrowser()
328
+ if browser == "" {
329
+ panic(TnNodeError("Error", "ERR_WEBVIEW_NO_BROWSER", "No webview to open a window with: install Chrome, Edge or Chromium"))
330
+ }
331
+ var removals []string
332
+ target := w.webview.url
333
+ if w.webview.html != "" {
334
+ // A file, since a page in a data: URL is limited by the command line's length
335
+ page, err := os.CreateTemp("", "tnwebview-*.html")
336
+ if err != nil {
337
+ panic(TnNewError(err.Error()))
338
+ }
339
+ page.WriteString(w.webview.html)
340
+ page.Close()
341
+ removals = append(removals, page.Name())
342
+ slashed := filepath.ToSlash(page.Name())
343
+ if !strings.HasPrefix(slashed, "/") {
344
+ slashed = "/" + slashed
345
+ }
346
+ target = (&tnurl.URL{Scheme: "file", Path: slashed}).String()
347
+ }
348
+ if target == "" {
349
+ target = "about:blank"
350
+ }
351
+ // A profile of its own: the browser process then lives as long as this window,
352
+ // instead of handing it to a browser that is already running
353
+ var profile string
354
+ if w.webview.dir != "" {
355
+ profile = filepath.Join(w.webview.dir, "Browser")
356
+ } else {
357
+ dir, err := os.MkdirTemp("", "tnwebview-")
358
+ if err != nil {
359
+ panic(TnNewError(err.Error()))
360
+ }
361
+ profile = dir
362
+ removals = append(removals, dir)
363
+ }
364
+ cmd := exec.Command(browser,
365
+ "--app="+target,
366
+ "--user-data-dir="+profile,
367
+ fmt.Sprintf("--window-size=%d,%d", w.width, w.height),
368
+ "--no-first-run",
369
+ "--no-default-browser-check",
370
+ // An app window, not a browser session: no account sign-in or translate prompts
371
+ "--disable-sync",
372
+ "--disable-features=msImplicitSignin,Translate")
373
+ wait, kill, err := tnWebviewStartBrowser(cmd)
374
+ if err != nil {
375
+ panic(TnNewError(err.Error()))
376
+ }
377
+ go func() {
378
+ wait()
379
+ for _, path := range removals {
380
+ os.RemoveAll(path)
381
+ }
382
+ closed()
383
+ }()
384
+ return &tnWebviewBrowser{kill: kill}
385
+ }`;
386
+ // WebView2 on a locked thread of its own, one per window. Calls from the program
387
+ // wait in pending until the window exists, then go through its message loop.
388
+ const webviewWindowsHelper = `type tnWebview2 struct {
389
+ mu sync.Mutex
390
+ view webview2.WebView
391
+ pending []func(view webview2.WebView)
392
+ }
393
+
394
+ func (b *tnWebview2) do(fn func(view webview2.WebView)) {
395
+ b.mu.Lock()
396
+ defer b.mu.Unlock()
397
+ if b.view == nil {
398
+ b.pending = append(b.pending, fn)
399
+ return
400
+ }
401
+ view := b.view
402
+ view.Dispatch(func() { fn(view) })
403
+ }
404
+
405
+ func (b *tnWebview2) navigate(url string) {
406
+ b.do(func(view webview2.WebView) { view.Navigate(url) })
407
+ }
408
+
409
+ func (b *tnWebview2) setHtml(html string) {
410
+ b.do(func(view webview2.WebView) { view.SetHtml(html) })
411
+ }
412
+
413
+ func (b *tnWebview2) eval(js string) {
414
+ b.do(func(view webview2.WebView) { view.Eval(js) })
415
+ }
416
+
417
+ func (b *tnWebview2) reload() {
418
+ b.do(func(view webview2.WebView) { view.Eval("location.reload()") })
419
+ }
420
+
421
+ func (b *tnWebview2) setTitle(title string) {
422
+ b.do(func(view webview2.WebView) { view.SetTitle(title) })
423
+ }
424
+
425
+ func (b *tnWebview2) close() {
426
+ b.do(func(view webview2.WebView) { view.Destroy() })
427
+ }
428
+
429
+ // Sharp text on scaled displays: pixels per logical pixel, in percent
430
+ func tnWebviewDpiScale() uint {
431
+ user32 := syscall.NewLazyDLL("user32.dll")
432
+ if aware := user32.NewProc("SetProcessDpiAwarenessContext"); aware.Find() == nil {
433
+ aware.Call(^uintptr(3)) // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
434
+ }
435
+ if system := user32.NewProc("GetDpiForSystem"); system.Find() == nil {
436
+ if dpi, _, _ := system.Call(); dpi > 0 {
437
+ return uint(dpi) * 100 / 96
438
+ }
439
+ }
440
+ return 100
441
+ }
442
+
443
+ // Beside the executable there may be no write access; the runtime needs the folder
444
+ func tnWebviewDataDir() string {
445
+ base, err := os.UserCacheDir()
446
+ if err != nil {
447
+ base = os.TempDir()
448
+ }
449
+ exe, _ := os.Executable()
450
+ name := strings.TrimSuffix(filepath.Base(exe), filepath.Ext(exe))
451
+ return filepath.Join(base, name, "WebView2")
452
+ }
453
+
454
+ func tnWebviewOpenEmbedded(w *TnWebviewWindow, closed func()) tnWebviewBackend {
455
+ b := &tnWebview2{}
456
+ title, width, height, logical, resizable := w.title, w.width, w.height, w.logical, w.resizable
457
+ target, html, devtools := w.webview.url, w.webview.html, w.webview.devtools
458
+ dir := w.webview.dir
459
+ if dir == "" {
460
+ dir = tnWebviewDataDir()
461
+ }
462
+ go func() {
463
+ runtime.LockOSThread()
464
+ scale := tnWebviewDpiScale()
465
+ pixelWidth, pixelHeight := width, height
466
+ if logical {
467
+ pixelWidth, pixelHeight = width*scale/100, height*scale/100
468
+ }
469
+ view := webview2.NewWithOptions(webview2.WebViewOptions{
470
+ Debug: devtools,
471
+ DataPath: dir,
472
+ AutoFocus: true,
473
+ WindowOptions: webview2.WindowOptions{Title: title, Width: pixelWidth, Height: pixelHeight},
474
+ })
475
+ if view == nil {
476
+ TnLoopPost(func() {
477
+ panic(TnNodeError("Error", "ERR_WEBVIEW_CREATE", "Could not create the WebView2 window"))
478
+ })
479
+ closed()
480
+ return
481
+ }
482
+ if !resizable {
483
+ view.SetSize(int(pixelWidth), int(pixelHeight), webview2.HintFixed)
484
+ }
485
+ if html != "" {
486
+ view.SetHtml(html)
487
+ } else if target != "" {
488
+ view.Navigate(target)
489
+ }
490
+ b.mu.Lock()
491
+ b.view = view
492
+ pending := b.pending
493
+ b.pending = nil
494
+ b.mu.Unlock()
495
+ for _, fn := range pending {
496
+ fn(view)
497
+ }
498
+ view.Run()
499
+ closed()
500
+ }()
501
+ return b
502
+ }
503
+
504
+ func tnWebviewOpen(w *TnWebviewWindow, closed func()) tnWebviewBackend {
505
+ if os.Getenv("TYPENATIVE_WEBVIEW") != "browser" {
506
+ // Checked first: go-webview2 ends the process when the runtime can't start
507
+ if version, err := webviewloader.GetInstalledVersion(); err == nil && version != "" {
508
+ return tnWebviewOpenEmbedded(w, closed)
509
+ }
510
+ }
511
+ return tnWebviewOpenBrowser(w, closed)
512
+ }
513
+
514
+ type tnWebviewJobCounts struct {
515
+ times [4]int64
516
+ pageFaults uint32
517
+ processes uint32
518
+ active uint32
519
+ terminated uint32
520
+ }
521
+
522
+ // Edge restarts itself, so the process started here isn't the one showing the
523
+ // window. A job holds them all, and ends them if this program dies first.
524
+ func tnWebviewStartBrowser(cmd *exec.Cmd) (func(), func(), error) {
525
+ job, err := windows.CreateJobObject(nil, nil)
526
+ if err != nil {
527
+ return nil, nil, err
528
+ }
529
+ var limits windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION
530
+ limits.BasicLimitInformation.LimitFlags = windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
531
+ windows.SetInformationJobObject(job, windows.JobObjectExtendedLimitInformation, uintptr(unsafe.Pointer(&limits)), uint32(unsafe.Sizeof(limits)))
532
+ if err := cmd.Start(); err != nil {
533
+ windows.CloseHandle(job)
534
+ return nil, nil, err
535
+ }
536
+ process, err := windows.OpenProcess(windows.PROCESS_SET_QUOTA|windows.PROCESS_TERMINATE, false, uint32(cmd.Process.Pid))
537
+ if err == nil {
538
+ err = windows.AssignProcessToJobObject(job, process)
539
+ windows.CloseHandle(process)
540
+ }
541
+ if err != nil {
542
+ cmd.Process.Kill()
543
+ cmd.Wait()
544
+ windows.CloseHandle(job)
545
+ return nil, nil, err
546
+ }
547
+ wait := func() {
548
+ cmd.Wait()
549
+ for {
550
+ var counts tnWebviewJobCounts
551
+ // 1: JobObjectBasicAccountingInformation
552
+ err := windows.QueryInformationJobObject(job, 1, uintptr(unsafe.Pointer(&counts)), uint32(unsafe.Sizeof(counts)), nil)
553
+ if err != nil || counts.active == 0 {
554
+ break
555
+ }
556
+ time.Sleep(200 * time.Millisecond)
557
+ }
558
+ windows.CloseHandle(job)
559
+ }
560
+ return wait, func() { windows.TerminateJobObject(job, 0) }, nil
561
+ }`;
562
+ // Elsewhere only the browser app window. The DevTools pipe says when its page
563
+ // closes: on macOS the browser process outlives its last window.
564
+ const webviewOtherHelper = `func tnWebviewOpen(w *TnWebviewWindow, closed func()) tnWebviewBackend {
565
+ return tnWebviewOpenBrowser(w, closed)
566
+ }
567
+
568
+ func tnWebviewStartBrowser(cmd *exec.Cmd) (func(), func(), error) {
569
+ // The browser reads fd 3 and writes fd 4
570
+ browserIn, toBrowser, err := os.Pipe()
571
+ if err != nil {
572
+ return nil, nil, err
573
+ }
574
+ fromBrowser, browserOut, err := os.Pipe()
575
+ if err != nil {
576
+ return nil, nil, err
577
+ }
578
+ cmd.ExtraFiles = []*os.File{browserIn, browserOut}
579
+ cmd.Args = append(cmd.Args, "--remote-debugging-pipe")
580
+ err = cmd.Start()
581
+ browserIn.Close()
582
+ browserOut.Close()
583
+ if err != nil {
584
+ toBrowser.Close()
585
+ fromBrowser.Close()
586
+ return nil, nil, err
587
+ }
588
+ go tnWebviewWatchPages(cmd, toBrowser, fromBrowser)
589
+ return func() { cmd.Wait() }, func() { cmd.Process.Kill() }, nil
590
+ }
591
+
592
+ // Ends the browser once its last page is gone
593
+ func tnWebviewWatchPages(cmd *exec.Cmd, toBrowser *os.File, fromBrowser *os.File) {
594
+ defer toBrowser.Close()
595
+ defer fromBrowser.Close()
596
+ io.WriteString(toBrowser, "{\\"id\\":1,\\"method\\":\\"Target.setDiscoverTargets\\",\\"params\\":{\\"discover\\":true}}\\x00")
597
+ pages := map[string]bool{}
598
+ reader := bufio.NewReader(fromBrowser)
599
+ for {
600
+ line, err := reader.ReadBytes(0)
601
+ if err != nil {
602
+ return
603
+ }
604
+ var message struct {
605
+ Method string
606
+ Params struct {
607
+ TargetId string
608
+ TargetInfo struct {
609
+ TargetId string
610
+ Type string
611
+ }
612
+ }
613
+ }
614
+ if json.Unmarshal(line[:len(line)-1], &message) != nil {
615
+ continue
616
+ }
617
+ switch message.Method {
618
+ case "Target.targetCreated":
619
+ if message.Params.TargetInfo.Type == "page" {
620
+ pages[message.Params.TargetInfo.TargetId] = true
621
+ }
622
+ case "Target.targetDestroyed":
623
+ if pages[message.Params.TargetId] {
624
+ delete(pages, message.Params.TargetId)
625
+ if len(pages) == 0 {
626
+ cmd.Process.Kill()
627
+ return
628
+ }
629
+ }
630
+ }
631
+ }
632
+ }`;
633
+ const WEBVIEW_EMITTER = 'on=*TnEventEmitter; once=*TnEventEmitter; addListener=*TnEventEmitter; off=*TnEventEmitter; removeListener=*TnEventEmitter; removeAllListeners=*TnEventEmitter; emit=bool; listenerCount=float64';
634
+ export function registerWebview(r) {
635
+ const mod = '@webviewjs/webview';
636
+ defineModule(r, mod);
637
+ defineHelper(r, 'nodeWebviewOS@windows', ['github.com/jchv/go-webview2', 'github.com/jchv/go-webview2/webviewloader', 'golang.org/x/sys/windows', 'os', 'os/exec', 'path/filepath', 'runtime', 'strings', 'sync', 'syscall', 'time', 'unsafe'], [], webviewWindowsHelper);
638
+ defineHelper(r, 'nodeWebviewOS@other', ['bufio', 'encoding/json', 'io', 'os', 'os/exec'], [], webviewOtherHelper);
639
+ defineHelper(r, 'nodeWebview', ['fmt', 'net/url', 'os', 'os/exec', 'path/filepath', 'runtime', 'strings'], ['dynamic', 'nodeEvents', 'eventLoop', 'promise', 'error', 'nodeWebviewOS@os'], webviewHelper);
640
+ defineClass(r, `${mod}.Application`, '*TnWebviewApp', 'class', `${WEBVIEW_EMITTER}; createWebContext=*TnWebviewContext; createBrowserWindow=*TnWebviewWindow; isReady=bool; run=; whenReady=chan struct{}; exit=`, '', '', '');
641
+ defineClass(r, `${mod}.BrowserWindow`, '*TnWebviewWindow', 'class', `${WEBVIEW_EMITTER}; createWebview=*TnWebview; setTitle=; close=`, '', '', '');
642
+ defineClass(r, `${mod}.Webview`, '*TnWebview', 'class', 'loadUrl=; loadHtml=; evaluateScript=; reload=', '', '', '');
643
+ defineClass(r, `${mod}.WebContext`, '*TnWebviewContext', 'class', '', '', '', '');
644
+ defineClass(r, `${mod}.ApplicationEvent`, '*TnWebviewEvent', 'class', '', 'event=string', '', '');
645
+ const listeners = (_n) => ['*TnWebviewEvent'];
646
+ r.paramTypers[`${mod}.Application#on`] = listeners;
647
+ r.paramTypers[`${mod}.Application#once`] = listeners;
648
+ r.paramTypers[`${mod}.BrowserWindow#on`] = listeners;
649
+ r.paramTypers[`${mod}.BrowserWindow#once`] = listeners;
650
+ r.constructors[`${mod}.Application`] = (_c) => {
651
+ r.helper('nodeWebview');
652
+ return 'TnNewWebviewApp()';
653
+ };
654
+ }