iobroker.javascript 10.0.0 → 10.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +48 -12
  2. package/admin/assets/AiChatPanel-C_WbKMGX.js +242 -0
  3. package/admin/assets/AiDiffView-BtXbDWZ8.js +1 -0
  4. package/admin/assets/Debugger-DAdJnEhw.js +15 -0
  5. package/admin/assets/Error-DQ1pzKcf.js +1 -0
  6. package/admin/assets/Import-BjMtH6Gk.js +1 -0
  7. package/admin/assets/RulesEditor-dDRPHw4X.js +1 -0
  8. package/admin/assets/RulesEditor-k-DMHotH.css +1 -0
  9. package/admin/assets/{ScriptEditor-BGIuoNei.js → ScriptEditor-CZSc7rwE.js} +2 -2
  10. package/admin/assets/ScriptEditorVanillaMonaco-DEKg14_A.js +3 -0
  11. package/admin/assets/_virtual_mf-localSharedImportMap___mfe_internal__iobroker_javascript__mf_owner__1-DPmwd_G2.js +1 -0
  12. package/admin/assets/_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-C8inUeKt.js +1243 -0
  13. package/admin/assets/_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-VcQjt7_9.js +9 -0
  14. package/admin/assets/aiPromptBuilder-D5FDo74i.js +1 -0
  15. package/admin/assets/blockly-DBw-ytY1.js +1047 -0
  16. package/admin/assets/blocks_action-BqfWEwpf.js +1 -0
  17. package/admin/assets/blocks_convert-CX0i-JfS.js +3 -0
  18. package/admin/assets/blocks_logic-D-QSzw95.js +1 -0
  19. package/admin/assets/blocks_number-D7JuNYsw.js +1 -0
  20. package/admin/assets/blocks_object-C9DzAlc7.js +1 -0
  21. package/admin/assets/blocks_procedures-BJMz6HWW.js +3 -0
  22. package/admin/assets/blocks_sendto-DRh7lk9o.js +5 -0
  23. package/admin/assets/blocks_switch-BfmboMex.js +2 -0
  24. package/admin/assets/blocks_system-B-78JfAc.js +1 -0
  25. package/admin/assets/blocks_text-CGbR0Ozw.js +1 -0
  26. package/admin/assets/blocks_time-5vS2geJg.js +1 -0
  27. package/admin/assets/blocks_timeout-BdaTywfN.js +1 -0
  28. package/admin/assets/blocks_trigger-D8kgHKbg.js +2 -0
  29. package/admin/assets/blocks_words-BhHIf_1o.js +1 -0
  30. package/admin/assets/{cronHoverProvider-pKJkSevo.js → cronHoverProvider-DpgESCox.js} +1 -1
  31. package/admin/assets/dist-CaOsN0XW.js +4 -0
  32. package/admin/assets/field_cron-B40zwSfJ.js +1 -0
  33. package/admin/assets/field_oid-KfoBnEM9.js +1 -0
  34. package/admin/assets/field_script-yXhe1iCp.js +1 -0
  35. package/admin/assets/helpers-B0ByElPJ.js +1 -0
  36. package/admin/assets/hostInit-9REPDUe7.js +1 -0
  37. package/admin/assets/index-07o_WKsX.js +726 -0
  38. package/admin/assets/index-Z8Hkv58g.css +1 -0
  39. package/admin/assets/{inlineChatWidget-ZaisTOLh.js → inlineChatWidget-B9y_gQcH.js} +2 -2
  40. package/admin/assets/{inlineDiffController-hTwHHqcc.js → inlineDiffController-C07CdIFo.js} +2 -2
  41. package/admin/assets/{mf-entry-bootstrap-0-d6052b31.js → mf-entry-bootstrap-0-efcb49d3.js} +7 -2
  42. package/admin/assets/stateHoverProvider-CqeoOjXs.js +9 -0
  43. package/admin/assets/{virtualExposes-Ed0lGq7k.js → virtualExposes-DgGB-18P.js} +1 -1
  44. package/admin/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__iobroker_javascript__remoteEntry_js-BwSvIKEV.js +1 -0
  45. package/admin/assets/virtual_mf-exposes___mfe_internal__iobroker_javascript__remoteEntry_js-ChiJXsfH.js +1 -0
  46. package/admin/custom/assets/Components-BCQTjBgm.js +1 -0
  47. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1-BuAc8OyX.js +1 -0
  48. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_react__loadShare__.js-BGJv4zZP.js +1 -0
  49. package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_styled__loadShare__.js-CGb5Cofy.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_styled__loadShare__.js-B4E6MFJ4.js} +1 -1
  50. package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BVCIAgbo.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-aRlxyEhq.js} +78 -78
  51. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-DQwzYx75.js +1494 -0
  52. package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare__leaflet__loadShare__.js-h-rCw3iz.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare__leaflet__loadShare__.js-n2zIPi0L.js} +1 -1
  53. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-xxszBNje.js +9 -0
  54. package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__prebuild__date_mf_2_fns__prebuild__-Cb5TR7FB.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__prebuild__date_mf_2_fns__prebuild__-Tq7tesSS.js} +1 -1
  55. package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__prebuild__leaflet__prebuild__-DARUoA03.js → _virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__prebuild__leaflet__prebuild__-BeF0jEWM.js} +1 -1
  56. package/admin/custom/assets/hostInit-CHwrowP4.js +1 -0
  57. package/admin/custom/assets/{index-uEKAoVT7.js → index-Cm6xl9K4.js} +1 -1
  58. package/admin/custom/assets/{lib-Yj8cfN0A.js → lib-bhrFL6jR.js} +1 -1
  59. package/admin/custom/assets/{mf-entry-bootstrap-0-77793feb.js → mf-entry-bootstrap-0-f08941e2.js} +7 -2
  60. package/admin/custom/assets/{setYear-DJ9FbdkO.js → setYear-DzTZ2h9A.js} +1 -1
  61. package/admin/custom/assets/virtualExposes-B5LJmnfO.js +1 -0
  62. package/admin/custom/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-ML-chjs6.js +1 -0
  63. package/admin/custom/assets/virtual_mf-exposes___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-C3ImybiM.js +2 -0
  64. package/admin/custom/customComponents.js +12 -1
  65. package/admin/custom/i18n/de.json +11 -1
  66. package/admin/custom/i18n/en.json +11 -1
  67. package/admin/custom/i18n/es.json +11 -1
  68. package/admin/custom/i18n/fr.json +11 -1
  69. package/admin/custom/i18n/it.json +11 -1
  70. package/admin/custom/i18n/nl.json +11 -1
  71. package/admin/custom/i18n/pl.json +11 -1
  72. package/admin/custom/i18n/pt.json +11 -1
  73. package/admin/custom/i18n/ru.json +11 -1
  74. package/admin/custom/i18n/uk.json +11 -1
  75. package/admin/custom/i18n/zh-cn.json +11 -1
  76. package/admin/google-blockly/VERSION +1 -0
  77. package/admin/google-blockly/media/drop.mp3 +0 -0
  78. package/admin/google-blockly/msg/js/de.js +332 -56
  79. package/admin/google-blockly/msg/js/en.js +319 -43
  80. package/admin/google-blockly/msg/js/es.js +319 -42
  81. package/admin/google-blockly/msg/js/fr.js +315 -39
  82. package/admin/google-blockly/msg/js/it.js +327 -51
  83. package/admin/google-blockly/msg/js/nl.js +376 -100
  84. package/admin/google-blockly/msg/js/pl.js +318 -42
  85. package/admin/google-blockly/msg/js/pt.js +318 -42
  86. package/admin/google-blockly/msg/js/ru.js +320 -44
  87. package/admin/google-blockly/msg/js/uk.js +326 -50
  88. package/admin/google-blockly/msg/js/zh-cn.js +322 -46
  89. package/admin/i18n/de.json +51 -26
  90. package/admin/i18n/en.json +50 -25
  91. package/admin/i18n/es.json +51 -18
  92. package/admin/i18n/fr.json +50 -17
  93. package/admin/i18n/it.json +50 -17
  94. package/admin/i18n/nl.json +50 -17
  95. package/admin/i18n/pl.json +51 -18
  96. package/admin/i18n/pt.json +50 -17
  97. package/admin/i18n/ru.json +50 -17
  98. package/admin/i18n/uk.json +50 -17
  99. package/admin/i18n/zh-cn.json +50 -17
  100. package/admin/jsonConfig.json +398 -0
  101. package/admin/mf-manifest.json +1 -1
  102. package/admin/mf-stats.json +1 -1
  103. package/admin/remoteEntry.js +12 -1
  104. package/admin/tab.html +6 -98
  105. package/build/lib/javascript.d.ts +48 -0
  106. package/build/lib/mirror.js +9 -0
  107. package/build/lib/mirror.js.map +1 -1
  108. package/build/lib/sandbox.js +37 -0
  109. package/build/lib/sandbox.js.map +1 -1
  110. package/build/lib/secrets.js +220 -0
  111. package/build/lib/secrets.js.map +1 -0
  112. package/build/lib/typescriptSettings.js +112 -2
  113. package/build/lib/typescriptSettings.js.map +1 -1
  114. package/build/lib/typescriptTools.js +168 -43
  115. package/build/lib/typescriptTools.js.map +1 -1
  116. package/build/main.js +61 -5
  117. package/build/main.js.map +1 -1
  118. package/build/types.d.ts +48 -0
  119. package/docs/en/blockly.md +29 -0
  120. package/docs/en/javascript.md +72 -0
  121. package/docs/en/upgrade-guide.md +3 -0
  122. package/io-package.json +59 -28
  123. package/package.json +8 -3
  124. package/admin/assets/AiChatPanel-p0KAg6Cs.js +0 -237
  125. package/admin/assets/AiDiffView-BPTLnNx1.js +0 -1
  126. package/admin/assets/AiScriptAnalyzer--BHML2rN.js +0 -9
  127. package/admin/assets/BlocklyEditor-CAjVMhYT.js +0 -81
  128. package/admin/assets/ContextWrapper-BVc8wTK_.css +0 -1
  129. package/admin/assets/ContextWrapper-D9CrnNKs.js +0 -127
  130. package/admin/assets/Debugger-SjROokFI.js +0 -15
  131. package/admin/assets/Error-DDfrxAt2.js +0 -1
  132. package/admin/assets/Import-DpTg1Jow.js +0 -1
  133. package/admin/assets/RulesEditor-BSRFWpEm.css +0 -1
  134. package/admin/assets/RulesEditor-D0hgrcBc.js +0 -1
  135. package/admin/assets/ScriptEditorVanillaMonaco-DyMQtoTQ.js +0 -3
  136. package/admin/assets/_virtual_mf-localSharedImportMap___mfe_internal__iobroker_javascript__mf_owner__1-DWJotR1B.js +0 -1
  137. package/admin/assets/_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-CxICLr5Z.js +0 -1243
  138. package/admin/assets/_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-BBAXJaqI.js +0 -9
  139. package/admin/assets/aiCodeLensProvider-hyAmut0e.js +0 -4
  140. package/admin/assets/aiPromptBuilder-Bs27qOHT.js +0 -7
  141. package/admin/assets/blocklyDarkTheme-DEiAX5DT.js +0 -1
  142. package/admin/assets/dist-uw5orDgd.js +0 -4
  143. package/admin/assets/hostInit-BFg5u9hY.js +0 -1
  144. package/admin/assets/index-B1gICjdq.js +0 -192
  145. package/admin/assets/index-BHhhebRG.css +0 -1
  146. package/admin/assets/mjs-DWqivHEk.js +0 -90
  147. package/admin/assets/stateHoverProvider-C7DawIs-.js +0 -9
  148. package/admin/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__iobroker_javascript__remoteEntry_js-BYs71IQF.js +0 -1
  149. package/admin/assets/virtual_mf-exposes___mfe_internal__iobroker_javascript__remoteEntry_js-DnnXQRkG.js +0 -1
  150. package/admin/custom/assets/Components-BrDyDHXh.js +0 -1
  151. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1-CyYJM2-v.js +0 -1
  152. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_react__loadShare__.js-BdzCssLn.js +0 -1
  153. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-BkB0anQX.js +0 -1494
  154. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-BotqDuw-.js +0 -9
  155. package/admin/custom/assets/hostInit-DJx2uXXy.js +0 -1
  156. package/admin/custom/assets/virtualExposes-CxDjLoYu.js +0 -1
  157. package/admin/custom/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-BU-ugy_7.js +0 -1
  158. package/admin/custom/assets/virtual_mf-exposes-ssr___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-BEfZbrf7.js +0 -2
  159. package/admin/custom/assets/virtual_mf-exposes___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-CTeZ0Jpm.js +0 -2
  160. package/admin/google-blockly/blockly_compressed.js +0 -1679
  161. package/admin/google-blockly/blocks_compressed.js +0 -193
  162. package/admin/google-blockly/javascript_compressed.js +0 -264
  163. package/admin/google-blockly/msg/messages.js +0 -1630
  164. package/admin/google-blockly/own/blocks_action.js +0 -765
  165. package/admin/google-blockly/own/blocks_convert.js +0 -480
  166. package/admin/google-blockly/own/blocks_logic.js +0 -459
  167. package/admin/google-blockly/own/blocks_number.js +0 -30
  168. package/admin/google-blockly/own/blocks_object.js +0 -402
  169. package/admin/google-blockly/own/blocks_procedures.js +0 -688
  170. package/admin/google-blockly/own/blocks_sendto.js +0 -702
  171. package/admin/google-blockly/own/blocks_switch.js +0 -257
  172. package/admin/google-blockly/own/blocks_system.js +0 -1409
  173. package/admin/google-blockly/own/blocks_text.js +0 -104
  174. package/admin/google-blockly/own/blocks_time.js +0 -639
  175. package/admin/google-blockly/own/blocks_timeout.js +0 -551
  176. package/admin/google-blockly/own/blocks_trigger.js +0 -1791
  177. package/admin/google-blockly/own/blocks_words.js +0 -708
  178. package/admin/google-blockly/own/field_cron.js +0 -158
  179. package/admin/google-blockly/own/field_oid.js +0 -642
  180. package/admin/google-blockly/own/field_script.js +0 -159
@@ -9,6 +9,12 @@ const node_fs_1 = require("node:fs");
9
9
  const node_path_1 = require("node:path");
10
10
  const typescript_1 = require("typescript");
11
11
  const tools_1 = require("./tools");
12
+ /**
13
+ * The transformed sources are stored in the ioBroker database and mirrored to disk, so they must
14
+ * not depend on the platform or on a TypeScript default. TypeScript 5 printed CRLF here and
15
+ * TypeScript 6 prints LF - pinning it keeps a compiler update from silently rewriting every script.
16
+ */
17
+ const PRINTER_OPTIONS = { newLine: typescript_1.NewLineKind.LineFeed };
12
18
  /**
13
19
  * Resolves all TypeScript lib files for the editor
14
20
  *
@@ -49,41 +55,117 @@ function normalizeDTSImport(filename) {
49
55
  return (0, node_path_1.join)(filename, 'index.d.ts');
50
56
  }
51
57
  /**
52
- * Resolves the type declarations of a 3rd party package for the editor
58
+ * Wraps a package's root declarations in `declare module "<pkg>"` if - and only if - they are not a
59
+ * module themselves.
60
+ *
61
+ * This used to be applied to every package. That broke all of them that ship real typings: inside an
62
+ * ambient module declaration TypeScript does not resolve the relative paths a barrel file re-exports
63
+ * from, so every name the package exported became `any` - which is why type inference never worked
64
+ * for e.g. rxjs (https://github.com/ioBroker/ioBroker.javascript/issues/2341). Such a file is now
65
+ * left alone and found through ordinary module resolution.
66
+ *
67
+ * A declaration file without any top-level `import`/`export` is a script, not a module, and
68
+ * `import ... from "<pkg>"` would not accept it. Those still need the wrapper - and having no
69
+ * imports, they cannot suffer from the problem above.
70
+ *
71
+ * A file that only points at other files (`@types/node` is nothing but `/// <reference path>` lines)
72
+ * is left alone as well: the wrapper would cut those references off from the global scope they are
73
+ * meant to populate.
74
+ *
75
+ * @param pkg The package the declarations belong to
76
+ * @param content The content of the root declaration file
77
+ */
78
+ function wrapRootTypingsIfNeeded(pkg, content) {
79
+ const isModule = /^\s*(?:import|export)\b/m.test(content);
80
+ const isAmbientDeclaration = /^\s*declare module/m.test(content);
81
+ const referencesOtherFiles = /\/\/\/\s*<reference path=/.test(content);
82
+ return isModule || isAmbientDeclaration || referencesOtherFiles
83
+ ? content
84
+ : `declare module "${pkg}" { ${content} }`;
85
+ }
86
+ /**
87
+ * Finds the package.json of a package on disk.
88
+ *
89
+ * `require.resolve("<pkg>/package.json")` goes through Node's module resolution, and a package with
90
+ * an `exports` map that does not list `./package.json` makes that throw - which is common enough
91
+ * among modern packages to matter. The directories Node would have searched are then looked at
92
+ * directly, which no `exports` map can hide.
93
+ *
94
+ * @param pkg The package to look for
95
+ */
96
+ function findPackageJson(pkg) {
97
+ try {
98
+ return require.resolve(`${pkg}/package.json`);
99
+ }
100
+ catch {
101
+ // the package may be there but refuse to hand out its manifest
102
+ }
103
+ return (require.resolve.paths(pkg) || [])
104
+ .map(dir => (0, node_path_1.join)(dir, pkg, 'package.json'))
105
+ .find(candidate => (0, node_fs_1.existsSync)(candidate));
106
+ }
107
+ /**
108
+ * Finds the declaration entry point of a package.
109
+ *
110
+ * A package that ships an `exports` map often keeps the legacy `types` field only as a stub - rxjs 7
111
+ * declares `"types": "index.d.ts"` although no such file exists and the real declarations sit in
112
+ * `./dist/types/`. A candidate therefore only counts if the file is really there
113
+ * (https://github.com/ioBroker/ioBroker.javascript/issues/928).
114
+ *
115
+ * @param packageJson The parsed package.json
116
+ * @param packageRoot The directory that package.json lives in
117
+ */
118
+ function findRootTypings(packageJson, packageRoot) {
119
+ const mainExport = packageJson.exports?.['.'];
120
+ const fromExports = mainExport && typeof mainExport === 'object'
121
+ ? (mainExport.types ??
122
+ mainExport.require?.types ??
123
+ mainExport.import?.types ??
124
+ mainExport.default?.types)
125
+ : undefined;
126
+ // the legacy fields come first: they are what a package without an `exports` map has, and where
127
+ // both exist they agree
128
+ return [packageJson.types, packageJson.typings, fromExports].find(candidate => typeof candidate === 'string' && (0, node_fs_1.existsSync)(normalizeDTSImport((0, node_path_1.join)(packageRoot, candidate))));
129
+ }
130
+ /**
131
+ * Resolves the type declarations of a 3rd party package for the editor and the compiler
132
+ *
133
+ * The declarations are handed to TypeScript as a virtual file system. They are placed under the name
134
+ * the *scripts* import - `node_modules/rxjs/...` - not under the name the package has on disk: the
135
+ * js-controller installs script libraries under an adapter-scoped alias, and TypeScript has to
136
+ * resolve `import ... from "rxjs"` against these files.
53
137
  *
54
138
  * @param pkg The package whose typings we're interested in
55
139
  * @param adapterScopedPackageName the package name on the system
56
- * @param wrapInDeclareModule Whether the root file should be wrapped in `declare module "<pkg>" { ... }`
57
140
  * @returns The found declarations or undefined if none were found
58
141
  */
59
- function resolveTypings(pkg, adapterScopedPackageName, wrapInDeclareModule) {
142
+ function resolveTypings(pkg, adapterScopedPackageName) {
60
143
  let packageJsonPath;
61
144
  let packageJson;
62
145
  let rootTypings;
63
146
  let pkgIncludesTypings = true;
64
- function tryToLoadPackage(path) {
147
+ function tryToLoadPackage(name) {
148
+ const found = findPackageJson(name);
149
+ if (!found) {
150
+ return;
151
+ }
65
152
  try {
66
- packageJsonPath = require.resolve(path);
67
- packageJson = require(packageJsonPath);
68
- rootTypings =
69
- typeof packageJson.types === 'string'
70
- ? packageJson.types
71
- : typeof packageJson.typings === 'string'
72
- ? packageJson.typings
73
- : undefined;
153
+ packageJsonPath = found;
154
+ packageJson = require(found);
155
+ rootTypings = findRootTypings(packageJson, (0, node_path_1.dirname)(found));
74
156
  }
75
157
  catch {
76
158
  /* ignore */
77
159
  }
78
160
  }
79
161
  // First, try to resolve the package itself in case it brings its own typings
80
- tryToLoadPackage(`${adapterScopedPackageName}/package.json`);
162
+ tryToLoadPackage(adapterScopedPackageName);
81
163
  if (!rootTypings) {
82
- tryToLoadPackage(`${pkg}/package.json`);
164
+ tryToLoadPackage(pkg);
83
165
  }
84
166
  // If that didn't work, try again with the @types version of the package
85
167
  if (!rootTypings) {
86
- tryToLoadPackage(`@types/${pkg}/package.json`);
168
+ tryToLoadPackage(`@types/${pkg}`);
87
169
  pkgIncludesTypings = false;
88
170
  }
89
171
  // TODO: If that didn't work, download @types/<packagename> and retry the previous step
@@ -95,56 +177,99 @@ function resolveTypings(pkg, adapterScopedPackageName, wrapInDeclareModule) {
95
177
  return undefined;
96
178
  }
97
179
  const packageRoot = (0, node_path_1.dirname)(packageJsonPath);
98
- const normalizeImportPath = (filename) => (0, node_path_1.normalize)(`node_modules/${pkgIncludesTypings ? adapterScopedPackageName : `@types/${pkg}`}/${(0, node_path_1.relative)(packageRoot, filename)}`).replace(/\\/g, '/');
99
- const ret = {};
100
- // We need to look at `import/export ... from 'modulename'` and `/// <reference path='...' />`
101
- const importDtsRegex = /^\s*(?:import|export) .+ from ["'](\.+\/[^"']+)["']/g;
180
+ /**
181
+ * The directory the declarations get in the virtual file system. It has to be the one the
182
+ * `package.json` below is written to, otherwise TypeScript reads that file, follows its `types`
183
+ * entry and finds nothing - which used to leave every import from the package typed as `any`.
184
+ */
185
+ const virtualPackageDir = `node_modules/${pkgIncludesTypings ? '' : '@types/'}${pkg}`;
186
+ // We need to look at everything that names another file of the package: `import ... from "./x"`,
187
+ // `export ... from "./x"`, the side effect import `import "./x"`, `import x = require("./x")`,
188
+ // and `/// <reference path='...' />`.
189
+ //
190
+ // The `m` flag is what makes `^` match every line instead of only the start of the file. Without
191
+ // it, exactly one import per file was followed - and only if it happened to be the first thing in
192
+ // it. For rxjs 6 that collected 6 of its ~800 declaration files.
193
+ //
194
+ // Everything between the keyword and the path is skipped, so the shape of the import does not
195
+ // matter and it may span several lines. `[^;]` stops that at the statement's semicolon, so a
196
+ // match can never run into the next statement.
197
+ const importDtsRegex = /^\s*(?:import|export)\s[^;]*?["'](\.+\/[^"']+)["']/gm;
102
198
  const pathReferenceRegex = /\/\/\/ <reference path=["']([^"']+)["'] \/>/g;
103
199
  const matchAllImports = (str) => [...(0, tools_1.matchAll)(importDtsRegex, str), ...(0, tools_1.matchAll)(pathReferenceRegex, str)].map(groups => groups[0]);
104
200
  // the paths are relative to the package.json - we need an absolute path to read the files
105
201
  rootTypings = (0, node_path_1.join)(packageRoot, rootTypings);
106
202
  // some @types packages specify `index` as their typings file instead of `index.d.ts`
107
203
  rootTypings = normalizeDTSImport(rootTypings);
108
- // include package.json in typings, so TypeScript can look up the correct entry point
109
- const relativePath = `node_modules/${pkgIncludesTypings ? '' : '@types/'}${pkg}/package.json`.replace(/\\/g, '/');
110
- ret[relativePath] = JSON.stringify(packageJson);
111
- // Used to test whether a .d.ts file already uses "declare module" or not
112
- const declareModuleRegex = /^\s*declare module/gm;
113
- // recursively load all typings
204
+ // recursively load all typings, keyed by their location on disk
205
+ const collected = new Map();
114
206
  const definitionQueue = [rootTypings];
115
207
  while (definitionQueue.length > 0) {
116
208
  const filename = definitionQueue.shift();
117
- const dirName = (0, node_path_1.dirname)(filename);
118
- // Read the file and remember it in the return dictionary
209
+ if (collected.has(filename)) {
210
+ continue;
211
+ }
119
212
  let fileContent;
120
213
  try {
121
214
  fileContent = (0, node_fs_1.readFileSync)(filename, 'utf8');
122
215
  }
123
216
  catch (e) {
124
- // The typings are malformed
125
- console.error(`Failed to load definitions for ${pkg}: ${e.toString()}`);
126
- // Since we cannot use them, return undefined
127
- return undefined;
217
+ // Without the entry point there is nothing to hand to TypeScript
218
+ if (filename === rootTypings) {
219
+ console.error(`Failed to load definitions for ${pkg}: ${e.toString()}`);
220
+ return undefined;
221
+ }
222
+ // A referenced file was there a moment ago but cannot be read now. Dropping every
223
+ // declaration of the package over one unreadable file would be out of proportion.
224
+ console.warn(`Skipped a definition file of ${pkg}: ${e.toString()}`);
225
+ continue;
128
226
  }
129
- // We need to store the filename relative to the base dir
130
- const relativePath = normalizeImportPath(filename);
131
- // If necessary, wrap the root typings (only those!)
132
- ret[relativePath] =
133
- wrapInDeclareModule && filename === rootTypings && !declareModuleRegex.test(fileContent)
134
- ? `declare module "${pkg}" { ${fileContent} }`
135
- : fileContent;
227
+ collected.set(filename, fileContent);
136
228
  // If this file references another .d.ts file, we need to load that too
137
229
  matchAllImports(fileContent)
138
230
  // resolve the file relative to the current directory
139
- .map(file => (0, node_path_1.join)(dirName, file))
231
+ .map(file => (0, node_path_1.join)((0, node_path_1.dirname)(filename), file))
140
232
  // find out the correct path of the file we want to import
141
233
  .map(normalizeDTSImport)
234
+ // A package may import something it does not ship declarations for, and the matcher
235
+ // above may pick up a string that only looks like a path
236
+ .filter(file => (0, node_fs_1.existsSync)(file))
142
237
  // Find all libs we have not loaded yet
143
- .filter(file => !(normalizeImportPath(file) in ret))
238
+ .filter(file => !collected.has(file))
144
239
  .forEach(file => definitionQueue.push(file));
145
240
  }
241
+ /**
242
+ * The directory that becomes `node_modules/<pkg>` in the virtual file system.
243
+ *
244
+ * `virtual-tsc` resolves with `moduleResolution: node10`, which looks the entry point up next to
245
+ * the package - so laying the files out around the entry point rather than around the
246
+ * package.json is what makes a package work whose declarations sit in a subdirectory. For a
247
+ * package whose entry point is at its root - the usual case - this is the package root and
248
+ * nothing changes.
249
+ */
250
+ let virtualRoot = (0, node_path_1.dirname)(rootTypings);
251
+ if ([...collected.keys()].some(file => (0, node_path_1.relative)(virtualRoot, file).startsWith('..'))) {
252
+ // Declarations reach above the entry point. Moving them would break the relative imports
253
+ // between them, so the layout of the package is kept as it is.
254
+ virtualRoot = packageRoot;
255
+ }
256
+ const toVirtualPath = (filename) => (0, node_path_1.normalize)(`${virtualPackageDir}/${(0, node_path_1.relative)(virtualRoot, filename)}`).replace(/\\/g, '/');
257
+ const ret = {};
258
+ for (const [filename, fileContent] of collected) {
259
+ ret[toVirtualPath(filename)] =
260
+ filename === rootTypings ? wrapRootTypingsIfNeeded(pkg, fileContent) : fileContent;
261
+ }
262
+ // Include a package.json, so TypeScript can look up the entry point. It describes the layout
263
+ // above, not the one the package has on disk - and it is deliberately minimal: the original
264
+ // `exports` map refers to paths that do not exist here, and TypeScript refuses to resolve the
265
+ // package at all when it finds one it cannot follow under `moduleResolution: node10`.
266
+ ret[`${virtualPackageDir}/package.json`] = JSON.stringify({
267
+ name: pkg,
268
+ version: packageJson?.version,
269
+ types: `./${(0, node_path_1.relative)(virtualRoot, rootTypings).replace(/\\/g, '/')}`,
270
+ });
146
271
  // Avoid returning empty declarations
147
- if (Object.keys(ret).length === 0) {
272
+ if (!collected.size) {
148
273
  return undefined;
149
274
  }
150
275
  return ret;
@@ -386,7 +511,7 @@ function transformScriptBeforeCompilation(source, isGlobal) {
386
511
  };
387
512
  const sourceFile = (0, typescript_1.createSourceFile)('index.ts', source, typescript_1.ScriptTarget.ESNext, /* setParentNodes */ true);
388
513
  const result = (0, typescript_1.transform)(sourceFile, [transformer]);
389
- return (0, typescript_1.createPrinter)().printNode(typescript_1.EmitHint.Unspecified, result.transformed[0], sourceFile);
514
+ return (0, typescript_1.createPrinter)(PRINTER_OPTIONS).printNode(typescript_1.EmitHint.Unspecified, result.transformed[0], sourceFile);
390
515
  }
391
516
  /**
392
517
  * Takes the global declarations for a TypeScript and wraps export statements in `declare global`
@@ -422,7 +547,7 @@ function transformGlobalDeclarations(decl) {
422
547
  };
423
548
  const sourceFile = (0, typescript_1.createSourceFile)('index.d.ts', decl, typescript_1.ScriptTarget.ESNext, /* setParentNodes */ true);
424
549
  const result = (0, typescript_1.transform)(sourceFile, [transformer]);
425
- return (0, typescript_1.createPrinter)().printNode(typescript_1.EmitHint.Unspecified, result.transformed[0], sourceFile);
550
+ return (0, typescript_1.createPrinter)(PRINTER_OPTIONS).printNode(typescript_1.EmitHint.Unspecified, result.transformed[0], sourceFile);
426
551
  }
427
552
  /**
428
553
  * Translates a script ID to a filename for the compiler
@@ -1 +1 @@
1
- {"version":3,"file":"typescriptTools.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BAAO,CAAC,uBAAuB,CAC3B,SAAS,EACT,KAAK,EACL,oBAAO,CAAC,kBAAkB,CAAC,EAAE,CAAC,EAC9B,SAAS,EACT,SAAS,CACZ;yBACJ,CAAC;iBACX,CAAC,CAAC;YACP,CAAC;YAED,OAAO,IAAI,CAAC;QAChB,CAAC,CAAC,CAAC;IACX,CAAC,CAAC;IAEF,MAAM,UAAU,GAAG,IAAA,6BAAgB,EAAC,YAAY,EAAE,IAAI,EAAE,yBAAY,CAAC,MAAM,EAAE,oBAAoB,CAAC,IAAI,CAAC,CAAC;IAExG,MAAM,MAAM,GAAG,IAAA,sBAAS,EAAC,UAAU,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;IACpD,OAAO,IAAA,0BAAa,GAAE,CAAC,SAAS,CAAC,qBAAQ,CAAC,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;AAC9F,CAAC;AAED;;;;GAIG;AACH,SAAgB,oBAAoB,CAAC,QAAgB;IACjD,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC;AAC3E,CAAC","sourcesContent":["'use strict';\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, normalize, relative } from 'node:path';\nimport {\n type Statement,\n isImportDeclaration,\n isImportEqualsDeclaration,\n isExportDeclaration,\n isExportAssignment,\n isTypeAliasDeclaration,\n isInterfaceDeclaration,\n isModuleDeclaration,\n isEnumDeclaration,\n isClassDeclaration,\n isFunctionDeclaration,\n isVariableStatement,\n isExpressionStatement,\n createSourceFile,\n createPrinter,\n transform,\n ScriptTarget,\n factory,\n SyntaxKind,\n type Modifier,\n NodeFlags,\n type ModuleDeclaration,\n visitNode,\n visitNodes,\n isSourceFile,\n EmitHint,\n type NodeArray,\n type TransformerFactory,\n type SourceFile,\n type TransformationContext,\n type Transformer,\n} from 'typescript';\nimport { matchAll } from './tools';\n\n/**\n * Resolves all TypeScript lib files for the editor\n *\n * @param targetLib The lib to target (e.g., es2017)\n */\nexport function resolveTypescriptLibs(\n targetLib: 'es2017' | 'es2018' | 'es2019' | 'es2020' | 'es2021' | 'es2022' | 'esnext',\n): Record<string, string> {\n const typescriptLibRoot = dirname(require.resolve(`typescript/lib/lib.d.ts`));\n const ret: Record<string, string> = {};\n\n const libReferenceRegex = /\\/\\/\\/ <reference lib=[\"']([^\"']+)[\"'] \\/>/g;\n const matchAllLibs = (str: string): string[] => matchAll(libReferenceRegex, str).map(groups => groups[0]);\n\n const libQueue: string[] = [targetLib];\n while (libQueue.length > 0) {\n const libName = libQueue.shift();\n const filename = `lib.${libName}.d.ts`;\n // Read the file and remember it in the return dictionary\n const fileContent = readFileSync(join(typescriptLibRoot, filename), 'utf8');\n ret[filename] = fileContent;\n // If this file references another lib file, we need to load that too.\n // A reference looks like this: /// <reference lib=\"es2015.core\" />\n // Find all libs we have not loaded yet\n matchAllLibs(fileContent)\n .filter(lib => !(`lib.${lib}.d.ts` in ret))\n .forEach(lib => libQueue.push(lib));\n }\n\n return ret;\n}\n\nfunction normalizeDTSImport(filename: string): string {\n // An import is either...\n // a normal import\n if (filename.endsWith('.d.ts')) {\n return filename;\n }\n // an extensionless import\n if (existsSync(`${filename}.d.ts`)) {\n return `${filename}.d.ts`;\n }\n // or a directory import\n return join(filename, 'index.d.ts');\n}\n\n/**\n * Resolves the type declarations of a 3rd party package for the editor\n *\n * @param pkg The package whose typings we're interested in\n * @param adapterScopedPackageName the package name on the system\n * @param wrapInDeclareModule Whether the root file should be wrapped in `declare module \"<pkg>\" { ... }`\n * @returns The found declarations or undefined if none were found\n */\nexport function resolveTypings(\n pkg: string,\n adapterScopedPackageName: string,\n wrapInDeclareModule?: boolean,\n): Record<string, string> | undefined {\n let packageJsonPath: string | undefined;\n let packageJson: Record<string, any> | undefined;\n let rootTypings: string | undefined;\n let pkgIncludesTypings = true;\n\n function tryToLoadPackage(path: string): void {\n try {\n packageJsonPath = require.resolve(path);\n packageJson = require(packageJsonPath);\n rootTypings =\n typeof (packageJson as Record<string, any>).types === 'string'\n ? (packageJson as Record<string, any>).types\n : typeof (packageJson as Record<string, any>).typings === 'string'\n ? (packageJson as Record<string, any>).typings\n : undefined;\n } catch {\n /* ignore */\n }\n }\n\n // First, try to resolve the package itself in case it brings its own typings\n tryToLoadPackage(`${adapterScopedPackageName}/package.json`);\n\n if (!rootTypings) {\n tryToLoadPackage(`${pkg}/package.json`);\n }\n // If that didn't work, try again with the @types version of the package\n if (!rootTypings) {\n tryToLoadPackage(`@types/${pkg}/package.json`);\n pkgIncludesTypings = false;\n }\n\n // TODO: If that didn't work, download @types/<packagename> and retry the previous step\n\n // Nothing to do here since we found no packages\n if (!rootTypings) {\n return undefined;\n }\n\n if (!packageJsonPath) {\n return undefined;\n }\n\n const packageRoot: string = dirname(packageJsonPath);\n const normalizeImportPath = (filename: string): string =>\n normalize(\n `node_modules/${pkgIncludesTypings ? adapterScopedPackageName : `@types/${pkg}`}/${relative(packageRoot, filename)}`,\n ).replace(/\\\\/g, '/');\n\n const ret: Record<string, string> = {};\n\n // We need to look at `import/export ... from 'modulename'` and `/// <reference path='...' />`\n const importDtsRegex = /^\\s*(?:import|export) .+ from [\"'](\\.+\\/[^\"']+)[\"']/g;\n const pathReferenceRegex = /\\/\\/\\/ <reference path=[\"']([^\"']+)[\"'] \\/>/g;\n const matchAllImports = (str: string): string[] =>\n [...matchAll(importDtsRegex, str), ...matchAll(pathReferenceRegex, str)].map(groups => groups[0]);\n\n // the paths are relative to the package.json - we need an absolute path to read the files\n rootTypings = join(packageRoot, rootTypings);\n // some @types packages specify `index` as their typings file instead of `index.d.ts`\n rootTypings = normalizeDTSImport(rootTypings);\n\n // include package.json in typings, so TypeScript can look up the correct entry point\n const relativePath = `node_modules/${pkgIncludesTypings ? '' : '@types/'}${pkg}/package.json`.replace(/\\\\/g, '/');\n ret[relativePath] = JSON.stringify(packageJson);\n\n // Used to test whether a .d.ts file already uses \"declare module\" or not\n const declareModuleRegex = /^\\s*declare module/gm;\n\n // recursively load all typings\n const definitionQueue = [rootTypings];\n while (definitionQueue.length > 0) {\n const filename: string = definitionQueue.shift() as string;\n const dirName = dirname(filename);\n // Read the file and remember it in the return dictionary\n let fileContent: string;\n try {\n fileContent = readFileSync(filename, 'utf8');\n } catch (e: any) {\n // The typings are malformed\n console.error(`Failed to load definitions for ${pkg}: ${e.toString()}`);\n // Since we cannot use them, return undefined\n return undefined;\n }\n // We need to store the filename relative to the base dir\n const relativePath = normalizeImportPath(filename);\n // If necessary, wrap the root typings (only those!)\n ret[relativePath] =\n wrapInDeclareModule && filename === rootTypings && !declareModuleRegex.test(fileContent)\n ? `declare module \"${pkg}\" { ${fileContent} }`\n : fileContent;\n // If this file references another .d.ts file, we need to load that too\n matchAllImports(fileContent)\n // resolve the file relative to the current directory\n .map(file => join(dirName, file))\n // find out the correct path of the file we want to import\n .map(normalizeDTSImport)\n // Find all libs we have not loaded yet\n .filter(file => !(normalizeImportPath(file) in ret))\n .forEach(file => definitionQueue.push(file));\n }\n // Avoid returning empty declarations\n if (Object.keys(ret).length === 0) {\n return undefined;\n }\n return ret;\n}\n\n/**\n * @param s Statement to check whether it must be hoisted to the top of the file\n * @param isGlobal Whether this is a global script or a normal one\n */\nfunction mustBeHoisted(s: Statement & { modifiers?: Modifier[] }, isGlobal?: boolean): boolean {\n return !!(\n // Import/export statements must be moved to the top\n isImportDeclaration(s) ||\n isImportEqualsDeclaration(s) ||\n isExportDeclaration(s) ||\n isExportAssignment(s) ||\n // as well as many declarations\n isTypeAliasDeclaration(s) ||\n isInterfaceDeclaration(s) ||\n isModuleDeclaration(s) ||\n isEnumDeclaration(s) ||\n (isGlobal &&\n // in global scripts we don't wrap classes and functions, so they can be accessed from non-global scripts\n (isClassDeclaration(s) || isFunctionDeclaration(s))) ||\n // and declare ... / export ... statements\n s.modifiers?.some(s => s.kind === SyntaxKind.DeclareKeyword || s.kind === SyntaxKind.ExportKeyword)\n );\n}\n\nfunction canBeExported(s: Statement): boolean {\n return (\n // const, let, var\n isVariableStatement(s) ||\n // type, interface, enum, class, function\n isTypeAliasDeclaration(s) ||\n isInterfaceDeclaration(s) ||\n isEnumDeclaration(s) ||\n isClassDeclaration(s) ||\n isFunctionDeclaration(s)\n );\n}\n\nfunction addExportModifier(s: Statement & { modifiers?: Modifier[] }): Statement {\n let modifiers: Modifier[] | undefined;\n // Add export modifiers\n if (!s.modifiers) {\n modifiers = [factory.createModifier(SyntaxKind.ExportKeyword)];\n } else if (!s.modifiers.some(m => m.kind === SyntaxKind.ExportKeyword)) {\n modifiers = [...s.modifiers, factory.createModifier(SyntaxKind.ExportKeyword)];\n } else {\n return s;\n }\n\n if (isVariableStatement(s)) {\n return factory.updateVariableStatement(s, modifiers, s.declarationList);\n }\n if (isTypeAliasDeclaration(s)) {\n return factory.updateTypeAliasDeclaration(s, modifiers, s.name, s.typeParameters, s.type);\n }\n if (isInterfaceDeclaration(s)) {\n return factory.updateInterfaceDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isEnumDeclaration(s)) {\n return factory.updateEnumDeclaration(s, modifiers, s.name, s.members);\n }\n if (isClassDeclaration(s)) {\n return factory.updateClassDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isFunctionDeclaration(s)) {\n return factory.updateFunctionDeclaration(\n s,\n modifiers,\n s.asteriskToken,\n s.name,\n s.typeParameters,\n s.parameters,\n s.type,\n s.body,\n );\n }\n return s;\n}\n\nfunction removeDeclareModifier(s: Statement & { modifiers?: Modifier[] }): Statement {\n let modifiers: Modifier[] | undefined;\n // Remove declare modifiers\n if (s.modifiers) {\n modifiers = s.modifiers.filter(m => m.kind !== SyntaxKind.DeclareKeyword);\n } else {\n return s;\n }\n\n if (isVariableStatement(s)) {\n return factory.updateVariableStatement(s, modifiers, s.declarationList);\n }\n if (isTypeAliasDeclaration(s)) {\n return factory.updateTypeAliasDeclaration(s, modifiers, s.name, s.typeParameters, s.type);\n }\n if (isInterfaceDeclaration(s)) {\n return factory.updateInterfaceDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isEnumDeclaration(s)) {\n return factory.updateEnumDeclaration(s, modifiers, s.name, s.members);\n }\n if (isClassDeclaration(s)) {\n return factory.updateClassDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isFunctionDeclaration(s)) {\n return factory.updateFunctionDeclaration(\n s,\n modifiers,\n s.asteriskToken,\n s.name,\n s.typeParameters,\n s.parameters,\n s.type,\n s.body,\n );\n }\n\n return s;\n}\n\n// taken from node_modules\\@types\\node\\globals.d.ts\n// the globally available things must be wrapped in `declare global` if the user wants to augment them\nconst NodeJSGlobals = [\n 'Array',\n 'ArrayBuffer',\n 'Boolean',\n 'Buffer',\n 'DataView',\n 'Date',\n 'Error',\n 'EvalError',\n 'Float32Array',\n 'Float64Array',\n 'Function',\n 'GLOBAL',\n 'Infinity',\n 'Int16Array',\n 'Int32Array',\n 'Int8Array',\n 'Intl',\n 'JSON',\n 'Map',\n 'Math',\n 'NaN',\n 'Number',\n 'Object',\n 'Promise',\n 'RangeError',\n 'ReferenceError',\n 'RegExp',\n 'Set',\n 'String',\n 'Symbol',\n 'SyntaxError',\n 'TypeError',\n 'URIError',\n 'Uint16Array',\n 'Uint32Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'WeakMap',\n 'WeakSet',\n 'clearImmediate',\n 'clearInterval',\n 'clearTimeout',\n 'console',\n 'decodeURI',\n 'decodeURIComponent',\n 'encodeURI',\n 'encodeURIComponent',\n 'escape',\n 'eval',\n 'global',\n 'isFinite',\n 'isNaN',\n 'parseFloat',\n 'parseInt',\n 'process',\n 'root',\n 'setImmediate',\n 'setInterval',\n 'setTimeout',\n 'queueMicrotask',\n 'undefined',\n 'unescape',\n 'gc',\n 'v8debug',\n];\n\nfunction isGlobalAugmentation(s: Statement): boolean {\n return !!(\n (isInterfaceDeclaration(s) || isClassDeclaration(s) || isFunctionDeclaration(s)) &&\n s.name &&\n NodeJSGlobals.includes(s.name.text)\n );\n}\n\nfunction wrapInDeclareGlobal(statements: Statement[]): ModuleDeclaration {\n return factory.createModuleDeclaration(\n [factory.createModifier(SyntaxKind.DeclareKeyword)],\n factory.createIdentifier('global'),\n factory.createModuleBlock(statements),\n NodeFlags.GlobalAugmentation,\n );\n}\n\n/**\n * Takes a TypeScript script and does the necessary transformations, so it can be compiled properly\n *\n * @param source The original TypeScript source\n * @param isGlobal Whether the transformed script is a global script or not\n */\nexport function transformScriptBeforeCompilation(source: string, isGlobal?: boolean): string {\n const transformer: TransformerFactory<SourceFile> = (_context: TransformationContext): Transformer<SourceFile> => {\n return (sourceFile: SourceFile) =>\n visitNode(sourceFile, (node: SourceFile): any => {\n if (isSourceFile(node)) {\n // Wrap all declarations that augment global interfaces in `declare global`\n const augmentations = node.statements.filter(s => isGlobalAugmentation(s));\n const nonAugmentations = node.statements.filter(s => !isGlobalAugmentation(s));\n\n // If there is no top level await, don't move all the statements around\n const hasTLA = node.statements.some(\n s => isExpressionStatement(s) && s.expression.kind === SyntaxKind.AwaitExpression,\n );\n // Move all statements to the top of the file that cannot appear in a function body\n let hoistedStatements = hasTLA\n ? factory.createNodeArray(nonAugmentations.filter(s => mustBeHoisted(s, isGlobal)))\n : factory.createNodeArray(nonAugmentations);\n\n // The rest gets wrapped\n const wrappedStatements = hasTLA ? nonAugmentations.filter(s => !mustBeHoisted(s, isGlobal)) : [];\n\n // When transforming global scripts, we need to do a couple of things\n if (isGlobal) {\n // 1. We need to add an export modifier to everything at the top level that can be exported\n hoistedStatements = visitNodes(\n hoistedStatements,\n // @ts-expect-error s is definitely a Statement\n s => (canBeExported(s) ? addExportModifier(s) : s),\n ) as NodeArray<Statement>;\n // 3. We need to transform the generated declarations to use `declare global` (this will happen in transformGlobalDeclarations)\n }\n const needsEmptyExport =\n // An empty export is necessary when there is no import declaration\n !node.statements.some(s => isImportDeclaration(s) || isImportEqualsDeclaration(s)) &&\n // And there is no statement in a global script which had an export modifier added\n (!(\n isGlobal &&\n hoistedStatements.some(\n // @ts-expect-error s should have modifiers\n s => s.modifiers?.some(m => m.kind === SyntaxKind.ExportKeyword),\n )\n ) ||\n // Or if there is a `declare global` statement\n !!augmentations);\n\n return factory.updateSourceFile(node, [\n // Put the hoisted statements at the top (or all of them if there's no top level await)\n ...hoistedStatements,\n // Then add everything that augments the global scope\n ...(augmentations && augmentations.length ? [wrapInDeclareGlobal(augmentations)] : []),\n ...(hasTLA\n ? // If there is a top-level await, wrap all non-hoisted statements in (async () => { ... })();\n [\n factory.createExpressionStatement(\n factory.createCallExpression(\n factory.createArrowFunction(\n [factory.createModifier(SyntaxKind.AsyncKeyword)],\n undefined,\n [],\n undefined,\n undefined,\n factory.createBlock(wrappedStatements),\n ),\n undefined,\n undefined,\n ),\n ),\n ]\n : []),\n ...(needsEmptyExport\n ? [\n // Put an empty export {}; at the bottom to force TypeScript to treat the script as a module\n factory.createExportDeclaration(\n undefined, // ModifierLike[] | undefined\n false, // isTypeOnly\n factory.createNamedExports([]), // NamedExportBindings | undefined\n undefined, // moduleSpecifier\n undefined, // attributes\n ),\n ]\n : []),\n ]);\n }\n return node;\n });\n };\n\n const sourceFile = createSourceFile('index.ts', source, ScriptTarget.ESNext, /* setParentNodes */ true);\n\n const result = transform(sourceFile, [transformer]);\n return createPrinter().printNode(EmitHint.Unspecified, result.transformed[0], sourceFile);\n}\n\n/**\n * Takes the global declarations for a TypeScript and wraps export statements in `declare global`\n *\n * @param decl The untransformed global declarations\n */\nexport function transformGlobalDeclarations(decl: string): string {\n const transformer: TransformerFactory<SourceFile> = (_context: TransformationContext): any => {\n return (sourceFile: SourceFile) =>\n visitNode(sourceFile, (node: SourceFile): SourceFile => {\n if (isSourceFile(node)) {\n // All non-export-statements stay at the root level, the rest is wrapped in `declare global`\n const exportStatements = node.statements.filter(\n // @ts-expect-error s should have modifiers\n s => s.modifiers?.some(m => m.kind === SyntaxKind.ExportKeyword),\n );\n const otherStatements = node.statements.filter(s => !exportStatements.includes(s));\n\n const hasExportStatements = exportStatements.length > 0;\n const hasImport = otherStatements.some(s => isImportDeclaration(s) || isImportEqualsDeclaration(s));\n\n return factory.updateSourceFile(node, [\n ...otherStatements,\n ...(hasExportStatements\n ? [wrapInDeclareGlobal(exportStatements.map(s => removeDeclareModifier(s)))]\n : []),\n ...(hasImport\n ? [] // If there is an import, the script is already treated as a module\n : [\n // Otherwise, put an empty export {}; at the bottom to force TypeScript to treat the script as a module\n factory.createExportDeclaration(\n undefined,\n false,\n factory.createNamedExports([]),\n undefined,\n undefined,\n ),\n ]),\n ]);\n }\n\n return node;\n });\n };\n\n const sourceFile = createSourceFile('index.d.ts', decl, ScriptTarget.ESNext, /* setParentNodes */ true);\n\n const result = transform(sourceFile, [transformer]);\n return createPrinter().printNode(EmitHint.Unspecified, result.transformed[0], sourceFile);\n}\n\n/**\n * Translates a script ID to a filename for the compiler\n *\n * @param scriptID The ID of the script\n */\nexport function scriptIdToTSFilename(scriptID: string): string {\n return `${scriptID.replace(/^script.js./, '').replace(/\\./g, '/')}.ts`;\n}\n"]}
1
+ {"version":3,"file":"typescriptTools.js","sourceRoot":"","sources":["../../src/lib/typescriptTools.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAqDb,sDAuBC;AA6GD,wCAqJC;AAoND,4EA2FC;AAOD,kEA2CC;AAOD,oDAEC;AAtrBD,qCAAmD;AACnD,yCAA+D;AAC/D,2CAiCoB;AACpB,mCAAmC;AAGnC;;;;GAIG;AACH,MAAM,eAAe,GAAG,EAAE,OAAO,EAAE,wBAAW,CAAC,QAAQ,EAAE,CAAC;AAE1D;;;;GAIG;AACH,SAAgB,qBAAqB,CAAC,SAAmB;IACrD,MAAM,iBAAiB,GAAG,IAAA,mBAAO,EAAC,OAAO,CAAC,OAAO,CAAC,yBAAyB,CAAC,CAAC,CAAC;IAC9E,MAAM,GAAG,GA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AAC,CAAC;IACpD,OAAO,IAAA,0BAAa,EAAC,eAAe,CAAC,CAAC,SAAS,CAAC,qBAAQ,CAAC,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC;AAC7G,CAAC;AAED;;;;GAIG;AACH,SAAgB,oBAAoB,CAAC,QAAgB;IACjD,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,CAAC;AAC3E,CAAC","sourcesContent":["'use strict';\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, normalize, relative } from 'node:path';\nimport {\n type Statement,\n isImportDeclaration,\n isImportEqualsDeclaration,\n isExportDeclaration,\n isExportAssignment,\n isTypeAliasDeclaration,\n isInterfaceDeclaration,\n isModuleDeclaration,\n isEnumDeclaration,\n isClassDeclaration,\n isFunctionDeclaration,\n isVariableStatement,\n isExpressionStatement,\n createSourceFile,\n createPrinter,\n transform,\n ScriptTarget,\n factory,\n SyntaxKind,\n type Modifier,\n NodeFlags,\n NewLineKind,\n type ModuleDeclaration,\n visitNode,\n visitNodes,\n isSourceFile,\n EmitHint,\n type NodeArray,\n type TransformerFactory,\n type SourceFile,\n type TransformationContext,\n type Transformer,\n} from 'typescript';\nimport { matchAll } from './tools';\nimport type { TsTarget } from '../types';\n\n/**\n * The transformed sources are stored in the ioBroker database and mirrored to disk, so they must\n * not depend on the platform or on a TypeScript default. TypeScript 5 printed CRLF here and\n * TypeScript 6 prints LF - pinning it keeps a compiler update from silently rewriting every script.\n */\nconst PRINTER_OPTIONS = { newLine: NewLineKind.LineFeed };\n\n/**\n * Resolves all TypeScript lib files for the editor\n *\n * @param targetLib The lib to target (e.g., es2017)\n */\nexport function resolveTypescriptLibs(targetLib: TsTarget): Record<string, string> {\n const typescriptLibRoot = dirname(require.resolve(`typescript/lib/lib.d.ts`));\n const ret: Record<string, string> = {};\n\n const libReferenceRegex = /\\/\\/\\/ <reference lib=[\"']([^\"']+)[\"'] \\/>/g;\n const matchAllLibs = (str: string): string[] => matchAll(libReferenceRegex, str).map(groups => groups[0]);\n\n const libQueue: string[] = [targetLib];\n while (libQueue.length > 0) {\n const libName = libQueue.shift();\n const filename = `lib.${libName}.d.ts`;\n // Read the file and remember it in the return dictionary\n const fileContent = readFileSync(join(typescriptLibRoot, filename), 'utf8');\n ret[filename] = fileContent;\n // If this file references another lib file, we need to load that too.\n // A reference looks like this: /// <reference lib=\"es2015.core\" />\n // Find all libs we have not loaded yet\n matchAllLibs(fileContent)\n .filter(lib => !(`lib.${lib}.d.ts` in ret))\n .forEach(lib => libQueue.push(lib));\n }\n\n return ret;\n}\n\nfunction normalizeDTSImport(filename: string): string {\n // An import is either...\n // a normal import\n if (filename.endsWith('.d.ts')) {\n return filename;\n }\n // an extensionless import\n if (existsSync(`${filename}.d.ts`)) {\n return `${filename}.d.ts`;\n }\n // or a directory import\n return join(filename, 'index.d.ts');\n}\n\n/**\n * Wraps a package's root declarations in `declare module \"<pkg>\"` if - and only if - they are not a\n * module themselves.\n *\n * This used to be applied to every package. That broke all of them that ship real typings: inside an\n * ambient module declaration TypeScript does not resolve the relative paths a barrel file re-exports\n * from, so every name the package exported became `any` - which is why type inference never worked\n * for e.g. rxjs (https://github.com/ioBroker/ioBroker.javascript/issues/2341). Such a file is now\n * left alone and found through ordinary module resolution.\n *\n * A declaration file without any top-level `import`/`export` is a script, not a module, and\n * `import ... from \"<pkg>\"` would not accept it. Those still need the wrapper - and having no\n * imports, they cannot suffer from the problem above.\n *\n * A file that only points at other files (`@types/node` is nothing but `/// <reference path>` lines)\n * is left alone as well: the wrapper would cut those references off from the global scope they are\n * meant to populate.\n *\n * @param pkg The package the declarations belong to\n * @param content The content of the root declaration file\n */\nfunction wrapRootTypingsIfNeeded(pkg: string, content: string): string {\n const isModule = /^\\s*(?:import|export)\\b/m.test(content);\n const isAmbientDeclaration = /^\\s*declare module/m.test(content);\n const referencesOtherFiles = /\\/\\/\\/\\s*<reference path=/.test(content);\n\n return isModule || isAmbientDeclaration || referencesOtherFiles\n ? content\n : `declare module \"${pkg}\" { ${content} }`;\n}\n\n/**\n * Finds the package.json of a package on disk.\n *\n * `require.resolve(\"<pkg>/package.json\")` goes through Node's module resolution, and a package with\n * an `exports` map that does not list `./package.json` makes that throw - which is common enough\n * among modern packages to matter. The directories Node would have searched are then looked at\n * directly, which no `exports` map can hide.\n *\n * @param pkg The package to look for\n */\nfunction findPackageJson(pkg: string): string | undefined {\n try {\n return require.resolve(`${pkg}/package.json`);\n } catch {\n // the package may be there but refuse to hand out its manifest\n }\n\n return (require.resolve.paths(pkg) || [])\n .map(dir => join(dir, pkg, 'package.json'))\n .find(candidate => existsSync(candidate));\n}\n\n/**\n * Finds the declaration entry point of a package.\n *\n * A package that ships an `exports` map often keeps the legacy `types` field only as a stub - rxjs 7\n * declares `\"types\": \"index.d.ts\"` although no such file exists and the real declarations sit in\n * `./dist/types/`. A candidate therefore only counts if the file is really there\n * (https://github.com/ioBroker/ioBroker.javascript/issues/928).\n *\n * @param packageJson The parsed package.json\n * @param packageRoot The directory that package.json lives in\n */\nfunction findRootTypings(packageJson: Record<string, any>, packageRoot: string): string | undefined {\n const mainExport: unknown = packageJson.exports?.['.'];\n const fromExports =\n mainExport && typeof mainExport === 'object'\n ? ((mainExport as Record<string, any>).types ??\n (mainExport as Record<string, any>).require?.types ??\n (mainExport as Record<string, any>).import?.types ??\n (mainExport as Record<string, any>).default?.types)\n : undefined;\n\n // the legacy fields come first: they are what a package without an `exports` map has, and where\n // both exist they agree\n return [packageJson.types, packageJson.typings, fromExports].find(\n candidate => typeof candidate === 'string' && existsSync(normalizeDTSImport(join(packageRoot, candidate))),\n );\n}\n\n/**\n * Resolves the type declarations of a 3rd party package for the editor and the compiler\n *\n * The declarations are handed to TypeScript as a virtual file system. They are placed under the name\n * the *scripts* import - `node_modules/rxjs/...` - not under the name the package has on disk: the\n * js-controller installs script libraries under an adapter-scoped alias, and TypeScript has to\n * resolve `import ... from \"rxjs\"` against these files.\n *\n * @param pkg The package whose typings we're interested in\n * @param adapterScopedPackageName the package name on the system\n * @returns The found declarations or undefined if none were found\n */\nexport function resolveTypings(pkg: string, adapterScopedPackageName: string): Record<string, string> | undefined {\n let packageJsonPath: string | undefined;\n let packageJson: Record<string, any> | undefined;\n let rootTypings: string | undefined;\n let pkgIncludesTypings = true;\n\n function tryToLoadPackage(name: string): void {\n const found = findPackageJson(name);\n if (!found) {\n return;\n }\n try {\n packageJsonPath = found;\n packageJson = require(found);\n rootTypings = findRootTypings(packageJson as Record<string, any>, dirname(found));\n } catch {\n /* ignore */\n }\n }\n\n // First, try to resolve the package itself in case it brings its own typings\n tryToLoadPackage(adapterScopedPackageName);\n\n if (!rootTypings) {\n tryToLoadPackage(pkg);\n }\n // If that didn't work, try again with the @types version of the package\n if (!rootTypings) {\n tryToLoadPackage(`@types/${pkg}`);\n pkgIncludesTypings = false;\n }\n\n // TODO: If that didn't work, download @types/<packagename> and retry the previous step\n\n // Nothing to do here since we found no packages\n if (!rootTypings) {\n return undefined;\n }\n\n if (!packageJsonPath) {\n return undefined;\n }\n\n const packageRoot: string = dirname(packageJsonPath);\n /**\n * The directory the declarations get in the virtual file system. It has to be the one the\n * `package.json` below is written to, otherwise TypeScript reads that file, follows its `types`\n * entry and finds nothing - which used to leave every import from the package typed as `any`.\n */\n const virtualPackageDir = `node_modules/${pkgIncludesTypings ? '' : '@types/'}${pkg}`;\n\n // We need to look at everything that names another file of the package: `import ... from \"./x\"`,\n // `export ... from \"./x\"`, the side effect import `import \"./x\"`, `import x = require(\"./x\")`,\n // and `/// <reference path='...' />`.\n //\n // The `m` flag is what makes `^` match every line instead of only the start of the file. Without\n // it, exactly one import per file was followed - and only if it happened to be the first thing in\n // it. For rxjs 6 that collected 6 of its ~800 declaration files.\n //\n // Everything between the keyword and the path is skipped, so the shape of the import does not\n // matter and it may span several lines. `[^;]` stops that at the statement's semicolon, so a\n // match can never run into the next statement.\n const importDtsRegex = /^\\s*(?:import|export)\\s[^;]*?[\"'](\\.+\\/[^\"']+)[\"']/gm;\n const pathReferenceRegex = /\\/\\/\\/ <reference path=[\"']([^\"']+)[\"'] \\/>/g;\n const matchAllImports = (str: string): string[] =>\n [...matchAll(importDtsRegex, str), ...matchAll(pathReferenceRegex, str)].map(groups => groups[0]);\n\n // the paths are relative to the package.json - we need an absolute path to read the files\n rootTypings = join(packageRoot, rootTypings);\n // some @types packages specify `index` as their typings file instead of `index.d.ts`\n rootTypings = normalizeDTSImport(rootTypings);\n\n // recursively load all typings, keyed by their location on disk\n const collected = new Map<string, string>();\n const definitionQueue = [rootTypings];\n while (definitionQueue.length > 0) {\n const filename: string = definitionQueue.shift() as string;\n if (collected.has(filename)) {\n continue;\n }\n let fileContent: string;\n try {\n fileContent = readFileSync(filename, 'utf8');\n } catch (e: any) {\n // Without the entry point there is nothing to hand to TypeScript\n if (filename === rootTypings) {\n console.error(`Failed to load definitions for ${pkg}: ${e.toString()}`);\n return undefined;\n }\n // A referenced file was there a moment ago but cannot be read now. Dropping every\n // declaration of the package over one unreadable file would be out of proportion.\n console.warn(`Skipped a definition file of ${pkg}: ${e.toString()}`);\n continue;\n }\n collected.set(filename, fileContent);\n // If this file references another .d.ts file, we need to load that too\n matchAllImports(fileContent)\n // resolve the file relative to the current directory\n .map(file => join(dirname(filename), file))\n // find out the correct path of the file we want to import\n .map(normalizeDTSImport)\n // A package may import something it does not ship declarations for, and the matcher\n // above may pick up a string that only looks like a path\n .filter(file => existsSync(file))\n // Find all libs we have not loaded yet\n .filter(file => !collected.has(file))\n .forEach(file => definitionQueue.push(file));\n }\n\n /**\n * The directory that becomes `node_modules/<pkg>` in the virtual file system.\n *\n * `virtual-tsc` resolves with `moduleResolution: node10`, which looks the entry point up next to\n * the package - so laying the files out around the entry point rather than around the\n * package.json is what makes a package work whose declarations sit in a subdirectory. For a\n * package whose entry point is at its root - the usual case - this is the package root and\n * nothing changes.\n */\n let virtualRoot = dirname(rootTypings);\n if ([...collected.keys()].some(file => relative(virtualRoot, file).startsWith('..'))) {\n // Declarations reach above the entry point. Moving them would break the relative imports\n // between them, so the layout of the package is kept as it is.\n virtualRoot = packageRoot;\n }\n\n const toVirtualPath = (filename: string): string =>\n normalize(`${virtualPackageDir}/${relative(virtualRoot, filename)}`).replace(/\\\\/g, '/');\n\n const ret: Record<string, string> = {};\n for (const [filename, fileContent] of collected) {\n ret[toVirtualPath(filename)] =\n filename === rootTypings ? wrapRootTypingsIfNeeded(pkg, fileContent) : fileContent;\n }\n\n // Include a package.json, so TypeScript can look up the entry point. It describes the layout\n // above, not the one the package has on disk - and it is deliberately minimal: the original\n // `exports` map refers to paths that do not exist here, and TypeScript refuses to resolve the\n // package at all when it finds one it cannot follow under `moduleResolution: node10`.\n ret[`${virtualPackageDir}/package.json`] = JSON.stringify({\n name: pkg,\n version: packageJson?.version,\n types: `./${relative(virtualRoot, rootTypings).replace(/\\\\/g, '/')}`,\n });\n\n // Avoid returning empty declarations\n if (!collected.size) {\n return undefined;\n }\n return ret;\n}\n\n/**\n * @param s Statement to check whether it must be hoisted to the top of the file\n * @param isGlobal Whether this is a global script or a normal one\n */\nfunction mustBeHoisted(s: Statement & { modifiers?: Modifier[] }, isGlobal?: boolean): boolean {\n return !!(\n // Import/export statements must be moved to the top\n isImportDeclaration(s) ||\n isImportEqualsDeclaration(s) ||\n isExportDeclaration(s) ||\n isExportAssignment(s) ||\n // as well as many declarations\n isTypeAliasDeclaration(s) ||\n isInterfaceDeclaration(s) ||\n isModuleDeclaration(s) ||\n isEnumDeclaration(s) ||\n (isGlobal &&\n // in global scripts we don't wrap classes and functions, so they can be accessed from non-global scripts\n (isClassDeclaration(s) || isFunctionDeclaration(s))) ||\n // and declare ... / export ... statements\n s.modifiers?.some(s => s.kind === SyntaxKind.DeclareKeyword || s.kind === SyntaxKind.ExportKeyword)\n );\n}\n\nfunction canBeExported(s: Statement): boolean {\n return (\n // const, let, var\n isVariableStatement(s) ||\n // type, interface, enum, class, function\n isTypeAliasDeclaration(s) ||\n isInterfaceDeclaration(s) ||\n isEnumDeclaration(s) ||\n isClassDeclaration(s) ||\n isFunctionDeclaration(s)\n );\n}\n\nfunction addExportModifier(s: Statement & { modifiers?: Modifier[] }): Statement {\n let modifiers: Modifier[] | undefined;\n // Add export modifiers\n if (!s.modifiers) {\n modifiers = [factory.createModifier(SyntaxKind.ExportKeyword)];\n } else if (!s.modifiers.some(m => m.kind === SyntaxKind.ExportKeyword)) {\n modifiers = [...s.modifiers, factory.createModifier(SyntaxKind.ExportKeyword)];\n } else {\n return s;\n }\n\n if (isVariableStatement(s)) {\n return factory.updateVariableStatement(s, modifiers, s.declarationList);\n }\n if (isTypeAliasDeclaration(s)) {\n return factory.updateTypeAliasDeclaration(s, modifiers, s.name, s.typeParameters, s.type);\n }\n if (isInterfaceDeclaration(s)) {\n return factory.updateInterfaceDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isEnumDeclaration(s)) {\n return factory.updateEnumDeclaration(s, modifiers, s.name, s.members);\n }\n if (isClassDeclaration(s)) {\n return factory.updateClassDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isFunctionDeclaration(s)) {\n return factory.updateFunctionDeclaration(\n s,\n modifiers,\n s.asteriskToken,\n s.name,\n s.typeParameters,\n s.parameters,\n s.type,\n s.body,\n );\n }\n return s;\n}\n\nfunction removeDeclareModifier(s: Statement & { modifiers?: Modifier[] }): Statement {\n let modifiers: Modifier[] | undefined;\n // Remove declare modifiers\n if (s.modifiers) {\n modifiers = s.modifiers.filter(m => m.kind !== SyntaxKind.DeclareKeyword);\n } else {\n return s;\n }\n\n if (isVariableStatement(s)) {\n return factory.updateVariableStatement(s, modifiers, s.declarationList);\n }\n if (isTypeAliasDeclaration(s)) {\n return factory.updateTypeAliasDeclaration(s, modifiers, s.name, s.typeParameters, s.type);\n }\n if (isInterfaceDeclaration(s)) {\n return factory.updateInterfaceDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isEnumDeclaration(s)) {\n return factory.updateEnumDeclaration(s, modifiers, s.name, s.members);\n }\n if (isClassDeclaration(s)) {\n return factory.updateClassDeclaration(s, modifiers, s.name, s.typeParameters, s.heritageClauses, s.members);\n }\n if (isFunctionDeclaration(s)) {\n return factory.updateFunctionDeclaration(\n s,\n modifiers,\n s.asteriskToken,\n s.name,\n s.typeParameters,\n s.parameters,\n s.type,\n s.body,\n );\n }\n\n return s;\n}\n\n// taken from node_modules\\@types\\node\\globals.d.ts\n// the globally available things must be wrapped in `declare global` if the user wants to augment them\nconst NodeJSGlobals = [\n 'Array',\n 'ArrayBuffer',\n 'Boolean',\n 'Buffer',\n 'DataView',\n 'Date',\n 'Error',\n 'EvalError',\n 'Float32Array',\n 'Float64Array',\n 'Function',\n 'GLOBAL',\n 'Infinity',\n 'Int16Array',\n 'Int32Array',\n 'Int8Array',\n 'Intl',\n 'JSON',\n 'Map',\n 'Math',\n 'NaN',\n 'Number',\n 'Object',\n 'Promise',\n 'RangeError',\n 'ReferenceError',\n 'RegExp',\n 'Set',\n 'String',\n 'Symbol',\n 'SyntaxError',\n 'TypeError',\n 'URIError',\n 'Uint16Array',\n 'Uint32Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'WeakMap',\n 'WeakSet',\n 'clearImmediate',\n 'clearInterval',\n 'clearTimeout',\n 'console',\n 'decodeURI',\n 'decodeURIComponent',\n 'encodeURI',\n 'encodeURIComponent',\n 'escape',\n 'eval',\n 'global',\n 'isFinite',\n 'isNaN',\n 'parseFloat',\n 'parseInt',\n 'process',\n 'root',\n 'setImmediate',\n 'setInterval',\n 'setTimeout',\n 'queueMicrotask',\n 'undefined',\n 'unescape',\n 'gc',\n 'v8debug',\n];\n\nfunction isGlobalAugmentation(s: Statement): boolean {\n return !!(\n (isInterfaceDeclaration(s) || isClassDeclaration(s) || isFunctionDeclaration(s)) &&\n s.name &&\n NodeJSGlobals.includes(s.name.text)\n );\n}\n\nfunction wrapInDeclareGlobal(statements: Statement[]): ModuleDeclaration {\n return factory.createModuleDeclaration(\n [factory.createModifier(SyntaxKind.DeclareKeyword)],\n factory.createIdentifier('global'),\n factory.createModuleBlock(statements),\n NodeFlags.GlobalAugmentation,\n );\n}\n\n/**\n * Takes a TypeScript script and does the necessary transformations, so it can be compiled properly\n *\n * @param source The original TypeScript source\n * @param isGlobal Whether the transformed script is a global script or not\n */\nexport function transformScriptBeforeCompilation(source: string, isGlobal?: boolean): string {\n const transformer: TransformerFactory<SourceFile> = (_context: TransformationContext): Transformer<SourceFile> => {\n return (sourceFile: SourceFile) =>\n visitNode(sourceFile, (node: SourceFile): any => {\n if (isSourceFile(node)) {\n // Wrap all declarations that augment global interfaces in `declare global`\n const augmentations = node.statements.filter(s => isGlobalAugmentation(s));\n const nonAugmentations = node.statements.filter(s => !isGlobalAugmentation(s));\n\n // If there is no top level await, don't move all the statements around\n const hasTLA = node.statements.some(\n s => isExpressionStatement(s) && s.expression.kind === SyntaxKind.AwaitExpression,\n );\n // Move all statements to the top of the file that cannot appear in a function body\n let hoistedStatements = hasTLA\n ? factory.createNodeArray(nonAugmentations.filter(s => mustBeHoisted(s, isGlobal)))\n : factory.createNodeArray(nonAugmentations);\n\n // The rest gets wrapped\n const wrappedStatements = hasTLA ? nonAugmentations.filter(s => !mustBeHoisted(s, isGlobal)) : [];\n\n // When transforming global scripts, we need to do a couple of things\n if (isGlobal) {\n // 1. We need to add an export modifier to everything at the top level that can be exported\n hoistedStatements = visitNodes(\n hoistedStatements,\n // @ts-expect-error s is definitely a Statement\n s => (canBeExported(s) ? addExportModifier(s) : s),\n ) as NodeArray<Statement>;\n // 3. We need to transform the generated declarations to use `declare global` (this will happen in transformGlobalDeclarations)\n }\n const needsEmptyExport =\n // An empty export is necessary when there is no import declaration\n !node.statements.some(s => isImportDeclaration(s) || isImportEqualsDeclaration(s)) &&\n // And there is no statement in a global script which had an export modifier added\n (!(\n isGlobal &&\n hoistedStatements.some(\n // @ts-expect-error s should have modifiers\n s => s.modifiers?.some(m => m.kind === SyntaxKind.ExportKeyword),\n )\n ) ||\n // Or if there is a `declare global` statement\n !!augmentations);\n\n return factory.updateSourceFile(node, [\n // Put the hoisted statements at the top (or all of them if there's no top level await)\n ...hoistedStatements,\n // Then add everything that augments the global scope\n ...(augmentations && augmentations.length ? [wrapInDeclareGlobal(augmentations)] : []),\n ...(hasTLA\n ? // If there is a top-level await, wrap all non-hoisted statements in (async () => { ... })();\n [\n factory.createExpressionStatement(\n factory.createCallExpression(\n factory.createArrowFunction(\n [factory.createModifier(SyntaxKind.AsyncKeyword)],\n undefined,\n [],\n undefined,\n undefined,\n factory.createBlock(wrappedStatements),\n ),\n undefined,\n undefined,\n ),\n ),\n ]\n : []),\n ...(needsEmptyExport\n ? [\n // Put an empty export {}; at the bottom to force TypeScript to treat the script as a module\n factory.createExportDeclaration(\n undefined, // ModifierLike[] | undefined\n false, // isTypeOnly\n factory.createNamedExports([]), // NamedExportBindings | undefined\n undefined, // moduleSpecifier\n undefined, // attributes\n ),\n ]\n : []),\n ]);\n }\n return node;\n });\n };\n\n const sourceFile = createSourceFile('index.ts', source, ScriptTarget.ESNext, /* setParentNodes */ true);\n\n const result = transform(sourceFile, [transformer]);\n return createPrinter(PRINTER_OPTIONS).printNode(EmitHint.Unspecified, result.transformed[0], sourceFile);\n}\n\n/**\n * Takes the global declarations for a TypeScript and wraps export statements in `declare global`\n *\n * @param decl The untransformed global declarations\n */\nexport function transformGlobalDeclarations(decl: string): string {\n const transformer: TransformerFactory<SourceFile> = (_context: TransformationContext): any => {\n return (sourceFile: SourceFile) =>\n visitNode(sourceFile, (node: SourceFile): SourceFile => {\n if (isSourceFile(node)) {\n // All non-export-statements stay at the root level, the rest is wrapped in `declare global`\n const exportStatements = node.statements.filter(\n // @ts-expect-error s should have modifiers\n s => s.modifiers?.some(m => m.kind === SyntaxKind.ExportKeyword),\n );\n const otherStatements = node.statements.filter(s => !exportStatements.includes(s));\n\n const hasExportStatements = exportStatements.length > 0;\n const hasImport = otherStatements.some(s => isImportDeclaration(s) || isImportEqualsDeclaration(s));\n\n return factory.updateSourceFile(node, [\n ...otherStatements,\n ...(hasExportStatements\n ? [wrapInDeclareGlobal(exportStatements.map(s => removeDeclareModifier(s)))]\n : []),\n ...(hasImport\n ? [] // If there is an import, the script is already treated as a module\n : [\n // Otherwise, put an empty export {}; at the bottom to force TypeScript to treat the script as a module\n factory.createExportDeclaration(\n undefined,\n false,\n factory.createNamedExports([]),\n undefined,\n undefined,\n ),\n ]),\n ]);\n }\n\n return node;\n });\n };\n\n const sourceFile = createSourceFile('index.d.ts', decl, ScriptTarget.ESNext, /* setParentNodes */ true);\n\n const result = transform(sourceFile, [transformer]);\n return createPrinter(PRINTER_OPTIONS).printNode(EmitHint.Unspecified, result.transformed[0], sourceFile);\n}\n\n/**\n * Translates a script ID to a filename for the compiler\n *\n * @param scriptID The ID of the script\n */\nexport function scriptIdToTSFilename(scriptID: string): string {\n return `${scriptID.replace(/^script.js./, '').replace(/\\./g, '/')}.ts`;\n}\n"]}