import-in-the-middle 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ {
2
+ ".": "1.9.0"
3
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## [1.9.0](https://github.com/nodejs/import-in-the-middle/compare/import-in-the-middle-v1.8.1...import-in-the-middle-v1.9.0) (2024-07-08)
4
+
5
+
6
+ ### Features
7
+
8
+ * Allow passing of `include` or `exclude` list via `module.register()` ([#124](https://github.com/nodejs/import-in-the-middle/issues/124)) ([381f48c](https://github.com/nodejs/import-in-the-middle/commit/381f48c07ff755e88495f688c75c4912926194c7))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * CJS `require('.')` resolution ([#108](https://github.com/nodejs/import-in-the-middle/issues/108)) ([29c77b5](https://github.com/nodejs/import-in-the-middle/commit/29c77b560aec0429154632c950923d12db36f79e))
14
+ * Include source url for parsing failures ([#109](https://github.com/nodejs/import-in-the-middle/issues/109)) ([49d69ba](https://github.com/nodejs/import-in-the-middle/commit/49d69ba9e785d4b6a1b38d7da1293cb744b6d7e3))
15
+ * Use `process.emitWarning` to log wrapping errors ([#114](https://github.com/nodejs/import-in-the-middle/issues/114)) ([a3778ac](https://github.com/nodejs/import-in-the-middle/commit/a3778acfbe2220ce5d521232b41da23b4383e1e3))
@@ -0,0 +1,4 @@
1
+ # Code of Conduct
2
+
3
+ The Code of Conduct, which applies to this project, can be found at
4
+ https://github.com/nodejs/admin/blob/HEAD/CODE_OF_CONDUCT.md
package/CONTRIBUTING.md CHANGED
@@ -1,6 +1,34 @@
1
- # Contributing to import-in-the-middle
1
+ # Contributing to `import-in-the-middle`
2
2
 
3
- First of all, thanks for contributing!
3
+ ## Code of Conduct
4
4
 
5
- * If you think you've found an issue, please open a Github issue.
6
- * To propose improvements, feel free to submit a PR.
5
+ Please read the
6
+ [Code of Conduct](https://github.com/nodejs/admin/blob/main/CODE_OF_CONDUCT.md)
7
+ which explains the minimum behavior expectations for `import-in-the-middle` contributors.
8
+
9
+ <a id="developers-certificate-of-origin"></a>
10
+ ## Developer's Certificate of Origin 1.1
11
+
12
+ By making a contribution to this project, I certify that:
13
+
14
+ * (a) The contribution was created in whole or in part by me and I
15
+ have the right to submit it under the open source license
16
+ indicated in the file; or
17
+
18
+ * (b) The contribution is based upon previous work that, to the best
19
+ of my knowledge, is covered under an appropriate open source
20
+ license and I have the right under that license to submit that
21
+ work with modifications, whether created in whole or in part
22
+ by me, under the same open source license (unless I am
23
+ permitted to submit under a different license), as indicated
24
+ in the file; or
25
+
26
+ * (c) The contribution was provided directly to me by some other
27
+ person who certified (a), (b) or (c) and I have not modified
28
+ it.
29
+
30
+ * (d) I understand and agree that this project and the contribution
31
+ are public and that a record of the contribution (including all
32
+ personal information I submit with it, including my sign-off) is
33
+ maintained indefinitely and may be redistributed consistent with
34
+ this project or the open source license(s) involved.
package/GOVERNANCE.md ADDED
@@ -0,0 +1,28 @@
1
+ # `import-in-the-middle` Project Governance
2
+
3
+ ## Collaborators
4
+
5
+ `import-in-the-middle` core collaborators maintain the
6
+ [nodejs/import-in-the-middle](https://github.com/nodejs/import-in-the-middle)
7
+ GitHub repository.
8
+ The GitHub team for `import-in-the-middle` core collaborators is
9
+ [@nodejs/import-in-the-middle-maintainers](https://github.com/orgs/nodejs/teams/import-in-the-middle-maintainers).
10
+ Collaborators have commit access to the
11
+ [nodejs/import-in-the-middle](https://github.com/nodejs/import-in-the-middle)
12
+ repository.
13
+
14
+ Both collaborators and non-collaborators may propose changes to the `import-in-the-middle`
15
+ source code. The mechanism to propose such a change is a GitHub pull request.
16
+ Collaborators review and merge (_land_) pull requests.
17
+
18
+ ## PR Approval
19
+
20
+ Two collaborators must approve a pull request before the pull request can land.
21
+ Approving a pull request indicates that the collaborator accepts responsibility
22
+ for the change. Approval must be from collaborators who are not authors of the
23
+ change and at least one approval must be from a collaborator outside the authors
24
+ direct team.
25
+
26
+ If a collaborator opposes a proposed change, then the change cannot land. Often,
27
+ discussions or further changes result in collaborators removing their
28
+ opposition.
package/LICENSE CHANGED
@@ -1,13 +1,201 @@
1
- Copyright 2021 Datadog, Inc.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
2
4
 
3
- Licensed under the Apache License, Version 2.0 (the "License");
4
- you may not use this file except in compliance with the License.
5
- You may obtain a copy of the License at
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
6
 
7
- http://www.apache.org/licenses/LICENSE-2.0
7
+ 1. Definitions.
8
8
 
9
- Unless required by applicable law or agreed to in writing, software
10
- distributed under the License is distributed on an "AS IS" BASIS,
11
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- See the License for the specific language governing permissions and
13
- limitations under the License.
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE CHANGED
@@ -1,4 +1,34 @@
1
- Datadog import-in-the-middle
2
- Copyright 2021 Datadog, Inc.
1
+ import-in-the-middle is licensed for use as follows:
3
2
 
4
- This product includes software developed at Datadog (https://www.datadoghq.com/).
3
+ Copyright 2024 Node.js contributors. All rights reserved.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ This license applies to parts of import-in-the-middle originating from the
18
+ https://github.com/DataDog/import-in-the-middle repository:
19
+
20
+ This product includes software developed at Datadog (https://www.datadoghq.com/).
21
+
22
+ Copyright 2021 Datadog, Inc.
23
+
24
+ Licensed under the Apache License, Version 2.0 (the "License");
25
+ you may not use this file except in compliance with the License.
26
+ You may obtain a copy of the License at
27
+
28
+ http://www.apache.org/licenses/LICENSE-2.0
29
+
30
+ Unless required by applicable law or agreed to in writing, software
31
+ distributed under the License is distributed on an "AS IS" BASIS,
32
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33
+ See the License for the specific language governing permissions and
34
+ limitations under the License.
package/README.md CHANGED
@@ -38,6 +38,39 @@ command-line option.
38
38
  --loader=import-in-the-middle/hook.mjs
39
39
  ```
40
40
 
41
+ It's also possible to register the loader hook programmatically via the Node
42
+ [`module.register()`](https://nodejs.org/api/module.html#moduleregisterspecifier-parenturl-options)
43
+ API. However, for this to be able to hook non-dynamic imports, it needs to be
44
+ loaded before your app code is evaluated via the `--import` command-line option.
45
+
46
+ `my-loader.mjs`
47
+ ```js
48
+ import * as module from 'module'
49
+
50
+ module.register('import-in-the-middle/hook.mjs', import.meta.url)
51
+ ```
52
+ ```shell
53
+ node --import=./my-loader.mjs ./my-code.mjs
54
+ ```
55
+
56
+ When registering the loader hook programmatically, it's possible to pass a list
57
+ of modules or file URLs to either exclude or specifically include which modules
58
+ are intercepted. This is useful if a module is not compatible with the loader
59
+ hook.
60
+ ```js
61
+ import * as module from 'module'
62
+
63
+ // Exclude intercepting a specific module by name
64
+ module.register('import-in-the-middle/hook.mjs', import.meta.url, {
65
+ data: { exclude: ['package-i-want-to-exclude'] }
66
+ })
67
+
68
+ // Only intercept a specific module by name
69
+ module.register('import-in-the-middle/hook.mjs', import.meta.url, {
70
+ data: { include: ['package-i-want-to-include'] }
71
+ })
72
+ ```
73
+
41
74
  ## Limitations
42
75
 
43
76
  * You cannot add new exports to a module. You can only modify existing ones.
package/hook.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2021 Datadog, Inc.
4
4
 
5
5
  const { URL } = require('url')
6
+ const { inspect } = require('util')
6
7
  const specifiers = new Map()
7
8
  const isWin = process.platform === 'win32'
8
9
 
@@ -115,6 +116,46 @@ function isBareSpecifier (specifier) {
115
116
  }
116
117
  }
117
118
 
119
+ function isBareSpecifierOrFileUrl (input) {
120
+ // Relative and absolute paths
121
+ if (
122
+ input.startsWith('.') ||
123
+ input.startsWith('/')) {
124
+ return false
125
+ }
126
+
127
+ try {
128
+ // eslint-disable-next-line no-new
129
+ const url = new URL(input)
130
+ return url.protocol === 'file:'
131
+ } catch (err) {
132
+ // Anything that fails parsing is a bare specifier
133
+ return true
134
+ }
135
+ }
136
+
137
+ function ensureArrayWithBareSpecifiersAndFileUrls (array, type) {
138
+ if (!Array.isArray(array)) {
139
+ return undefined
140
+ }
141
+
142
+ const invalid = array.filter(s => !isBareSpecifierOrFileUrl(s))
143
+
144
+ if (invalid.length) {
145
+ throw new Error(`'${type}' option only supports bare specifiers and file URLs. Invalid entries: ${inspect(invalid)}`)
146
+ }
147
+
148
+ return array
149
+ }
150
+
151
+ function emitWarning (err) {
152
+ // Unfortunately, process.emitWarning does not output the full error
153
+ // with error.cause like console.warn does so we need to inspect it when
154
+ // tracing warnings
155
+ const warnMessage = process.execArgv.includes('--trace-warnings') ? inspect(err) : err
156
+ process.emitWarning(warnMessage)
157
+ }
158
+
118
159
  /**
119
160
  * Processes a module's exports and builds a set of setter blocks.
120
161
  *
@@ -208,11 +249,19 @@ function addIitm (url) {
208
249
  function createHook (meta) {
209
250
  let cachedResolve
210
251
  const iitmURL = new URL('lib/register.js', meta.url).toString()
252
+ let includeModules, excludeModules
253
+
254
+ async function initialize (data) {
255
+ if (data) {
256
+ includeModules = ensureArrayWithBareSpecifiersAndFileUrls(data.include, 'include')
257
+ excludeModules = ensureArrayWithBareSpecifiersAndFileUrls(data.exclude, 'exclude')
258
+ }
259
+ }
211
260
 
212
261
  async function resolve (specifier, context, parentResolve) {
213
262
  cachedResolve = parentResolve
214
263
 
215
- // See github.com/DataDog/import-in-the-middle/pull/76.
264
+ // See github.com/nodejs/import-in-the-middle/pull/76.
216
265
  if (specifier === iitmURL) {
217
266
  return {
218
267
  url: specifier,
@@ -225,14 +274,27 @@ function createHook (meta) {
225
274
  if (isWin && parentURL.indexOf('file:node') === 0) {
226
275
  context.parentURL = ''
227
276
  }
228
- const url = await parentResolve(newSpecifier, context, parentResolve)
229
- if (parentURL === '' && !EXTENSION_RE.test(url.url)) {
230
- entrypoint = url.url
231
- return { url: url.url, format: 'commonjs' }
277
+ const result = await parentResolve(newSpecifier, context, parentResolve)
278
+ if (parentURL === '' && !EXTENSION_RE.test(result.url)) {
279
+ entrypoint = result.url
280
+ return { url: result.url, format: 'commonjs' }
281
+ }
282
+
283
+ // For included/excluded modules, we check the specifier to match libraries
284
+ // that are loaded with bare specifiers from node_modules.
285
+ //
286
+ // For non-bare specifier imports, we only support matching file URL strings
287
+ // because using relative paths would be very error prone!
288
+ if (includeModules && !includeModules.some(lib => lib === specifier || lib === result.url.url)) {
289
+ return result
290
+ }
291
+
292
+ if (excludeModules && excludeModules.some(lib => lib === specifier || lib === result.url.url)) {
293
+ return result
232
294
  }
233
295
 
234
296
  if (isIitm(parentURL, meta) || hasIitm(parentURL)) {
235
- return url
297
+ return result
236
298
  }
237
299
 
238
300
  // Node.js v21 renames importAssertions to importAttributes
@@ -240,24 +302,24 @@ function createHook (meta) {
240
302
  (context.importAssertions && context.importAssertions.type === 'json') ||
241
303
  (context.importAttributes && context.importAttributes.type === 'json')
242
304
  ) {
243
- return url
305
+ return result
244
306
  }
245
307
 
246
308
  // If the file is referencing itself, we need to skip adding the iitm search params
247
- if (url.url === parentURL) {
309
+ if (result.url === parentURL) {
248
310
  return {
249
- url: url.url,
311
+ url: result.url,
250
312
  shortCircuit: true,
251
- format: url.format
313
+ format: result.format
252
314
  }
253
315
  }
254
316
 
255
- specifiers.set(url.url, specifier)
317
+ specifiers.set(result.url, specifier)
256
318
 
257
319
  return {
258
- url: addIitm(url.url),
320
+ url: addIitm(result.url),
259
321
  shortCircuit: true,
260
- format: url.format
322
+ format: result.format
261
323
  }
262
324
  }
263
325
 
@@ -303,7 +365,7 @@ register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(rea
303
365
  // it would be very tricky to debug
304
366
  const err = new Error(`'import-in-the-middle' failed to wrap '${realUrl}'`)
305
367
  err.cause = cause
306
- console.warn(err)
368
+ emitWarning(err)
307
369
 
308
370
  // Revert back to the non-iitm URL
309
371
  url = realUrl
@@ -328,9 +390,10 @@ register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(rea
328
390
  }
329
391
 
330
392
  if (NODE_MAJOR >= 17 || (NODE_MAJOR === 16 && NODE_MINOR >= 12)) {
331
- return { load, resolve }
393
+ return { initialize, load, resolve }
332
394
  } else {
333
395
  return {
396
+ initialize,
334
397
  load,
335
398
  resolve,
336
399
  getSource,
package/hook.mjs CHANGED
@@ -4,6 +4,6 @@
4
4
 
5
5
  import { createHook } from './hook.js'
6
6
 
7
- const { load, resolve, getFormat, getSource } = createHook(import.meta)
7
+ const { initialize, load, resolve, getFormat, getSource } = createHook(import.meta)
8
8
 
9
- export { load, resolve, getFormat, getSource }
9
+ export { initialize, load, resolve, getFormat, getSource }
@@ -43,6 +43,9 @@ async function getCjsExports (url, context, parentLoad, source) {
43
43
  full.add(each)
44
44
  }
45
45
  } else {
46
+ if (re === '.') {
47
+ re = './'
48
+ }
46
49
  // Resolve the re-exported module relative to the current module.
47
50
  const newUrl = pathToFileURL(require.resolve(re, { paths: [dirname(fileURLToPath(url))] })).href
48
51
  for (const each of await getExports(newUrl, context, parentLoad)) {
@@ -92,23 +95,29 @@ async function getExports (url, context, parentLoad) {
92
95
  source = readFileSync(fileURLToPath(url), 'utf8')
93
96
  }
94
97
 
95
- if (format === 'module') {
96
- return getEsmExports(source)
97
- }
98
+ try {
99
+ if (format === 'module') {
100
+ return getEsmExports(source)
101
+ }
98
102
 
99
- if (format === 'commonjs') {
100
- return getCjsExports(url, context, parentLoad, source)
101
- }
103
+ if (format === 'commonjs') {
104
+ return await getCjsExports(url, context, parentLoad, source)
105
+ }
102
106
 
103
- // At this point our `format` is either undefined or not known by us. Fall
104
- // back to parsing as ESM/CJS.
105
- const esmExports = getEsmExports(source)
106
- if (!esmExports.length) {
107
- // TODO(bengl) it's might be possible to get here if somehow the format
108
- // isn't set at first and yet we have an ESM module with no exports.
109
- // I couldn't construct an example that would do this, so maybe it's
110
- // impossible?
111
- return getCjsExports(url, context, parentLoad, source)
107
+ // At this point our `format` is either undefined or not known by us. Fall
108
+ // back to parsing as ESM/CJS.
109
+ const esmExports = getEsmExports(source)
110
+ if (!esmExports.length) {
111
+ // TODO(bengl) it's might be possible to get here if somehow the format
112
+ // isn't set at first and yet we have an ESM module with no exports.
113
+ // I couldn't construct an example that would do this, so maybe it's
114
+ // impossible?
115
+ return await getCjsExports(url, context, parentLoad, source)
116
+ }
117
+ } catch (cause) {
118
+ const err = new Error(`Failed to parse '${url}'`)
119
+ err.cause = cause
120
+ throw err
112
121
  }
113
122
  }
114
123
 
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "import-in-the-middle",
3
- "version": "1.8.1",
3
+ "version": "1.9.0",
4
4
  "description": "Intercept imports in Node.js",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
- "test": "c8 --reporter lcov --check-coverage --lines 50 imhotap --files test/{hook,low-level,other,get-esm-exports}/*",
7
+ "test": "c8 --reporter lcov --check-coverage --lines 50 imhotap --files test/{hook,low-level,other,get-esm-exports,register}/*",
8
+ "test:e2e": "node test/check-exports/test.mjs",
8
9
  "test:ts": "c8 --reporter lcov imhotap --files test/typescript/*.test.mts",
9
10
  "coverage": "c8 --reporter html imhotap --files test/{hook,low-level,other,get-esm-exports}/* && echo '\nNow open coverage/index.html\n'",
10
11
  "lint": "eslint .",
@@ -12,7 +13,7 @@
12
13
  },
13
14
  "repository": {
14
15
  "type": "git",
15
- "url": "git+ssh://git@github.com/DataDog/import-in-the-middle.git"
16
+ "url": "git+ssh://git@github.com/nodejs/import-in-the-middle.git"
16
17
  },
17
18
  "keywords": [
18
19
  "import",
@@ -25,9 +26,9 @@
25
26
  "author": "Bryan English <bryan.english@datadoghq.com>",
26
27
  "license": "Apache-2.0",
27
28
  "bugs": {
28
- "url": "https://github.com/DataDog/import-in-the-middle/issues"
29
+ "url": "https://github.com/nodejs/import-in-the-middle/issues"
29
30
  },
30
- "homepage": "https://github.com/DataDog/import-in-the-middle#readme",
31
+ "homepage": "https://github.com/nodejs/import-in-the-middle#readme",
31
32
  "imhotap": {
32
33
  "runner": "node",
33
34
  "test-env": "NODE_OPTIONS=--no-warnings --require ./test/version-check.js --experimental-loader ./test/generic-loader.mjs"
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
3
+ "bootstrap-sha": "57d2459748492abd55e04a679d8b5752b90dfab4",
4
+ "packages": {
5
+ ".": {
6
+ "pull-request-title-pattern": "chore: release v${version}",
7
+ "release-type": "node"
8
+ }
9
+ }
10
+ }
@@ -0,0 +1,317 @@
1
+ import { spawnSync } from 'child_process'
2
+ import { deepStrictEqual } from 'assert'
3
+ import { dirname, resolve } from 'path'
4
+ import { fileURLToPath } from 'url'
5
+
6
+ const cwd = dirname(fileURLToPath(import.meta.url))
7
+ const hook = resolve(cwd, '..', '..', 'hook.mjs')
8
+
9
+ const mostPopular240NpmModules = [
10
+ 'ansi-styles',
11
+ 'semver',
12
+ 'supports-color',
13
+ 'chalk', 'has-flag',
14
+ 'debug',
15
+ 'tslib',
16
+ 'color-convert',
17
+ 'ms',
18
+ 'color-name',
19
+ 'lru-cache',
20
+ 'minimatch',
21
+ 'strip-ansi',
22
+ 'source-map',
23
+ 'ansi-regex',
24
+ 'glob',
25
+ 'readable-stream',
26
+ 'commander',
27
+ 'yallist',
28
+ 'string-width',
29
+ 'escape-string-regexp',
30
+ 'brace-expansion',
31
+ 'find-up',
32
+ 'p-locate',
33
+ 'locate-path',
34
+ 'wrap-ansi',
35
+ 'p-limit',
36
+ 'safe-buffer',
37
+ 'kind-of',
38
+ 'minipass',
39
+ 'uuid',
40
+ 'string_decoder',
41
+ 'ajv',
42
+ 'emoji-regex',
43
+ 'isarray',
44
+ 'react-is',
45
+ 'fs-extra',
46
+ 'is-fullwidth-code-point',
47
+ 'get-stream',
48
+ 'json-schema-traverse',
49
+ 'yargs-parser',
50
+ 'glob-parent',
51
+ 'yargs',
52
+ 'rimraf',
53
+ 'acorn',
54
+ 'which',
55
+ 'estraverse',
56
+ 'js-yaml',
57
+ 'path-exists',
58
+ 'argparse',
59
+ 'pretty-format',
60
+ 'resolve-from',
61
+ 'cliui',
62
+ 'schema-utils',
63
+ 'globals',
64
+ 'camelcase',
65
+ 'execa',
66
+ 'punycode',
67
+ 'path-key',
68
+ 'signal-exit',
69
+ 'inherits',
70
+ 'resolve',
71
+ 'mkdirp',
72
+ 'is-stream',
73
+ 'ws',
74
+ 'universalify',
75
+ 'qs',
76
+ 'slash',
77
+ 'json5',
78
+ 'iconv-lite',
79
+ 'form-data',
80
+ 'is-number',
81
+ 'eslint-visitor-keys',
82
+ '@jest/types',
83
+ 'postcss',
84
+ 'make-dir',
85
+ 'pify',
86
+ 'cross-spawn',
87
+ 'braces',
88
+ 'whatwg-url',
89
+ 'fill-range',
90
+ 'eslint-scope',
91
+ 'tr46',
92
+ 'micromatch',
93
+ 'convert-source-map',
94
+ 'define-property',
95
+ 'agent-base',
96
+ 'shebang-regex',
97
+ 'shebang-command',
98
+ 'mimic-fn',
99
+ 'globby',
100
+ 'npm-run-path',
101
+ 'mime',
102
+ '@babel/code-frame',
103
+ 'extend-shallow',
104
+ 'to-regex-range',
105
+ 'onetime',
106
+ 'https-proxy-agent',
107
+ 'y18n',
108
+ 'buffer',
109
+ 'strip-bom',
110
+ 'is-glob',
111
+ 'doctrine',
112
+ 'picocolors',
113
+ 'pkg-dir',
114
+ '@babel/types',
115
+ 'regenerator-runtime',
116
+ 'human-signals',
117
+ '@jridgewell/trace-mapping',
118
+ 'ignore',
119
+ 'jsesc',
120
+ 'parse-json',
121
+ 'jest-worker',
122
+ 'graceful-fs',
123
+ 'jest-util',
124
+ 'jsonfile',
125
+ 'normalize-path',
126
+ 'strip-json-comments',
127
+ 'cosmiconfig',
128
+ 'minimist',
129
+ 'path-type',
130
+ '@babel/parser',
131
+ 'balanced-match',
132
+ 'picomatch',
133
+ 'typescript',
134
+ 'isexe',
135
+ 'statuses',
136
+ 'entities',
137
+ 'bytes',
138
+ 'node-fetch',
139
+ 'http-errors',
140
+ '@babel/highlight',
141
+ '@babel/helper-validator-identifier',
142
+ 'function-bind',
143
+ 'async',
144
+ 'sprintf-js',
145
+ '@babel/generator',
146
+ 'is-extendable',
147
+ 'get-intrinsic',
148
+ 'lodash',
149
+ 'mime-db',
150
+ 'source-map-support',
151
+ 'mime-types',
152
+ 'is-arrayish',
153
+ '@babel/core',
154
+ 'once',
155
+ 'anymatch',
156
+ 'depd',
157
+ 'hosted-git-info',
158
+ 'path-to-regexp',
159
+ 'axios',
160
+ 'is-core-module',
161
+ '@babel/template',
162
+ 'cookie',
163
+ 'write-file-atomic',
164
+ 'js-tokens',
165
+ '@typescript-eslint/typescript-estree',
166
+ '@typescript-eslint/types',
167
+ 'object-inspect',
168
+ 'wrappy',
169
+ 'is-extglob',
170
+ 'chokidar',
171
+ '@typescript-eslint/visitor-keys',
172
+ 'call-bind',
173
+ 'loader-utils',
174
+ 'browserslist',
175
+ 'http-proxy-agent',
176
+ 'fast-glob',
177
+ 'concat-map',
178
+ 'inflight',
179
+ 'ajv-keywords',
180
+ 'ansi-escapes',
181
+ 'ci-info',
182
+ 'fast-deep-equal',
183
+ 'caniuse-lite',
184
+ 'fs.realpath',
185
+ '@jridgewell/gen-mapping',
186
+ 'setprototypeof',
187
+ 'strip-final-newline',
188
+ 'optionator',
189
+ 'path-is-absolute',
190
+ '@babel/traverse',
191
+ 'core-util-is',
192
+ 'has-symbols',
193
+ 'yocto-queue',
194
+ 'p-try',
195
+ 'electron-to-chromium',
196
+ '@smithy/smithy-client',
197
+ 'yaml',
198
+ 'ini',
199
+ '@babel/helper-plugin-utils',
200
+ 'jest-get-type',
201
+ 'type-check',
202
+ 'levn',
203
+ 'is-descriptor',
204
+ 'prelude-ls',
205
+ 'slice-ansi',
206
+ '@typescript-eslint/scope-manager',
207
+ 'isobject',
208
+ 'esprima',
209
+ '@babel/helper-split-export-declaration',
210
+ 'callsites',
211
+ 'readdirp',
212
+ 'escalade',
213
+ 'import-fresh',
214
+ 'get-caller-file',
215
+ '@jridgewell/sourcemap-codec',
216
+ 'acorn-walk',
217
+ 'rxjs',
218
+ 'ieee754',
219
+ 'is-plain-obj',
220
+ 'istanbul-lib-instrument',
221
+ '@babel/helper-module-imports',
222
+ 'side-channel',
223
+ 'normalize-package-data',
224
+ 'is-plain-object',
225
+ '@jridgewell/resolve-uri',
226
+ 'follow-redirects',
227
+ 'array-union',
228
+ 'json-parse-even-better-errors',
229
+ 'path-parse',
230
+ 'has-property-descriptors',
231
+ 'uri-js',
232
+ 'safer-buffer',
233
+ '@babel/helpers',
234
+ 'on-finished',
235
+ '@babel/helper-function-name',
236
+ 'p-map',
237
+ 'postcss-value-parser',
238
+ 'indent-string',
239
+ '@babel/helper-module-transforms',
240
+ 'object-assign',
241
+ 'delayed-stream',
242
+ '@nodelib/fs.stat',
243
+ 'require-directory',
244
+ 'diff',
245
+ 'parse5',
246
+ 'asynckit',
247
+ 'tmp',
248
+ 'combined-stream'
249
+ ]
250
+
251
+ const otherCommonModulesUsedWithInstrumentation = [
252
+ 'express',
253
+ 'fastify',
254
+ '@hapi/hapi',
255
+ 'connect',
256
+ 'svelte',
257
+ '@sveltejs/kit',
258
+ 'next',
259
+ 'gatsby',
260
+ '@remix-run/node',
261
+ '@remix-run/react'
262
+ ]
263
+
264
+ const modules = [...mostPopular240NpmModules, ...otherCommonModulesUsedWithInstrumentation]
265
+
266
+ function installLibs (names) {
267
+ spawnSync('npm', ['init', '-y'], { cwd })
268
+ spawnSync('npm', ['install', ...names], { cwd })
269
+ }
270
+
271
+ function getExports (name, loader) {
272
+ const args = ['--input-type=module', '--no-warnings', '-e', `import * as lib from '${name}'; console.log(JSON.stringify(Object.keys(lib)))`]
273
+ if (loader) args.push(loader)
274
+ const out = spawnSync(process.execPath, args, { cwd })
275
+ if (out.status !== 0) {
276
+ console.error(out.stderr.toString())
277
+ throw new Error(`Getting exports returned non-zero exit code '${name}'`)
278
+ }
279
+ const stdout = out.stdout.toString()
280
+ return JSON.parse(stdout).sort()
281
+ }
282
+
283
+ const NPM_LIST_SEMVER_PARSE = /└──.*@((0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?)/
284
+
285
+ function getVersion (name) {
286
+ const result = spawnSync('npm', ['list', name, '--depth', '0'], { cwd })
287
+ const stdout = result.output.toString()
288
+ const [, version] = stdout.match(NPM_LIST_SEMVER_PARSE)
289
+ return version
290
+ }
291
+
292
+ function testLib (name) {
293
+ const version = getVersion(name)
294
+ try {
295
+ const expected = getExports(name)
296
+ const actual = getExports(name, `--experimental-loader=${hook}`)
297
+ deepStrictEqual(actual, expected, `Exports for ${name} are different`)
298
+ console.log(`✅ Exports for ${name}@${version} match`)
299
+ return false
300
+ } catch (err) {
301
+ console.error(`❌ Error getting exports for ${name}@${version}:`, err)
302
+ return true
303
+ }
304
+ }
305
+
306
+ console.log(`📦 Installing ${modules.length} libraries...`)
307
+ installLibs(modules)
308
+
309
+ let errored = false
310
+ for (const mod of modules) {
311
+ errored += testLib(mod)
312
+ }
313
+
314
+ if (errored) {
315
+ console.error('❌ Some tests failed')
316
+ process.exit(1)
317
+ }
@@ -0,0 +1 @@
1
+ module.exports.foo = 'something'
@@ -0,0 +1 @@
1
+ module.exports = { ...require('.') }
@@ -8,7 +8,7 @@ import path from 'path'
8
8
 
9
9
  const filename = process.env.IITM_TEST_FILE
10
10
 
11
- export const { load, resolve, getFormat, getSource } =
12
- filename.includes('disabled')
11
+ export const { initialize, load, resolve, getFormat, getSource } =
12
+ filename.includes('disabled') || filename.includes('register')
13
13
  ? {}
14
14
  : (path.extname(filename).slice(-2) === 'ts' ? tsLoader : regularLoader)
@@ -0,0 +1,12 @@
1
+ import Hook from '../../index.js'
2
+ import { foo } from '../fixtures/require-root.js'
3
+ import { strictEqual } from 'assert'
4
+
5
+ Hook((exports, name) => {
6
+ if (name.endsWith('require-root.js')) {
7
+ strictEqual(exports.foo, 'something')
8
+ exports.foo += '-wrap'
9
+ }
10
+ })
11
+
12
+ strictEqual(foo, 'something-wrap')
@@ -0,0 +1,15 @@
1
+ import { register } from 'module'
2
+ import Hook from '../../index.js'
3
+ import { strictEqual } from 'assert'
4
+
5
+ register('../../hook.mjs', import.meta.url, { data: { exclude: ['util'] } })
6
+
7
+ const hooked = []
8
+
9
+ Hook((exports, name) => {
10
+ hooked.push(name)
11
+ })
12
+
13
+ await import('openai')
14
+
15
+ strictEqual(hooked.includes('util'), false)
@@ -0,0 +1,16 @@
1
+ import { register } from 'module'
2
+ import Hook from '../../index.js'
3
+ import { strictEqual } from 'assert'
4
+
5
+ register('../../hook.mjs', import.meta.url, { data: { include: ['openai'] } })
6
+
7
+ const hooked = []
8
+
9
+ Hook((exports, name) => {
10
+ hooked.push(name)
11
+ })
12
+
13
+ await import('openai')
14
+
15
+ strictEqual(hooked.length, 1)
16
+ strictEqual(hooked[0], 'openai')