zyzz 0.0.28 → 0.0.29

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 (302) hide show
  1. package/binding/wasi/wasi-worker.mjs +186 -0
  2. package/binding/wasi/zyzz.wasi.cjs +2302 -0
  3. package/binding/wasi/zyzz.wasm32-wasi.wasm +0 -0
  4. package/binding/zyzz.linux-x64-gnu.node +0 -0
  5. package/dist/babel/index.d.ts.map +1 -1
  6. package/dist/babel/index.js +2 -4
  7. package/dist/babel/index.js.map +1 -1
  8. package/dist/babel/internal/Compilation.d.ts +0 -1
  9. package/dist/babel/internal/Compilation.d.ts.map +1 -1
  10. package/dist/compiler/Graph.d.ts +14 -11
  11. package/dist/compiler/Graph.d.ts.map +1 -1
  12. package/dist/compiler/Graph.js +57 -1442
  13. package/dist/compiler/Graph.js.map +1 -1
  14. package/dist/compiler/Native.d.ts +7 -9
  15. package/dist/compiler/Native.d.ts.map +1 -1
  16. package/dist/compiler/Native.js +12 -716
  17. package/dist/compiler/Native.js.map +1 -1
  18. package/dist/compiler/Source.d.ts +122 -24
  19. package/dist/compiler/Source.d.ts.map +1 -1
  20. package/dist/compiler/Source.js +10 -1267
  21. package/dist/compiler/Source.js.map +1 -1
  22. package/dist/compiler/Transform.d.ts +4 -3
  23. package/dist/compiler/Transform.d.ts.map +1 -1
  24. package/dist/compiler/Transform.js +13 -961
  25. package/dist/compiler/Transform.js.map +1 -1
  26. package/dist/compiler/internal/AtRules.d.ts +5 -1
  27. package/dist/compiler/internal/AtRules.d.ts.map +1 -1
  28. package/dist/compiler/internal/AtRules.js +12 -106
  29. package/dist/compiler/internal/AtRules.js.map +1 -1
  30. package/dist/compiler/internal/Context.d.ts +11 -0
  31. package/dist/compiler/internal/Context.d.ts.map +1 -0
  32. package/dist/compiler/internal/Context.js +11 -0
  33. package/dist/compiler/internal/Context.js.map +1 -0
  34. package/dist/compiler/internal/Results.d.ts +148 -0
  35. package/dist/compiler/internal/Results.d.ts.map +1 -0
  36. package/dist/compiler/internal/Results.js +259 -0
  37. package/dist/compiler/internal/Results.js.map +1 -0
  38. package/dist/compiler/internal/Syntax.d.ts +0 -2
  39. package/dist/compiler/internal/Syntax.d.ts.map +1 -1
  40. package/dist/compiler/internal/Syntax.js +0 -2
  41. package/dist/compiler/internal/Syntax.js.map +1 -1
  42. package/dist/compiler/internal/Wire.d.ts +17 -0
  43. package/dist/compiler/internal/Wire.d.ts.map +1 -0
  44. package/dist/compiler/internal/Wire.js +795 -0
  45. package/dist/compiler/internal/Wire.js.map +1 -0
  46. package/dist/internal/Addon.d.ts +28 -0
  47. package/dist/internal/Addon.d.ts.map +1 -0
  48. package/dist/internal/Addon.js +87 -0
  49. package/dist/internal/Addon.js.map +1 -0
  50. package/dist/internal/Literal.d.ts +4 -1
  51. package/dist/internal/Literal.d.ts.map +1 -1
  52. package/dist/internal/Literal.js +4 -2
  53. package/dist/internal/Literal.js.map +1 -1
  54. package/dist/internal/Token.d.ts +2 -1
  55. package/dist/internal/Token.d.ts.map +1 -1
  56. package/dist/internal/Token.js +2 -2
  57. package/dist/internal/Token.js.map +1 -1
  58. package/dist/internal/Vlq.d.ts +14 -0
  59. package/dist/internal/Vlq.d.ts.map +1 -0
  60. package/dist/internal/Vlq.js +47 -0
  61. package/dist/internal/Vlq.js.map +1 -0
  62. package/dist/internal/Wasm.d.ts +22 -0
  63. package/dist/internal/Wasm.d.ts.map +1 -0
  64. package/dist/internal/Wasm.js +83 -0
  65. package/dist/internal/Wasm.js.map +1 -0
  66. package/dist/metro/Graph.d.ts +0 -1
  67. package/dist/metro/Graph.d.ts.map +1 -1
  68. package/dist/metro/transformer.d.ts.map +1 -1
  69. package/dist/metro/transformer.js +0 -1
  70. package/dist/metro/transformer.js.map +1 -1
  71. package/dist/next/internal/Project.d.ts.map +1 -1
  72. package/dist/next/internal/Project.js +2 -5
  73. package/dist/next/internal/Project.js.map +1 -1
  74. package/dist/node/Host.d.ts.map +1 -1
  75. package/dist/node/Host.js +0 -2
  76. package/dist/node/Host.js.map +1 -1
  77. package/dist/node/internal/Contracts.d.ts.map +1 -1
  78. package/dist/node/internal/Contracts.js +3 -7
  79. package/dist/node/internal/Contracts.js.map +1 -1
  80. package/dist/node/internal/Snapshot.d.ts +0 -1
  81. package/dist/node/internal/Snapshot.d.ts.map +1 -1
  82. package/dist/node/internal/Snapshot.js +0 -6
  83. package/dist/node/internal/Snapshot.js.map +1 -1
  84. package/dist/runtime/Composition.d.ts +2 -3
  85. package/dist/runtime/Composition.d.ts.map +1 -1
  86. package/dist/runtime/Composition.js +51 -30
  87. package/dist/runtime/Composition.js.map +1 -1
  88. package/dist/runtime/Recipe.d.ts.map +1 -1
  89. package/dist/runtime/Recipe.js +16 -12
  90. package/dist/runtime/Recipe.js.map +1 -1
  91. package/dist/unplugin/index.d.ts.map +1 -1
  92. package/dist/unplugin/index.js +3 -6
  93. package/dist/unplugin/index.js.map +1 -1
  94. package/dist/vite/index.d.ts.map +1 -1
  95. package/dist/vite/index.js +696 -201
  96. package/dist/vite/index.js.map +1 -1
  97. package/dist/web/Css.d.ts +8 -3
  98. package/dist/web/Css.d.ts.map +1 -1
  99. package/dist/web/Css.js +5 -721
  100. package/dist/web/Css.js.map +1 -1
  101. package/dist/web/internal/Block.d.ts +0 -2
  102. package/dist/web/internal/Block.d.ts.map +1 -1
  103. package/dist/web/internal/Block.js +1 -12
  104. package/dist/web/internal/Block.js.map +1 -1
  105. package/dist/web/internal/ClassName.d.ts +23 -18
  106. package/dist/web/internal/ClassName.d.ts.map +1 -1
  107. package/dist/web/internal/ClassName.js +26 -55
  108. package/dist/web/internal/ClassName.js.map +1 -1
  109. package/dist/web/internal/Contributions.d.ts +3 -5
  110. package/dist/web/internal/Contributions.d.ts.map +1 -1
  111. package/dist/web/internal/Contributions.js +0 -45
  112. package/dist/web/internal/Contributions.js.map +1 -1
  113. package/dist/web/internal/Engine.browser.d.ts +8 -0
  114. package/dist/web/internal/Engine.browser.d.ts.map +1 -0
  115. package/dist/web/internal/Engine.browser.js +42 -0
  116. package/dist/web/internal/Engine.browser.js.map +1 -0
  117. package/dist/web/internal/Engine.d.ts +9 -0
  118. package/dist/web/internal/Engine.d.ts.map +1 -0
  119. package/dist/web/internal/Engine.js +14 -0
  120. package/dist/web/internal/Engine.js.map +1 -0
  121. package/dist/web/internal/Themes.d.ts +1 -9
  122. package/dist/web/internal/Themes.d.ts.map +1 -1
  123. package/dist/web/internal/Themes.js +3 -221
  124. package/dist/web/internal/Themes.js.map +1 -1
  125. package/dist/web/internal/Wasm.generated.d.ts +4 -0
  126. package/dist/web/internal/Wasm.generated.d.ts.map +1 -0
  127. package/dist/web/internal/Wasm.generated.js +4 -0
  128. package/dist/web/internal/Wasm.generated.js.map +1 -0
  129. package/dist/web/internal/Wire.d.ts +19 -0
  130. package/dist/web/internal/Wire.d.ts.map +1 -0
  131. package/dist/web/internal/Wire.js +387 -0
  132. package/dist/web/internal/Wire.js.map +1 -0
  133. package/package.json +20 -1
  134. package/src/babel/index.ts +2 -5
  135. package/src/babel/internal/Compilation.ts +0 -1
  136. package/src/compiler/Graph.ts +89 -1930
  137. package/src/compiler/Native.ts +18 -871
  138. package/src/compiler/Source.ts +144 -1803
  139. package/src/compiler/Transform.ts +16 -1315
  140. package/src/compiler/internal/AtRules.ts +27 -115
  141. package/src/compiler/internal/Context.ts +11 -0
  142. package/src/compiler/internal/Results.ts +406 -0
  143. package/src/compiler/internal/Syntax.ts +0 -3
  144. package/src/compiler/internal/Wire.ts +1045 -0
  145. package/src/internal/Addon.ts +118 -0
  146. package/src/internal/Literal.ts +4 -2
  147. package/src/internal/Token.ts +2 -2
  148. package/src/internal/Vlq.ts +59 -0
  149. package/src/internal/Wasm.ts +111 -0
  150. package/src/metro/transformer.ts +0 -1
  151. package/src/next/internal/Project.ts +2 -9
  152. package/src/node/Host.ts +0 -2
  153. package/src/node/internal/Contracts.ts +3 -7
  154. package/src/node/internal/Snapshot.ts +0 -8
  155. package/src/runtime/Composition.ts +48 -25
  156. package/src/runtime/Recipe.ts +21 -14
  157. package/src/unplugin/index.ts +6 -6
  158. package/src/vite/index.ts +922 -221
  159. package/src/web/Css.ts +12 -908
  160. package/src/web/internal/Block.ts +0 -14
  161. package/src/web/internal/ClassName.ts +52 -85
  162. package/src/web/internal/Contributions.ts +3 -59
  163. package/src/web/internal/Engine.browser.ts +51 -0
  164. package/src/web/internal/Engine.ts +17 -0
  165. package/src/web/internal/Themes.ts +3 -279
  166. package/src/web/internal/Wasm.generated.ts +3 -0
  167. package/src/web/internal/Wire.ts +466 -0
  168. package/src/web/internal/wasm.d.ts +9 -0
  169. package/dist/compiler/internal/Applications.d.ts +0 -55
  170. package/dist/compiler/internal/Applications.d.ts.map +0 -1
  171. package/dist/compiler/internal/Applications.js +0 -393
  172. package/dist/compiler/internal/Applications.js.map +0 -1
  173. package/dist/compiler/internal/ColorProfiles.d.ts +0 -3
  174. package/dist/compiler/internal/ColorProfiles.d.ts.map +0 -1
  175. package/dist/compiler/internal/ColorProfiles.js +0 -84
  176. package/dist/compiler/internal/ColorProfiles.js.map +0 -1
  177. package/dist/compiler/internal/CompositionBindings.d.ts +0 -16
  178. package/dist/compiler/internal/CompositionBindings.d.ts.map +0 -1
  179. package/dist/compiler/internal/CompositionBindings.js +0 -89
  180. package/dist/compiler/internal/CompositionBindings.js.map +0 -1
  181. package/dist/compiler/internal/Compositions.d.ts +0 -37
  182. package/dist/compiler/internal/Compositions.d.ts.map +0 -1
  183. package/dist/compiler/internal/Compositions.js +0 -494
  184. package/dist/compiler/internal/Compositions.js.map +0 -1
  185. package/dist/compiler/internal/Configurations.d.ts +0 -26
  186. package/dist/compiler/internal/Configurations.d.ts.map +0 -1
  187. package/dist/compiler/internal/Configurations.js +0 -259
  188. package/dist/compiler/internal/Configurations.js.map +0 -1
  189. package/dist/compiler/internal/Contract.d.ts +0 -30
  190. package/dist/compiler/internal/Contract.d.ts.map +0 -1
  191. package/dist/compiler/internal/Contract.js +0 -753
  192. package/dist/compiler/internal/Contract.js.map +0 -1
  193. package/dist/compiler/internal/Contributions.d.ts +0 -54
  194. package/dist/compiler/internal/Contributions.d.ts.map +0 -1
  195. package/dist/compiler/internal/Contributions.js +0 -1151
  196. package/dist/compiler/internal/Contributions.js.map +0 -1
  197. package/dist/compiler/internal/Descriptors.d.ts +0 -15
  198. package/dist/compiler/internal/Descriptors.d.ts.map +0 -1
  199. package/dist/compiler/internal/Descriptors.js +0 -192
  200. package/dist/compiler/internal/Descriptors.js.map +0 -1
  201. package/dist/compiler/internal/Dynamic.d.ts +0 -14
  202. package/dist/compiler/internal/Dynamic.d.ts.map +0 -1
  203. package/dist/compiler/internal/Dynamic.js +0 -175
  204. package/dist/compiler/internal/Dynamic.js.map +0 -1
  205. package/dist/compiler/internal/Expression.d.ts +0 -19
  206. package/dist/compiler/internal/Expression.d.ts.map +0 -1
  207. package/dist/compiler/internal/Expression.js +0 -164
  208. package/dist/compiler/internal/Expression.js.map +0 -1
  209. package/dist/compiler/internal/Functions.d.ts +0 -5
  210. package/dist/compiler/internal/Functions.d.ts.map +0 -1
  211. package/dist/compiler/internal/Functions.js +0 -191
  212. package/dist/compiler/internal/Functions.js.map +0 -1
  213. package/dist/compiler/internal/Keyframes.d.ts +0 -5
  214. package/dist/compiler/internal/Keyframes.d.ts.map +0 -1
  215. package/dist/compiler/internal/Keyframes.js +0 -51
  216. package/dist/compiler/internal/Keyframes.js.map +0 -1
  217. package/dist/compiler/internal/Names.d.ts +0 -5
  218. package/dist/compiler/internal/Names.d.ts.map +0 -1
  219. package/dist/compiler/internal/Names.js +0 -37
  220. package/dist/compiler/internal/Names.js.map +0 -1
  221. package/dist/compiler/internal/NativeBindings.d.ts +0 -72
  222. package/dist/compiler/internal/NativeBindings.d.ts.map +0 -1
  223. package/dist/compiler/internal/NativeBindings.js +0 -171
  224. package/dist/compiler/internal/NativeBindings.js.map +0 -1
  225. package/dist/compiler/internal/NativeMedia.d.ts +0 -14
  226. package/dist/compiler/internal/NativeMedia.d.ts.map +0 -1
  227. package/dist/compiler/internal/NativeMedia.js +0 -287
  228. package/dist/compiler/internal/NativeMedia.js.map +0 -1
  229. package/dist/compiler/internal/NativeVars.d.ts +0 -28
  230. package/dist/compiler/internal/NativeVars.d.ts.map +0 -1
  231. package/dist/compiler/internal/NativeVars.js +0 -160
  232. package/dist/compiler/internal/NativeVars.js.map +0 -1
  233. package/dist/compiler/internal/PackedStyles.d.ts +0 -37
  234. package/dist/compiler/internal/PackedStyles.d.ts.map +0 -1
  235. package/dist/compiler/internal/PackedStyles.js +0 -344
  236. package/dist/compiler/internal/PackedStyles.js.map +0 -1
  237. package/dist/compiler/internal/Properties.d.ts +0 -5
  238. package/dist/compiler/internal/Properties.d.ts.map +0 -1
  239. package/dist/compiler/internal/Properties.js +0 -82
  240. package/dist/compiler/internal/Properties.js.map +0 -1
  241. package/dist/compiler/internal/RecipeConditions.d.ts +0 -41
  242. package/dist/compiler/internal/RecipeConditions.d.ts.map +0 -1
  243. package/dist/compiler/internal/RecipeConditions.js +0 -82
  244. package/dist/compiler/internal/RecipeConditions.js.map +0 -1
  245. package/dist/compiler/internal/RecipePayloads.d.ts +0 -31
  246. package/dist/compiler/internal/RecipePayloads.d.ts.map +0 -1
  247. package/dist/compiler/internal/RecipePayloads.js +0 -99
  248. package/dist/compiler/internal/RecipePayloads.js.map +0 -1
  249. package/dist/compiler/internal/Recipes.d.ts +0 -32
  250. package/dist/compiler/internal/Recipes.d.ts.map +0 -1
  251. package/dist/compiler/internal/Recipes.js +0 -339
  252. package/dist/compiler/internal/Recipes.js.map +0 -1
  253. package/dist/compiler/internal/Selectors.d.ts +0 -13
  254. package/dist/compiler/internal/Selectors.d.ts.map +0 -1
  255. package/dist/compiler/internal/Selectors.js +0 -280
  256. package/dist/compiler/internal/Selectors.js.map +0 -1
  257. package/dist/compiler/internal/Static.d.ts +0 -39
  258. package/dist/compiler/internal/Static.d.ts.map +0 -1
  259. package/dist/compiler/internal/Static.js +0 -534
  260. package/dist/compiler/internal/Static.js.map +0 -1
  261. package/dist/compiler/internal/Themes.d.ts +0 -190
  262. package/dist/compiler/internal/Themes.d.ts.map +0 -1
  263. package/dist/compiler/internal/Themes.js +0 -1577
  264. package/dist/compiler/internal/Themes.js.map +0 -1
  265. package/dist/compiler/internal/Vars.d.ts +0 -33
  266. package/dist/compiler/internal/Vars.d.ts.map +0 -1
  267. package/dist/compiler/internal/Vars.js +0 -387
  268. package/dist/compiler/internal/Vars.js.map +0 -1
  269. package/dist/compiler/internal/ViewTransitions.d.ts +0 -3
  270. package/dist/compiler/internal/ViewTransitions.d.ts.map +0 -1
  271. package/dist/compiler/internal/ViewTransitions.js +0 -68
  272. package/dist/compiler/internal/ViewTransitions.js.map +0 -1
  273. package/dist/internal/Cascade.d.ts +0 -74
  274. package/dist/internal/Cascade.d.ts.map +0 -1
  275. package/dist/internal/Cascade.js +0 -210
  276. package/dist/internal/Cascade.js.map +0 -1
  277. package/src/compiler/internal/Applications.ts +0 -610
  278. package/src/compiler/internal/ColorProfiles.ts +0 -93
  279. package/src/compiler/internal/CompositionBindings.ts +0 -120
  280. package/src/compiler/internal/Compositions.ts +0 -678
  281. package/src/compiler/internal/Configurations.ts +0 -349
  282. package/src/compiler/internal/Contract.ts +0 -1028
  283. package/src/compiler/internal/Contributions.ts +0 -1561
  284. package/src/compiler/internal/Descriptors.ts +0 -242
  285. package/src/compiler/internal/Dynamic.ts +0 -275
  286. package/src/compiler/internal/Expression.ts +0 -218
  287. package/src/compiler/internal/Functions.ts +0 -206
  288. package/src/compiler/internal/Keyframes.ts +0 -62
  289. package/src/compiler/internal/Names.ts +0 -48
  290. package/src/compiler/internal/NativeBindings.ts +0 -235
  291. package/src/compiler/internal/NativeMedia.ts +0 -342
  292. package/src/compiler/internal/NativeVars.ts +0 -231
  293. package/src/compiler/internal/PackedStyles.ts +0 -473
  294. package/src/compiler/internal/Properties.ts +0 -121
  295. package/src/compiler/internal/RecipeConditions.ts +0 -139
  296. package/src/compiler/internal/RecipePayloads.ts +0 -132
  297. package/src/compiler/internal/Recipes.ts +0 -531
  298. package/src/compiler/internal/Selectors.ts +0 -353
  299. package/src/compiler/internal/Static.ts +0 -784
  300. package/src/compiler/internal/Themes.ts +0 -2398
  301. package/src/compiler/internal/Vars.ts +0 -516
  302. package/src/compiler/internal/ViewTransitions.ts +0 -82
@@ -0,0 +1,2302 @@
1
+ // napi-rs-artifact-metadata:{"version":2,"rootEntry":"index.js","exports":["Graph","call","version"],"managedRootEntries":["browser.js","index.js","zyzz.wasm","zyzz.debug.wasm"]}
2
+ /* eslint-disable */
3
+ /* auto-generated by NAPI-RS */
4
+
5
+ const __napiBindingTarget = 'wasm32-wasi'
6
+ function __napiStampBindingTarget(exportsObject, target) {
7
+ if (
8
+ Object.prototype.hasOwnProperty.call(exportsObject, '__napiBindingTarget')
9
+ ) {
10
+ if (exportsObject.__napiBindingTarget === target) {
11
+ // Already ours: the root entry aliases the object it loaded, so a WASI
12
+ // fallback candidate — or a `NAPI_RS_NATIVE_LIBRARY_PATH` override that
13
+ // is a generated loader — arrives already stamped with this same value.
14
+ return target
15
+ }
16
+ const error = new Error(
17
+ '`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = "...")].',
18
+ )
19
+ error.code = 'ERR_NAPI_BINDING_TARGET_CONFLICT'
20
+ throw error
21
+ }
22
+ if (!Object.isExtensible(exportsObject)) {
23
+ // A `#[napi(module_exports)]` hook may seal or freeze this object
24
+ // (`Object::seal` / `Object::freeze`). Reporting the artifact is metadata,
25
+ // never a reason to fail an otherwise successful load, so the stamp is
26
+ // skipped. What a consumer still sees then follows the entry point: the
27
+ // browser and deferred loaders declare `__napiBindingTarget` at module
28
+ // level and go on reporting it, while the CommonJS entries hand back this
29
+ // very object as `module.exports`, so there the value is absent.
30
+ return target
31
+ }
32
+ try {
33
+ // [[Define]], not [[Set]]: an ordinary assignment walks the prototype
34
+ // chain, so an inherited accessor could swallow the value or throw and
35
+ // fail an otherwise successful load. The descriptor is what a successful
36
+ // assignment would have produced.
37
+ Object.defineProperty(exportsObject, '__napiBindingTarget', {
38
+ configurable: true,
39
+ enumerable: true,
40
+ value: target,
41
+ writable: true,
42
+ })
43
+ } catch {
44
+ // Same rule as the non-extensible skip above: reporting the artifact is
45
+ // metadata, never a reason to fail an otherwise successful load. An exotic
46
+ // object (a Proxy whose defineProperty trap refuses) is skipped, not
47
+ // thrown over.
48
+ }
49
+ // The CommonJS loaders assign this return value so `cjs-module-lexer` — and
50
+ // therefore Node's CJS -> ESM named export detection — can see
51
+ // `__napiBindingTarget` statically.
52
+ return target
53
+ }
54
+
55
+ const __nodeFs = require('node:fs')
56
+ const __nodePath = require('node:path')
57
+ const { WASI: __nodeWASI } = require('node:wasi')
58
+ const { Worker } = require('node:worker_threads')
59
+
60
+ const {
61
+ emnapiAsyncWorkPlugin: __emnapiAsyncWorkPlugin,
62
+ emnapiTSFNPlugin: __emnapiTSFNPlugin,
63
+ createOnMessage: __wasmCreateOnMessageForFsProxy,
64
+ instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync,
65
+ } = require('@napi-rs/wasm-runtime')
66
+ const { createContext: __emnapiCreateContext } = require('@emnapi/runtime')
67
+
68
+ function __getWasiWorkerExecArgv() {
69
+ const __workerExecArgv = []
70
+ for (let __index = 0; __index < process.execArgv.length; __index += 1) {
71
+ const __arg = process.execArgv[__index]
72
+ if (
73
+ __arg === '--input-type' ||
74
+ __arg === '--eval' ||
75
+ __arg === '-e' ||
76
+ __arg === '--print' ||
77
+ __arg === '-p'
78
+ ) {
79
+ __index += 1
80
+ continue
81
+ }
82
+ if (
83
+ __arg.startsWith('--input-type=') ||
84
+ __arg.startsWith('--eval=') ||
85
+ __arg.startsWith('--print=')
86
+ ) {
87
+ continue
88
+ }
89
+ __workerExecArgv.push(__arg)
90
+ }
91
+ return __workerExecArgv
92
+ }
93
+
94
+ function __isInvalidWasiWorkerExecArgv(errorMessage, argument) {
95
+ const __equalsIndex = argument.indexOf('=')
96
+ const __argumentName =
97
+ __equalsIndex === -1 ? argument : argument.slice(0, __equalsIndex)
98
+ return (
99
+ errorMessage.includes(': ' + __argumentName + ',') ||
100
+ errorMessage.includes(': ' + __argumentName + '=') ||
101
+ errorMessage.endsWith(': ' + __argumentName) ||
102
+ errorMessage.includes(', ' + __argumentName + ',') ||
103
+ errorMessage.includes(', ' + __argumentName + '=') ||
104
+ errorMessage.endsWith(', ' + __argumentName)
105
+ )
106
+ }
107
+
108
+ function __removeInvalidWasiWorkerExecArgv(execArgv, error) {
109
+ if (typeof error.message !== 'string') {
110
+ return
111
+ }
112
+ const __workerExecArgv = []
113
+ let __removed = false
114
+ for (let __index = 0; __index < execArgv.length; __index += 1) {
115
+ const __arg = execArgv[__index]
116
+ if (
117
+ __arg.startsWith('-') &&
118
+ __isInvalidWasiWorkerExecArgv(error.message, __arg)
119
+ ) {
120
+ __removed = true
121
+ if (
122
+ !__arg.includes('=') &&
123
+ __index + 1 < execArgv.length &&
124
+ !execArgv[__index + 1].startsWith('-')
125
+ ) {
126
+ __index += 1
127
+ }
128
+ continue
129
+ }
130
+ __workerExecArgv.push(__arg)
131
+ }
132
+ return __removed ? __workerExecArgv : undefined
133
+ }
134
+
135
+ function __createWasiWorker(filename) {
136
+ let __workerExecArgv = __getWasiWorkerExecArgv()
137
+ while (true) {
138
+ try {
139
+ return new Worker(filename, {
140
+ env: process.env,
141
+ execArgv: __workerExecArgv,
142
+ workerData: {
143
+ hostRoot: __hostRoot,
144
+ rootDir: __rootDir,
145
+ crashFlag: __wasiThreadCrashFlag,
146
+ crashReport: __wasiThreadCrashReport,
147
+ addonCrashFlag: __wasiAddonCrashFlag,
148
+ },
149
+ })
150
+ } catch (error) {
151
+ if (!error || error.code !== 'ERR_WORKER_INVALID_EXEC_ARGV') {
152
+ throw error
153
+ }
154
+ const __nextWorkerExecArgv =
155
+ __removeInvalidWasiWorkerExecArgv(__workerExecArgv, error)
156
+ if (!__nextWorkerExecArgv) {
157
+ throw error
158
+ }
159
+ __workerExecArgv = __nextWorkerExecArgv
160
+ }
161
+ }
162
+ }
163
+
164
+ // Set to 1 by a pool worker (see wasi-worker.mjs) right before it reports that
165
+ // its wasm thread died. Shared memory, so this thread reads it synchronously even
166
+ // while the worker's 'error' event is still queued behind the code that is
167
+ // exiting right now.
168
+ const __wasiThreadCrashFlag = new Int32Array(new SharedArrayBuffer(4))
169
+ // Written by the first pool worker whose wasm thread dies, before it raises the
170
+ // flag: its error and `threadId` (layout in wasi-worker.mjs). Read without
171
+ // waiting for any event, see `__readWasiThreadCrashReport`.
172
+ const __wasiThreadCrashReport = new SharedArrayBuffer(4096)
173
+ let __wasiThreadCrashReportRead
174
+ // The first error a pool worker reported through its 'error' event, and that
175
+ // worker's `threadId`. See `__getWasiThreadCrashError`.
176
+ let __wasiThreadCrashWorkerError
177
+ let __wasiThreadCrashWorkerId
178
+ let __wasiThreadCrashError
179
+ // Raised while `__runWasiInitializationRollbackSteps` runs, so its polls and
180
+ // steps stop after a crash the way a public disposal's do.
181
+ let __wasiInitializationRollbackActive = false
182
+ let __wasiThreadCrashed = false
183
+
184
+ // A view of the addon's crash flag, one word of the shared wasm memory, for the
185
+ // pool workers: they raise it when their wasm thread dies, and the shutdown
186
+ // waits inside the cleanup calls on this thread then trap instead of waiting on
187
+ // the dead thread for good. Undefined for an addon built with an older napi.
188
+ let __wasiAddonCrashFlag
189
+
190
+ function __captureWasiAddonCrashFlag(instance) {
191
+ try {
192
+ const getAddress = instance.exports.napi_wasm_thread_crash_flag_address
193
+ if (typeof getAddress !== 'function') {
194
+ return
195
+ }
196
+ const address = getAddress() >>> 0
197
+ const buffer = __sharedMemory.buffer
198
+ if (address === 0 || address % 4 !== 0 || address + 4 > buffer.byteLength) {
199
+ return
200
+ }
201
+ __wasiAddonCrashFlag = new Int32Array(buffer, address, 1)
202
+ } catch {}
203
+ }
204
+
205
+ /**
206
+ * Whether any wasm thread of this binding has died: a trap or an uncaught error
207
+ * in a pool worker, including one that failed to load after its thread spawn
208
+ * had already been reported as started.
209
+ *
210
+ * After that the shared wasm state cannot be trusted: a lock the dead thread
211
+ * held stays held, and a join or park that waits on it — the async runtime's
212
+ * `finish_shutdown` waiting for the dead thread's work to go idle — blocks
213
+ * this thread forever in a raw `memory.atomic.wait32`, which neither
214
+ * emnapi's crash check nor a signal can interrupt.
215
+ */
216
+ function __hasWasiThreadCrashed() {
217
+ if (__wasiThreadCrashed || Atomics.load(__wasiThreadCrashFlag, 0) !== 0) {
218
+ return true
219
+ }
220
+ const manager = __getWasiThreadManager()
221
+ return Boolean(manager && manager._fatalError)
222
+ }
223
+
224
+ let __wasiThreadCrashDisposePromise
225
+ // Raised by the crash disposal right before it terminates the workers. See
226
+ // `__wasiSetImmediate`.
227
+ let __wasiReentryClosed = false
228
+
229
+ /**
230
+ * emnapi's `features.setImmediate` for this binding's context. emnapi defers
231
+ * its calls back into wasm through it: `_emnapi_set_immediate` (libuv handle
232
+ * closes, threadsafe-function finalizers), threadsafe-function dispatch
233
+ * (`async-send`) and the finalizer queue. One queued before a crash disposal
234
+ * terminates the workers still runs after it, and a worker terminated while it
235
+ * held a lock in the wasm heap (napi's heap-sync allocator lock spins and never
236
+ * gives up) leaves that call spinning on this thread for good. The binding is
237
+ * unusable after a crash disposal, so those calls are dropped.
238
+ *
239
+ * Known residual, still able to enter wasm after a crash disposal because emnapi
240
+ * offers no hook for them: the `FinalizationRegistry` callbacks that free
241
+ * external memory when GC collects a value (`_free`, the shared-buffer meta
242
+ * release), threadsafe-function dispatch of `async-send` type 1 and
243
+ * `_emnapi_next_tick` (both `Promise.resolve().then`), and every deferred
244
+ * call under emnapi 1.x, whose `createContext` ignores `features`.
245
+ */
246
+ function __wasiSetImmediate(callback) {
247
+ return setImmediate(function () {
248
+ if (!__wasiReentryClosed) {
249
+ callback()
250
+ }
251
+ })
252
+ }
253
+
254
+ /**
255
+ * Stores the first error a pool worker reported, with the worker's id. Called
256
+ * from the loader's own 'error' listener, which runs before emnapi's.
257
+ */
258
+ function __recordWasiThreadCrashError(error, workerId) {
259
+ if (__wasiThreadCrashWorkerError !== undefined || error === undefined) {
260
+ return
261
+ }
262
+ __wasiThreadCrashWorkerError = error
263
+ __wasiThreadCrashWorkerId = workerId
264
+ __fillWasiThreadCrashError()
265
+ }
266
+
267
+ /**
268
+ * The error in the shared crash report, rebuilt once it is complete: the
269
+ * worker writes it before it raises the flag, so it is there as soon as the
270
+ * crash is seen. Plain JavaScript over shared memory; never enters wasm.
271
+ */
272
+ function __readWasiThreadCrashReport() {
273
+ if (__wasiThreadCrashReportRead !== undefined) {
274
+ return __wasiThreadCrashReportRead
275
+ }
276
+ try {
277
+ const header = new Int32Array(__wasiThreadCrashReport, 0, 3)
278
+ if (Atomics.load(header, 0) !== 2) {
279
+ return
280
+ }
281
+ const length = Atomics.load(header, 1)
282
+ const threadId = Atomics.load(header, 2)
283
+ let error
284
+ if (length > 0) {
285
+ // Copied out of shared memory: TextDecoder does not take a shared view.
286
+ const bytes = new Uint8Array(__wasiThreadCrashReport, 12, length).slice()
287
+ const report = JSON.parse(new TextDecoder().decode(bytes))
288
+ error = new Error(String(report.message))
289
+ if (typeof report.name === 'string') {
290
+ error.name = report.name
291
+ }
292
+ if (typeof report.stack === 'string') {
293
+ error.stack = report.stack
294
+ }
295
+ }
296
+ __wasiThreadCrashReportRead = { error, threadId }
297
+ } catch {
298
+ __wasiThreadCrashReportRead = { error: undefined, threadId: 0 }
299
+ }
300
+ return __wasiThreadCrashReportRead
301
+ }
302
+
303
+ /**
304
+ * The one error every crash path of this binding reports, created on first
305
+ * use.
306
+ *
307
+ * The shared flag is raised before this thread has processed the worker's
308
+ * 'error' event, and once the workers are terminated that event is often
309
+ * never delivered, so neither it nor emnapi's `_fatalError` can be counted
310
+ * on. The cause is filled in from the first source that has it: the error the
311
+ * 'error' listener kept, else the worker's shared crash report, else
312
+ * `_fatalError` — here, and again from the 'error' listener when it arrives
313
+ * later. Until then the error carries only its message.
314
+ */
315
+ function __getWasiThreadCrashError() {
316
+ if (__wasiThreadCrashError === undefined) {
317
+ __wasiThreadCrashError = new Error(
318
+ 'napi-rs: WASI binding cannot be disposed after a worker thread crashed',
319
+ )
320
+ }
321
+ __fillWasiThreadCrashError()
322
+ return __wasiThreadCrashError
323
+ }
324
+
325
+ function __fillWasiThreadCrashError() {
326
+ const crashError = __wasiThreadCrashError
327
+ if (crashError === undefined) {
328
+ return
329
+ }
330
+ try {
331
+ if (crashError.cause === undefined) {
332
+ let cause = __wasiThreadCrashWorkerError
333
+ if (cause === undefined) {
334
+ const report = __readWasiThreadCrashReport()
335
+ cause = report ? report.error : undefined
336
+ }
337
+ if (cause === undefined) {
338
+ const manager = __getWasiThreadManager()
339
+ cause = manager ? manager._fatalError : undefined
340
+ }
341
+ if (cause !== undefined && cause !== null) {
342
+ crashError.cause = cause
343
+ }
344
+ }
345
+ if (crashError.workerThreadId === undefined) {
346
+ let workerId = __wasiThreadCrashWorkerId
347
+ if (workerId === undefined) {
348
+ const report = __readWasiThreadCrashReport()
349
+ workerId = report && report.threadId > 0 ? report.threadId : undefined
350
+ }
351
+ if (workerId !== undefined) {
352
+ crashError.workerThreadId = workerId
353
+ }
354
+ }
355
+ } catch {}
356
+ }
357
+
358
+ /**
359
+ * Let the event loop drain after a wasm thread died, without entering wasm.
360
+ *
361
+ * emnapi's `Context` keeps a `NodejsWaitingRequestCounter` on Node: a
362
+ * `MessagePort` (`refCounter.refHandle`) that it refs when the count of
363
+ * in-flight async work and threadsafe-function requests leaves zero and unrefs
364
+ * when it comes back. The requests the dead thread held never complete, so the
365
+ * count never returns to zero and the port holds the process open for good.
366
+ * `Context.destroy()` would not release it either — and it runs cleanup
367
+ * hooks, which is exactly what must not happen now. So unref the port directly.
368
+ * The count is left as is: it stays above zero, so a later request never refs
369
+ * the port again.
370
+ *
371
+ * The field is private in emnapi's typings, so read it defensively; a context
372
+ * without it (a non-Node host, a future emnapi) is left alone.
373
+ */
374
+ function __releaseEmnapiWaitingRequestHandle() {
375
+ try {
376
+ const refCounter = __emnapiContext && __emnapiContext.refCounter
377
+ const refHandle = refCounter && refCounter.refHandle
378
+ if (refHandle && typeof refHandle.unref === 'function') {
379
+ refHandle.unref()
380
+ }
381
+ } catch {}
382
+ }
383
+
384
+ /**
385
+ * The public disposer after a wasm thread died. The normal chain drains async
386
+ * work, runs the environment cleanup barrier and destroys the context — every
387
+ * one of those re-enters wasm, and the barrier's shutdown waits for the dead
388
+ * thread's work in the same raw atomic wait `__disposeWasiBindingAtExit`
389
+ * avoids. An app that handled the worker's error and then disposes would block
390
+ * there for good. Only stop the workers, then reject: the binding was not
391
+ * cleaned up and cannot be, so reporting success would be a lie. The context
392
+ * is not destroyed — only its waiting-request port is unrefed, so the process
393
+ * can exit on its own — and the 'exit' listener takes its short path too.
394
+ *
395
+ * Latched: every later call returns the same promise.
396
+ */
397
+ function __disposeWasiBindingAfterThreadCrash() {
398
+ if (__wasiThreadCrashDisposePromise) {
399
+ return __wasiThreadCrashDisposePromise
400
+ }
401
+ __releaseEmnapiWaitingRequestHandle()
402
+ // No call into wasm after this: see `__wasiSetImmediate`.
403
+ __wasiReentryClosed = true
404
+ let workerResult
405
+ try {
406
+ workerResult = __terminateWasiWorkers()
407
+ } catch (terminateError) {
408
+ workerResult = Promise.reject(terminateError)
409
+ }
410
+ // Built at settlement, after the workers stopped: by then the 'error' event
411
+ // has usually delivered the worker's error.
412
+ __wasiThreadCrashDisposePromise = Promise.resolve(workerResult).then(
413
+ () => {
414
+ throw __getWasiThreadCrashError()
415
+ },
416
+ (terminateError) => {
417
+ throw __attachCleanupErrors(__getWasiThreadCrashError(), [
418
+ terminateError,
419
+ ])
420
+ },
421
+ )
422
+ return __wasiThreadCrashDisposePromise
423
+ }
424
+
425
+ /**
426
+ * Stops a public disposal that a thread crash overtook.
427
+ *
428
+ * The check at the top of `__disposeWasiBinding` only sees a crash that came
429
+ * first. A thread that dies once the chain is running leaves it polling for
430
+ * work the dead thread still counts — the async-work drain for
431
+ * `napi_wasm_async_work_pending`, the barrier's poll for
432
+ * `napi_wasm_runtime_work_pending` — and neither count ever reaches zero, so
433
+ * the poll's referenced timers keep the process alive forever with the
434
+ * disposal promise pending. Each poll turn and each step boundary calls this,
435
+ * and the throw ends the chain before anything re-enters wasm again; the
436
+ * disposer then settles it through `__settleWasiDisposalAfterThreadCrash`.
437
+ *
438
+ * The initialization rollback runs the same polls and steps, so they stop while
439
+ * it runs too; its wrapper, `__rollbackWasiInitialization`, then ends it
440
+ * through `__rollbackWasiInitializationAfterThreadCrash`. A bare poll with
441
+ * neither in flight is left alone.
442
+ */
443
+ function __abortWasiDisposalIfThreadCrashed() {
444
+ if (
445
+ (__wasiDisposePromise !== undefined ||
446
+ __wasiInitializationRollbackActive) &&
447
+ __hasWasiThreadCrashed()
448
+ ) {
449
+ throw new Error(
450
+ 'napi-rs: WASI disposal stopped because a worker thread crashed',
451
+ )
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Settles an in-flight public disposal whose chain failed after a thread
457
+ * died — stopped by `__abortWasiDisposalIfThreadCrashed` or failing any other
458
+ * way — through the crash disposal: it releases the waiting-request port,
459
+ * terminates the workers and rejects with the same error an entry-time crash
460
+ * gets. `__wasiDisposePromise` stays set, so this caller, every caller that
461
+ * joined it and every later one hold the same promise. Returns false when no
462
+ * thread died, leaving the ordinary failure handling alone.
463
+ */
464
+ function __settleWasiDisposalAfterThreadCrash(resolve, reject) {
465
+ if (!__hasWasiThreadCrashed()) {
466
+ return false
467
+ }
468
+ __disposeWasiBindingAfterThreadCrash().then(resolve, reject)
469
+ return true
470
+ }
471
+
472
+ /**
473
+ * Ends an initialization rollback after a wasm thread died, without entering
474
+ * wasm: the barrier, its finish and `Context.destroy()` are skipped, and the
475
+ * crash disposal releases the waiting-request port and terminates the workers,
476
+ * once. The initialization error itself is left to propagate: the crash error
477
+ * is returned as the rollback's cleanup error, so
478
+ * `__completeWasiInitializationRollback` attaches it — as the cause when the
479
+ * error has none — and keeps the record, since the context was not destroyed.
480
+ */
481
+ function __rollbackWasiInitializationAfterThreadCrash() {
482
+ const crashError = __getWasiThreadCrashError()
483
+ // Its rejection is `crashError` itself, which the caller reports.
484
+ void __disposeWasiBindingAfterThreadCrash().catch(() => {})
485
+ return [crashError]
486
+ }
487
+
488
+ const __wasiThreadPoolReconcileSymbol = Symbol.for('napi.rs.wasi.reconcileThreadPool')
489
+
490
+ /**
491
+ * Takes a Worker out of emnapi's reuse pool, if it is still there. emnapi
492
+ * terminates a pooled Worker that failed to load but (up to
493
+ * @emnapi/wasi-threads 2.1.0) leaves it in the pool, where the next thread
494
+ * spawn would pop it. A newer emnapi removes it itself, so this is a no-op
495
+ * then.
496
+ */
497
+ function __removeWasiPoolWorker(manager, worker) {
498
+ const index = manager.unusedWorkers.indexOf(worker)
499
+ if (index !== -1) {
500
+ manager.unusedWorkers.splice(index, 1)
501
+ }
502
+ }
503
+
504
+ /**
505
+ * Takes a Worker the thread manager just terminated out of `__wasiWorkers`
506
+ * once it has exited, not before. `terminateWorker` only starts Node's
507
+ * asynchronous `worker.terminate()` and drops its promise, so a disposal that
508
+ * begins before the exit has to find this Worker in the set and wait for it
509
+ * like any other. A second `terminate()` settles when the Worker has exited,
510
+ * the way `__terminateWasiWorkers` waits.
511
+ */
512
+ function __untrackWasiWorkerOnExit(worker) {
513
+ const terminated = worker.terminate()
514
+ if (__isThenable(terminated)) {
515
+ Promise.resolve(terminated).then(
516
+ () => {
517
+ __wasiWorkers.delete(worker)
518
+ },
519
+ // Left tracked: disposal terminates it again and reports the error.
520
+ () => {},
521
+ )
522
+ } else {
523
+ __wasiWorkers.delete(worker)
524
+ }
525
+ }
526
+
527
+ /**
528
+ * Matches emnapi's idle reuse pool to the addon's configured MultiThread worker
529
+ * count, which the addon exports as `napi_wasm_runtime_pool_workers`
530
+ * (napi-async-runtime; 0 under CurrentThread). `reuseWorker: true` starts the
531
+ * pool empty, so without this every pool thread the first async call spawns
532
+ * boots a Worker and loads the wasm into it first. Here each missing Worker is
533
+ * created and starts loading now; a spawn later pops one that is already
534
+ * booting. Idle Workers above the count are terminated, last in first out,
535
+ * the way a spawn takes them. A Worker a spawn already took is not in the pool
536
+ * and is left alone.
537
+ *
538
+ * Runs once after a successful load and, when the loader wraps it, after every
539
+ * successful `configureAsyncRuntime`. Also reachable as
540
+ * binding[Symbol.for('napi.rs.wasi.reconcileThreadPool')]().
541
+ * It never throws and never waits on a Worker: a Worker whose load fails is
542
+ * dropped from the pool when its load rejects. Nothing at all happens after a
543
+ * thread crash, once disposal started, or for an addon without the export.
544
+ */
545
+ function __reconcileWasiThreadPool() {
546
+ try {
547
+ if (__wasiDisposed || __wasiDisposePromise || __hasWasiThreadCrashed()) {
548
+ return
549
+ }
550
+ const read = __napiInstance?.exports?.napi_wasm_runtime_pool_workers
551
+ if (typeof read !== 'function') {
552
+ return
553
+ }
554
+ const count = read() >>> 0
555
+ const manager = __getWasiThreadManager()
556
+ if (
557
+ !manager ||
558
+ !Array.isArray(manager.unusedWorkers) ||
559
+ typeof manager.allocateUnusedWorker !== 'function' ||
560
+ typeof manager.loadWasmModuleToWorker !== 'function'
561
+ ) {
562
+ return
563
+ }
564
+ // Both loops are bounded by the difference they start from, so a manager
565
+ // that does not update `unusedWorkers` the way emnapi does cannot spin.
566
+ for (let excess = manager.unusedWorkers.length - count; excess > 0; excess--) {
567
+ const worker = manager.unusedWorkers[manager.unusedWorkers.length - 1]
568
+ manager.terminateWorker(worker)
569
+ __removeWasiPoolWorker(manager, worker)
570
+ __untrackWasiWorkerOnExit(worker)
571
+ // Compatibility with @emnapi/wasi-threads 2.1.0 and older:
572
+ // `terminateWorker` installs a reporter that logs every emnapi message
573
+ // still queued on the port, so a Worker that finished loading just
574
+ // before it was terminated prints 'received "loaded" command from
575
+ // terminated worker'. Nothing listens for that Worker any more, and a
576
+ // newer emnapi ignores the late 'loaded' itself, so this is harmless
577
+ // there. `__terminateWasiWorkers` does the same.
578
+ worker.onmessage = undefined
579
+ }
580
+ for (let missing = count - manager.unusedWorkers.length; missing > 0; missing--) {
581
+ let worker
582
+ try {
583
+ // Through `onCreateWorker`: tracked in `__wasiWorkers`, unref'd, and
584
+ // handed the crash flags like any pool Worker.
585
+ worker = manager.allocateUnusedWorker()
586
+ manager
587
+ .loadWasmModuleToWorker(worker)
588
+ .then(undefined, () => __removeWasiPoolWorker(manager, worker))
589
+ } catch {
590
+ if (worker !== undefined) {
591
+ __removeWasiPoolWorker(manager, worker)
592
+ try {
593
+ manager.terminateWorker(worker)
594
+ __untrackWasiWorkerOnExit(worker)
595
+ } catch {}
596
+ }
597
+ return
598
+ }
599
+ }
600
+ } catch {}
601
+ }
602
+
603
+ function __publishWasiThreadPoolReconcile(exports) {
604
+ Object.defineProperty(exports, __wasiThreadPoolReconcileSymbol, {
605
+ configurable: false,
606
+ enumerable: false,
607
+ value: __reconcileWasiThreadPool,
608
+ writable: false,
609
+ })
610
+ }
611
+
612
+ const __cwd = process.cwd()
613
+ const __rootDir = __nodePath.parse(__cwd).root
614
+ const __hostRoot =
615
+ process.platform === 'android' ? __cwd : __rootDir
616
+
617
+ const __wasi = new __nodeWASI({
618
+ version: 'preview1',
619
+ env: process.env,
620
+ preopens: {
621
+ [__rootDir]: __hostRoot,
622
+ [__hostRoot]: __hostRoot,
623
+ },
624
+ })
625
+
626
+ const __sharedMemory = new WebAssembly.Memory({
627
+ initial: 4000,
628
+ maximum: 65536,
629
+ shared: true,
630
+ })
631
+
632
+ let __wasmFilePath = __nodePath.join(__dirname, 'zyzz.wasm32-wasi.wasm')
633
+ const __wasmDebugFilePath = __nodePath.join(__dirname, 'zyzz.wasm32-wasi.debug.wasm')
634
+
635
+ if (__nodeFs.existsSync(__wasmDebugFilePath)) {
636
+ __wasmFilePath = __wasmDebugFilePath
637
+ } else if (!__nodeFs.existsSync(__wasmFilePath)) {
638
+ const __wasiPackageEntry = require.resolve('@zyzz/binding-wasm32-wasi')
639
+ const __packagedWasmFilePath = __nodePath.join(
640
+ __nodePath.dirname(__wasiPackageEntry),
641
+ 'zyzz.wasm32-wasi.wasm',
642
+ )
643
+ if (!__nodeFs.existsSync(__packagedWasmFilePath)) {
644
+ throw new Error(
645
+ '@zyzz/binding-wasm32-wasi is installed but is missing zyzz.wasm32-wasi.wasm.',
646
+ )
647
+ }
648
+ __wasmFilePath = __packagedWasmFilePath
649
+ }
650
+
651
+ const __wasmFile = __nodeFs.readFileSync(__wasmFilePath)
652
+ let __emnapiContext
653
+
654
+ const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
655
+ const __wasiWorkers = new Set()
656
+ // The thread manager has to be reachable *before* anything that can throw
657
+ // during load or registration. Initialization can fail after the pool has
658
+ // already spawned workers, and the rollback still has to mark their
659
+ // terminations as expected — but `__napiModule` is assigned only when
660
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
661
+ // plugin factory runs while the emnapi module is being created, before the
662
+ // wasm is loaded and before any registration function runs, and its context
663
+ // carries the very same manager instance.
664
+ let __wasiThreadManager
665
+
666
+ function __captureWasiThreadManager(context) {
667
+ if (context && context.PThread) {
668
+ __wasiThreadManager = context.PThread
669
+ }
670
+ return {}
671
+ }
672
+
673
+ function __getWasiThreadManager() {
674
+ const manager =
675
+ __wasiThreadManager !== undefined
676
+ ? __wasiThreadManager
677
+ : __napiModule
678
+ ? __napiModule.PThread
679
+ : undefined
680
+ if (manager && typeof manager.terminateWorker === 'function') {
681
+ return manager
682
+ }
683
+ return undefined
684
+ }
685
+ let __napiInstance
686
+ let __emnapiContextDestroyed = false
687
+ let __emnapiContextDestroyPromise
688
+ let __emnapiWasmEnvCleanupPrepared = false
689
+ let __emnapiWasmEnvCleanupPreparing = false
690
+ // The closer for a barrier that is parked between `…_begin` and `…_finish`,
691
+ // set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
692
+ // tell those two apart on its own: it is raised both for a purely synchronous
693
+ // frame — which must not be re-entered, and which nothing outside it can
694
+ // finish — and across this window, which spans real event-loop turns, so a
695
+ // caller that cannot yield can land in the middle of one. That caller can close
696
+ // this window, because `…_finish` is idempotent and joins, which is exactly
697
+ // what the single call does. See `__prepareWasmEnvCleanup`.
698
+ let __finishParkedWasmEnvCleanup
699
+ // Raised while a caller that can still yield is driving the barrier, so the
700
+ // queue it leaves behind is expected rather than lost. See
701
+ // `__reportUnreachedWasmEnvSettlements`.
702
+ let __emnapiWasmEnvCleanupYielding = false
703
+ let __emnapiWasmEnvSettlementLossReported = false
704
+ let __emnapiWasmEnvCleanupRan = false
705
+ let __emnapiWasmEnvCleanupDrained = false
706
+ let __emnapiWasmEnvCleanupDrainPromise
707
+ let __wasiDisposed = false
708
+ let __wasiAsyncWorkDrainPromise
709
+ let __wasiDisposePromise
710
+ let __completeWasiDisposal = function () {}
711
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
712
+ // that stopped short of destroying the context. See
713
+ // `__rollbackWasiInitialization`.
714
+ let __retainWasiRollbackForRetry = function () {}
715
+
716
+ function __isThenable(value) {
717
+ return (
718
+ value !== null &&
719
+ (typeof value === 'object' || typeof value === 'function') &&
720
+ typeof value.then === 'function'
721
+ )
722
+ }
723
+
724
+ function __createCleanupError(errors, message) {
725
+ if (errors.length === 1) {
726
+ return errors[0]
727
+ }
728
+ const __AggregateError = globalThis.AggregateError
729
+ if (typeof __AggregateError === 'function') {
730
+ return new __AggregateError(errors, message)
731
+ }
732
+ const error = new Error(message)
733
+ error.errors = errors
734
+ return error
735
+ }
736
+
737
+ function __attachCleanupErrors(error, cleanupErrors) {
738
+ if (cleanupErrors.length === 0) {
739
+ return error
740
+ }
741
+ const cleanupError = __createCleanupError(
742
+ cleanupErrors,
743
+ 'WASI binding cleanup failed',
744
+ )
745
+ try {
746
+ if (
747
+ error &&
748
+ (typeof error === 'object' || typeof error === 'function')
749
+ ) {
750
+ if (error.cause === undefined) {
751
+ error.cause = cleanupError
752
+ if (error.cause === cleanupError) {
753
+ return error
754
+ }
755
+ }
756
+ if (Array.isArray(error.cleanupErrors)) {
757
+ error.cleanupErrors.push(cleanupError)
758
+ return error
759
+ } else {
760
+ const attachedCleanupErrors = [cleanupError]
761
+ error.cleanupErrors = attachedCleanupErrors
762
+ if (error.cleanupErrors === attachedCleanupErrors) {
763
+ return error
764
+ }
765
+ }
766
+ }
767
+ } catch {}
768
+ const aggregate = __createCleanupError(
769
+ [error, cleanupError],
770
+ 'WASI binding initialization and cleanup failed',
771
+ )
772
+ try {
773
+ aggregate.cause = error
774
+ } catch {}
775
+ return aggregate
776
+ }
777
+
778
+ function __wrapEmnapiContextDestroyForSettlement(
779
+ context,
780
+ prepareEnvCleanup,
781
+ isPreparingEnvCleanup,
782
+ ) {
783
+ let destroy
784
+ try {
785
+ destroy = context.destroy
786
+ } catch {
787
+ return context
788
+ }
789
+ if (typeof destroy !== 'function') {
790
+ return context
791
+ }
792
+ try {
793
+ Object.defineProperty(context, 'destroy', {
794
+ configurable: true,
795
+ enumerable: false,
796
+ writable: true,
797
+ value: function () {
798
+ // Reentered from a promise hook that fired inside the barrier: the
799
+ // frame running it destroys as soon as it returns.
800
+ if (isPreparingEnvCleanup?.()) {
801
+ return
802
+ }
803
+ prepareEnvCleanup?.()
804
+ return Reflect.apply(destroy, this, arguments)
805
+ },
806
+ })
807
+ } catch {}
808
+ return context
809
+ }
810
+
811
+ function __isPreparingWasmEnvCleanup() {
812
+ return __emnapiWasmEnvCleanupPreparing
813
+ }
814
+
815
+ function __prepareWasmEnvCleanup() {
816
+ if (__emnapiWasmEnvCleanupPrepared) {
817
+ return
818
+ }
819
+ // A handshake parked between its two halves is one this frame can close, and
820
+ // must: every caller of this function is about to destroy the context, and
821
+ // the turns the poll is waiting for will not come — an 'exit' teardown is
822
+ // the last thing the process runs, and `Context.destroy()` takes the
823
+ // environment away. Closing it here runs `…_finish`, which is the call that joins, so
824
+ // this degrades to exactly the single call below. Leaving it open instead
825
+ // destroys the context with the barrier still raised, the runtime never
826
+ // joined and the workers never drained.
827
+ const finishParked = __finishParkedWasmEnvCleanup
828
+ if (finishParked !== undefined) {
829
+ finishParked()
830
+ __reportUnreachedWasmEnvSettlements()
831
+ return
832
+ }
833
+ if (__emnapiWasmEnvCleanupPreparing) {
834
+ return
835
+ }
836
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
837
+ if (typeof prepare === 'function') {
838
+ // The addon settles the promises it cancels synchronously, under a
839
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
840
+ // here must not reach this export again.
841
+ __emnapiWasmEnvCleanupPreparing = true
842
+ try {
843
+ prepare()
844
+ } finally {
845
+ __emnapiWasmEnvCleanupPreparing = false
846
+ }
847
+ __emnapiWasmEnvCleanupRan = true
848
+ __reportUnreachedWasmEnvSettlements()
849
+ }
850
+ __emnapiWasmEnvCleanupPrepared = true
851
+ }
852
+
853
+ /**
854
+ * Say so when the barrier leaves settlements queued and nothing is left that
855
+ * could deliver them.
856
+ *
857
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
858
+ * dispatch its queue. Every other caller of the barrier destroys in the same
859
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
860
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
861
+ * that queue with a null env and discards it. The promises those settlements
862
+ * were for then hang forever, silently.
863
+ *
864
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
865
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
866
+ * teardown down with it. Destroying anyway is still the right trade — the queue
867
+ * is already unreachable by then.
868
+ */
869
+ function __reportUnreachedWasmEnvSettlements() {
870
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
871
+ return
872
+ }
873
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
874
+ if (typeof pending !== 'function') {
875
+ return
876
+ }
877
+ let queued
878
+ try {
879
+ queued = pending()
880
+ } catch {
881
+ return
882
+ }
883
+ if (!queued) {
884
+ return
885
+ }
886
+ __emnapiWasmEnvSettlementLossReported = true
887
+ try {
888
+ const consoleHost = globalThis.console
889
+ if (consoleHost && typeof consoleHost.error === 'function') {
890
+ consoleHost.error(
891
+ "napi-rs: the wasm environment is being destroyed with " +
892
+ queued +
893
+ " queued promise settlement(s). Context.destroy() discards them, so those promises never settle. Dispose with binding[Symbol.for('napi.rs.wasi.dispose')]() instead: only it yields the event-loop turns the settlements need.",
894
+ )
895
+ }
896
+ } catch {}
897
+ }
898
+
899
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
900
+ // on, so the drain turns below interleave with that dispatch instead of racing
901
+ // ahead of it on a faster queue.
902
+ const __scheduleMacrotask = (function () {
903
+ if (typeof setImmediate === 'function') {
904
+ return function (callback) {
905
+ setImmediate(callback)
906
+ }
907
+ }
908
+ const __MessageChannel = globalThis.MessageChannel
909
+ if (typeof __MessageChannel === 'function') {
910
+ return function (callback) {
911
+ const channel = new __MessageChannel()
912
+ channel.port1.onmessage = function () {
913
+ channel.port1.onmessage = null
914
+ try {
915
+ channel.port1.close()
916
+ } catch {}
917
+ try {
918
+ channel.port2.close()
919
+ } catch {}
920
+ callback()
921
+ }
922
+ channel.port2.postMessage(null)
923
+ }
924
+ }
925
+ return function (callback) {
926
+ setTimeout(callback, 0)
927
+ }
928
+ })()
929
+
930
+ // A real, *referenced* timer, for waits that must let the whole host make
931
+ // progress between looks — the async-work drain polls the addon rather than
932
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
933
+ // would spin the loop instead of yielding it. Falls back to the macrotask
934
+ // scheduler on a host without timers.
935
+ function __scheduleTimer(callback, delay) {
936
+ const setTimer = globalThis.setTimeout
937
+ if (typeof setTimer !== 'function') {
938
+ __scheduleMacrotask(callback)
939
+ return
940
+ }
941
+ try {
942
+ setTimer(callback, delay)
943
+ } catch {
944
+ __scheduleMacrotask(callback)
945
+ }
946
+ }
947
+
948
+ // A real, referenced timer rather than a zero-delay macrotask, for the same
949
+ // reason the async-work drain uses one: this polls the addon instead of
950
+ // interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
951
+ // the loop instead of yielding it.
952
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
953
+ // Arrivals it takes before the poll paces on the host's timers alone. One
954
+ // proves nothing: a timer armed before the host's timers stopped still fires.
955
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
956
+ // How long a parked turn's own timer must already have been due before a
957
+ // backup that runs calls it dropped. Slack, not a deadline: a timer is due
958
+ // against the event loop's clock, which is read once per iteration, while
959
+ // these are `Date.now()` readings taken part-way through one, so the two
960
+ // drift apart by however long the loop has been inside the current iteration.
961
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
962
+ // How long a backup itself waits. What is left of it after the slack and one
963
+ // interval — 149 ms — has to cover the *two* poll turns that can separate a
964
+ // parked turn from the last backup armed while the host's timers still
965
+ // worked, so the ceiling on a single turn is half of it. See the invariant on
966
+ // `__armWasmRuntimePollStallBackup`.
967
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
968
+
969
+ /**
970
+ * Pacing state for one runtime-work poll.
971
+ *
972
+ * Per poll, never per module: whether the host's timers arrive is not a
973
+ * property of the module. A host can lose its timers between two disposals,
974
+ * and in the deferred shape every instance shares this module — one healthy
975
+ * instance must not disarm the fallback for the next one.
976
+ */
977
+ function __createWasmRuntimePollPace() {
978
+ return {
979
+ // Timers armed by *this* poll that have actually arrived.
980
+ arrivals: 0,
981
+ // The turn waiting on a timer alone *right now* — undefined whenever no
982
+ // turn is parked — and when that turn's own timer came due.
983
+ settleTurn: undefined,
984
+ turnTimerDueAt: 0,
985
+ }
986
+ }
987
+
988
+ /**
989
+ * The backup that ends a turn whose timer is never going to arrive.
990
+ *
991
+ * Once the poll paces on the timer alone it has nothing left to fall back on
992
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
993
+ * the turn that parks, and a parked poll schedules nothing that could notice.
994
+ * So every turn arms one of these before it yields, and each one compares due
995
+ * times instead of measuring how long the parked turn has been waiting.
996
+ *
997
+ * Invariant: a parked turn is ended by the newest backup that was armed while
998
+ * the host's timers still worked, and a backup ends a turn only when that
999
+ * turn's own timer was already due a whole window before the backup itself.
1000
+ * Neither half turns on how far apart the arms happen to fall — what bounds
1001
+ * the rescue is how far back that newest live backup is:
1002
+ *
1003
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
1004
+ * turn due a whole window earlier is still parked proves that turn's timer
1005
+ * was dropped rather than merely late. That same comparison is what leaves a
1006
+ * healthy host alone: there the turn's timer has already run and cleared
1007
+ * `settleTurn` before any backup due after it can look.
1008
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
1009
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
1010
+ * primitives and the macrotask wins, so such a turn can end with its own
1011
+ * timer — and the backup armed one line before it — already dead. The
1012
+ * arrival that then flips the poll onto the timer alone can itself be a
1013
+ * timer armed before the host's timers died. So the turn that parks can sit
1014
+ * two turns past the last live arm, and the newest live backup is due
1015
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
1016
+ * Arming on every turn is what holds it to two, rather than however far back
1017
+ * a throttle last let one through.
1018
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
1019
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
1020
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
1021
+ * Past that the turn stays parked and the disposal promise never settles.
1022
+ * The bound is deliberate: reaching it takes a host that drops timers
1023
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
1024
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
1025
+ * the second.
1026
+ *
1027
+ * The poll then goes back to arming both primitives until two fresh arrivals
1028
+ * prove the timers again. A host that stops running the timers it has
1029
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
1030
+ * pending rather than wedging the thread — the same outcome as a blocking
1031
+ * closure that never returns. Unreferenced wherever the host allows it: the
1032
+ * poll's own turn timers are what keep the loop alive, never these.
1033
+ */
1034
+ function __armWasmRuntimePollStallBackup(pace) {
1035
+ const setTimer = globalThis.setTimeout
1036
+ if (typeof setTimer !== 'function') {
1037
+ // Nothing to back up: `__scheduleTimer` is on the macrotask channel
1038
+ // already, and that one cannot park.
1039
+ return
1040
+ }
1041
+ // Read before arming, so this never claims to be due earlier than the timer
1042
+ // actually is: a backup ends a turn only when it is provably due after it.
1043
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS
1044
+ let handle
1045
+ try {
1046
+ handle = setTimer(() => {
1047
+ const settleTurn = pace.settleTurn
1048
+ if (
1049
+ !settleTurn ||
1050
+ pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS
1051
+ ) {
1052
+ // No turn is parked, or the parked one's timer came due too close to
1053
+ // this backup to call it dropped — it may still arrive, and the turn
1054
+ // that armed it armed a backup due a whole window after *that*.
1055
+ return
1056
+ }
1057
+ pace.arrivals = 0
1058
+ pace.settleTurn = undefined
1059
+ settleTurn()
1060
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS)
1061
+ } catch {
1062
+ return
1063
+ }
1064
+ if (handle && typeof handle.unref === 'function') {
1065
+ try {
1066
+ handle.unref()
1067
+ } catch {}
1068
+ }
1069
+ }
1070
+
1071
+ /**
1072
+ * One turn of the runtime-work poll.
1073
+ *
1074
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
1075
+ * missing or throws, but not when it is present, returns a handle and never
1076
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
1077
+ * host whose timers belong to an IO context that is already gone. That host
1078
+ * would park this poll forever, and the poll is unbounded, so nothing would
1079
+ * ever call `…_finish`.
1080
+ *
1081
+ * Arm both primitives until timers armed by this poll have arrived twice, and
1082
+ * let whichever lands first end the turn; the loser resolves nothing. A host
1083
+ * with working timers therefore pays the double arming for the first turn or
1084
+ * two — the macrotask wins the race, but the timers behind it still arrive and
1085
+ * are counted — and paces on the timer alone from then on, instead of spinning
1086
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
1087
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
1088
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
1089
+ * which ends the parked turn and puts this poll back on both.
1090
+ */
1091
+ function __yieldWasmRuntimePollTurn(pace) {
1092
+ // Armed before the turn yields, and by every turn: what rescues a parked
1093
+ // turn has to have been armed while the host's timers still worked, and the
1094
+ // turn that parks is the one whose own timer is already dead.
1095
+ __armWasmRuntimePollStallBackup(pace)
1096
+ return new Promise((resolve) => {
1097
+ let settled = false
1098
+ const settle = () => {
1099
+ if (settled) {
1100
+ return
1101
+ }
1102
+ settled = true
1103
+ if (pace.settleTurn === settle) {
1104
+ // Nothing is parked any more: a backup running later must not read a
1105
+ // due time this turn has already answered.
1106
+ pace.settleTurn = undefined
1107
+ }
1108
+ resolve()
1109
+ }
1110
+ __scheduleTimer(() => {
1111
+ pace.arrivals++
1112
+ settle()
1113
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS)
1114
+ // Read next to the arming it describes; see
1115
+ // `__armWasmRuntimePollStallBackup` for what the two due times mean.
1116
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS
1117
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
1118
+ __scheduleMacrotask(settle)
1119
+ return
1120
+ }
1121
+ // Paced by the timer alone from here; the backup is what ends this turn if
1122
+ // the timer never arrives.
1123
+ pace.settleTurn = settle
1124
+ pace.turnTimerDueAt = turnTimerDueAt
1125
+ })
1126
+ }
1127
+
1128
+ /**
1129
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
1130
+ * event-loop turns in the middle.
1131
+ *
1132
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
1133
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
1134
+ * waits on is this one, the only thread that can give a running blocking
1135
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
1136
+ * for work that can never finish. The addon's two-phase form splits that:
1137
+ * `…_begin` stops the runtime without joining and reports whether anything is
1138
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
1139
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
1140
+ * entire point.
1141
+ *
1142
+ * The poll has no deadline, for the same reason the async-work drain below has
1143
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
1144
+ * work it would join is the work that is waiting for a turn from this thread —
1145
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
1146
+ * thread can no longer be reached. A blocking closure that never returns keeps
1147
+ * the disposal promise pending instead, exactly as a task whose `execute` never
1148
+ * returns already keeps an *undisposed* process alive. The host contract is in
1149
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
1150
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
1151
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
1152
+ *
1153
+ * Feature-detected like every other export in this teardown, so an addon built
1154
+ * against a napi crate that predates the split keeps the single blocking call.
1155
+ * Returns nothing whenever the handshake finished without yielding, which keeps
1156
+ * an idle disposal synchronous.
1157
+ */
1158
+ function __prepareWasmEnvCleanupWithTurns() {
1159
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
1160
+ return
1161
+ }
1162
+ const exports = __napiInstance?.exports
1163
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin
1164
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish
1165
+ if (typeof begin !== 'function' || typeof finish !== 'function') {
1166
+ // No split to use. The settlement drain still follows this, so the queue
1167
+ // the single call leaves behind is expected rather than lost.
1168
+ __emnapiWasmEnvCleanupYielding = true
1169
+ try {
1170
+ __prepareWasmEnvCleanup()
1171
+ } finally {
1172
+ __emnapiWasmEnvCleanupYielding = false
1173
+ }
1174
+ return
1175
+ }
1176
+ const workPending = exports?.napi_wasm_runtime_work_pending
1177
+ // The in-flight flag stays raised across the turns below, so a `destroy()`
1178
+ // from one of the JavaScript handlers they run is the same no-op it is inside
1179
+ // the single call: the barrier is up and the runtime is mid-teardown, and
1180
+ // destroying between the halves would strand exactly what this delivers.
1181
+ __emnapiWasmEnvCleanupPreparing = true
1182
+ let live
1183
+ try {
1184
+ live = begin()
1185
+ } catch (error) {
1186
+ __emnapiWasmEnvCleanupPreparing = false
1187
+ throw error
1188
+ }
1189
+ __emnapiWasmEnvCleanupRan = true
1190
+ const finishCleanup = () => {
1191
+ if (__emnapiWasmEnvCleanupPrepared) {
1192
+ // Already closed by a caller that could not yield — the 'exit' teardown
1193
+ // reached `__prepareWasmEnvCleanup` while this poll was parked. `…_finish`
1194
+ // is idempotent, but the flags it lowers are not: running it again here
1195
+ // would clear a `preparing` some later barrier had raised.
1196
+ return
1197
+ }
1198
+ __finishParkedWasmEnvCleanup = undefined
1199
+ try {
1200
+ finish()
1201
+ } finally {
1202
+ __emnapiWasmEnvCleanupPreparing = false
1203
+ }
1204
+ __emnapiWasmEnvCleanupPrepared = true
1205
+ }
1206
+ if (!live || typeof workPending !== 'function') {
1207
+ finishCleanup()
1208
+ return
1209
+ }
1210
+ // Publish the closer before yielding: from here until `finishCleanup` runs,
1211
+ // a caller that cannot yield is entitled to end this handshake itself.
1212
+ __finishParkedWasmEnvCleanup = finishCleanup
1213
+ const finishCleanupUnlessCrashed = () => {
1214
+ try {
1215
+ __abortWasiDisposalIfThreadCrashed()
1216
+ } catch (error) {
1217
+ __finishParkedWasmEnvCleanup = undefined
1218
+ throw error
1219
+ }
1220
+ finishCleanup()
1221
+ }
1222
+ return (async () => {
1223
+ // Unbounded, exactly like the async-work drain below. The wait ends when
1224
+ // the addon reports its runtime work finished; the turns spent here are
1225
+ // what let that happen at all.
1226
+ const pace = __createWasmRuntimePollPace()
1227
+ for (;;) {
1228
+ await __yieldWasmRuntimePollTurn(pace)
1229
+ __abortWasiDisposalIfThreadCrashed()
1230
+ try {
1231
+ if (!workPending()) {
1232
+ return
1233
+ }
1234
+ } catch {
1235
+ // A trap is the only way this fails, and a trapped instance has no
1236
+ // reachable work left. Stop polling and finish.
1237
+ return
1238
+ }
1239
+ }
1240
+ })().then(finishCleanupUnlessCrashed, finishCleanupUnlessCrashed)
1241
+ }
1242
+
1243
+ // Turns to wait for while the addon still reports queued settlements. Reaching
1244
+ // zero is the only success. A counter still nonzero at this bound rejects the
1245
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
1246
+ // destroying the context over a still-queued settlement — the wait stays
1247
+ // bounded either way.
1248
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
1249
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
1250
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
1251
+ // call made on this thread (two), plus a margin.
1252
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
1253
+
1254
+ /**
1255
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
1256
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
1257
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
1258
+ * macrotask — two coalescing turns later, even for a call made on this very
1259
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
1260
+ * which drains the queue with a null env and *discards* whatever is still in it.
1261
+ *
1262
+ * So destroying without yielding first strands exactly the promises the barrier
1263
+ * exists to settle. Yield real event-loop turns until the addon reports the
1264
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
1265
+ * macrotask run.
1266
+ *
1267
+ * Returns nothing when there is nothing to wait for, which keeps disposal
1268
+ * synchronous in the common case.
1269
+ *
1270
+ * The "already drained" flag is set only once a wait has actually finished.
1271
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
1272
+ * that throws is enough — and a disposal that rejects stays retryable, so
1273
+ * marking the drain complete up front would make the retry skip it and destroy
1274
+ * the context with the barrier's settlements still queued.
1275
+ *
1276
+ * A wait that runs out of turns with the counter still nonzero rejects with
1277
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
1278
+ * "finished" is indistinguishable from the stranding above, and destroying
1279
+ * would discard the very settlement the wait was for. The rejection leaves the
1280
+ * flag unset and disposal retryable.
1281
+ */
1282
+ function __drainWasmEnvCleanup() {
1283
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
1284
+ return
1285
+ }
1286
+ if (__emnapiWasmEnvCleanupDrainPromise) {
1287
+ return __emnapiWasmEnvCleanupDrainPromise
1288
+ }
1289
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
1290
+ const observable = typeof pending === 'function'
1291
+ if (observable) {
1292
+ let queued
1293
+ try {
1294
+ queued = pending()
1295
+ } catch {
1296
+ __emnapiWasmEnvCleanupDrained = true
1297
+ return
1298
+ }
1299
+ if (!queued) {
1300
+ __emnapiWasmEnvCleanupDrained = true
1301
+ return
1302
+ }
1303
+ }
1304
+ const limit = observable
1305
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
1306
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
1307
+ const drainPromise = (async () => {
1308
+ let queued = 0
1309
+ for (let turn = 0; turn < limit; turn++) {
1310
+ await new Promise((resolve) => {
1311
+ __scheduleMacrotask(resolve)
1312
+ })
1313
+ if (!observable) {
1314
+ continue
1315
+ }
1316
+ try {
1317
+ queued = pending()
1318
+ } catch {
1319
+ return
1320
+ }
1321
+ if (!queued) {
1322
+ return
1323
+ }
1324
+ }
1325
+ if (!observable) {
1326
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
1327
+ // contract — there is nothing to consult, so finishing the turns is
1328
+ // finishing the drain.
1329
+ return
1330
+ }
1331
+ // The counter is still nonzero after every turn the bound allows. The wait
1332
+ // stays bounded — but claiming success here would be indistinguishable from
1333
+ // the stranding this drain exists to prevent: disposal would go on to
1334
+ // destroy the context, whose cleanup hook discards the still-queued
1335
+ // settlement with a null env, and the promise it was for hangs forever.
1336
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
1337
+ // unset, dispose() (and the rollback) decline to destroy, and a later
1338
+ // dispose() runs the drain again — by which time the queue has usually been
1339
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
1340
+ // attempt at most another bounded wait and a rejection, never a stranded
1341
+ // promise; the process-exit teardown still reclaims the context.
1342
+ const drainError = new Error(
1343
+ 'the wasm environment still reports ' +
1344
+ queued +
1345
+ ' queued settlement(s) after ' +
1346
+ limit +
1347
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
1348
+ )
1349
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
1350
+ throw drainError
1351
+ })().then(
1352
+ (value) => {
1353
+ // Set only when the wait actually finished AND the queue was seen empty
1354
+ // (or is unobservable): a drain that timed out with settlements still
1355
+ // queued rejects above and must stay repeatable.
1356
+ __emnapiWasmEnvCleanupDrained = true
1357
+ __emnapiWasmEnvCleanupDrainPromise = undefined
1358
+ return value
1359
+ },
1360
+ (error) => {
1361
+ __emnapiWasmEnvCleanupDrainPromise = undefined
1362
+ throw error
1363
+ },
1364
+ )
1365
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
1366
+ return drainPromise
1367
+ }
1368
+
1369
+ function __destroyEmnapiContext() {
1370
+ if (__emnapiContextDestroyed || __emnapiContext === undefined) {
1371
+ __emnapiContextDestroyed = true
1372
+ return
1373
+ }
1374
+ if (__emnapiContextDestroyPromise) {
1375
+ return __emnapiContextDestroyPromise
1376
+ }
1377
+
1378
+ __prepareWasmEnvCleanup()
1379
+ if (__isPreparingWasmEnvCleanup()) {
1380
+ // Reached from inside the synchronous barrier — a promise hook one of the
1381
+ // settlements above ran, which is the reentrancy the destroy wrapper
1382
+ // exists for. `Context.destroy()` below would hit that wrapper's in-flight
1383
+ // no-op and answer `undefined`, and recording that as a completed destroy
1384
+ // is what makes the frame that *did* start the barrier skip the real one
1385
+ // afterwards, leaving the context retained with its cleanup hooks unrun.
1386
+ // Refuse instead: nothing is flagged, and that frame destroys for real the
1387
+ // moment it returns. The deferred loader carries the same backstop. A
1388
+ // parked handshake cannot get here — `__prepareWasmEnvCleanup` closes one
1389
+ // rather than skipping it.
1390
+ return
1391
+ }
1392
+ const result = __emnapiContext.destroy()
1393
+ if (!__isThenable(result)) {
1394
+ __emnapiContextDestroyed = true
1395
+ return
1396
+ }
1397
+
1398
+ const destroyPromise = Promise.resolve(result).then(
1399
+ (value) => {
1400
+ __emnapiContextDestroyed = true
1401
+ return value
1402
+ },
1403
+ (error) => {
1404
+ __emnapiContextDestroyPromise = undefined
1405
+ throw error
1406
+ },
1407
+ )
1408
+ __emnapiContextDestroyPromise = destroyPromise
1409
+ return destroyPromise
1410
+ }
1411
+
1412
+ /**
1413
+ * Holds the event loop open until `work` settles.
1414
+ *
1415
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
1416
+ * binding cannot keep a process alive, and referencing them again for the
1417
+ * termination does not hold either — emnapi unreferences a worker the moment it
1418
+ * reports `async-thread-ready`, which for a worker that was still starting
1419
+ * lands *after* the termination began. Without a handle of its own, an
1420
+ * `await dispose()` with nothing else pending exits the process with its
1421
+ * promise unsettled, and everything after the `await` is skipped.
1422
+ *
1423
+ * The timer is cleared as soon as the work settles, so this never outlives the
1424
+ * disposal that asked for it.
1425
+ */
1426
+ function __keepEventLoopAliveUntil(work) {
1427
+ const setTimer = globalThis.setInterval
1428
+ const clearTimer = globalThis.clearInterval
1429
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
1430
+ return work
1431
+ }
1432
+ let timer
1433
+ try {
1434
+ timer = setTimer(function () {}, 50)
1435
+ } catch {
1436
+ return work
1437
+ }
1438
+ const release = function () {
1439
+ try {
1440
+ clearTimer(timer)
1441
+ } catch {}
1442
+ }
1443
+ return work.then(
1444
+ (value) => {
1445
+ release()
1446
+ return value
1447
+ },
1448
+ (error) => {
1449
+ release()
1450
+ throw error
1451
+ },
1452
+ )
1453
+ }
1454
+
1455
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
1456
+ // ends when the addon reports zero, so this only decides how promptly disposal
1457
+ // notices — not how long it waits.
1458
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
1459
+
1460
+ /**
1461
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
1462
+ * would strand it.
1463
+ *
1464
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
1465
+ * it is observable from JavaScript: the threadless archive resolves
1466
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
1467
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
1468
+ * imports nor exports those symbols and the only brackets a loader could watch
1469
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
1470
+ * functions. The addon is the one place both flavors go through, so it answers
1471
+ * for both, through the same kind of handshake the settlement drain uses:
1472
+ *
1473
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
1474
+ * started. Those completion callbacks run with `napi_cancelled`, which
1475
+ * napi-rs turns into a promise rejected with an `AbortError`.
1476
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
1477
+ * callback. Work already executing refuses cancellation and stays counted
1478
+ * until it finishes normally — which it can, because this runs before the
1479
+ * barrier, before `Context.destroy()` and before anything is terminated.
1480
+ *
1481
+ * Both exports are optional: an addon built against a napi crate that predates
1482
+ * them drains nothing and keeps the previous behavior, exactly as the
1483
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
1484
+ *
1485
+ * Returns nothing when there is nothing outstanding, which keeps disposal
1486
+ * synchronous in the common case. The promise it returns otherwise never
1487
+ * rejects.
1488
+ *
1489
+ * The wait has no deadline, and that is the point: giving up would destroy the
1490
+ * environment with a completion callback still owed, which is the stranding
1491
+ * this exists to prevent. A task whose `execute` never returns already keeps an
1492
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
1493
+ * rather than inventing a bound it cannot honor.
1494
+ *
1495
+ * Safe to call from inside a completion callback, which is reachable: settling
1496
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
1497
+ * being handed back, a threadsafe-function callback — and that JavaScript can
1498
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
1499
+ *
1500
+ * - The addon keeps a work registered until its completion callback
1501
+ * *finishes*, so the count read here is at least one and this takes the
1502
+ * polling path instead of declaring the environment drained and tearing it
1503
+ * down from inside the frame that is still settling a promise.
1504
+ * - The poll is a timer, so it cannot run until the callback has returned to
1505
+ * the host — by which time that work has left the registry. The count the
1506
+ * next poll reads is the one taken after the callback finished.
1507
+ *
1508
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
1509
+ * nested call joins this disposal rather than starting a second one.
1510
+ */
1511
+ function __drainWasiAsyncWork() {
1512
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
1513
+ return __wasiAsyncWorkDrainPromise
1514
+ }
1515
+ const exports = __napiInstance?.exports
1516
+ const pending = exports?.napi_wasm_async_work_pending
1517
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
1518
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
1519
+ return
1520
+ }
1521
+
1522
+ const readPending = () => {
1523
+ try {
1524
+ return pending()
1525
+ } catch (error) {
1526
+ // A trap is the only way this call fails: it reads a counter and cannot
1527
+ // allocate or call back into JavaScript. A trapped instance can no longer
1528
+ // run anything, so its outstanding work is unreachable by definition —
1529
+ // there is nothing left to wait for, and refusing to dispose would only
1530
+ // keep a dead instance and its stuck counter alive. Best-effort here is
1531
+ // the honest answer, and it is what disposal did before this drain
1532
+ // existed.
1533
+ //
1534
+ // Only a trap. Anything else means the export is not what this loader
1535
+ // thinks it is, which is a defect worth surfacing rather than disposing
1536
+ // over.
1537
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
1538
+ return 0
1539
+ }
1540
+ throw error
1541
+ }
1542
+ }
1543
+
1544
+ if (!readPending()) {
1545
+ return
1546
+ }
1547
+ try {
1548
+ cancelPending()
1549
+ } catch {
1550
+ // Cancellation is an optimization: it bounds the wait by the work already
1551
+ // executing. Failing it only means waiting for the whole queue instead.
1552
+ }
1553
+ if (!readPending()) {
1554
+ return
1555
+ }
1556
+
1557
+ const drainPromise = __keepEventLoopAliveUntil(
1558
+ (async () => {
1559
+ while (readPending()) {
1560
+ await new Promise((resolve) => {
1561
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
1562
+ })
1563
+ __abortWasiDisposalIfThreadCrashed()
1564
+ }
1565
+ })(),
1566
+ ).then(
1567
+ () => {
1568
+ __wasiAsyncWorkDrainPromise = undefined
1569
+ },
1570
+ (error) => {
1571
+ // A wait that could not run is not a wait that finished. The only way
1572
+ // here is a host whose timers and macrotask primitives all refuse, and
1573
+ // the work is still outstanding — reporting success would destroy the
1574
+ // environment over it, which is the stranding this exists to prevent.
1575
+ // Reject instead: disposal stays retryable, and the context is not
1576
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
1577
+ __wasiAsyncWorkDrainPromise = undefined
1578
+ throw error
1579
+ },
1580
+ )
1581
+ __wasiAsyncWorkDrainPromise = drainPromise
1582
+ return drainPromise
1583
+ }
1584
+
1585
+ /**
1586
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
1587
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
1588
+ * the manager's `exit` listener instead, which reports
1589
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
1590
+ * inside the emit — aborting the `once('exit')` that backs the terminate
1591
+ * promise, so disposal never settles and the process dies with an uncaught
1592
+ * exception. Mark the termination through the manager first.
1593
+ *
1594
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
1595
+ * the initialization rollback runs on the one path where instantiation never
1596
+ * returned, so `__napiModule` is still undefined there while the workers it
1597
+ * spawned are already registered and loaded.
1598
+ *
1599
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
1600
+ */
1601
+ function __terminateWasiWorkers() {
1602
+ const cleanupErrors = []
1603
+ const pending = []
1604
+ const threadManager = __getWasiThreadManager()
1605
+
1606
+ for (const worker of __wasiWorkers) {
1607
+ let result
1608
+ try {
1609
+ if (threadManager) {
1610
+ threadManager.terminateWorker(worker)
1611
+ // `terminateWorker` leaves behind a reporter that logs every message
1612
+ // still queued on the port, which Node flushes on exit. Nothing is
1613
+ // listening for those any more.
1614
+ worker.onmessage = undefined
1615
+ }
1616
+ result = worker.terminate()
1617
+ } catch (error) {
1618
+ cleanupErrors.push(error)
1619
+ continue
1620
+ }
1621
+ if (__isThenable(result)) {
1622
+ pending.push(
1623
+ Promise.resolve(result).then(
1624
+ () => {
1625
+ __wasiWorkers.delete(worker)
1626
+ },
1627
+ (error) => {
1628
+ cleanupErrors.push(error)
1629
+ },
1630
+ ),
1631
+ )
1632
+ } else {
1633
+ __wasiWorkers.delete(worker)
1634
+ }
1635
+ }
1636
+
1637
+ const finish = () => {
1638
+ if (cleanupErrors.length > 0) {
1639
+ throw __createCleanupError(
1640
+ cleanupErrors,
1641
+ 'Failed to terminate WASI workers',
1642
+ )
1643
+ }
1644
+ }
1645
+ return pending.length > 0
1646
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
1647
+ : finish()
1648
+ }
1649
+
1650
+ function __finishWasiDisposal() {
1651
+ const workerResult = __terminateWasiWorkers()
1652
+ if (__isThenable(workerResult)) {
1653
+ return Promise.resolve(workerResult).then(__completeWasiDisposal)
1654
+ }
1655
+ return __completeWasiDisposal()
1656
+ }
1657
+
1658
+ function __continueWasiDisposal() {
1659
+ __abortWasiDisposalIfThreadCrashed()
1660
+ const destroyResult = __destroyEmnapiContext()
1661
+ if (__isThenable(destroyResult)) {
1662
+ return Promise.resolve(destroyResult).then(__finishWasiDisposal)
1663
+ }
1664
+ return __finishWasiDisposal()
1665
+ }
1666
+
1667
+ function __drainWasmEnvForWasiDisposal() {
1668
+ __abortWasiDisposalIfThreadCrashed()
1669
+ const drainResult = __drainWasmEnvCleanup()
1670
+ if (__isThenable(drainResult)) {
1671
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
1672
+ }
1673
+ return __continueWasiDisposal()
1674
+ }
1675
+
1676
+ function __cleanUpWasmEnvForWasiDisposal() {
1677
+ __abortWasiDisposalIfThreadCrashed()
1678
+ // Run the pre-teardown barrier — yielding the turns its two-phase form asks
1679
+ // for, when the addon has one — then let the settlements it queued actually
1680
+ // reach JavaScript, and only then destroy the environment. Doing any two of
1681
+ // these back to back is what strands them.
1682
+ const prepareResult = __prepareWasmEnvCleanupWithTurns()
1683
+ if (__isThenable(prepareResult)) {
1684
+ return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal)
1685
+ }
1686
+ return __drainWasmEnvForWasiDisposal()
1687
+ }
1688
+
1689
+ function __startWasiDisposal() {
1690
+ // Outstanding `napi_async_work` goes first, while the environment is still
1691
+ // completely live: the completion callbacks run addon code, and everything
1692
+ // after this point takes that away from them — the barrier shuts the async
1693
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
1694
+ // the pool threads removes what would have reported the work finished.
1695
+ const asyncWorkResult = __drainWasiAsyncWork()
1696
+ if (__isThenable(asyncWorkResult)) {
1697
+ return Promise.resolve(asyncWorkResult).then(
1698
+ __cleanUpWasmEnvForWasiDisposal,
1699
+ )
1700
+ }
1701
+ return __cleanUpWasmEnvForWasiDisposal()
1702
+ }
1703
+
1704
+ /**
1705
+ * Disposes this generated WASI binding.
1706
+ *
1707
+ * Access this function with:
1708
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
1709
+ */
1710
+ function __disposeWasiBinding() {
1711
+ if (__wasiDisposePromise) {
1712
+ return __wasiDisposePromise
1713
+ }
1714
+ if (!__wasiDisposed && __hasWasiThreadCrashed()) {
1715
+ return __disposeWasiBindingAfterThreadCrash()
1716
+ }
1717
+ if (__wasiDisposed) {
1718
+ return Promise.resolve()
1719
+ }
1720
+
1721
+ let resolveDispose
1722
+ let rejectDispose
1723
+ const disposePromise = new Promise((resolve, reject) => {
1724
+ resolveDispose = resolve
1725
+ rejectDispose = reject
1726
+ })
1727
+ __wasiDisposePromise = disposePromise
1728
+
1729
+ let result
1730
+ try {
1731
+ result = __startWasiDisposal()
1732
+ } catch (error) {
1733
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1734
+ return disposePromise
1735
+ }
1736
+ __wasiDisposePromise = undefined
1737
+ rejectDispose(error)
1738
+ return disposePromise
1739
+ }
1740
+
1741
+ Promise.resolve(result).then(
1742
+ (value) => {
1743
+ __wasiDisposed = true
1744
+ resolveDispose(value)
1745
+ },
1746
+ (error) => {
1747
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1748
+ return
1749
+ }
1750
+ __wasiDisposePromise = undefined
1751
+ rejectDispose(error)
1752
+ },
1753
+ )
1754
+ return disposePromise
1755
+ }
1756
+
1757
+ function __publishWasiDispose(exports) {
1758
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
1759
+ configurable: false,
1760
+ enumerable: false,
1761
+ value: __disposeWasiBinding,
1762
+ writable: false,
1763
+ })
1764
+ }
1765
+
1766
+ function __finishWasiInitializationRollback(cleanupErrors) {
1767
+ let workerResult
1768
+ try {
1769
+ workerResult = __terminateWasiWorkers()
1770
+ } catch (cleanupError) {
1771
+ cleanupErrors.push(cleanupError)
1772
+ return cleanupErrors
1773
+ }
1774
+ if (__isThenable(workerResult)) {
1775
+ return Promise.resolve(workerResult)
1776
+ .catch((cleanupError) => {
1777
+ cleanupErrors.push(cleanupError)
1778
+ })
1779
+ .then(() => cleanupErrors)
1780
+ }
1781
+ return cleanupErrors
1782
+ }
1783
+
1784
+ function __destroyContextForWasiRollback(cleanupErrors) {
1785
+ __abortWasiDisposalIfThreadCrashed()
1786
+ let destroyResult
1787
+ try {
1788
+ destroyResult = __destroyEmnapiContext()
1789
+ } catch (cleanupError) {
1790
+ cleanupErrors.push(cleanupError)
1791
+ return __finishWasiInitializationRollback(cleanupErrors)
1792
+ }
1793
+ if (__isThenable(destroyResult)) {
1794
+ return Promise.resolve(destroyResult)
1795
+ .catch((cleanupError) => {
1796
+ cleanupErrors.push(cleanupError)
1797
+ })
1798
+ .then(() => __finishWasiInitializationRollback(cleanupErrors))
1799
+ }
1800
+ return __finishWasiInitializationRollback(cleanupErrors)
1801
+ }
1802
+
1803
+ /**
1804
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
1805
+ * hands it to whatever this flavor has that can still reclaim it.
1806
+ */
1807
+ function __retainFailedWasiRollback(cleanupErrors) {
1808
+ try {
1809
+ __retainWasiRollbackForRetry()
1810
+ } catch (cleanupError) {
1811
+ cleanupErrors.push(cleanupError)
1812
+ }
1813
+ return cleanupErrors
1814
+ }
1815
+
1816
+ /**
1817
+ * Initialization can fail *after* registration has already run, and registration
1818
+ * runs with a live environment: a module-init hook can start async work and then
1819
+ * return an error, and the promise it created may already have escaped into
1820
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
1821
+ * path needs the same drain the ordinary disposal does — destroying without
1822
+ * yielding discards the queue with a null env and strands the promise.
1823
+ *
1824
+ * Stays synchronous when nothing is queued, which covers every failure before
1825
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
1826
+ *
1827
+ * A barrier or drain that did *not* finish stops the rollback short of
1828
+ * destroying, which is what `dispose()` already does — a rejected drain there
1829
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
1830
+ * two trades, and not because of what it saves:
1831
+ *
1832
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
1833
+ * threadsafe function's cleanup hook, which drains the queue with a null env
1834
+ * and discards it, so a promise that already escaped into JavaScript hangs
1835
+ * forever with nothing left that could ever settle it.
1836
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
1837
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
1838
+ * which this module's scope holds either way. What stopping short retains is
1839
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
1840
+ * - Retry is not theoretical. A rollback that records a cleanup error is
1841
+ * already kept in the process-wide registry above, so re-`require()`ing this
1842
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
1843
+ * means the replay drains again rather than skipping it. Destroying first is
1844
+ * what makes that retained record useless.
1845
+ *
1846
+ * The residual cost is honest: the CJS flavor hands the context to its
1847
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
1848
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
1849
+ * throws while evaluating is permanently errored, so re-importing rethrows
1850
+ * without re-running this file — and there the context stays until the realm
1851
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
1852
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
1853
+ */
1854
+ function __runWasiInitializationRollbackSteps() {
1855
+ // The environment teardown this rollback performs, kept nested so it cannot
1856
+ // be reached without the async-work drain below running first.
1857
+ function __rollbackWasmEnvForWasiInitialization() {
1858
+ __abortWasiDisposalIfThreadCrashed()
1859
+ const cleanupErrors = []
1860
+ let prepareResult
1861
+ try {
1862
+ prepareResult = __prepareWasmEnvCleanupWithTurns()
1863
+ } catch (cleanupError) {
1864
+ cleanupErrors.push(cleanupError)
1865
+ return __retainFailedWasiRollback(cleanupErrors)
1866
+ }
1867
+ if (__isThenable(prepareResult)) {
1868
+ return Promise.resolve(prepareResult).then(
1869
+ () => __drainWasmEnvForWasiRollback(cleanupErrors),
1870
+ (cleanupError) => {
1871
+ cleanupErrors.push(cleanupError)
1872
+ return __retainFailedWasiRollback(cleanupErrors)
1873
+ },
1874
+ )
1875
+ }
1876
+ return __drainWasmEnvForWasiRollback(cleanupErrors)
1877
+ }
1878
+
1879
+ // The settlement drain of the rollback above, reached either straight away or
1880
+ // after the barrier's two-phase form has yielded its turns. A barrier that
1881
+ // did not finish never gets here: it retains instead, exactly as a drain that
1882
+ // did not finish does.
1883
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
1884
+ __abortWasiDisposalIfThreadCrashed()
1885
+ let drainResult
1886
+ try {
1887
+ drainResult = __drainWasmEnvCleanup()
1888
+ } catch (cleanupError) {
1889
+ cleanupErrors.push(cleanupError)
1890
+ return __retainFailedWasiRollback(cleanupErrors)
1891
+ }
1892
+ if (__isThenable(drainResult)) {
1893
+ return Promise.resolve(drainResult).then(
1894
+ () => __destroyContextForWasiRollback(cleanupErrors),
1895
+ (cleanupError) => {
1896
+ cleanupErrors.push(cleanupError)
1897
+ return __retainFailedWasiRollback(cleanupErrors)
1898
+ },
1899
+ )
1900
+ }
1901
+ return __destroyContextForWasiRollback(cleanupErrors)
1902
+ }
1903
+
1904
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
1905
+ // work before the load goes on to fail, and this rollback tears down exactly
1906
+ // what those completions need. Settle them while everything is still live,
1907
+ // before the barrier and the teardown above take that away.
1908
+ //
1909
+ // A drain that could not finish leaves async work possibly outstanding, and
1910
+ // destroying the context over it would strand exactly what this rollback is
1911
+ // there to settle. Stop short and retain instead — the same trade
1912
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
1913
+ // the context stays reclaimable by a retry or by this flavor's own
1914
+ // last-resort teardown.
1915
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
1916
+ __retainFailedWasiRollback([cleanupError])
1917
+ let asyncWorkResult
1918
+ try {
1919
+ asyncWorkResult = __drainWasiAsyncWork()
1920
+ } catch (cleanupError) {
1921
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
1922
+ }
1923
+ if (__isThenable(asyncWorkResult)) {
1924
+ return Promise.resolve(asyncWorkResult).then(
1925
+ __rollbackWasmEnvForWasiInitialization,
1926
+ __retainAfterAsyncWorkDrainFailure,
1927
+ )
1928
+ }
1929
+ return __rollbackWasmEnvForWasiInitialization()
1930
+ }
1931
+
1932
+ /**
1933
+ * The rollback above, stopped when a wasm thread has died.
1934
+ *
1935
+ * Its polls wait for work the dead thread still counts, so they never end, and
1936
+ * the barrier's `…_finish` and `Context.destroy()` would re-enter wasm
1937
+ * and wait on that thread for good. While the rollback runs, the poll turns
1938
+ * and step boundaries stop it (`__abortWasiDisposalIfThreadCrashed`), and a
1939
+ * crash seen before, during or after it ends it through
1940
+ * `__rollbackWasiInitializationAfterThreadCrash`. Without a crash the
1941
+ * result — synchronous or not — is passed through unchanged.
1942
+ */
1943
+ function __rollbackWasiInitialization() {
1944
+ if (__hasWasiThreadCrashed()) {
1945
+ return __rollbackWasiInitializationAfterThreadCrash()
1946
+ }
1947
+ __wasiInitializationRollbackActive = true
1948
+ let result
1949
+ try {
1950
+ result = __runWasiInitializationRollbackSteps()
1951
+ } catch (error) {
1952
+ __wasiInitializationRollbackActive = false
1953
+ if (__hasWasiThreadCrashed()) {
1954
+ return __rollbackWasiInitializationAfterThreadCrash()
1955
+ }
1956
+ throw error
1957
+ }
1958
+ if (!__isThenable(result)) {
1959
+ __wasiInitializationRollbackActive = false
1960
+ return __hasWasiThreadCrashed()
1961
+ ? __rollbackWasiInitializationAfterThreadCrash()
1962
+ : result
1963
+ }
1964
+ return Promise.resolve(result).then(
1965
+ (cleanupErrors) => {
1966
+ __wasiInitializationRollbackActive = false
1967
+ return __hasWasiThreadCrashed()
1968
+ ? __rollbackWasiInitializationAfterThreadCrash()
1969
+ : cleanupErrors
1970
+ },
1971
+ (error) => {
1972
+ __wasiInitializationRollbackActive = false
1973
+ if (__hasWasiThreadCrashed()) {
1974
+ return __rollbackWasiInitializationAfterThreadCrash()
1975
+ }
1976
+ throw error
1977
+ },
1978
+ )
1979
+ }
1980
+
1981
+ const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
1982
+ const __wasiRollbackRegistryKey =
1983
+ typeof __filename === 'string' ? __filename : __wasmFilePath
1984
+
1985
+ function __getWasiRollbackRegistry() {
1986
+ const existing = process[__wasiRollbackRegistrySymbol]
1987
+ if (existing !== undefined) {
1988
+ if (!(existing instanceof Map)) {
1989
+ throw new TypeError(
1990
+ 'The process-wide NAPI-RS WASI rollback registry is invalid',
1991
+ )
1992
+ }
1993
+ return existing
1994
+ }
1995
+ const registry = new Map()
1996
+ Object.defineProperty(process, __wasiRollbackRegistrySymbol, {
1997
+ configurable: false,
1998
+ enumerable: false,
1999
+ value: registry,
2000
+ writable: false,
2001
+ })
2002
+ return registry
2003
+ }
2004
+
2005
+ const __wasiRollbackRegistry = __getWasiRollbackRegistry()
2006
+
2007
+ function __completeWasiInitializationRollback(record, cleanupErrors) {
2008
+ try {
2009
+ if (cleanupErrors.length === 0) {
2010
+ if (
2011
+ __wasiRollbackRegistry.get(__wasiRollbackRegistryKey) === record
2012
+ ) {
2013
+ __wasiRollbackRegistry.delete(__wasiRollbackRegistryKey)
2014
+ }
2015
+ return
2016
+ }
2017
+ record.error = __attachCleanupErrors(record.error, cleanupErrors)
2018
+ } catch (cleanupError) {
2019
+ try {
2020
+ record.error = __createCleanupError(
2021
+ [record.error, cleanupError],
2022
+ 'WASI binding initialization and cleanup failed',
2023
+ )
2024
+ } catch {}
2025
+ } finally {
2026
+ record.active = false
2027
+ record.promise = undefined
2028
+ }
2029
+ }
2030
+
2031
+ function __runWasiInitializationRollback(record) {
2032
+ if (record.active) {
2033
+ return
2034
+ }
2035
+ record.active = true
2036
+
2037
+ let rollbackResult
2038
+ try {
2039
+ rollbackResult = record.rollback()
2040
+ } catch (cleanupError) {
2041
+ __completeWasiInitializationRollback(record, [cleanupError])
2042
+ return
2043
+ }
2044
+
2045
+ if (!__isThenable(rollbackResult)) {
2046
+ __completeWasiInitializationRollback(record, rollbackResult)
2047
+ return
2048
+ }
2049
+
2050
+ record.promise = Promise.resolve(rollbackResult).then(
2051
+ (cleanupErrors) => {
2052
+ __completeWasiInitializationRollback(record, cleanupErrors)
2053
+ },
2054
+ (cleanupError) => {
2055
+ __completeWasiInitializationRollback(record, [cleanupError])
2056
+ },
2057
+ )
2058
+ }
2059
+
2060
+ const __pendingWasiRollback = __wasiRollbackRegistry.get(
2061
+ __wasiRollbackRegistryKey,
2062
+ )
2063
+ if (__pendingWasiRollback !== undefined) {
2064
+ __runWasiInitializationRollback(__pendingWasiRollback)
2065
+ throw __pendingWasiRollback.error
2066
+ }
2067
+
2068
+ let __wasiModule
2069
+ let __napiModule
2070
+ let __wasiExitListenerRegistered = false
2071
+
2072
+ function __removeWasiExitListener() {
2073
+ if (
2074
+ __wasiExitListenerRegistered &&
2075
+ typeof process.removeListener === 'function'
2076
+ ) {
2077
+ process.removeListener('exit', __disposeWasiBindingAtExit)
2078
+ }
2079
+ __wasiExitListenerRegistered = false
2080
+ }
2081
+
2082
+ function __disposeWasiBindingAtExit() {
2083
+ __wasiExitListenerRegistered = false
2084
+ if (__hasWasiThreadCrashed()) {
2085
+ // Never re-enter wasm after a thread died: the environment cleanup joins
2086
+ // the dead thread's work and would hang the exit forever — SIGTERM
2087
+ // included, since its JavaScript listener never gets a turn. Stop the
2088
+ // workers and leave.
2089
+ try {
2090
+ void Promise.resolve(__terminateWasiWorkers()).catch(() => {})
2091
+ } catch {}
2092
+ return
2093
+ }
2094
+ // An 'exit' handler cannot yield, so it cannot wait for queued promise
2095
+ // settlements the way __startWasiDisposal does — the process is leaving and
2096
+ // those promises have no observer left anyway. Run the synchronous teardown
2097
+ // directly. Every step is idempotent, which also makes this the synchronous
2098
+ // finish for a disposal that is still waiting for its drain — and, through
2099
+ // __prepareWasmEnvCleanup, for one still parked between the two halves of
2100
+ // the environment cleanup barrier: there are no turns left to poll with, so
2101
+ // this closes that handshake with `…_finish`, which joins.
2102
+ try {
2103
+ __destroyEmnapiContext()
2104
+ } catch {}
2105
+ try {
2106
+ const workerResult = __terminateWasiWorkers()
2107
+ if (__isThenable(workerResult)) {
2108
+ void Promise.resolve(workerResult).catch(() => {})
2109
+ }
2110
+ } catch {}
2111
+ }
2112
+
2113
+ function __registerWasiExitListener() {
2114
+ if (
2115
+ !__wasiExitListenerRegistered &&
2116
+ typeof process.once === 'function'
2117
+ ) {
2118
+ process.once('exit', __disposeWasiBindingAtExit)
2119
+ __wasiExitListenerRegistered = true
2120
+ }
2121
+ }
2122
+
2123
+ __completeWasiDisposal = __removeWasiExitListener
2124
+ // A rollback that could not reach the queued settlements keeps the context so
2125
+ // the registry replay above can retry it. Nothing forces that replay to happen,
2126
+ // so hand the context to the same synchronous teardown a successful load uses:
2127
+ // a process that exits without ever retrying still runs the cleanup hooks. The
2128
+ // handler cannot yield, so it does not settle anything — but by then the process
2129
+ // is leaving and those promises have no observer left anyway.
2130
+ __retainWasiRollbackForRetry = __registerWasiExitListener
2131
+
2132
+ function __captureEmnapiAutoDestroyListener() {
2133
+ if (
2134
+ typeof process.prependListener !== 'function' ||
2135
+ typeof process.removeListener !== 'function'
2136
+ ) {
2137
+ return
2138
+ }
2139
+ let __autoDestroyListener
2140
+ const __captureListener = (__event, __listener) => {
2141
+ if (__event === 'beforeExit' && __autoDestroyListener === undefined) {
2142
+ __autoDestroyListener = __listener
2143
+ }
2144
+ }
2145
+ try {
2146
+ // Run before existing newListener hooks so a hook that registers its own
2147
+ // beforeExit listener cannot be mistaken for emnapi's registration.
2148
+ process.prependListener('newListener', __captureListener)
2149
+ } catch {
2150
+ return
2151
+ }
2152
+ return () => {
2153
+ try {
2154
+ process.removeListener('newListener', __captureListener)
2155
+ } catch {}
2156
+ if (__autoDestroyListener !== undefined) {
2157
+ try {
2158
+ process.removeListener('beforeExit', __autoDestroyListener)
2159
+ } catch {}
2160
+ }
2161
+ }
2162
+ }
2163
+
2164
+ try {
2165
+ const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
2166
+ try {
2167
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
2168
+ __emnapiCreateContext({ autoDestroy: false, features: { setImmediate: __wasiSetImmediate } }),
2169
+ __prepareWasmEnvCleanup,
2170
+ __isPreparingWasmEnvCleanup,
2171
+ )
2172
+ // emnapi 2.x still registers an unconditional once-listener for
2173
+ // beforeExit that auto-destroys the context, and suppressDestroy() only
2174
+ // neutralizes its callback without removing it. This loader owns cleanup
2175
+ // through its 'exit' listener, so emnapi's listener is captured and
2176
+ // removed; suppressDestroy() remains the safety net when removal fails.
2177
+ __emnapiContext.suppressDestroy()
2178
+ } finally {
2179
+ // Remove only the exact emnapi callback captured above.
2180
+ __finishAutoDestroyCapture?.()
2181
+ }
2182
+
2183
+ ;({
2184
+ instance: __napiInstance,
2185
+ module: __wasiModule,
2186
+ napiModule: __napiModule,
2187
+ } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
2188
+ context: __emnapiContext,
2189
+ asyncWorkPoolSize: (function () {
2190
+ const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE)
2191
+ // NaN > 0 is false
2192
+ if (threadsSizeFromEnv > 0) {
2193
+ return threadsSizeFromEnv
2194
+ } else {
2195
+ return 4
2196
+ }
2197
+ })(),
2198
+ reuseWorker: true,
2199
+ plugins: [
2200
+ __captureWasiThreadManager,
2201
+ __emnapiAsyncWorkPlugin,
2202
+ __emnapiTSFNPlugin,
2203
+ ],
2204
+ wasi: __wasi,
2205
+ onCreateWorker() {
2206
+ const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
2207
+ __wasiWorkers.add(worker)
2208
+ // Registered before emnapi's own listeners, which rethrow the error.
2209
+ worker.on('error', (error) => {
2210
+ __wasiThreadCrashed = true
2211
+ __recordWasiThreadCrashError(error, worker.threadId)
2212
+ })
2213
+ worker.onmessage = ({ data }) => {
2214
+ __wasmCreateOnMessageForFsProxy(__nodeFs)(data)
2215
+ }
2216
+
2217
+ // The main thread of Node.js waits for all the active handles before exiting.
2218
+ // But Rust threads are never waited without `thread::join`.
2219
+ // So here we hack the code of Node.js to prevent the workers from being referenced (active).
2220
+ // According to https://github.com/nodejs/node/blob/19e0d472728c79d418b74bddff588bea70a403d0/lib/internal/worker.js#L415,
2221
+ // a worker is consist of two handles: kPublicPort and kHandle.
2222
+ {
2223
+ const kPublicPort = Object.getOwnPropertySymbols(worker).find((s) =>
2224
+ s.toString().includes('kPublicPort'),
2225
+ )
2226
+ if (kPublicPort) {
2227
+ worker[kPublicPort].ref = () => {}
2228
+ }
2229
+
2230
+ const kHandle = Object.getOwnPropertySymbols(worker).find((s) =>
2231
+ s.toString().includes('kHandle'),
2232
+ )
2233
+ if (kHandle) {
2234
+ worker[kHandle].ref = () => {}
2235
+ }
2236
+
2237
+ worker.unref()
2238
+ // These stubs stay in place for the worker's whole life, disposal
2239
+ // included: `__keepEventLoopAliveUntil` is what holds the process open
2240
+ // while a termination is pending, precisely because a worker's own
2241
+ // references cannot be relied on for it.
2242
+ }
2243
+ return worker
2244
+ },
2245
+ overwriteImports(importObject) {
2246
+ importObject.env = {
2247
+ ...importObject.env,
2248
+ ...importObject.napi,
2249
+ ...importObject.emnapi,
2250
+ memory: __sharedMemory,
2251
+ }
2252
+ return importObject
2253
+ },
2254
+ beforeInit({ instance }) {
2255
+ __napiInstance = instance
2256
+ __captureWasiAddonCrashFlag(instance)
2257
+ for (const name of Object.keys(instance.exports)) {
2258
+ if (name.startsWith('__napi_register__')) {
2259
+ instance.exports[name]()
2260
+ }
2261
+ }
2262
+ },
2263
+ }))
2264
+ __publishWasiDispose(__napiModule.exports)
2265
+ __publishWasiThreadPoolReconcile(__napiModule.exports)
2266
+ // The CommonJS tail below aliases `__napiModule.exports`; a named module
2267
+ // export does not travel with it, so carry the marker on the binding itself
2268
+ // too. Three things pin the stamp to exactly this spot:
2269
+ // - inside this `try`, because the guard throws on a
2270
+ // `#[napi(module_exports)]` hook that claimed the name, and only the
2271
+ // catch below tears the environment — context, workers, exit listener —
2272
+ // back down;
2273
+ // - after the async runtime host install, which hands this same object to
2274
+ // addon-provided registration functions that may put anything on it;
2275
+ // - assigning onto the loader's own `module.exports`, which is still the
2276
+ // original object here, so an addon accessor with a refusing setter is
2277
+ // never written through. `cjs-module-lexer` — Node's CJS -> ESM named
2278
+ // export detection — reads the static `module.exports.<name> =` either
2279
+ // way, and the later `module.exports = __napiModule.exports` does not
2280
+ // undo that.
2281
+ module.exports.__napiBindingTarget = __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
2282
+ __registerWasiExitListener()
2283
+ } catch (error) {
2284
+ const rollback = {
2285
+ active: false,
2286
+ error,
2287
+ promise: undefined,
2288
+ rollback: __rollbackWasiInitialization,
2289
+ }
2290
+ __wasiRollbackRegistry.set(__wasiRollbackRegistryKey, rollback)
2291
+ __runWasiInitializationRollback(rollback)
2292
+ throw rollback.error
2293
+ }
2294
+ // Preload the pool for the count the addon configured during registration.
2295
+ // See `__reconcileWasiThreadPool`.
2296
+ try {
2297
+ __reconcileWasiThreadPool()
2298
+ } catch {}
2299
+ module.exports = __napiModule.exports
2300
+ module.exports.Graph = __napiModule.exports.Graph
2301
+ module.exports.call = __napiModule.exports.call
2302
+ module.exports.version = __napiModule.exports.version