tungsten 0.4.12 → 0.4.13

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 (245) hide show
  1. package/dist/.build-complete +1 -1
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/AnyComponent.d.ts.map +1 -1
  4. package/dist/Components.d.ts.map +1 -1
  5. package/dist/Components.js +11 -8
  6. package/dist/DomPointer.js +1 -1
  7. package/dist/DomRegion.js +2 -2
  8. package/dist/Framework.js +1 -1
  9. package/dist/FrameworkConfig.d.ts.map +1 -1
  10. package/dist/Instance/Instance.js +1 -1
  11. package/dist/RenderedContentNode.d.ts.map +1 -1
  12. package/dist/RenderedContentNode.js +2 -1
  13. package/dist/Sass.d.ts.map +1 -1
  14. package/dist/Sass.js +1 -0
  15. package/dist/Servers/DevServer.d.ts.map +1 -1
  16. package/dist/Servers/DevServer.js +4 -3
  17. package/dist/Servers/ProdServer.js +1 -1
  18. package/dist/Servers/StaticSiteServer.js +1 -1
  19. package/dist/Servers/loadEnvsDev.d.ts +1 -1
  20. package/dist/Servers/loadEnvsDev.d.ts.map +1 -1
  21. package/dist/Servers/loadEnvsDev.js +4 -2
  22. package/dist/Servers/routing.d.ts.map +1 -1
  23. package/dist/Servers/routing.js +1 -1
  24. package/dist/Store/Store.js +1 -1
  25. package/dist/Store/TypeSafeStore.js +1 -1
  26. package/dist/Store/makeStore.js +1 -1
  27. package/dist/Store/registerStore.js +1 -1
  28. package/dist/TElement.js +1 -1
  29. package/dist/TungstenApp.js +6 -2
  30. package/dist/api/getExport.d.ts.map +1 -1
  31. package/dist/api/getExport.js +1 -0
  32. package/dist/babelPlugins/BabelTransformBindDirect.js +2 -0
  33. package/dist/babelPlugins/BabelTransformBindVar.d.ts.map +1 -1
  34. package/dist/babelPlugins/BabelTransformComponentState.d.ts.map +1 -1
  35. package/dist/babelPlugins/BabelTransformComponentStyles.d.ts.map +1 -1
  36. package/dist/babelPlugins/BabelTransformComponentStyles.js +5 -4
  37. package/dist/babelPlugins/BabelTransformCssImports.d.ts.map +1 -1
  38. package/dist/babelPlugins/BabelTransformCssImports.js +2 -2
  39. package/dist/babelPlugins/BabelTransformDependencyImportsOld.js +1 -1
  40. package/dist/babelPlugins/BabelTransformDeproxyState.d.ts.map +1 -1
  41. package/dist/babelPlugins/BabelTransformPackageImports.d.ts.map +1 -1
  42. package/dist/babelPlugins/BabelTransformPackageImports.js +10 -5
  43. package/dist/babelPlugins/BabelTransformRemoveBlocks.d.ts.map +1 -1
  44. package/dist/babelPlugins/transformPackageImports/BabelTransformDependencyImportsCjs.d.ts.map +1 -1
  45. package/dist/babelPlugins/transformPackageImports/BabelTransformDependencyImportsCjs.js +2 -1
  46. package/dist/babelPlugins/transformPackageImports/BabelTransformDependencyImportsEsm.d.ts.map +1 -1
  47. package/dist/babelPlugins/transformPackageImports/BabelTransformDependencyImportsEsm.js +2 -1
  48. package/dist/bin/args.js +1 -1
  49. package/dist/bin/commands/build.js +1 -1
  50. package/dist/bin/commands/compileSimplePackage.js +1 -0
  51. package/dist/bin/index.d.ts.map +1 -1
  52. package/dist/bin/index.js +11 -3
  53. package/dist/bin/vendorHook.d.ts +3 -0
  54. package/dist/bin/vendorHook.d.ts.map +1 -0
  55. package/dist/bin/vendorHook.js +34 -0
  56. package/dist/browserStorage.js +4 -2
  57. package/dist/build/babel.user.common.config.d.ts +2 -0
  58. package/dist/build/babel.user.common.config.d.ts.map +1 -1
  59. package/dist/build/babel.user.common.config.js +10 -4
  60. package/dist/build/compileJavascript.d.ts.map +1 -1
  61. package/dist/build/compileJavascript.js +40 -27
  62. package/dist/build/compileStyles.js +4 -4
  63. package/dist/build/copyAssets.js +3 -3
  64. package/dist/build/copyPublicFiles.js +3 -3
  65. package/dist/build/frameworkStylesheets.js +1 -1
  66. package/dist/build/getAllSxyClientModules.d.ts.map +1 -1
  67. package/dist/build/getAllSxyClientModules.js +4 -28
  68. package/dist/build/getSxyClientPackageAliases.d.ts.map +1 -1
  69. package/dist/build/makeBabelUserDevConfig.d.ts.map +1 -1
  70. package/dist/build/makeBabelUserProdConfig.d.ts.map +1 -1
  71. package/dist/build/rollupExtractComponentStylesheets.js +1 -1
  72. package/dist/build/sassImportParser.js +2 -2
  73. package/dist/build/tallyBabel.d.ts +3 -0
  74. package/dist/build/tallyBabel.d.ts.map +1 -0
  75. package/dist/build/tallyBabel.js +11 -0
  76. package/dist/clone.js +4 -4
  77. package/dist/compat/context.d.ts.map +1 -1
  78. package/dist/compat/types.d.ts.map +1 -1
  79. package/dist/componentProxyHandlers.d.ts.map +1 -1
  80. package/dist/componentProxyHandlers.js +5 -9
  81. package/dist/components/Stylesheet.d.ts +1 -2
  82. package/dist/components/Stylesheet.d.ts.map +1 -1
  83. package/dist/components/Stylesheet.js +1 -1
  84. package/dist/components/bindable/BindableCheckbox.d.ts.map +1 -1
  85. package/dist/components/bindable/BindableInput.d.ts.map +1 -1
  86. package/dist/components/bindable/BindableInputTypedLegacy.d.ts.map +1 -1
  87. package/dist/components/bindable/BindableRadio.d.ts.map +1 -1
  88. package/dist/components/bindable/BindableTextarea.d.ts.map +1 -1
  89. package/dist/components/library/RichTextEditor/RichTextEditor.js +2 -2
  90. package/dist/components/library/RichTextEditor/contentTree.js +1 -1
  91. package/dist/concat.d.ts.map +1 -1
  92. package/dist/concat.js +2 -2
  93. package/dist/copy.d.ts.map +1 -1
  94. package/dist/createRoutes.d.ts +1 -1
  95. package/dist/createRoutes.d.ts.map +1 -1
  96. package/dist/env/Env.js +2 -2
  97. package/dist/env/getEnvSchemas.d.ts +2 -2
  98. package/dist/env/getEnvSchemas.d.ts.map +1 -1
  99. package/dist/env/getEnvSchemas.js +7 -5
  100. package/dist/env/windowGlobalEnvStatement.d.ts.map +1 -1
  101. package/dist/findProjectDir.d.ts.map +1 -1
  102. package/dist/findProjectDir.js +18 -4
  103. package/dist/findUserConfig.js +2 -2
  104. package/dist/foreach.js +1 -0
  105. package/dist/frameworkConfigSchema.js +2 -2
  106. package/dist/getComponent.d.ts.map +1 -1
  107. package/dist/getComponentDev.d.ts.map +1 -1
  108. package/dist/getRoutes.d.ts.map +1 -1
  109. package/dist/getRoutes.js +13 -22
  110. package/dist/getRoutesDevs.d.ts.map +1 -1
  111. package/dist/getStackTrace.js +1 -1
  112. package/dist/glob.d.ts +5 -0
  113. package/dist/glob.d.ts.map +1 -0
  114. package/dist/glob.js +103 -0
  115. package/dist/helpers/getFetchCompatibleHeaders.js +2 -2
  116. package/dist/hmr/applyHmrModule.js +5 -5
  117. package/dist/hmr/componentIdentity.js +1 -1
  118. package/dist/hmr/instanceRegistry.js +2 -2
  119. package/dist/hooks/useReducer.d.ts.map +1 -1
  120. package/dist/hooks/useState.d.ts.map +1 -1
  121. package/dist/hooks/useState.js +2 -8
  122. package/dist/hydrate/hydrate.d.ts +1 -1
  123. package/dist/hydrate/hydrate.d.ts.map +1 -1
  124. package/dist/hydrate/hydrate.js +26 -24
  125. package/dist/hydrate/reconcileHydratedAttributes.js +2 -2
  126. package/dist/makeFinalConfig.d.ts.map +1 -1
  127. package/dist/makeFinalConfig.js +2 -2
  128. package/dist/markOptionSelected.js +1 -1
  129. package/dist/mergeConfigs.d.ts.map +1 -1
  130. package/dist/mergeConfigs.js +11 -2
  131. package/dist/mutatingFunctions.js +3 -3
  132. package/dist/postcssPlugins/TransformCssNames.js +2 -2
  133. package/dist/rawHtml/parseHtml.js +1 -1
  134. package/dist/render/componentNodeToRenderingTree.d.ts.map +1 -1
  135. package/dist/render/componentNodeToRenderingTree.js +6 -17
  136. package/dist/render/contentToHtml.d.ts.map +1 -1
  137. package/dist/render/contentToHtml.js +1 -1
  138. package/dist/render/getFunctionBodyAsString.d.ts.map +1 -1
  139. package/dist/render/getFunctionBodyAsString.js +2 -5
  140. package/dist/render/processProps.js +2 -2
  141. package/dist/render/renderingTreeToHtml.d.ts.map +1 -1
  142. package/dist/render/rootToHtml.d.ts.map +1 -1
  143. package/dist/routing/Route.js +1 -1
  144. package/dist/routing/RouteDataFunction.type.d.ts.map +1 -1
  145. package/dist/routing/RoutesWithSafeParams.js +1 -1
  146. package/dist/routing/WebRedirect.d.ts.map +1 -1
  147. package/dist/routing/compareRequestToRegex.js +2 -2
  148. package/dist/routing/getPathPriority.js +1 -1
  149. package/dist/serverRpc.d.ts.map +1 -1
  150. package/dist/slash.d.ts +2 -0
  151. package/dist/slash.d.ts.map +1 -0
  152. package/dist/slash.js +5 -0
  153. package/dist/spawnShellCommand.js +1 -1
  154. package/dist/staticGen/staticGen.d.ts.map +1 -1
  155. package/dist/staticGen/staticGen.js +9 -7
  156. package/dist/staticGen/staticGenFunctions.js +1 -1
  157. package/dist/style/jssToCss.d.ts.map +1 -1
  158. package/dist/style/jssToCss.js +11 -9
  159. package/dist/style/unusedStyles.d.ts.map +1 -1
  160. package/dist/testing/host.js +11 -11
  161. package/dist/testing/hydrateTestApp.d.ts.map +1 -1
  162. package/dist/testing/hydrateTestApp.js +9 -9
  163. package/dist/testing/index.d.ts.map +1 -1
  164. package/dist/testing/installTestStyleProcessors.js +1 -1
  165. package/dist/testing/loadEnv.d.ts +4 -1
  166. package/dist/testing/loadEnv.d.ts.map +1 -1
  167. package/dist/testing/loadEnv.js +2 -2
  168. package/dist/testing/temp/componentPackageMock.js +3 -3
  169. package/dist/timeProfiler.d.ts +4 -0
  170. package/dist/timeProfiler.d.ts.map +1 -1
  171. package/dist/timeProfiler.js +16 -0
  172. package/dist/todo.js +2 -1
  173. package/dist/update/integrateUpdateVdom.d.ts.map +1 -1
  174. package/dist/update/integrateUpdateVdom.js +17 -14
  175. package/dist/update/integrateUpdateVdomPrebuild.js +5 -5
  176. package/dist/watch.js +2 -2
  177. package/package.json +10 -29
  178. package/types/modules.d.ts +0 -1
  179. package/vendor/babel-core.js +26 -0
  180. package/vendor/babel-parser.js +9 -0
  181. package/vendor/babel-plugin-syntax-import-assertions.js +50 -0
  182. package/vendor/babel-preset-react.js +872 -0
  183. package/vendor/babel-preset-typescript.js +26 -0
  184. package/vendor/babel-types.js +9 -0
  185. package/vendor/chalk-extensions.js +1994 -0
  186. package/vendor/chalk.js +647 -0
  187. package/vendor/chokidar.js +6889 -0
  188. package/vendor/chunk-1TN2rK3j.js +1218 -0
  189. package/vendor/chunk-1UuLTU0U.js +34 -0
  190. package/vendor/chunk-B_NeooyV.js +86 -0
  191. package/vendor/chunk-C12hSZn7.js +88 -0
  192. package/vendor/chunk-C3YkUGz5.js +19 -0
  193. package/vendor/chunk-C3fcZDjl.js +41964 -0
  194. package/vendor/chunk-C9FSKeSx.js +14603 -0
  195. package/vendor/chunk-CPArXGxa.js +14623 -0
  196. package/vendor/cjs-module-lexer.js +6 -0
  197. package/vendor/dotenv.js +412 -0
  198. package/vendor/express.js +40577 -0
  199. package/vendor/import-meta-resolve.js +2201 -0
  200. package/vendor/manifest.json +29 -0
  201. package/vendor/postcss.js +8546 -0
  202. package/vendor/serialize-javascript.js +293 -0
  203. package/vendor/sxy-lib-arrays.js +113 -0
  204. package/vendor/sxy-lib-object-copy.js +1781 -0
  205. package/vendor/sxy-lib-objects.js +156 -0
  206. package/vendor/sxy-lib-promises.js +47 -0
  207. package/vendor/sxy-package-investigator.js +202 -0
  208. package/vendor/valibot.js +7664 -0
  209. package/dist/Servers/hono/DevServerHono.d.ts +0 -2
  210. package/dist/Servers/hono/DevServerHono.d.ts.map +0 -1
  211. package/dist/Servers/hono/DevServerHono.js +0 -423
  212. package/dist/Servers/hono/ProdServerHono.d.ts +0 -2
  213. package/dist/Servers/hono/ProdServerHono.d.ts.map +0 -1
  214. package/dist/Servers/hono/ProdServerHono.js +0 -220
  215. package/dist/Servers/hono/TungstenServerHono.d.ts +0 -6
  216. package/dist/Servers/hono/TungstenServerHono.d.ts.map +0 -1
  217. package/dist/Servers/hono/TungstenServerHono.js +0 -36
  218. package/dist/api/ApiEndpointHono.d.ts +0 -3
  219. package/dist/api/ApiEndpointHono.d.ts.map +0 -1
  220. package/dist/api/ApiEndpointHono.js +0 -1
  221. package/dist/api/ApiRouteHono.d.ts +0 -7
  222. package/dist/api/ApiRouteHono.d.ts.map +0 -1
  223. package/dist/api/ApiRouteHono.js +0 -1
  224. package/dist/api/ApiRoutesHono.d.ts +0 -5
  225. package/dist/api/ApiRoutesHono.d.ts.map +0 -1
  226. package/dist/api/ApiRoutesHono.js +0 -1
  227. package/dist/api/getApiRoutesHono.d.ts +0 -6
  228. package/dist/api/getApiRoutesHono.d.ts.map +0 -1
  229. package/dist/api/getApiRoutesHono.js +0 -14
  230. package/dist/build/compilePackages.d.ts +0 -2
  231. package/dist/build/compilePackages.d.ts.map +0 -1
  232. package/dist/build/compilePackages.js +0 -89
  233. package/dist/build/findRequiredUserModule.d.ts +0 -2
  234. package/dist/build/findRequiredUserModule.d.ts.map +0 -1
  235. package/dist/build/findRequiredUserModule.js +0 -36
  236. package/dist/build/processPackage.d.ts +0 -4
  237. package/dist/build/processPackage.d.ts.map +0 -1
  238. package/dist/build/processPackage.js +0 -91
  239. package/dist/build/tallyBabelPlugins.d.ts +0 -3
  240. package/dist/build/tallyBabelPlugins.d.ts.map +0 -1
  241. package/dist/build/tallyBabelPlugins.js +0 -63
  242. package/dist/testing/loadEnvSetup.d.ts +0 -2
  243. package/dist/testing/loadEnvSetup.d.ts.map +0 -1
  244. package/dist/testing/loadEnvSetup.js +0 -7
  245. package/sxy-loader.config.js +0 -7
@@ -0,0 +1,2201 @@
1
+ import { createRequire as __tungstenCreateRequire } from 'node:module';
2
+ const require = __tungstenCreateRequire(import.meta.url);
3
+ import assert from 'node:assert';
4
+ import fs, { realpathSync, statSync } from 'node:fs';
5
+ import process from 'node:process';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import path from 'node:path';
8
+ import { builtinModules } from 'node:module';
9
+ import v8 from 'node:v8';
10
+ import { format, inspect } from 'node:util';
11
+
12
+ /**
13
+ * @typedef ErrnoExceptionFields
14
+ * @property {number | undefined} [errnode]
15
+ * @property {string | undefined} [code]
16
+ * @property {string | undefined} [path]
17
+ * @property {string | undefined} [syscall]
18
+ * @property {string | undefined} [url]
19
+ *
20
+ * @typedef {Error & ErrnoExceptionFields} ErrnoException
21
+ */
22
+
23
+
24
+ const own$1 = {}.hasOwnProperty;
25
+
26
+ const classRegExp = /^([A-Z][a-z\d]*)+$/;
27
+ // Sorted by a rough estimate on most frequently used entries.
28
+ const kTypes = new Set([
29
+ 'string',
30
+ 'function',
31
+ 'number',
32
+ 'object',
33
+ // Accept 'Function' and 'Object' as alternative to the lower cased version.
34
+ 'Function',
35
+ 'Object',
36
+ 'boolean',
37
+ 'bigint',
38
+ 'symbol'
39
+ ]);
40
+
41
+ const codes = {};
42
+
43
+ /**
44
+ * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
45
+ * We cannot use Intl.ListFormat because it's not available in
46
+ * --without-intl builds.
47
+ *
48
+ * @param {Array<string>} array
49
+ * An array of strings.
50
+ * @param {string} [type]
51
+ * The list type to be inserted before the last element.
52
+ * @returns {string}
53
+ */
54
+ function formatList(array, type = 'and') {
55
+ return array.length < 3
56
+ ? array.join(` ${type} `)
57
+ : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
58
+ }
59
+
60
+ /** @type {Map<string, MessageFunction | string>} */
61
+ const messages = new Map();
62
+ const nodeInternalPrefix = '__node_internal_';
63
+ /** @type {number} */
64
+ let userStackTraceLimit;
65
+
66
+ codes.ERR_INVALID_ARG_TYPE = createError(
67
+ 'ERR_INVALID_ARG_TYPE',
68
+ /**
69
+ * @param {string} name
70
+ * @param {Array<string> | string} expected
71
+ * @param {unknown} actual
72
+ */
73
+ (name, expected, actual) => {
74
+ assert.ok(typeof name === 'string', "'name' must be a string");
75
+ if (!Array.isArray(expected)) {
76
+ expected = [expected];
77
+ }
78
+
79
+ let message = 'The ';
80
+ if (name.endsWith(' argument')) {
81
+ // For cases like 'first argument'
82
+ message += `${name} `;
83
+ } else {
84
+ const type = name.includes('.') ? 'property' : 'argument';
85
+ message += `"${name}" ${type} `;
86
+ }
87
+
88
+ message += 'must be ';
89
+
90
+ /** @type {Array<string>} */
91
+ const types = [];
92
+ /** @type {Array<string>} */
93
+ const instances = [];
94
+ /** @type {Array<string>} */
95
+ const other = [];
96
+
97
+ for (const value of expected) {
98
+ assert.ok(
99
+ typeof value === 'string',
100
+ 'All expected entries have to be of type string'
101
+ );
102
+
103
+ if (kTypes.has(value)) {
104
+ types.push(value.toLowerCase());
105
+ } else if (classRegExp.exec(value) === null) {
106
+ assert.ok(
107
+ value !== 'object',
108
+ 'The value "object" should be written as "Object"'
109
+ );
110
+ other.push(value);
111
+ } else {
112
+ instances.push(value);
113
+ }
114
+ }
115
+
116
+ // Special handle `object` in case other instances are allowed to outline
117
+ // the differences between each other.
118
+ if (instances.length > 0) {
119
+ const pos = types.indexOf('object');
120
+ if (pos !== -1) {
121
+ types.slice(pos, 1);
122
+ instances.push('Object');
123
+ }
124
+ }
125
+
126
+ if (types.length > 0) {
127
+ message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(
128
+ types,
129
+ 'or'
130
+ )}`;
131
+ if (instances.length > 0 || other.length > 0) message += ' or ';
132
+ }
133
+
134
+ if (instances.length > 0) {
135
+ message += `an instance of ${formatList(instances, 'or')}`;
136
+ if (other.length > 0) message += ' or ';
137
+ }
138
+
139
+ if (other.length > 0) {
140
+ if (other.length > 1) {
141
+ message += `one of ${formatList(other, 'or')}`;
142
+ } else {
143
+ if (other[0].toLowerCase() !== other[0]) message += 'an ';
144
+ message += `${other[0]}`;
145
+ }
146
+ }
147
+
148
+ message += `. Received ${determineSpecificType(actual)}`;
149
+
150
+ return message
151
+ },
152
+ TypeError
153
+ );
154
+
155
+ codes.ERR_INVALID_MODULE_SPECIFIER = createError(
156
+ 'ERR_INVALID_MODULE_SPECIFIER',
157
+ /**
158
+ * @param {string} request
159
+ * @param {string} reason
160
+ * @param {string} [base]
161
+ */
162
+ (request, reason, base = undefined) => {
163
+ return `Invalid module "${request}" ${reason}${
164
+ base ? ` imported from ${base}` : ''
165
+ }`
166
+ },
167
+ TypeError
168
+ );
169
+
170
+ codes.ERR_INVALID_PACKAGE_CONFIG = createError(
171
+ 'ERR_INVALID_PACKAGE_CONFIG',
172
+ /**
173
+ * @param {string} path
174
+ * @param {string} [base]
175
+ * @param {string} [message]
176
+ */
177
+ (path, base, message) => {
178
+ return `Invalid package config ${path}${
179
+ base ? ` while importing ${base}` : ''
180
+ }${message ? `. ${message}` : ''}`
181
+ },
182
+ Error
183
+ );
184
+
185
+ codes.ERR_INVALID_PACKAGE_TARGET = createError(
186
+ 'ERR_INVALID_PACKAGE_TARGET',
187
+ /**
188
+ * @param {string} packagePath
189
+ * @param {string} key
190
+ * @param {unknown} target
191
+ * @param {boolean} [isImport=false]
192
+ * @param {string} [base]
193
+ */
194
+ (packagePath, key, target, isImport = false, base = undefined) => {
195
+ const relatedError =
196
+ typeof target === 'string' &&
197
+ !isImport &&
198
+ target.length > 0 &&
199
+ !target.startsWith('./');
200
+ if (key === '.') {
201
+ assert.ok(isImport === false);
202
+ return (
203
+ `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
204
+ `in the package config ${packagePath}package.json${
205
+ base ? ` imported from ${base}` : ''
206
+ }${relatedError ? '; targets must start with "./"' : ''}`
207
+ )
208
+ }
209
+
210
+ return `Invalid "${
211
+ isImport ? 'imports' : 'exports'
212
+ }" target ${JSON.stringify(
213
+ target
214
+ )} defined for '${key}' in the package config ${packagePath}package.json${
215
+ base ? ` imported from ${base}` : ''
216
+ }${relatedError ? '; targets must start with "./"' : ''}`
217
+ },
218
+ Error
219
+ );
220
+
221
+ codes.ERR_MODULE_NOT_FOUND = createError(
222
+ 'ERR_MODULE_NOT_FOUND',
223
+ /**
224
+ * @param {string} path
225
+ * @param {string} base
226
+ * @param {boolean} [exactUrl]
227
+ */
228
+ (path, base, exactUrl = false) => {
229
+ return `Cannot find ${
230
+ exactUrl ? 'module' : 'package'
231
+ } '${path}' imported from ${base}`
232
+ },
233
+ Error
234
+ );
235
+
236
+ codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
237
+ 'ERR_NETWORK_IMPORT_DISALLOWED',
238
+ "import of '%s' by %s is not supported: %s",
239
+ Error
240
+ );
241
+
242
+ codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
243
+ 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
244
+ /**
245
+ * @param {string} specifier
246
+ * @param {string} packagePath
247
+ * @param {string} base
248
+ */
249
+ (specifier, packagePath, base) => {
250
+ return `Package import specifier "${specifier}" is not defined${
251
+ packagePath ? ` in package ${packagePath}package.json` : ''
252
+ } imported from ${base}`
253
+ },
254
+ TypeError
255
+ );
256
+
257
+ codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
258
+ 'ERR_PACKAGE_PATH_NOT_EXPORTED',
259
+ /**
260
+ * @param {string} packagePath
261
+ * @param {string} subpath
262
+ * @param {string} [base]
263
+ */
264
+ (packagePath, subpath, base = undefined) => {
265
+ if (subpath === '.')
266
+ return `No "exports" main defined in ${packagePath}package.json${
267
+ base ? ` imported from ${base}` : ''
268
+ }`
269
+ return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${
270
+ base ? ` imported from ${base}` : ''
271
+ }`
272
+ },
273
+ Error
274
+ );
275
+
276
+ codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
277
+ 'ERR_UNSUPPORTED_DIR_IMPORT',
278
+ "Directory import '%s' is not supported " +
279
+ 'resolving ES modules imported from %s',
280
+ Error
281
+ );
282
+
283
+ codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError(
284
+ 'ERR_UNSUPPORTED_RESOLVE_REQUEST',
285
+ 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
286
+ TypeError
287
+ );
288
+
289
+ codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
290
+ 'ERR_UNKNOWN_FILE_EXTENSION',
291
+ /**
292
+ * @param {string} extension
293
+ * @param {string} path
294
+ */
295
+ (extension, path) => {
296
+ return `Unknown file extension "${extension}" for ${path}`
297
+ },
298
+ TypeError
299
+ );
300
+
301
+ codes.ERR_INVALID_ARG_VALUE = createError(
302
+ 'ERR_INVALID_ARG_VALUE',
303
+ /**
304
+ * @param {string} name
305
+ * @param {unknown} value
306
+ * @param {string} [reason='is invalid']
307
+ */
308
+ (name, value, reason = 'is invalid') => {
309
+ let inspected = inspect(value);
310
+
311
+ if (inspected.length > 128) {
312
+ inspected = `${inspected.slice(0, 128)}...`;
313
+ }
314
+
315
+ const type = name.includes('.') ? 'property' : 'argument';
316
+
317
+ return `The ${type} '${name}' ${reason}. Received ${inspected}`
318
+ },
319
+ TypeError
320
+ // Note: extra classes have been shaken out.
321
+ // , RangeError
322
+ );
323
+
324
+ /**
325
+ * Utility function for registering the error codes. Only used here. Exported
326
+ * *only* to allow for testing.
327
+ * @param {string} sym
328
+ * @param {MessageFunction | string} value
329
+ * @param {ErrorConstructor} constructor
330
+ * @returns {new (...parameters: Array<any>) => Error}
331
+ */
332
+ function createError(sym, value, constructor) {
333
+ // Special case for SystemError that formats the error message differently
334
+ // The SystemErrors only have SystemError as their base classes.
335
+ messages.set(sym, value);
336
+
337
+ return makeNodeErrorWithCode(constructor, sym)
338
+ }
339
+
340
+ /**
341
+ * @param {ErrorConstructor} Base
342
+ * @param {string} key
343
+ * @returns {ErrorConstructor}
344
+ */
345
+ function makeNodeErrorWithCode(Base, key) {
346
+ // @ts-expect-error It’s a Node error.
347
+ return NodeError
348
+ /**
349
+ * @param {Array<unknown>} parameters
350
+ */
351
+ function NodeError(...parameters) {
352
+ const limit = Error.stackTraceLimit;
353
+ if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
354
+ const error = new Base();
355
+ // Reset the limit and setting the name property.
356
+ if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
357
+ const message = getMessage(key, parameters, error);
358
+ Object.defineProperties(error, {
359
+ // Note: no need to implement `kIsNodeError` symbol, would be hard,
360
+ // probably.
361
+ message: {
362
+ value: message,
363
+ enumerable: false,
364
+ writable: true,
365
+ configurable: true
366
+ },
367
+ toString: {
368
+ /** @this {Error} */
369
+ value() {
370
+ return `${this.name} [${key}]: ${this.message}`
371
+ },
372
+ enumerable: false,
373
+ writable: true,
374
+ configurable: true
375
+ }
376
+ });
377
+
378
+ captureLargerStackTrace(error);
379
+ // @ts-expect-error It’s a Node error.
380
+ error.code = key;
381
+ return error
382
+ }
383
+ }
384
+
385
+ /**
386
+ * @returns {boolean}
387
+ */
388
+ function isErrorStackTraceLimitWritable() {
389
+ // Do no touch Error.stackTraceLimit as V8 would attempt to install
390
+ // it again during deserialization.
391
+ try {
392
+ if (v8.startupSnapshot.isBuildingSnapshot()) {
393
+ return false
394
+ }
395
+ } catch {}
396
+
397
+ const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
398
+ if (desc === undefined) {
399
+ return Object.isExtensible(Error)
400
+ }
401
+
402
+ return own$1.call(desc, 'writable') && desc.writable !== undefined
403
+ ? desc.writable
404
+ : desc.set !== undefined
405
+ }
406
+
407
+ /**
408
+ * This function removes unnecessary frames from Node.js core errors.
409
+ * @template {(...parameters: unknown[]) => unknown} T
410
+ * @param {T} wrappedFunction
411
+ * @returns {T}
412
+ */
413
+ function hideStackFrames(wrappedFunction) {
414
+ // We rename the functions that will be hidden to cut off the stacktrace
415
+ // at the outermost one
416
+ const hidden = nodeInternalPrefix + wrappedFunction.name;
417
+ Object.defineProperty(wrappedFunction, 'name', {value: hidden});
418
+ return wrappedFunction
419
+ }
420
+
421
+ const captureLargerStackTrace = hideStackFrames(
422
+ /**
423
+ * @param {Error} error
424
+ * @returns {Error}
425
+ */
426
+ // @ts-expect-error: fine
427
+ function (error) {
428
+ const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
429
+ if (stackTraceLimitIsWritable) {
430
+ userStackTraceLimit = Error.stackTraceLimit;
431
+ Error.stackTraceLimit = Number.POSITIVE_INFINITY;
432
+ }
433
+
434
+ Error.captureStackTrace(error);
435
+
436
+ // Reset the limit
437
+ if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
438
+
439
+ return error
440
+ }
441
+ );
442
+
443
+ /**
444
+ * @param {string} key
445
+ * @param {Array<unknown>} parameters
446
+ * @param {Error} self
447
+ * @returns {string}
448
+ */
449
+ function getMessage(key, parameters, self) {
450
+ const message = messages.get(key);
451
+ assert.ok(message !== undefined, 'expected `message` to be found');
452
+
453
+ if (typeof message === 'function') {
454
+ assert.ok(
455
+ message.length <= parameters.length, // Default options do not count.
456
+ `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
457
+ `match the required ones (${message.length}).`
458
+ );
459
+ return Reflect.apply(message, self, parameters)
460
+ }
461
+
462
+ const regex = /%[dfijoOs]/g;
463
+ let expectedLength = 0;
464
+ while (regex.exec(message) !== null) expectedLength++;
465
+ assert.ok(
466
+ expectedLength === parameters.length,
467
+ `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
468
+ `match the required ones (${expectedLength}).`
469
+ );
470
+ if (parameters.length === 0) return message
471
+
472
+ parameters.unshift(message);
473
+ return Reflect.apply(format, null, parameters)
474
+ }
475
+
476
+ /**
477
+ * Determine the specific type of a value for type-mismatch errors.
478
+ * @param {unknown} value
479
+ * @returns {string}
480
+ */
481
+ function determineSpecificType(value) {
482
+ if (value === null || value === undefined) {
483
+ return String(value)
484
+ }
485
+
486
+ if (typeof value === 'function' && value.name) {
487
+ return `function ${value.name}`
488
+ }
489
+
490
+ if (typeof value === 'object') {
491
+ if (value.constructor && value.constructor.name) {
492
+ return `an instance of ${value.constructor.name}`
493
+ }
494
+
495
+ return `${inspect(value, {depth: -1})}`
496
+ }
497
+
498
+ let inspected = inspect(value, {colors: false});
499
+
500
+ if (inspected.length > 28) {
501
+ inspected = `${inspected.slice(0, 25)}...`;
502
+ }
503
+
504
+ return `type ${typeof value} (${inspected})`
505
+ }
506
+
507
+ // Manually “tree shaken” from:
508
+ // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/package_json_reader.js>
509
+ // Last checked on: Apr 29, 2024.
510
+ // Removed the native dependency.
511
+ // Also: no need to cache, we do that in resolve already.
512
+
513
+
514
+ const hasOwnProperty$1 = {}.hasOwnProperty;
515
+
516
+ const {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes;
517
+
518
+ /** @type {Map<string, PackageConfig>} */
519
+ const cache = new Map();
520
+
521
+ /**
522
+ * @param {string} jsonPath
523
+ * @param {{specifier: URL | string, base?: URL}} options
524
+ * @returns {PackageConfig}
525
+ */
526
+ function read(jsonPath, {base, specifier}) {
527
+ const existing = cache.get(jsonPath);
528
+
529
+ if (existing) {
530
+ return existing
531
+ }
532
+
533
+ /** @type {string | undefined} */
534
+ let string;
535
+
536
+ try {
537
+ string = fs.readFileSync(path.toNamespacedPath(jsonPath), 'utf8');
538
+ } catch (error) {
539
+ const exception = /** @type {ErrnoException} */ (error);
540
+
541
+ if (exception.code !== 'ENOENT') {
542
+ throw exception
543
+ }
544
+ }
545
+
546
+ /** @type {PackageConfig} */
547
+ const result = {
548
+ exists: false,
549
+ pjsonPath: jsonPath,
550
+ main: undefined,
551
+ name: undefined,
552
+ type: 'none', // Ignore unknown types for forwards compatibility
553
+ exports: undefined,
554
+ imports: undefined
555
+ };
556
+
557
+ if (string !== undefined) {
558
+ /** @type {Record<string, unknown>} */
559
+ let parsed;
560
+
561
+ try {
562
+ parsed = JSON.parse(string);
563
+ } catch (error_) {
564
+ const cause = /** @type {ErrnoException} */ (error_);
565
+ const error = new ERR_INVALID_PACKAGE_CONFIG$1(
566
+ jsonPath,
567
+ (base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier),
568
+ cause.message
569
+ );
570
+ error.cause = cause;
571
+ throw error
572
+ }
573
+
574
+ result.exists = true;
575
+
576
+ if (
577
+ hasOwnProperty$1.call(parsed, 'name') &&
578
+ typeof parsed.name === 'string'
579
+ ) {
580
+ result.name = parsed.name;
581
+ }
582
+
583
+ if (
584
+ hasOwnProperty$1.call(parsed, 'main') &&
585
+ typeof parsed.main === 'string'
586
+ ) {
587
+ result.main = parsed.main;
588
+ }
589
+
590
+ if (hasOwnProperty$1.call(parsed, 'exports')) {
591
+ // @ts-expect-error: assume valid.
592
+ result.exports = parsed.exports;
593
+ }
594
+
595
+ if (hasOwnProperty$1.call(parsed, 'imports')) {
596
+ // @ts-expect-error: assume valid.
597
+ result.imports = parsed.imports;
598
+ }
599
+
600
+ // Ignore unknown types for forwards compatibility
601
+ if (
602
+ hasOwnProperty$1.call(parsed, 'type') &&
603
+ (parsed.type === 'commonjs' || parsed.type === 'module')
604
+ ) {
605
+ result.type = parsed.type;
606
+ }
607
+ }
608
+
609
+ cache.set(jsonPath, result);
610
+
611
+ return result
612
+ }
613
+
614
+ /**
615
+ * @param {URL | string} resolved
616
+ * @returns {PackageConfig}
617
+ */
618
+ function getPackageScopeConfig(resolved) {
619
+ // Note: in Node, this is now a native module.
620
+ let packageJSONUrl = new URL('package.json', resolved);
621
+
622
+ while (true) {
623
+ const packageJSONPath = packageJSONUrl.pathname;
624
+ if (packageJSONPath.endsWith('node_modules/package.json')) {
625
+ break
626
+ }
627
+
628
+ const packageConfig = read(fileURLToPath(packageJSONUrl), {
629
+ specifier: resolved
630
+ });
631
+
632
+ if (packageConfig.exists) {
633
+ return packageConfig
634
+ }
635
+
636
+ const lastPackageJSONUrl = packageJSONUrl;
637
+ packageJSONUrl = new URL('../package.json', packageJSONUrl);
638
+
639
+ // Terminates at root where ../package.json equals ../../package.json
640
+ // (can't just check "/package.json" for Windows support).
641
+ if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
642
+ break
643
+ }
644
+ }
645
+
646
+ const packageJSONPath = fileURLToPath(packageJSONUrl);
647
+ // ^^ Note: in Node, this is now a native module.
648
+
649
+ return {
650
+ pjsonPath: packageJSONPath,
651
+ exists: false,
652
+ type: 'none'
653
+ }
654
+ }
655
+
656
+ /**
657
+ * Returns the package type for a given URL.
658
+ * @param {URL} url - The URL to get the package type for.
659
+ * @returns {PackageType}
660
+ */
661
+ function getPackageType(url) {
662
+ // To do @anonrig: Write a C++ function that returns only "type".
663
+ return getPackageScopeConfig(url).type
664
+ }
665
+
666
+ // Manually “tree shaken” from:
667
+ // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/esm/get_format.js>
668
+ // Last checked on: Apr 29, 2024.
669
+
670
+
671
+ const {ERR_UNKNOWN_FILE_EXTENSION} = codes;
672
+
673
+ const hasOwnProperty = {}.hasOwnProperty;
674
+
675
+ /** @type {Record<string, string>} */
676
+ const extensionFormatMap = {
677
+ // @ts-expect-error: hush.
678
+ __proto__: null,
679
+ '.cjs': 'commonjs',
680
+ '.js': 'module',
681
+ '.json': 'json',
682
+ '.mjs': 'module'
683
+ };
684
+
685
+ /**
686
+ * @param {string | null} mime
687
+ * @returns {string | null}
688
+ */
689
+ function mimeToFormat(mime) {
690
+ if (
691
+ mime &&
692
+ /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)
693
+ )
694
+ return 'module'
695
+ if (mime === 'application/json') return 'json'
696
+ return null
697
+ }
698
+
699
+ /**
700
+ * @callback ProtocolHandler
701
+ * @param {URL} parsed
702
+ * @param {{parentURL: string, source?: Buffer}} context
703
+ * @param {boolean} ignoreErrors
704
+ * @returns {string | null | void}
705
+ */
706
+
707
+ /**
708
+ * @type {Record<string, ProtocolHandler>}
709
+ */
710
+ const protocolHandlers = {
711
+ // @ts-expect-error: hush.
712
+ __proto__: null,
713
+ 'data:': getDataProtocolModuleFormat,
714
+ 'file:': getFileProtocolModuleFormat,
715
+ 'http:': getHttpProtocolModuleFormat,
716
+ 'https:': getHttpProtocolModuleFormat,
717
+ 'node:'() {
718
+ return 'builtin'
719
+ }
720
+ };
721
+
722
+ /**
723
+ * @param {URL} parsed
724
+ */
725
+ function getDataProtocolModuleFormat(parsed) {
726
+ const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
727
+ parsed.pathname
728
+ ) || [null, null, null];
729
+ return mimeToFormat(mime)
730
+ }
731
+
732
+ /**
733
+ * Returns the file extension from a URL.
734
+ *
735
+ * Should give similar result to
736
+ * `require('node:path').extname(require('node:url').fileURLToPath(url))`
737
+ * when used with a `file:` URL.
738
+ *
739
+ * @param {URL} url
740
+ * @returns {string}
741
+ */
742
+ function extname(url) {
743
+ const pathname = url.pathname;
744
+ let index = pathname.length;
745
+
746
+ while (index--) {
747
+ const code = pathname.codePointAt(index);
748
+
749
+ if (code === 47 /* `/` */) {
750
+ return ''
751
+ }
752
+
753
+ if (code === 46 /* `.` */) {
754
+ return pathname.codePointAt(index - 1) === 47 /* `/` */
755
+ ? ''
756
+ : pathname.slice(index)
757
+ }
758
+ }
759
+
760
+ return ''
761
+ }
762
+
763
+ /**
764
+ * @type {ProtocolHandler}
765
+ */
766
+ function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
767
+ const value = extname(url);
768
+
769
+ if (value === '.js') {
770
+ const packageType = getPackageType(url);
771
+
772
+ if (packageType !== 'none') {
773
+ return packageType
774
+ }
775
+
776
+ return 'commonjs'
777
+ }
778
+
779
+ if (value === '') {
780
+ const packageType = getPackageType(url);
781
+
782
+ // Legacy behavior
783
+ if (packageType === 'none' || packageType === 'commonjs') {
784
+ return 'commonjs'
785
+ }
786
+
787
+ // Note: we don’t implement WASM, so we don’t need
788
+ // `getFormatOfExtensionlessFile` from `formats`.
789
+ return 'module'
790
+ }
791
+
792
+ const format = extensionFormatMap[value];
793
+ if (format) return format
794
+
795
+ // Explicit undefined return indicates load hook should rerun format check
796
+ if (ignoreErrors) {
797
+ return undefined
798
+ }
799
+
800
+ const filepath = fileURLToPath(url);
801
+ throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath)
802
+ }
803
+
804
+ function getHttpProtocolModuleFormat() {
805
+ // To do: HTTPS imports.
806
+ }
807
+
808
+ /**
809
+ * @param {URL} url
810
+ * @param {{parentURL: string}} context
811
+ * @returns {string | null}
812
+ */
813
+ function defaultGetFormatWithoutErrors(url, context) {
814
+ const protocol = url.protocol;
815
+
816
+ if (!hasOwnProperty.call(protocolHandlers, protocol)) {
817
+ return null
818
+ }
819
+
820
+ return protocolHandlers[protocol](url, context, true) || null
821
+ }
822
+
823
+ // Manually “tree shaken” from:
824
+ // <https://github.com/nodejs/node/blob/81a9a97/lib/internal/modules/esm/utils.js>
825
+ // Last checked on: Apr 29, 2024.
826
+
827
+
828
+ const {ERR_INVALID_ARG_VALUE} = codes;
829
+
830
+ // In Node itself these values are populated from CLI arguments, before any
831
+ // user code runs.
832
+ // Here we just define the defaults.
833
+ const DEFAULT_CONDITIONS = Object.freeze(['node', 'import']);
834
+ const DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS);
835
+
836
+ /**
837
+ * Returns the default conditions for ES module loading.
838
+ */
839
+ function getDefaultConditions() {
840
+ return DEFAULT_CONDITIONS
841
+ }
842
+
843
+ /**
844
+ * Returns the default conditions for ES module loading, as a Set.
845
+ */
846
+ function getDefaultConditionsSet() {
847
+ return DEFAULT_CONDITIONS_SET
848
+ }
849
+
850
+ /**
851
+ * @param {Array<string>} [conditions]
852
+ * @returns {Set<string>}
853
+ */
854
+ function getConditionsSet(conditions) {
855
+ if (conditions !== undefined && conditions !== getDefaultConditions()) {
856
+ if (!Array.isArray(conditions)) {
857
+ throw new ERR_INVALID_ARG_VALUE(
858
+ 'conditions',
859
+ conditions,
860
+ 'expected an array'
861
+ )
862
+ }
863
+
864
+ return new Set(conditions)
865
+ }
866
+
867
+ return getDefaultConditionsSet()
868
+ }
869
+
870
+ // Manually “tree shaken” from:
871
+ // <https://github.com/nodejs/node/blob/81a9a97/lib/internal/modules/esm/resolve.js>
872
+ // Last checked on: Apr 29, 2024.
873
+
874
+
875
+ const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
876
+
877
+ const {
878
+ ERR_NETWORK_IMPORT_DISALLOWED,
879
+ ERR_INVALID_MODULE_SPECIFIER,
880
+ ERR_INVALID_PACKAGE_CONFIG,
881
+ ERR_INVALID_PACKAGE_TARGET,
882
+ ERR_MODULE_NOT_FOUND,
883
+ ERR_PACKAGE_IMPORT_NOT_DEFINED,
884
+ ERR_PACKAGE_PATH_NOT_EXPORTED,
885
+ ERR_UNSUPPORTED_DIR_IMPORT,
886
+ ERR_UNSUPPORTED_RESOLVE_REQUEST
887
+ } = codes;
888
+
889
+ const own = {}.hasOwnProperty;
890
+
891
+ const invalidSegmentRegEx =
892
+ /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
893
+ const deprecatedInvalidSegmentRegEx =
894
+ /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
895
+ const invalidPackageNameRegEx = /^\.|%|\\/;
896
+ const patternRegEx = /\*/g;
897
+ const encodedSeparatorRegEx = /%2f|%5c/i;
898
+ /** @type {Set<string>} */
899
+ const emittedPackageWarnings = new Set();
900
+
901
+ const doubleSlashRegEx = /[/\\]{2}/;
902
+
903
+ /**
904
+ *
905
+ * @param {string} target
906
+ * @param {string} request
907
+ * @param {string} match
908
+ * @param {URL} packageJsonUrl
909
+ * @param {boolean} internal
910
+ * @param {URL} base
911
+ * @param {boolean} isTarget
912
+ */
913
+ function emitInvalidSegmentDeprecation(
914
+ target,
915
+ request,
916
+ match,
917
+ packageJsonUrl,
918
+ internal,
919
+ base,
920
+ isTarget
921
+ ) {
922
+ // @ts-expect-error: apparently it does exist, TS.
923
+ if (process.noDeprecation) {
924
+ return
925
+ }
926
+
927
+ const pjsonPath = fileURLToPath(packageJsonUrl);
928
+ const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
929
+ process.emitWarning(
930
+ `Use of deprecated ${
931
+ double ? 'double slash' : 'leading or trailing slash matching'
932
+ } resolving "${target}" for module ` +
933
+ `request "${request}" ${
934
+ request === match ? '' : `matched to "${match}" `
935
+ }in the "${
936
+ internal ? 'imports' : 'exports'
937
+ }" field module resolution of the package at ${pjsonPath}${
938
+ base ? ` imported from ${fileURLToPath(base)}` : ''
939
+ }.`,
940
+ 'DeprecationWarning',
941
+ 'DEP0166'
942
+ );
943
+ }
944
+
945
+ /**
946
+ * @param {URL} url
947
+ * @param {URL} packageJsonUrl
948
+ * @param {URL} base
949
+ * @param {string} [main]
950
+ * @returns {void}
951
+ */
952
+ function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
953
+ // @ts-expect-error: apparently it does exist, TS.
954
+ if (process.noDeprecation) {
955
+ return
956
+ }
957
+
958
+ const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href});
959
+ if (format !== 'module') return
960
+ const urlPath = fileURLToPath(url.href);
961
+ const packagePath = fileURLToPath(new URL('.', packageJsonUrl));
962
+ const basePath = fileURLToPath(base);
963
+ if (!main) {
964
+ process.emitWarning(
965
+ `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
966
+ packagePath.length
967
+ )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`,
968
+ 'DeprecationWarning',
969
+ 'DEP0151'
970
+ );
971
+ } else if (path.resolve(packagePath, main) !== urlPath) {
972
+ process.emitWarning(
973
+ `Package ${packagePath} has a "main" field set to "${main}", ` +
974
+ `excluding the full filename and extension to the resolved file at "${urlPath.slice(
975
+ packagePath.length
976
+ )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is ` +
977
+ 'deprecated for ES modules.',
978
+ 'DeprecationWarning',
979
+ 'DEP0151'
980
+ );
981
+ }
982
+ }
983
+
984
+ /**
985
+ * @param {string} path
986
+ * @returns {Stats | undefined}
987
+ */
988
+ function tryStatSync(path) {
989
+ // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
990
+ try {
991
+ return statSync(path)
992
+ } catch {
993
+ // Note: in Node code this returns `new Stats`,
994
+ // but in Node 22 that’s marked as a deprecated internal API.
995
+ // Which, well, we kinda are, but still to prevent that warning,
996
+ // just yield `undefined`.
997
+ }
998
+ }
999
+
1000
+ /**
1001
+ * Legacy CommonJS main resolution:
1002
+ * 1. let M = pkg_url + (json main field)
1003
+ * 2. TRY(M, M.js, M.json, M.node)
1004
+ * 3. TRY(M/index.js, M/index.json, M/index.node)
1005
+ * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
1006
+ * 5. NOT_FOUND
1007
+ *
1008
+ * @param {URL} url
1009
+ * @returns {boolean}
1010
+ */
1011
+ function fileExists(url) {
1012
+ const stats = statSync(url, {throwIfNoEntry: false});
1013
+ const isFile = stats ? stats.isFile() : undefined;
1014
+ return isFile === null || isFile === undefined ? false : isFile
1015
+ }
1016
+
1017
+ /**
1018
+ * @param {URL} packageJsonUrl
1019
+ * @param {PackageConfig} packageConfig
1020
+ * @param {URL} base
1021
+ * @returns {URL}
1022
+ */
1023
+ function legacyMainResolve(packageJsonUrl, packageConfig, base) {
1024
+ /** @type {URL | undefined} */
1025
+ let guess;
1026
+ if (packageConfig.main !== undefined) {
1027
+ guess = new URL(packageConfig.main, packageJsonUrl);
1028
+ // Note: fs check redundances will be handled by Descriptor cache here.
1029
+ if (fileExists(guess)) return guess
1030
+
1031
+ const tries = [
1032
+ `./${packageConfig.main}.js`,
1033
+ `./${packageConfig.main}.json`,
1034
+ `./${packageConfig.main}.node`,
1035
+ `./${packageConfig.main}/index.js`,
1036
+ `./${packageConfig.main}/index.json`,
1037
+ `./${packageConfig.main}/index.node`
1038
+ ];
1039
+ let i = -1;
1040
+
1041
+ while (++i < tries.length) {
1042
+ guess = new URL(tries[i], packageJsonUrl);
1043
+ if (fileExists(guess)) break
1044
+ guess = undefined;
1045
+ }
1046
+
1047
+ if (guess) {
1048
+ emitLegacyIndexDeprecation(
1049
+ guess,
1050
+ packageJsonUrl,
1051
+ base,
1052
+ packageConfig.main
1053
+ );
1054
+ return guess
1055
+ }
1056
+ // Fallthrough.
1057
+ }
1058
+
1059
+ const tries = ['./index.js', './index.json', './index.node'];
1060
+ let i = -1;
1061
+
1062
+ while (++i < tries.length) {
1063
+ guess = new URL(tries[i], packageJsonUrl);
1064
+ if (fileExists(guess)) break
1065
+ guess = undefined;
1066
+ }
1067
+
1068
+ if (guess) {
1069
+ emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
1070
+ return guess
1071
+ }
1072
+
1073
+ // Not found.
1074
+ throw new ERR_MODULE_NOT_FOUND(
1075
+ fileURLToPath(new URL('.', packageJsonUrl)),
1076
+ fileURLToPath(base)
1077
+ )
1078
+ }
1079
+
1080
+ /**
1081
+ * @param {URL} resolved
1082
+ * @param {URL} base
1083
+ * @param {boolean} [preserveSymlinks]
1084
+ * @returns {URL}
1085
+ */
1086
+ function finalizeResolution(resolved, base, preserveSymlinks) {
1087
+ if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
1088
+ throw new ERR_INVALID_MODULE_SPECIFIER(
1089
+ resolved.pathname,
1090
+ 'must not include encoded "/" or "\\" characters',
1091
+ fileURLToPath(base)
1092
+ )
1093
+ }
1094
+
1095
+ /** @type {string} */
1096
+ let filePath;
1097
+
1098
+ try {
1099
+ filePath = fileURLToPath(resolved);
1100
+ } catch (error) {
1101
+ const cause = /** @type {ErrnoException} */ (error);
1102
+ Object.defineProperty(cause, 'input', {value: String(resolved)});
1103
+ Object.defineProperty(cause, 'module', {value: String(base)});
1104
+ throw cause
1105
+ }
1106
+
1107
+ const stats = tryStatSync(
1108
+ filePath.endsWith('/') ? filePath.slice(-1) : filePath
1109
+ );
1110
+
1111
+ if (stats && stats.isDirectory()) {
1112
+ const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath(base));
1113
+ // @ts-expect-error Add this for `import.meta.resolve`.
1114
+ error.url = String(resolved);
1115
+ throw error
1116
+ }
1117
+
1118
+ if (!stats || !stats.isFile()) {
1119
+ const error = new ERR_MODULE_NOT_FOUND(
1120
+ filePath || resolved.pathname,
1121
+ base && fileURLToPath(base),
1122
+ true
1123
+ );
1124
+ // @ts-expect-error Add this for `import.meta.resolve`.
1125
+ error.url = String(resolved);
1126
+ throw error
1127
+ }
1128
+
1129
+ if (!preserveSymlinks) {
1130
+ const real = realpathSync(filePath);
1131
+ const {search, hash} = resolved;
1132
+ resolved = pathToFileURL(real + (filePath.endsWith(path.sep) ? '/' : ''));
1133
+ resolved.search = search;
1134
+ resolved.hash = hash;
1135
+ }
1136
+
1137
+ return resolved
1138
+ }
1139
+
1140
+ /**
1141
+ * @param {string} specifier
1142
+ * @param {URL | undefined} packageJsonUrl
1143
+ * @param {URL} base
1144
+ * @returns {Error}
1145
+ */
1146
+ function importNotDefined(specifier, packageJsonUrl, base) {
1147
+ return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
1148
+ specifier,
1149
+ packageJsonUrl && fileURLToPath(new URL('.', packageJsonUrl)),
1150
+ fileURLToPath(base)
1151
+ )
1152
+ }
1153
+
1154
+ /**
1155
+ * @param {string} subpath
1156
+ * @param {URL} packageJsonUrl
1157
+ * @param {URL} base
1158
+ * @returns {Error}
1159
+ */
1160
+ function exportsNotFound(subpath, packageJsonUrl, base) {
1161
+ return new ERR_PACKAGE_PATH_NOT_EXPORTED(
1162
+ fileURLToPath(new URL('.', packageJsonUrl)),
1163
+ subpath,
1164
+ base && fileURLToPath(base)
1165
+ )
1166
+ }
1167
+
1168
+ /**
1169
+ * @param {string} request
1170
+ * @param {string} match
1171
+ * @param {URL} packageJsonUrl
1172
+ * @param {boolean} internal
1173
+ * @param {URL} [base]
1174
+ * @returns {never}
1175
+ */
1176
+ function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
1177
+ const reason = `request is not a valid match in pattern "${match}" for the "${
1178
+ internal ? 'imports' : 'exports'
1179
+ }" resolution of ${fileURLToPath(packageJsonUrl)}`;
1180
+ throw new ERR_INVALID_MODULE_SPECIFIER(
1181
+ request,
1182
+ reason,
1183
+ base && fileURLToPath(base)
1184
+ )
1185
+ }
1186
+
1187
+ /**
1188
+ * @param {string} subpath
1189
+ * @param {unknown} target
1190
+ * @param {URL} packageJsonUrl
1191
+ * @param {boolean} internal
1192
+ * @param {URL} [base]
1193
+ * @returns {Error}
1194
+ */
1195
+ function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
1196
+ target =
1197
+ typeof target === 'object' && target !== null
1198
+ ? JSON.stringify(target, null, '')
1199
+ : `${target}`;
1200
+
1201
+ return new ERR_INVALID_PACKAGE_TARGET(
1202
+ fileURLToPath(new URL('.', packageJsonUrl)),
1203
+ subpath,
1204
+ target,
1205
+ internal,
1206
+ base && fileURLToPath(base)
1207
+ )
1208
+ }
1209
+
1210
+ /**
1211
+ * @param {string} target
1212
+ * @param {string} subpath
1213
+ * @param {string} match
1214
+ * @param {URL} packageJsonUrl
1215
+ * @param {URL} base
1216
+ * @param {boolean} pattern
1217
+ * @param {boolean} internal
1218
+ * @param {boolean} isPathMap
1219
+ * @param {Set<string> | undefined} conditions
1220
+ * @returns {URL}
1221
+ */
1222
+ function resolvePackageTargetString(
1223
+ target,
1224
+ subpath,
1225
+ match,
1226
+ packageJsonUrl,
1227
+ base,
1228
+ pattern,
1229
+ internal,
1230
+ isPathMap,
1231
+ conditions
1232
+ ) {
1233
+ if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
1234
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1235
+
1236
+ if (!target.startsWith('./')) {
1237
+ if (internal && !target.startsWith('../') && !target.startsWith('/')) {
1238
+ let isURL = false;
1239
+
1240
+ try {
1241
+ new URL(target);
1242
+ isURL = true;
1243
+ } catch {
1244
+ // Continue regardless of error.
1245
+ }
1246
+
1247
+ if (!isURL) {
1248
+ const exportTarget = pattern
1249
+ ? RegExpPrototypeSymbolReplace.call(
1250
+ patternRegEx,
1251
+ target,
1252
+ () => subpath
1253
+ )
1254
+ : target + subpath;
1255
+
1256
+ return packageResolve(exportTarget, packageJsonUrl, conditions)
1257
+ }
1258
+ }
1259
+
1260
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1261
+ }
1262
+
1263
+ if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
1264
+ if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
1265
+ if (!isPathMap) {
1266
+ const request = pattern
1267
+ ? match.replace('*', () => subpath)
1268
+ : match + subpath;
1269
+ const resolvedTarget = pattern
1270
+ ? RegExpPrototypeSymbolReplace.call(
1271
+ patternRegEx,
1272
+ target,
1273
+ () => subpath
1274
+ )
1275
+ : target;
1276
+ emitInvalidSegmentDeprecation(
1277
+ resolvedTarget,
1278
+ request,
1279
+ match,
1280
+ packageJsonUrl,
1281
+ internal,
1282
+ base,
1283
+ true
1284
+ );
1285
+ }
1286
+ } else {
1287
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1288
+ }
1289
+ }
1290
+
1291
+ const resolved = new URL(target, packageJsonUrl);
1292
+ const resolvedPath = resolved.pathname;
1293
+ const packagePath = new URL('.', packageJsonUrl).pathname;
1294
+
1295
+ if (!resolvedPath.startsWith(packagePath))
1296
+ throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
1297
+
1298
+ if (subpath === '') return resolved
1299
+
1300
+ if (invalidSegmentRegEx.exec(subpath) !== null) {
1301
+ const request = pattern
1302
+ ? match.replace('*', () => subpath)
1303
+ : match + subpath;
1304
+ if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
1305
+ if (!isPathMap) {
1306
+ const resolvedTarget = pattern
1307
+ ? RegExpPrototypeSymbolReplace.call(
1308
+ patternRegEx,
1309
+ target,
1310
+ () => subpath
1311
+ )
1312
+ : target;
1313
+ emitInvalidSegmentDeprecation(
1314
+ resolvedTarget,
1315
+ request,
1316
+ match,
1317
+ packageJsonUrl,
1318
+ internal,
1319
+ base,
1320
+ false
1321
+ );
1322
+ }
1323
+ } else {
1324
+ throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
1325
+ }
1326
+ }
1327
+
1328
+ if (pattern) {
1329
+ return new URL(
1330
+ RegExpPrototypeSymbolReplace.call(
1331
+ patternRegEx,
1332
+ resolved.href,
1333
+ () => subpath
1334
+ )
1335
+ )
1336
+ }
1337
+
1338
+ return new URL(subpath, resolved)
1339
+ }
1340
+
1341
+ /**
1342
+ * @param {string} key
1343
+ * @returns {boolean}
1344
+ */
1345
+ function isArrayIndex(key) {
1346
+ const keyNumber = Number(key);
1347
+ if (`${keyNumber}` !== key) return false
1348
+ return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff
1349
+ }
1350
+
1351
+ /**
1352
+ * @param {URL} packageJsonUrl
1353
+ * @param {unknown} target
1354
+ * @param {string} subpath
1355
+ * @param {string} packageSubpath
1356
+ * @param {URL} base
1357
+ * @param {boolean} pattern
1358
+ * @param {boolean} internal
1359
+ * @param {boolean} isPathMap
1360
+ * @param {Set<string> | undefined} conditions
1361
+ * @returns {URL | null}
1362
+ */
1363
+ function resolvePackageTarget(
1364
+ packageJsonUrl,
1365
+ target,
1366
+ subpath,
1367
+ packageSubpath,
1368
+ base,
1369
+ pattern,
1370
+ internal,
1371
+ isPathMap,
1372
+ conditions
1373
+ ) {
1374
+ if (typeof target === 'string') {
1375
+ return resolvePackageTargetString(
1376
+ target,
1377
+ subpath,
1378
+ packageSubpath,
1379
+ packageJsonUrl,
1380
+ base,
1381
+ pattern,
1382
+ internal,
1383
+ isPathMap,
1384
+ conditions
1385
+ )
1386
+ }
1387
+
1388
+ if (Array.isArray(target)) {
1389
+ /** @type {Array<unknown>} */
1390
+ const targetList = target;
1391
+ if (targetList.length === 0) return null
1392
+
1393
+ /** @type {ErrnoException | null | undefined} */
1394
+ let lastException;
1395
+ let i = -1;
1396
+
1397
+ while (++i < targetList.length) {
1398
+ const targetItem = targetList[i];
1399
+ /** @type {URL | null} */
1400
+ let resolveResult;
1401
+ try {
1402
+ resolveResult = resolvePackageTarget(
1403
+ packageJsonUrl,
1404
+ targetItem,
1405
+ subpath,
1406
+ packageSubpath,
1407
+ base,
1408
+ pattern,
1409
+ internal,
1410
+ isPathMap,
1411
+ conditions
1412
+ );
1413
+ } catch (error) {
1414
+ const exception = /** @type {ErrnoException} */ (error);
1415
+ lastException = exception;
1416
+ if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue
1417
+ throw error
1418
+ }
1419
+
1420
+ if (resolveResult === undefined) continue
1421
+
1422
+ if (resolveResult === null) {
1423
+ lastException = null;
1424
+ continue
1425
+ }
1426
+
1427
+ return resolveResult
1428
+ }
1429
+
1430
+ if (lastException === undefined || lastException === null) {
1431
+ return null
1432
+ }
1433
+
1434
+ throw lastException
1435
+ }
1436
+
1437
+ if (typeof target === 'object' && target !== null) {
1438
+ const keys = Object.getOwnPropertyNames(target);
1439
+ let i = -1;
1440
+
1441
+ while (++i < keys.length) {
1442
+ const key = keys[i];
1443
+ if (isArrayIndex(key)) {
1444
+ throw new ERR_INVALID_PACKAGE_CONFIG(
1445
+ fileURLToPath(packageJsonUrl),
1446
+ base,
1447
+ '"exports" cannot contain numeric property keys.'
1448
+ )
1449
+ }
1450
+ }
1451
+
1452
+ i = -1;
1453
+
1454
+ while (++i < keys.length) {
1455
+ const key = keys[i];
1456
+ if (key === 'default' || (conditions && conditions.has(key))) {
1457
+ // @ts-expect-error: indexable.
1458
+ const conditionalTarget = /** @type {unknown} */ (target[key]);
1459
+ const resolveResult = resolvePackageTarget(
1460
+ packageJsonUrl,
1461
+ conditionalTarget,
1462
+ subpath,
1463
+ packageSubpath,
1464
+ base,
1465
+ pattern,
1466
+ internal,
1467
+ isPathMap,
1468
+ conditions
1469
+ );
1470
+ if (resolveResult === undefined) continue
1471
+ return resolveResult
1472
+ }
1473
+ }
1474
+
1475
+ return null
1476
+ }
1477
+
1478
+ if (target === null) {
1479
+ return null
1480
+ }
1481
+
1482
+ throw invalidPackageTarget(
1483
+ packageSubpath,
1484
+ target,
1485
+ packageJsonUrl,
1486
+ internal,
1487
+ base
1488
+ )
1489
+ }
1490
+
1491
+ /**
1492
+ * @param {unknown} exports
1493
+ * @param {URL} packageJsonUrl
1494
+ * @param {URL} base
1495
+ * @returns {boolean}
1496
+ */
1497
+ function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
1498
+ if (typeof exports === 'string' || Array.isArray(exports)) return true
1499
+ if (typeof exports !== 'object' || exports === null) return false
1500
+
1501
+ const keys = Object.getOwnPropertyNames(exports);
1502
+ let isConditionalSugar = false;
1503
+ let i = 0;
1504
+ let keyIndex = -1;
1505
+ while (++keyIndex < keys.length) {
1506
+ const key = keys[keyIndex];
1507
+ const currentIsConditionalSugar = key === '' || key[0] !== '.';
1508
+ if (i++ === 0) {
1509
+ isConditionalSugar = currentIsConditionalSugar;
1510
+ } else if (isConditionalSugar !== currentIsConditionalSugar) {
1511
+ throw new ERR_INVALID_PACKAGE_CONFIG(
1512
+ fileURLToPath(packageJsonUrl),
1513
+ base,
1514
+ '"exports" cannot contain some keys starting with \'.\' and some not.' +
1515
+ ' The exports object must either be an object of package subpath keys' +
1516
+ ' or an object of main entry condition name keys only.'
1517
+ )
1518
+ }
1519
+ }
1520
+
1521
+ return isConditionalSugar
1522
+ }
1523
+
1524
+ /**
1525
+ * @param {string} match
1526
+ * @param {URL} pjsonUrl
1527
+ * @param {URL} base
1528
+ */
1529
+ function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
1530
+ // @ts-expect-error: apparently it does exist, TS.
1531
+ if (process.noDeprecation) {
1532
+ return
1533
+ }
1534
+
1535
+ const pjsonPath = fileURLToPath(pjsonUrl);
1536
+ if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return
1537
+ emittedPackageWarnings.add(pjsonPath + '|' + match);
1538
+ process.emitWarning(
1539
+ `Use of deprecated trailing slash pattern mapping "${match}" in the ` +
1540
+ `"exports" field module resolution of the package at ${pjsonPath}${
1541
+ base ? ` imported from ${fileURLToPath(base)}` : ''
1542
+ }. Mapping specifiers ending in "/" is no longer supported.`,
1543
+ 'DeprecationWarning',
1544
+ 'DEP0155'
1545
+ );
1546
+ }
1547
+
1548
+ /**
1549
+ * @param {URL} packageJsonUrl
1550
+ * @param {string} packageSubpath
1551
+ * @param {Record<string, unknown>} packageConfig
1552
+ * @param {URL} base
1553
+ * @param {Set<string> | undefined} conditions
1554
+ * @returns {URL}
1555
+ */
1556
+ function packageExportsResolve(
1557
+ packageJsonUrl,
1558
+ packageSubpath,
1559
+ packageConfig,
1560
+ base,
1561
+ conditions
1562
+ ) {
1563
+ let exports = packageConfig.exports;
1564
+
1565
+ if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
1566
+ exports = {'.': exports};
1567
+ }
1568
+
1569
+ if (
1570
+ own.call(exports, packageSubpath) &&
1571
+ !packageSubpath.includes('*') &&
1572
+ !packageSubpath.endsWith('/')
1573
+ ) {
1574
+ // @ts-expect-error: indexable.
1575
+ const target = exports[packageSubpath];
1576
+ const resolveResult = resolvePackageTarget(
1577
+ packageJsonUrl,
1578
+ target,
1579
+ '',
1580
+ packageSubpath,
1581
+ base,
1582
+ false,
1583
+ false,
1584
+ false,
1585
+ conditions
1586
+ );
1587
+ if (resolveResult === null || resolveResult === undefined) {
1588
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base)
1589
+ }
1590
+
1591
+ return resolveResult
1592
+ }
1593
+
1594
+ let bestMatch = '';
1595
+ let bestMatchSubpath = '';
1596
+ const keys = Object.getOwnPropertyNames(exports);
1597
+ let i = -1;
1598
+
1599
+ while (++i < keys.length) {
1600
+ const key = keys[i];
1601
+ const patternIndex = key.indexOf('*');
1602
+
1603
+ if (
1604
+ patternIndex !== -1 &&
1605
+ packageSubpath.startsWith(key.slice(0, patternIndex))
1606
+ ) {
1607
+ // When this reaches EOL, this can throw at the top of the whole function:
1608
+ //
1609
+ // if (StringPrototypeEndsWith(packageSubpath, '/'))
1610
+ // throwInvalidSubpath(packageSubpath)
1611
+ //
1612
+ // To match "imports" and the spec.
1613
+ if (packageSubpath.endsWith('/')) {
1614
+ emitTrailingSlashPatternDeprecation(
1615
+ packageSubpath,
1616
+ packageJsonUrl,
1617
+ base
1618
+ );
1619
+ }
1620
+
1621
+ const patternTrailer = key.slice(patternIndex + 1);
1622
+
1623
+ if (
1624
+ packageSubpath.length >= key.length &&
1625
+ packageSubpath.endsWith(patternTrailer) &&
1626
+ patternKeyCompare(bestMatch, key) === 1 &&
1627
+ key.lastIndexOf('*') === patternIndex
1628
+ ) {
1629
+ bestMatch = key;
1630
+ bestMatchSubpath = packageSubpath.slice(
1631
+ patternIndex,
1632
+ packageSubpath.length - patternTrailer.length
1633
+ );
1634
+ }
1635
+ }
1636
+ }
1637
+
1638
+ if (bestMatch) {
1639
+ // @ts-expect-error: indexable.
1640
+ const target = /** @type {unknown} */ (exports[bestMatch]);
1641
+ const resolveResult = resolvePackageTarget(
1642
+ packageJsonUrl,
1643
+ target,
1644
+ bestMatchSubpath,
1645
+ bestMatch,
1646
+ base,
1647
+ true,
1648
+ false,
1649
+ packageSubpath.endsWith('/'),
1650
+ conditions
1651
+ );
1652
+
1653
+ if (resolveResult === null || resolveResult === undefined) {
1654
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base)
1655
+ }
1656
+
1657
+ return resolveResult
1658
+ }
1659
+
1660
+ throw exportsNotFound(packageSubpath, packageJsonUrl, base)
1661
+ }
1662
+
1663
+ /**
1664
+ * @param {string} a
1665
+ * @param {string} b
1666
+ */
1667
+ function patternKeyCompare(a, b) {
1668
+ const aPatternIndex = a.indexOf('*');
1669
+ const bPatternIndex = b.indexOf('*');
1670
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
1671
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
1672
+ if (baseLengthA > baseLengthB) return -1
1673
+ if (baseLengthB > baseLengthA) return 1
1674
+ if (aPatternIndex === -1) return 1
1675
+ if (bPatternIndex === -1) return -1
1676
+ if (a.length > b.length) return -1
1677
+ if (b.length > a.length) return 1
1678
+ return 0
1679
+ }
1680
+
1681
+ /**
1682
+ * @param {string} name
1683
+ * @param {URL} base
1684
+ * @param {Set<string>} [conditions]
1685
+ * @returns {URL}
1686
+ */
1687
+ function packageImportsResolve(name, base, conditions) {
1688
+ if (name === '#' || name.startsWith('#/') || name.endsWith('/')) {
1689
+ const reason = 'is not a valid internal imports specifier name';
1690
+ throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath(base))
1691
+ }
1692
+
1693
+ /** @type {URL | undefined} */
1694
+ let packageJsonUrl;
1695
+
1696
+ const packageConfig = getPackageScopeConfig(base);
1697
+
1698
+ if (packageConfig.exists) {
1699
+ packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
1700
+ const imports = packageConfig.imports;
1701
+ if (imports) {
1702
+ if (own.call(imports, name) && !name.includes('*')) {
1703
+ const resolveResult = resolvePackageTarget(
1704
+ packageJsonUrl,
1705
+ imports[name],
1706
+ '',
1707
+ name,
1708
+ base,
1709
+ false,
1710
+ true,
1711
+ false,
1712
+ conditions
1713
+ );
1714
+ if (resolveResult !== null && resolveResult !== undefined) {
1715
+ return resolveResult
1716
+ }
1717
+ } else {
1718
+ let bestMatch = '';
1719
+ let bestMatchSubpath = '';
1720
+ const keys = Object.getOwnPropertyNames(imports);
1721
+ let i = -1;
1722
+
1723
+ while (++i < keys.length) {
1724
+ const key = keys[i];
1725
+ const patternIndex = key.indexOf('*');
1726
+
1727
+ if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
1728
+ const patternTrailer = key.slice(patternIndex + 1);
1729
+ if (
1730
+ name.length >= key.length &&
1731
+ name.endsWith(patternTrailer) &&
1732
+ patternKeyCompare(bestMatch, key) === 1 &&
1733
+ key.lastIndexOf('*') === patternIndex
1734
+ ) {
1735
+ bestMatch = key;
1736
+ bestMatchSubpath = name.slice(
1737
+ patternIndex,
1738
+ name.length - patternTrailer.length
1739
+ );
1740
+ }
1741
+ }
1742
+ }
1743
+
1744
+ if (bestMatch) {
1745
+ const target = imports[bestMatch];
1746
+ const resolveResult = resolvePackageTarget(
1747
+ packageJsonUrl,
1748
+ target,
1749
+ bestMatchSubpath,
1750
+ bestMatch,
1751
+ base,
1752
+ true,
1753
+ true,
1754
+ false,
1755
+ conditions
1756
+ );
1757
+
1758
+ if (resolveResult !== null && resolveResult !== undefined) {
1759
+ return resolveResult
1760
+ }
1761
+ }
1762
+ }
1763
+ }
1764
+ }
1765
+
1766
+ throw importNotDefined(name, packageJsonUrl, base)
1767
+ }
1768
+
1769
+ /**
1770
+ * @param {string} specifier
1771
+ * @param {URL} base
1772
+ */
1773
+ function parsePackageName(specifier, base) {
1774
+ let separatorIndex = specifier.indexOf('/');
1775
+ let validPackageName = true;
1776
+ let isScoped = false;
1777
+ if (specifier[0] === '@') {
1778
+ isScoped = true;
1779
+ if (separatorIndex === -1 || specifier.length === 0) {
1780
+ validPackageName = false;
1781
+ } else {
1782
+ separatorIndex = specifier.indexOf('/', separatorIndex + 1);
1783
+ }
1784
+ }
1785
+
1786
+ const packageName =
1787
+ separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
1788
+
1789
+ // Package name cannot have leading . and cannot have percent-encoding or
1790
+ // \\ separators.
1791
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
1792
+ validPackageName = false;
1793
+ }
1794
+
1795
+ if (!validPackageName) {
1796
+ throw new ERR_INVALID_MODULE_SPECIFIER(
1797
+ specifier,
1798
+ 'is not a valid package name',
1799
+ fileURLToPath(base)
1800
+ )
1801
+ }
1802
+
1803
+ const packageSubpath =
1804
+ '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
1805
+
1806
+ return {packageName, packageSubpath, isScoped}
1807
+ }
1808
+
1809
+ /**
1810
+ * @param {string} specifier
1811
+ * @param {URL} base
1812
+ * @param {Set<string> | undefined} conditions
1813
+ * @returns {URL}
1814
+ */
1815
+ function packageResolve(specifier, base, conditions) {
1816
+ if (builtinModules.includes(specifier)) {
1817
+ return new URL('node:' + specifier)
1818
+ }
1819
+
1820
+ const {packageName, packageSubpath, isScoped} = parsePackageName(
1821
+ specifier,
1822
+ base
1823
+ );
1824
+
1825
+ // ResolveSelf
1826
+ const packageConfig = getPackageScopeConfig(base);
1827
+
1828
+ // Can’t test.
1829
+ /* c8 ignore next 16 */
1830
+ if (packageConfig.exists) {
1831
+ const packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
1832
+ if (
1833
+ packageConfig.name === packageName &&
1834
+ packageConfig.exports !== undefined &&
1835
+ packageConfig.exports !== null
1836
+ ) {
1837
+ return packageExportsResolve(
1838
+ packageJsonUrl,
1839
+ packageSubpath,
1840
+ packageConfig,
1841
+ base,
1842
+ conditions
1843
+ )
1844
+ }
1845
+ }
1846
+
1847
+ let packageJsonUrl = new URL(
1848
+ './node_modules/' + packageName + '/package.json',
1849
+ base
1850
+ );
1851
+ let packageJsonPath = fileURLToPath(packageJsonUrl);
1852
+ /** @type {string} */
1853
+ let lastPath;
1854
+ do {
1855
+ const stat = tryStatSync(packageJsonPath.slice(0, -13));
1856
+ if (!stat || !stat.isDirectory()) {
1857
+ lastPath = packageJsonPath;
1858
+ packageJsonUrl = new URL(
1859
+ (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
1860
+ packageName +
1861
+ '/package.json',
1862
+ packageJsonUrl
1863
+ );
1864
+ packageJsonPath = fileURLToPath(packageJsonUrl);
1865
+ continue
1866
+ }
1867
+
1868
+ // Package match.
1869
+ const packageConfig = read(packageJsonPath, {base, specifier});
1870
+ if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
1871
+ return packageExportsResolve(
1872
+ packageJsonUrl,
1873
+ packageSubpath,
1874
+ packageConfig,
1875
+ base,
1876
+ conditions
1877
+ )
1878
+ }
1879
+
1880
+ if (packageSubpath === '.') {
1881
+ return legacyMainResolve(packageJsonUrl, packageConfig, base)
1882
+ }
1883
+
1884
+ return new URL(packageSubpath, packageJsonUrl)
1885
+ // Cross-platform root check.
1886
+ } while (packageJsonPath.length !== lastPath.length)
1887
+
1888
+ throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), false)
1889
+ }
1890
+
1891
+ /**
1892
+ * @param {string} specifier
1893
+ * @returns {boolean}
1894
+ */
1895
+ function isRelativeSpecifier(specifier) {
1896
+ if (specifier[0] === '.') {
1897
+ if (specifier.length === 1 || specifier[1] === '/') return true
1898
+ if (
1899
+ specifier[1] === '.' &&
1900
+ (specifier.length === 2 || specifier[2] === '/')
1901
+ ) {
1902
+ return true
1903
+ }
1904
+ }
1905
+
1906
+ return false
1907
+ }
1908
+
1909
+ /**
1910
+ * @param {string} specifier
1911
+ * @returns {boolean}
1912
+ */
1913
+ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
1914
+ if (specifier === '') return false
1915
+ if (specifier[0] === '/') return true
1916
+ return isRelativeSpecifier(specifier)
1917
+ }
1918
+
1919
+ /**
1920
+ * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
1921
+ * sync and slightly lower-level than `resolve`).
1922
+ *
1923
+ * @param {string} specifier
1924
+ * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
1925
+ * @param {URL} base
1926
+ * Full URL (to a file) that `specifier` is resolved relative from.
1927
+ * @param {Set<string>} [conditions]
1928
+ * Conditions.
1929
+ * @param {boolean} [preserveSymlinks]
1930
+ * Keep symlinks instead of resolving them.
1931
+ * @returns {URL}
1932
+ * A URL object to the found thing.
1933
+ */
1934
+ function moduleResolve(specifier, base, conditions, preserveSymlinks) {
1935
+ // Note: The Node code supports `base` as a string (in this internal API) too,
1936
+ // we don’t.
1937
+ if (conditions === undefined) {
1938
+ conditions = getConditionsSet();
1939
+ }
1940
+
1941
+ const protocol = base.protocol;
1942
+ const isData = protocol === 'data:';
1943
+ const isRemote = isData || protocol === 'http:' || protocol === 'https:';
1944
+ // Order swapped from spec for minor perf gain.
1945
+ // Ok since relative URLs cannot parse as URLs.
1946
+ /** @type {URL | undefined} */
1947
+ let resolved;
1948
+
1949
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
1950
+ try {
1951
+ resolved = new URL(specifier, base);
1952
+ } catch (error_) {
1953
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
1954
+ error.cause = error_;
1955
+ throw error
1956
+ }
1957
+ } else if (protocol === 'file:' && specifier[0] === '#') {
1958
+ resolved = packageImportsResolve(specifier, base, conditions);
1959
+ } else {
1960
+ try {
1961
+ resolved = new URL(specifier);
1962
+ } catch (error_) {
1963
+ // Note: actual code uses `canBeRequiredWithoutScheme`.
1964
+ if (isRemote && !builtinModules.includes(specifier)) {
1965
+ const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
1966
+ error.cause = error_;
1967
+ throw error
1968
+ }
1969
+
1970
+ resolved = packageResolve(specifier, base, conditions);
1971
+ }
1972
+ }
1973
+
1974
+ assert.ok(resolved !== undefined, 'expected to be defined');
1975
+
1976
+ if (resolved.protocol !== 'file:') {
1977
+ return resolved
1978
+ }
1979
+
1980
+ return finalizeResolution(resolved, base, preserveSymlinks)
1981
+ }
1982
+
1983
+ /**
1984
+ * @param {string} specifier
1985
+ * @param {URL | undefined} parsed
1986
+ * @param {URL | undefined} parsedParentURL
1987
+ */
1988
+ function checkIfDisallowedImport(specifier, parsed, parsedParentURL) {
1989
+ if (parsedParentURL) {
1990
+ // Avoid accessing the `protocol` property due to the lazy getters.
1991
+ const parentProtocol = parsedParentURL.protocol;
1992
+
1993
+ if (parentProtocol === 'http:' || parentProtocol === 'https:') {
1994
+ if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
1995
+ // Avoid accessing the `protocol` property due to the lazy getters.
1996
+ const parsedProtocol = parsed?.protocol;
1997
+
1998
+ // `data:` and `blob:` disallowed due to allowing file: access via
1999
+ // indirection
2000
+ if (
2001
+ parsedProtocol &&
2002
+ parsedProtocol !== 'https:' &&
2003
+ parsedProtocol !== 'http:'
2004
+ ) {
2005
+ throw new ERR_NETWORK_IMPORT_DISALLOWED(
2006
+ specifier,
2007
+ parsedParentURL,
2008
+ 'remote imports cannot import from a local location.'
2009
+ )
2010
+ }
2011
+
2012
+ return {url: parsed?.href || ''}
2013
+ }
2014
+
2015
+ if (builtinModules.includes(specifier)) {
2016
+ throw new ERR_NETWORK_IMPORT_DISALLOWED(
2017
+ specifier,
2018
+ parsedParentURL,
2019
+ 'remote imports cannot import from a local location.'
2020
+ )
2021
+ }
2022
+
2023
+ throw new ERR_NETWORK_IMPORT_DISALLOWED(
2024
+ specifier,
2025
+ parsedParentURL,
2026
+ 'only relative and absolute specifiers are supported.'
2027
+ )
2028
+ }
2029
+ }
2030
+ }
2031
+
2032
+ // Note: this is from:
2033
+ // <https://github.com/nodejs/node/blob/3e74590/lib/internal/url.js#L687>
2034
+ /**
2035
+ * Checks if a value has the shape of a WHATWG URL object.
2036
+ *
2037
+ * Using a symbol or instanceof would not be able to recognize URL objects
2038
+ * coming from other implementations (e.g. in Electron), so instead we are
2039
+ * checking some well known properties for a lack of a better test.
2040
+ *
2041
+ * We use `href` and `protocol` as they are the only properties that are
2042
+ * easy to retrieve and calculate due to the lazy nature of the getters.
2043
+ *
2044
+ * @template {unknown} Value
2045
+ * @param {Value} self
2046
+ * @returns {Value is URL}
2047
+ */
2048
+ function isURL(self) {
2049
+ return Boolean(
2050
+ self &&
2051
+ typeof self === 'object' &&
2052
+ 'href' in self &&
2053
+ typeof self.href === 'string' &&
2054
+ 'protocol' in self &&
2055
+ typeof self.protocol === 'string' &&
2056
+ self.href &&
2057
+ self.protocol
2058
+ )
2059
+ }
2060
+
2061
+ /**
2062
+ * Validate user-input in `context` supplied by a custom loader.
2063
+ *
2064
+ * @param {unknown} parentURL
2065
+ * @returns {asserts parentURL is URL | string | undefined}
2066
+ */
2067
+ function throwIfInvalidParentURL(parentURL) {
2068
+ if (parentURL === undefined) {
2069
+ return // Main entry point, so no parent
2070
+ }
2071
+
2072
+ if (typeof parentURL !== 'string' && !isURL(parentURL)) {
2073
+ throw new codes.ERR_INVALID_ARG_TYPE(
2074
+ 'parentURL',
2075
+ ['string', 'URL'],
2076
+ parentURL
2077
+ )
2078
+ }
2079
+ }
2080
+
2081
+ /**
2082
+ * @param {string} specifier
2083
+ * @param {{parentURL?: string, conditions?: Array<string>}} context
2084
+ * @returns {{url: string, format?: string | null}}
2085
+ */
2086
+ function defaultResolve(specifier, context = {}) {
2087
+ const {parentURL} = context;
2088
+ assert.ok(parentURL !== undefined, 'expected `parentURL` to be defined');
2089
+ throwIfInvalidParentURL(parentURL);
2090
+
2091
+ /** @type {URL | undefined} */
2092
+ let parsedParentURL;
2093
+ if (parentURL) {
2094
+ try {
2095
+ parsedParentURL = new URL(parentURL);
2096
+ } catch {
2097
+ // Ignore exception
2098
+ }
2099
+ }
2100
+
2101
+ /** @type {URL | undefined} */
2102
+ let parsed;
2103
+ /** @type {string | undefined} */
2104
+ let protocol;
2105
+
2106
+ try {
2107
+ parsed = shouldBeTreatedAsRelativeOrAbsolutePath(specifier)
2108
+ ? new URL(specifier, parsedParentURL)
2109
+ : new URL(specifier);
2110
+
2111
+ // Avoid accessing the `protocol` property due to the lazy getters.
2112
+ protocol = parsed.protocol;
2113
+
2114
+ if (protocol === 'data:') {
2115
+ return {url: parsed.href, format: null}
2116
+ }
2117
+ } catch {
2118
+ // Ignore exception
2119
+ }
2120
+
2121
+ // There are multiple deep branches that can either throw or return; instead
2122
+ // of duplicating that deeply nested logic for the possible returns, DRY and
2123
+ // check for a return. This seems the least gnarly.
2124
+ const maybeReturn = checkIfDisallowedImport(
2125
+ specifier,
2126
+ parsed,
2127
+ parsedParentURL
2128
+ );
2129
+
2130
+ if (maybeReturn) return maybeReturn
2131
+
2132
+ // This must come after checkIfDisallowedImport
2133
+ if (protocol === undefined && parsed) {
2134
+ protocol = parsed.protocol;
2135
+ }
2136
+
2137
+ if (protocol === 'node:') {
2138
+ return {url: specifier}
2139
+ }
2140
+
2141
+ // This must come after checkIfDisallowedImport
2142
+ if (parsed && parsed.protocol === 'node:') return {url: specifier}
2143
+
2144
+ const conditions = getConditionsSet(context.conditions);
2145
+
2146
+ const url = moduleResolve(specifier, new URL(parentURL), conditions, false);
2147
+
2148
+ return {
2149
+ // Do NOT cast `url` to a string: that will work even when there are real
2150
+ // problems, silencing them
2151
+ url: url.href,
2152
+ format: defaultGetFormatWithoutErrors(url, {parentURL})
2153
+ }
2154
+ }
2155
+
2156
+ /**
2157
+ * @typedef {import('./lib/errors.js').ErrnoException} ErrnoException
2158
+ */
2159
+
2160
+
2161
+ /**
2162
+ * Match `import.meta.resolve` except that `parent` is required (you can pass
2163
+ * `import.meta.url`).
2164
+ *
2165
+ * @param {string} specifier
2166
+ * The module specifier to resolve relative to parent
2167
+ * (`/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`,
2168
+ * etc).
2169
+ * @param {string} parent
2170
+ * The absolute parent module URL to resolve from.
2171
+ * You must pass `import.meta.url` or something else.
2172
+ * @returns {string}
2173
+ * Returns a string to a full `file:`, `data:`, or `node:` URL
2174
+ * to the found thing.
2175
+ */
2176
+ function resolve(specifier, parent) {
2177
+ if (!parent) {
2178
+ throw new Error(
2179
+ 'Please pass `parent`: `import-meta-resolve` cannot ponyfill that'
2180
+ )
2181
+ }
2182
+
2183
+ try {
2184
+ return defaultResolve(specifier, {parentURL: parent}).url
2185
+ } catch (error) {
2186
+ // See: <https://github.com/nodejs/node/blob/45f5c9b/lib/internal/modules/esm/initialize_import_meta.js#L34>
2187
+ const exception = /** @type {ErrnoException} */ (error);
2188
+
2189
+ if (
2190
+ (exception.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ||
2191
+ exception.code === 'ERR_MODULE_NOT_FOUND') &&
2192
+ typeof exception.url === 'string'
2193
+ ) {
2194
+ return exception.url
2195
+ }
2196
+
2197
+ throw error
2198
+ }
2199
+ }
2200
+
2201
+ export { moduleResolve, resolve };