source: frontend/node_modules/cjs-module-lexer/README.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 13.8 KB
RevLine 
[9af201e]1# CJS Module Lexer
2
3[![Build Status][travis-image]][travis-url]
4
5A [very fast](#benchmarks) JS CommonJS module syntax lexer used to detect the most likely list of named exports of a CommonJS module.
6
7Outputs the list of named exports (`exports.name = ...`) and possible module reexports (`module.exports = require('...')`), including the common transpiler variations of these cases.
8
9Forked from https://github.com/guybedford/es-module-lexer.
10
11_Comprehensively handles the JS language grammar while remaining small and fast. - ~90ms per MB of JS cold and ~15ms per MB of JS warm, [see benchmarks](#benchmarks) for more info._
12
13### Project Status
14
15This project is used in Node.js core for detecting the named exports available when importing a CJS module into ESM, and is maintained for this purpose.
16
17PRs will be accepted and upstreamed for parser bugs, performance improvements or new syntax support only.
18
19_Detection patterns for this project are **frozen**_. This is because adding any new export detection patterns would result in fragmented backwards-compatibility. Specifically, it would be very difficult to figure out why an ES module named export for CommonJS might work in newer Node.js versions but not older versions. This problem would only be discovered downstream of module authors, with the fix for module authors being to then have to understand which patterns in this project provide full backwards-compatibily. Rather, by fully freezing the detected patterns, if it works in any Node.js version it will work in any other. Build tools can also reliably treat the supported syntax for this project as a part of their output target for ensuring syntax support.
20
21### Usage
22
23```
24npm install cjs-module-lexer
25```
26
27For use in CommonJS:
28
29```js
30const { parse } = require('cjs-module-lexer');
31
32// `init` return a promise for parity with the ESM API, but you do not have to call it
33
34const { exports, reexports } = parse(`
35 // named exports detection
36 module.exports.a = 'a';
37 (function () {
38 exports.b = 'b';
39 })();
40 Object.defineProperty(exports, 'c', { value: 'c' });
41 /* exports.d = 'not detected'; */
42
43 // reexports detection
44 if (maybe) module.exports = require('./dep1.js');
45 if (another) module.exports = require('./dep2.js');
46
47 // literal exports assignments
48 module.exports = { a, b: c, d, 'e': f }
49
50 // __esModule detection
51 Object.defineProperty(module.exports, '__esModule', { value: true })
52`);
53
54// exports === ['a', 'b', 'c', '__esModule']
55// reexports === ['./dep1.js', './dep2.js']
56```
57
58When using the ESM version, Wasm is supported instead:
59
60```js
61import { parse, init } from 'cjs-module-lexer';
62// init() needs to be called and waited upon, or use initSync() to compile
63// Wasm blockingly and synchronously.
64await init();
65const { exports, reexports } = parse(source);
66```
67
68The Wasm build is around 1.5x faster and without a cold start.
69
70### Grammar
71
72CommonJS exports matches are run against the source token stream.
73
74The token grammar is:
75
76```
77IDENTIFIER: As defined by ECMA-262, without support for identifier `\` escapes, filtered to remove strict reserved words:
78 "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "enum"
79
80STRING_LITERAL: A `"` or `'` bounded ECMA-262 string literal.
81
82MODULE_EXPORTS: `module` `.` `exports`
83
84EXPORTS_IDENTIFIER: MODULE_EXPORTS_IDENTIFIER | `exports`
85
86EXPORTS_DOT_ASSIGN: EXPORTS_IDENTIFIER `.` IDENTIFIER `=`
87
88EXPORTS_LITERAL_COMPUTED_ASSIGN: EXPORTS_IDENTIFIER `[` STRING_LITERAL `]` `=`
89
90EXPORTS_LITERAL_PROP: (IDENTIFIER (`:` IDENTIFIER)?) | (STRING_LITERAL `:` IDENTIFIER)
91
92EXPORTS_SPREAD: `...` (IDENTIFIER | REQUIRE)
93
94EXPORTS_MEMBER: EXPORTS_DOT_ASSIGN | EXPORTS_LITERAL_COMPUTED_ASSIGN
95
96EXPORTS_DEFINE: `Object` `.` `defineProperty `(` EXPORTS_IDENFITIER `,` STRING_LITERAL
97
98EXPORTS_DEFINE_VALUE: EXPORTS_DEFINE `, {`
99 (`enumerable: true,`)?
100 (
101 `value:` |
102 `get` (`: function` IDENTIFIER? )? `() {` return IDENTIFIER (`.` IDENTIFIER | `[` STRING_LITERAL `]`)? `;`? `}` `,`?
103 )
104 `})`
105
106EXPORTS_LITERAL: MODULE_EXPORTS `=` `{` (EXPORTS_LITERAL_PROP | EXPORTS_SPREAD) `,`)+ `}`
107
108REQUIRE: `require` `(` STRING_LITERAL `)`
109
110EXPORTS_ASSIGN: (`var` | `const` | `let`) IDENTIFIER `=` (`_interopRequireWildcard (`)? REQUIRE
111
112MODULE_EXPORTS_ASSIGN: MODULE_EXPORTS `=` REQUIRE
113
114EXPORT_STAR: (`__export` | `__exportStar`) `(` REQUIRE
115
116EXPORT_STAR_LIB: `Object.keys(` IDENTIFIER$1 `).forEach(function (` IDENTIFIER$2 `) {`
117 (
118 (
119 `if (` IDENTIFIER$2 `===` ( `'default'` | `"default"` ) `||` IDENTIFIER$2 `===` ( '__esModule' | `"__esModule"` ) `) return` `;`?
120 (
121 (`if (Object` `.prototype`? `.hasOwnProperty.call(` IDENTIFIER `, ` IDENTIFIER$2 `)) return` `;`?)?
122 (`if (` IDENTIFIER$2 `in` EXPORTS_IDENTIFIER `&&` EXPORTS_IDENTIFIER `[` IDENTIFIER$2 `] ===` IDENTIFIER$1 `[` IDENTIFIER$2 `]) return` `;`)?
123 )?
124 ) |
125 `if (` IDENTIFIER$2 `!==` ( `'default'` | `"default"` ) (`&& !` (`Object` `.prototype`? `.hasOwnProperty.call(` IDENTIFIER `, ` IDENTIFIER$2 `)` | IDENTIFIER `.hasOwnProperty(` IDENTIFIER$2 `)`))? `)`
126 )
127 (
128 EXPORTS_IDENTIFIER `[` IDENTIFIER$2 `] =` IDENTIFIER$1 `[` IDENTIFIER$2 `]` `;`? |
129 `Object.defineProperty(` EXPORTS_IDENTIFIER `, ` IDENTIFIER$2 `, { enumerable: true, get` (`: function` IDENTIFIER? )? `() { return ` IDENTIFIER$1 `[` IDENTIFIER$2 `]` `;`? `}` `,`? `})` `;`?
130 )
131 `})`
132```
133
134Spacing between tokens is taken to be any ECMA-262 whitespace, ECMA-262 block comment or ECMA-262 line comment.
135
136* The returned export names are taken to be the combination of:
137 1. All `IDENTIFIER` and `STRING_LITERAL` slots for `EXPORTS_MEMBER` and `EXPORTS_LITERAL` matches.
138 2. The first `STRING_LITERAL` slot for all `EXPORTS_DEFINE_VALUE` matches where that same string is not an `EXPORTS_DEFINE` match that is not also an `EXPORTS_DEFINE_VALUE` match.
139* The reexport specifiers are taken to be the combination of:
140 1. The `REQUIRE` matches of the last matched of either `MODULE_EXPORTS_ASSIGN` or `EXPORTS_LITERAL`.
141 2. All _top-level_ `EXPORT_STAR` `REQUIRE` matches and `EXPORTS_ASSIGN` matches whose `IDENTIFIER` also matches the first `IDENTIFIER` in `EXPORT_STAR_LIB`.
142
143### Parsing Examples
144
145#### Named Exports Parsing
146
147The basic matching rules for named exports are `exports.name`, `exports['name']` or `Object.defineProperty(exports, 'name', ...)`. This matching is done without scope analysis and regardless of the expression position:
148
149```js
150// DETECTS EXPORTS: a, b
151(function (exports) {
152 exports.a = 'a';
153 exports['b'] = 'b';
154})(exports);
155```
156
157Because there is no scope analysis, the above detection may overclassify:
158
159```js
160// DETECTS EXPORTS: a, b, c
161(function (exports, Object) {
162 exports.a = 'a';
163 exports['b'] = 'b';
164 if (false)
165 exports.c = 'c';
166})(NOT_EXPORTS, NOT_OBJECT);
167```
168
169It will in turn underclassify in cases where the identifiers are renamed:
170
171```js
172// DETECTS: NO EXPORTS
173(function (e) {
174 e.a = 'a';
175 e['b'] = 'b';
176})(exports);
177```
178
179#### Getter Exports Parsing
180
181`Object.defineProperty` is detected for specifically value and getter forms returning an identifier or member expression:
182
183```js
184// DETECTS: a, b, c, d, __esModule
185Object.defineProperty(exports, 'a', {
186 enumerable: true,
187 get: function () {
188 return q.p;
189 }
190});
191Object.defineProperty(exports, 'b', {
192 enumerable: true,
193 get: function () {
194 return q['p'];
195 }
196});
197Object.defineProperty(exports, 'c', {
198 enumerable: true,
199 get () {
200 return b;
201 }
202});
203Object.defineProperty(exports, 'd', { value: 'd' });
204Object.defineProperty(exports, '__esModule', { value: true });
205```
206
207Value properties are also detected specifically:
208
209```js
210Object.defineProperty(exports, 'a', {
211 value: 'no problem'
212});
213```
214
215To avoid matching getters that have side effects, any getter for an export name that does not support the forms above will
216opt-out of the getter matching:
217
218```js
219// DETECTS: NO EXPORTS
220Object.defineProperty(exports, 'a', {
221 get () {
222 return 'nope';
223 }
224});
225
226if (false) {
227 Object.defineProperty(module.exports, 'a', {
228 get () {
229 return dynamic();
230 }
231 })
232}
233```
234
235Alternative object definition structures or getter function bodies are not detected:
236
237```js
238// DETECTS: NO EXPORTS
239Object.defineProperty(exports, 'a', {
240 enumerable: false,
241 get () {
242 return p;
243 }
244});
245Object.defineProperty(exports, 'b', {
246 configurable: true,
247 get () {
248 return p;
249 }
250});
251Object.defineProperty(exports, 'c', {
252 get: () => p
253});
254Object.defineProperty(exports, 'd', {
255 enumerable: true,
256 get: function () {
257 return dynamic();
258 }
259});
260Object.defineProperty(exports, 'e', {
261 enumerable: true,
262 get () {
263 return 'str';
264 }
265});
266```
267
268`Object.defineProperties` is also not supported.
269
270#### Exports Object Assignment
271
272A best-effort is made to detect `module.exports` object assignments, but because this is not a full parser, arbitrary expressions are not handled in the
273object parsing process.
274
275Simple object definitions are supported:
276
277```js
278// DETECTS EXPORTS: a, b, c
279module.exports = {
280 a,
281 'b': b,
282 c: c,
283 ...d
284};
285```
286
287Object properties that are not identifiers or string expressions will bail out of the object detection, while spreads are ignored:
288
289```js
290// DETECTS EXPORTS: a, b
291module.exports = {
292 a,
293 ...d,
294 b: require('c'),
295 c: "not detected since require('c') above bails the object detection"
296}
297```
298
299`Object.defineProperties` is not currently supported either.
300
301#### module.exports reexport assignment
302
303Any `module.exports = require('mod')` assignment is detected as a reexport, but only the last one is returned:
304
305```js
306// DETECTS REEXPORTS: c
307module.exports = require('a');
308(module => module.exports = require('b'))(NOT_MODULE);
309if (false) module.exports = require('c');
310```
311
312This is to avoid over-classification in Webpack bundles with externals which include `module.exports = require('external')` in their source for every external dependency.
313
314In exports object assignment, any spread of `require()` are detected as multiple separate reexports:
315
316```js
317// DETECTS REEXPORTS: a, b
318module.exports = require('ignored');
319module.exports = {
320 ...require('a'),
321 ...require('b')
322};
323```
324
325#### Transpiler Re-exports
326
327For named exports, transpiler output works well with the rules described above.
328
329But for star re-exports, special care is taken to support common patterns of transpiler outputs from Babel and TypeScript as well as bundlers like RollupJS.
330These reexport and star reexport patterns are restricted to only be detected at the top-level as provided by the direct output of these tools.
331
332For example, `export * from 'external'` is output by Babel as:
333
334```js
335"use strict";
336
337exports.__esModule = true;
338
339var _external = require("external");
340
341Object.keys(_external).forEach(function (key) {
342 if (key === "default" || key === "__esModule") return;
343 exports[key] = _external[key];
344});
345```
346
347Where the `var _external = require("external")` is specifically detected as well as the `Object.keys(_external)` statement, down to the exact
348for of that entire expression including minor variations of the output. The `_external` and `key` identifiers are carefully matched in this
349detection.
350
351Similarly for TypeScript, `export * from 'external'` is output as:
352
353```js
354"use strict";
355function __export(m) {
356 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
357}
358Object.defineProperty(exports, "__esModule", { value: true });
359__export(require("external"));
360```
361
362Where the `__export(require("external"))` statement is explicitly detected as a reexport, including variations `tslib.__export` and `__exportStar`.
363
364### Environment Support
365
366Node.js 10+, and [all browsers with Web Assembly support](https://caniuse.com/#feat=wasm).
367
368### JS Grammar Support
369
370* Token state parses all line comments, block comments, strings, template strings, blocks, parens and punctuators.
371* Division operator / regex token ambiguity is handled via backtracking checks against punctuator prefixes, including closing brace or paren backtracking.
372* Always correctly parses valid JS source, but may parse invalid JS source without errors.
373
374### Benchmarks
375
376Benchmarks can be run with `npm run bench`.
377
378Current results:
379
380JS Build:
381
382```
383Module load time
384> 4ms
385Cold Run, All Samples
386test/samples/*.js (3635 KiB)
387> 299ms
388
389Warm Runs (average of 25 runs)
390test/samples/angular.js (1410 KiB)
391> 13.96ms
392test/samples/angular.min.js (303 KiB)
393> 4.72ms
394test/samples/d3.js (553 KiB)
395> 6.76ms
396test/samples/d3.min.js (250 KiB)
397> 4ms
398test/samples/magic-string.js (34 KiB)
399> 0.64ms
400test/samples/magic-string.min.js (20 KiB)
401> 0ms
402test/samples/rollup.js (698 KiB)
403> 8.48ms
404test/samples/rollup.min.js (367 KiB)
405> 5.36ms
406
407Warm Runs, All Samples (average of 25 runs)
408test/samples/*.js (3635 KiB)
409> 40.28ms
410```
411
412Wasm Build:
413```
414Module load time
415> 10ms
416Cold Run, All Samples
417test/samples/*.js (3635 KiB)
418> 43ms
419
420Warm Runs (average of 25 runs)
421test/samples/angular.js (1410 KiB)
422> 9.32ms
423test/samples/angular.min.js (303 KiB)
424> 3.16ms
425test/samples/d3.js (553 KiB)
426> 5ms
427test/samples/d3.min.js (250 KiB)
428> 2.32ms
429test/samples/magic-string.js (34 KiB)
430> 0.16ms
431test/samples/magic-string.min.js (20 KiB)
432> 0ms
433test/samples/rollup.js (698 KiB)
434> 6.28ms
435test/samples/rollup.min.js (367 KiB)
436> 3.6ms
437
438Warm Runs, All Samples (average of 25 runs)
439test/samples/*.js (3635 KiB)
440> 27.76ms
441```
442
443### Wasm Build Steps
444
445To build download the WASI SDK from https://github.com/WebAssembly/wasi-sdk/releases.
446
447The Makefile assumes the existence of "wasi-sdk-11.0" and "wabt" (optional) as sibling folders to this project.
448
449The build through the Makefile is then run via `make lib/lexer.wasm`, which can also be triggered via `npm run build-wasm` to create `dist/lexer.js`.
450
451On Windows it may be preferable to use the Linux subsystem.
452
453After the Web Assembly build, the CJS build can be triggered via `npm run build`.
454
455Optimization passes are run with [Binaryen](https://github.com/WebAssembly/binaryen) prior to publish to reduce the Web Assembly footprint.
456
457### License
458
459MIT
460
461[travis-url]: https://travis-ci.org/guybedford/es-module-lexer
462[travis-image]: https://travis-ci.org/guybedford/es-module-lexer.svg?branch=master
Note: See TracBrowser for help on using the repository browser.