@modern-js/node-bundle-require 2.0.0-beta.3 → 2.0.0-beta.6

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,74 @@
1
1
  # @modern-js/node-bundle-require
2
2
 
3
+ ## 2.0.0-beta.6
4
+
5
+ ### Major Changes
6
+
7
+ - dda38c9c3e: chore: v2
8
+
9
+ ### Patch Changes
10
+
11
+ - a2509bfbdb: feat: bump esbuild from 0.14.38 to 0.15.7
12
+
13
+ feat: 将 esbuild 从 0.14.38 版本升级至 0.15.7 版本
14
+
15
+ - Updated dependencies [7879e8f711]
16
+ - Updated dependencies [6aca875011]
17
+ - Updated dependencies [2e6031955e]
18
+ - Updated dependencies [7b7d12cf8f]
19
+ - Updated dependencies [7efeed4]
20
+ - Updated dependencies [92f0eade39]
21
+ - Updated dependencies [edd1cfb1af]
22
+ - Updated dependencies [cc971eabfc]
23
+ - Updated dependencies [5b9049f2e9]
24
+ - Updated dependencies [92004d1906]
25
+ - Updated dependencies [b8bbe036c7]
26
+ - Updated dependencies [d5a31df781]
27
+ - Updated dependencies [dda38c9c3e]
28
+ - Updated dependencies [3bbea92b2a]
29
+ - Updated dependencies [b710adb843]
30
+ - Updated dependencies [ea7cf06257]
31
+ - Updated dependencies [bbe4c4ab64]
32
+ - Updated dependencies [e4558a0bc4]
33
+ - Updated dependencies [abf3421a75]
34
+ - Updated dependencies [543be9558e]
35
+ - Updated dependencies [14b712da84]
36
+ - @modern-js/utils@2.0.0-beta.6
37
+
38
+ ## 2.0.0-beta.4
39
+
40
+ ### Major Changes
41
+
42
+ - dda38c9c3e: chore: v2
43
+
44
+ ### Patch Changes
45
+
46
+ - a2509bfbdb: feat: bump esbuild from 0.14.38 to 0.15.7
47
+
48
+ feat: 将 esbuild 从 0.14.38 版本升级至 0.15.7 版本
49
+
50
+ - Updated dependencies [7879e8f]
51
+ - Updated dependencies [6aca875]
52
+ - Updated dependencies [2e6031955e]
53
+ - Updated dependencies [7b7d12c]
54
+ - Updated dependencies [92f0eade39]
55
+ - Updated dependencies [edd1cfb1af]
56
+ - Updated dependencies [cc971eabfc]
57
+ - Updated dependencies [5b9049f2e9]
58
+ - Updated dependencies [92004d1906]
59
+ - Updated dependencies [b8bbe036c7]
60
+ - Updated dependencies [d5a31df781]
61
+ - Updated dependencies [dda38c9c3e]
62
+ - Updated dependencies [3bbea92b2a]
63
+ - Updated dependencies [b710adb843]
64
+ - Updated dependencies [ea7cf06]
65
+ - Updated dependencies [bbe4c4a]
66
+ - Updated dependencies [e4558a0]
67
+ - Updated dependencies [abf3421a75]
68
+ - Updated dependencies [543be9558e]
69
+ - Updated dependencies [14b712da84]
70
+ - @modern-js/utils@2.0.0-beta.4
71
+
3
72
  ## 2.0.0-beta.3
4
73
 
5
74
  ### Major Changes
@@ -1,145 +1,172 @@
1
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
4
- import path from 'path';
5
- import { fs, pkgUp, nanoid, CONFIG_CACHE_DIR, createDebugger } from '@modern-js/utils';
6
- import { build } from 'esbuild';
7
- const debug = createDebugger('node-bundle');
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
28
+ };
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
39
+ };
40
+ import path from "path";
41
+ import {
42
+ fs,
43
+ pkgUp,
44
+ nanoid,
45
+ CONFIG_CACHE_DIR,
46
+ createDebugger
47
+ } from "@modern-js/utils";
48
+ import { build } from "esbuild";
49
+ const debug = createDebugger("node-bundle");
8
50
  const JS_EXT_RE = /\.(mjs|cjs|ts|js|tsx|jsx)$/;
9
51
  const BUNDLED_EXT_RE = /\.(ts|mts|cts|tsx|mjs)$/;
10
-
11
- // Must not start with "/" or "./" or "../"
12
- // "/test/node_modules/foo"
13
- // "c:/node_modules/foo"
14
- export const EXTERNAL_REGEXP = /^[^./]|^\.[^./]|^\.\.[^/]/;
52
+ const EXTERNAL_REGEXP = /^[^./]|^\.[^./]|^\.\.[^/]/;
15
53
  function inferLoader(ext) {
16
- if (ext === '.mjs' || ext === '.cjs') {
17
- return 'js';
54
+ if (ext === ".mjs" || ext === ".cjs") {
55
+ return "js";
18
56
  }
19
57
  return ext.slice(1);
20
58
  }
21
- async function isTypeModulePkg(cwd) {
22
- const pkgJsonPath = await pkgUp({
23
- cwd
59
+ function isTypeModulePkg(cwd) {
60
+ return __async(this, null, function* () {
61
+ const pkgJsonPath = yield pkgUp({ cwd });
62
+ if (pkgJsonPath) {
63
+ const pkgJson = yield fs.readJSON(pkgJsonPath);
64
+ return pkgJson.type === "module";
65
+ }
66
+ return false;
24
67
  });
25
- if (pkgJsonPath) {
26
- const pkgJson = await fs.readJSON(pkgJsonPath);
27
- return pkgJson.type === 'module';
28
- }
29
- return false;
30
68
  }
31
- export const defaultGetOutputFile = async filepath => path.resolve(CONFIG_CACHE_DIR, `${filepath}-${Date.now()}.${nanoid()}.bundled.cjs`);
32
- export async function bundle(filepath, options) {
33
- if (!JS_EXT_RE.test(filepath)) {
34
- throw new Error(`${filepath} is not a valid JS file`);
35
- }
36
- debug('bundle', filepath, options);
37
- const getOutputFile = (options === null || options === void 0 ? void 0 : options.getOutputFile) || defaultGetOutputFile;
38
- const outfile = await getOutputFile(path.basename(filepath));
39
- await build(_objectSpread(_objectSpread({
40
- entryPoints: [filepath],
41
- outfile,
42
- format: 'cjs',
43
- platform: 'node',
44
- bundle: true,
45
- // fix transforming error when the project's tsconfig.json
46
- // sets `target: "es5"`
47
- // reference: https://github.com/evanw/esbuild/releases/tag/v0.12.6
48
- target: 'esnext'
49
- }, options === null || options === void 0 ? void 0 : options.esbuildOptions), {}, {
50
- plugins: [...((options === null || options === void 0 ? void 0 : options.esbuildPlugins) || []),
51
- // https://github.com/evanw/esbuild/issues/1051#issuecomment-806325487
52
- {
53
- name: 'native-node-modules',
54
- setup(build) {
55
- // If a ".node" file is imported within a module in the "file" namespace, resolve
56
- // it to an absolute path and put it into the "node-file" virtual namespace.
57
- build.onResolve({
58
- filter: /\.node$/,
59
- namespace: 'file'
60
- }, args => ({
61
- path: require.resolve(args.path, {
62
- paths: [args.resolveDir]
63
- }),
64
- namespace: 'node-file'
65
- }));
66
-
67
- // Files in the "node-file" virtual namespace call "require()" on the
68
- // path from esbuild of the ".node" file in the output directory.
69
- build.onLoad({
70
- filter: /.*/,
71
- namespace: 'node-file'
72
- }, args => ({
73
- contents: `
69
+ const defaultGetOutputFile = (filepath) => __async(void 0, null, function* () {
70
+ return path.resolve(
71
+ CONFIG_CACHE_DIR,
72
+ `${filepath}-${Date.now()}.${nanoid()}.bundled.cjs`
73
+ );
74
+ });
75
+ function bundle(filepath, options) {
76
+ return __async(this, null, function* () {
77
+ if (!JS_EXT_RE.test(filepath)) {
78
+ throw new Error(`${filepath} is not a valid JS file`);
79
+ }
80
+ debug("bundle", filepath, options);
81
+ const getOutputFile = (options == null ? void 0 : options.getOutputFile) || defaultGetOutputFile;
82
+ const outfile = yield getOutputFile(path.basename(filepath));
83
+ yield build(__spreadProps(__spreadValues({
84
+ entryPoints: [filepath],
85
+ outfile,
86
+ format: "cjs",
87
+ platform: "node",
88
+ bundle: true,
89
+ target: "esnext"
90
+ }, options == null ? void 0 : options.esbuildOptions), {
91
+ plugins: [
92
+ ...(options == null ? void 0 : options.esbuildPlugins) || [],
93
+ {
94
+ name: "native-node-modules",
95
+ setup(build2) {
96
+ build2.onResolve({ filter: /\.node$/, namespace: "file" }, (args) => ({
97
+ path: require.resolve(args.path, { paths: [args.resolveDir] }),
98
+ namespace: "node-file"
99
+ }));
100
+ build2.onLoad({ filter: /.*/, namespace: "node-file" }, (args) => ({
101
+ contents: `
74
102
  import path from ${JSON.stringify(args.path)}
75
103
  try { module.exports = require(path) }
76
104
  catch {}
77
105
  `
78
- }));
79
-
80
- // If a ".node" file is imported within a module in the "node-file" namespace, put
81
- // it in the "file" namespace where esbuild's default loading behavior will handle
82
- // it. It is already an absolute path since we resolved it to one above.
83
- build.onResolve({
84
- filter: /\.node$/,
85
- namespace: 'node-file'
86
- }, args => ({
87
- path: args.path,
88
- namespace: 'file'
89
- }));
90
-
91
- // Tell esbuild's default loading behavior to use the "file" loader for
92
- // these ".node" files.
93
- const opts = build.initialOptions;
94
- opts.loader = opts.loader || {};
95
- opts.loader['.node'] = 'file';
96
- }
97
- }, {
98
- name: 'replace-path',
99
- setup(ctx) {
100
- ctx.onLoad({
101
- filter: JS_EXT_RE
102
- }, async args => {
103
- const contents = fs.readFileSync(args.path, 'utf-8');
104
- return {
105
- contents: contents.replace(/\b__filename\b/g, JSON.stringify(args.path)).replace(/\b__dirname\b/g, JSON.stringify(path.dirname(args.path))).replace(/\bimport\.meta\.url\b/g, JSON.stringify(`file://${args.path}`)),
106
- loader: inferLoader(path.extname(args.path))
107
- };
108
- });
109
- }
110
- },
111
- // https://github.com/evanw/esbuild/issues/619#issuecomment-751995294
112
- {
113
- name: 'make-all-packages-external',
114
- setup(_build) {
115
- _build.onResolve({
116
- filter: EXTERNAL_REGEXP
117
- }, async args => {
118
- let external = true;
119
- // FIXME: windows external entrypoint
120
- if (args.kind === 'entry-point') {
121
- external = false;
106
+ }));
107
+ build2.onResolve(
108
+ { filter: /\.node$/, namespace: "node-file" },
109
+ (args) => ({
110
+ path: args.path,
111
+ namespace: "file"
112
+ })
113
+ );
114
+ const opts = build2.initialOptions;
115
+ opts.loader = opts.loader || {};
116
+ opts.loader[".node"] = "file";
122
117
  }
123
- try {
124
- const resolvedPath = require.resolve(args.path, {
125
- paths: [args.resolveDir]
126
- });
127
- // If it is a typescript or esm package, we should bundle it.
128
- if (BUNDLED_EXT_RE.test(resolvedPath) || (await isTypeModulePkg(resolvedPath))) {
118
+ },
119
+ {
120
+ name: "replace-path",
121
+ setup(ctx) {
122
+ ctx.onLoad({ filter: JS_EXT_RE }, (args) => __async(this, null, function* () {
123
+ const contents = fs.readFileSync(args.path, "utf-8");
129
124
  return {
130
- external: false
125
+ contents: contents.replace(/\b__filename\b/g, JSON.stringify(args.path)).replace(
126
+ /\b__dirname\b/g,
127
+ JSON.stringify(path.dirname(args.path))
128
+ ).replace(
129
+ /\bimport\.meta\.url\b/g,
130
+ JSON.stringify(`file://${args.path}`)
131
+ ),
132
+ loader: inferLoader(path.extname(args.path))
131
133
  };
132
- }
133
- } catch (err) {
134
- // If the package can not be resolved, do nothing.
134
+ }));
135
135
  }
136
- return {
137
- path: args.path,
138
- external
139
- };
140
- });
141
- }
142
- }]
143
- }));
144
- return outfile;
145
- }
136
+ },
137
+ {
138
+ name: "make-all-packages-external",
139
+ setup(_build) {
140
+ _build.onResolve({ filter: EXTERNAL_REGEXP }, (args) => __async(this, null, function* () {
141
+ let external = true;
142
+ if (args.kind === "entry-point") {
143
+ external = false;
144
+ }
145
+ try {
146
+ const resolvedPath = require.resolve(args.path, {
147
+ paths: [args.resolveDir]
148
+ });
149
+ if (BUNDLED_EXT_RE.test(resolvedPath) || (yield isTypeModulePkg(resolvedPath))) {
150
+ return {
151
+ external: false
152
+ };
153
+ }
154
+ } catch (err) {
155
+ }
156
+ return {
157
+ path: args.path,
158
+ external
159
+ };
160
+ }));
161
+ }
162
+ }
163
+ ]
164
+ }));
165
+ return outfile;
166
+ });
167
+ }
168
+ export {
169
+ EXTERNAL_REGEXP,
170
+ bundle,
171
+ defaultGetOutputFile
172
+ };
@@ -1,30 +1,51 @@
1
- import { fs } from '@modern-js/utils';
1
+ var __async = (__this, __arguments, generator) => {
2
+ return new Promise((resolve, reject) => {
3
+ var fulfilled = (value) => {
4
+ try {
5
+ step(generator.next(value));
6
+ } catch (e) {
7
+ reject(e);
8
+ }
9
+ };
10
+ var rejected = (value) => {
11
+ try {
12
+ step(generator.throw(value));
13
+ } catch (e) {
14
+ reject(e);
15
+ }
16
+ };
17
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
18
+ step((generator = generator.apply(__this, __arguments)).next());
19
+ });
20
+ };
21
+ import { fs } from "@modern-js/utils";
2
22
  import { bundle, defaultGetOutputFile } from "./bundle";
3
- export { bundle, defaultGetOutputFile };
4
23
  function deleteRequireCache(path) {
5
24
  if (require.cache[path]) {
6
25
  delete require.cache[path];
7
26
  }
8
27
  if (module.children) {
9
- module.children = module.children.filter(item => item.filename !== path);
28
+ module.children = module.children.filter((item) => item.filename !== path);
10
29
  }
11
30
  }
12
- export async function bundleRequire(filepath, options) {
13
- const configFile = await bundle(filepath, options);
14
- let mod;
15
- const req = (options === null || options === void 0 ? void 0 : options.require) || require;
16
- try {
17
- mod = await req(configFile);
18
-
19
- // Webpack will check require history for persistent cache.
20
- // If webpack can not resolve the file, the previous cache pack will become invalid.
21
- // The bundled file is temporary, so we should clear the require history to avoid breaking the webpack cache.
22
- deleteRequireCache(configFile);
23
- } finally {
24
- // default auto clear configFile
25
- if ((options === null || options === void 0 ? void 0 : options.autoClear) === undefined || options.autoClear) {
26
- fs.unlinkSync(configFile);
31
+ function bundleRequire(filepath, options) {
32
+ return __async(this, null, function* () {
33
+ const configFile = yield bundle(filepath, options);
34
+ let mod;
35
+ const req = (options == null ? void 0 : options.require) || require;
36
+ try {
37
+ mod = yield req(configFile);
38
+ deleteRequireCache(configFile);
39
+ } finally {
40
+ if ((options == null ? void 0 : options.autoClear) === void 0 || options.autoClear) {
41
+ fs.unlinkSync(configFile);
42
+ }
27
43
  }
28
- }
29
- return mod;
30
- }
44
+ return mod;
45
+ });
46
+ }
47
+ export {
48
+ bundle,
49
+ bundleRequire,
50
+ defaultGetOutputFile
51
+ };
File without changes
@@ -1,156 +1,195 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __export = (target, all) => {
25
+ for (var name in all)
26
+ __defProp(target, name, { get: all[name], enumerable: true });
27
+ };
28
+ var __copyProps = (to, from, except, desc) => {
29
+ if (from && typeof from === "object" || typeof from === "function") {
30
+ for (let key of __getOwnPropNames(from))
31
+ if (!__hasOwnProp.call(to, key) && key !== except)
32
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
33
+ }
34
+ return to;
35
+ };
36
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
37
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
+ mod
39
+ ));
40
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
41
+ var __async = (__this, __arguments, generator) => {
42
+ return new Promise((resolve, reject) => {
43
+ var fulfilled = (value) => {
44
+ try {
45
+ step(generator.next(value));
46
+ } catch (e) {
47
+ reject(e);
48
+ }
49
+ };
50
+ var rejected = (value) => {
51
+ try {
52
+ step(generator.throw(value));
53
+ } catch (e) {
54
+ reject(e);
55
+ }
56
+ };
57
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
58
+ step((generator = generator.apply(__this, __arguments)).next());
59
+ });
60
+ };
61
+ var bundle_exports = {};
62
+ __export(bundle_exports, {
63
+ EXTERNAL_REGEXP: () => EXTERNAL_REGEXP,
64
+ bundle: () => bundle,
65
+ defaultGetOutputFile: () => defaultGetOutputFile
5
66
  });
6
- exports.EXTERNAL_REGEXP = void 0;
7
- exports.bundle = bundle;
8
- exports.defaultGetOutputFile = void 0;
9
- var _path = _interopRequireDefault(require("path"));
10
- var _utils = require("@modern-js/utils");
11
- var _esbuild = require("esbuild");
12
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
14
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
15
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
16
- const debug = (0, _utils.createDebugger)('node-bundle');
67
+ module.exports = __toCommonJS(bundle_exports);
68
+ var import_path = __toESM(require("path"));
69
+ var import_utils = require("@modern-js/utils");
70
+ var import_esbuild = require("esbuild");
71
+ const debug = (0, import_utils.createDebugger)("node-bundle");
17
72
  const JS_EXT_RE = /\.(mjs|cjs|ts|js|tsx|jsx)$/;
18
73
  const BUNDLED_EXT_RE = /\.(ts|mts|cts|tsx|mjs)$/;
19
-
20
- // Must not start with "/" or "./" or "../"
21
- // "/test/node_modules/foo"
22
- // "c:/node_modules/foo"
23
74
  const EXTERNAL_REGEXP = /^[^./]|^\.[^./]|^\.\.[^/]/;
24
- exports.EXTERNAL_REGEXP = EXTERNAL_REGEXP;
25
75
  function inferLoader(ext) {
26
- if (ext === '.mjs' || ext === '.cjs') {
27
- return 'js';
76
+ if (ext === ".mjs" || ext === ".cjs") {
77
+ return "js";
28
78
  }
29
79
  return ext.slice(1);
30
80
  }
31
- async function isTypeModulePkg(cwd) {
32
- const pkgJsonPath = await (0, _utils.pkgUp)({
33
- cwd
81
+ function isTypeModulePkg(cwd) {
82
+ return __async(this, null, function* () {
83
+ const pkgJsonPath = yield (0, import_utils.pkgUp)({ cwd });
84
+ if (pkgJsonPath) {
85
+ const pkgJson = yield import_utils.fs.readJSON(pkgJsonPath);
86
+ return pkgJson.type === "module";
87
+ }
88
+ return false;
34
89
  });
35
- if (pkgJsonPath) {
36
- const pkgJson = await _utils.fs.readJSON(pkgJsonPath);
37
- return pkgJson.type === 'module';
38
- }
39
- return false;
40
90
  }
41
- const defaultGetOutputFile = async filepath => _path.default.resolve(_utils.CONFIG_CACHE_DIR, `${filepath}-${Date.now()}.${(0, _utils.nanoid)()}.bundled.cjs`);
42
- exports.defaultGetOutputFile = defaultGetOutputFile;
43
- async function bundle(filepath, options) {
44
- if (!JS_EXT_RE.test(filepath)) {
45
- throw new Error(`${filepath} is not a valid JS file`);
46
- }
47
- debug('bundle', filepath, options);
48
- const getOutputFile = (options === null || options === void 0 ? void 0 : options.getOutputFile) || defaultGetOutputFile;
49
- const outfile = await getOutputFile(_path.default.basename(filepath));
50
- await (0, _esbuild.build)(_objectSpread(_objectSpread({
51
- entryPoints: [filepath],
52
- outfile,
53
- format: 'cjs',
54
- platform: 'node',
55
- bundle: true,
56
- // fix transforming error when the project's tsconfig.json
57
- // sets `target: "es5"`
58
- // reference: https://github.com/evanw/esbuild/releases/tag/v0.12.6
59
- target: 'esnext'
60
- }, options === null || options === void 0 ? void 0 : options.esbuildOptions), {}, {
61
- plugins: [...((options === null || options === void 0 ? void 0 : options.esbuildPlugins) || []),
62
- // https://github.com/evanw/esbuild/issues/1051#issuecomment-806325487
63
- {
64
- name: 'native-node-modules',
65
- setup(build) {
66
- // If a ".node" file is imported within a module in the "file" namespace, resolve
67
- // it to an absolute path and put it into the "node-file" virtual namespace.
68
- build.onResolve({
69
- filter: /\.node$/,
70
- namespace: 'file'
71
- }, args => ({
72
- path: require.resolve(args.path, {
73
- paths: [args.resolveDir]
74
- }),
75
- namespace: 'node-file'
76
- }));
77
-
78
- // Files in the "node-file" virtual namespace call "require()" on the
79
- // path from esbuild of the ".node" file in the output directory.
80
- build.onLoad({
81
- filter: /.*/,
82
- namespace: 'node-file'
83
- }, args => ({
84
- contents: `
91
+ const defaultGetOutputFile = (filepath) => __async(void 0, null, function* () {
92
+ return import_path.default.resolve(
93
+ import_utils.CONFIG_CACHE_DIR,
94
+ `${filepath}-${Date.now()}.${(0, import_utils.nanoid)()}.bundled.cjs`
95
+ );
96
+ });
97
+ function bundle(filepath, options) {
98
+ return __async(this, null, function* () {
99
+ if (!JS_EXT_RE.test(filepath)) {
100
+ throw new Error(`${filepath} is not a valid JS file`);
101
+ }
102
+ debug("bundle", filepath, options);
103
+ const getOutputFile = (options == null ? void 0 : options.getOutputFile) || defaultGetOutputFile;
104
+ const outfile = yield getOutputFile(import_path.default.basename(filepath));
105
+ yield (0, import_esbuild.build)(__spreadProps(__spreadValues({
106
+ entryPoints: [filepath],
107
+ outfile,
108
+ format: "cjs",
109
+ platform: "node",
110
+ bundle: true,
111
+ target: "esnext"
112
+ }, options == null ? void 0 : options.esbuildOptions), {
113
+ plugins: [
114
+ ...(options == null ? void 0 : options.esbuildPlugins) || [],
115
+ {
116
+ name: "native-node-modules",
117
+ setup(build2) {
118
+ build2.onResolve({ filter: /\.node$/, namespace: "file" }, (args) => ({
119
+ path: require.resolve(args.path, { paths: [args.resolveDir] }),
120
+ namespace: "node-file"
121
+ }));
122
+ build2.onLoad({ filter: /.*/, namespace: "node-file" }, (args) => ({
123
+ contents: `
85
124
  import path from ${JSON.stringify(args.path)}
86
125
  try { module.exports = require(path) }
87
126
  catch {}
88
127
  `
89
- }));
90
-
91
- // If a ".node" file is imported within a module in the "node-file" namespace, put
92
- // it in the "file" namespace where esbuild's default loading behavior will handle
93
- // it. It is already an absolute path since we resolved it to one above.
94
- build.onResolve({
95
- filter: /\.node$/,
96
- namespace: 'node-file'
97
- }, args => ({
98
- path: args.path,
99
- namespace: 'file'
100
- }));
101
-
102
- // Tell esbuild's default loading behavior to use the "file" loader for
103
- // these ".node" files.
104
- const opts = build.initialOptions;
105
- opts.loader = opts.loader || {};
106
- opts.loader['.node'] = 'file';
107
- }
108
- }, {
109
- name: 'replace-path',
110
- setup(ctx) {
111
- ctx.onLoad({
112
- filter: JS_EXT_RE
113
- }, async args => {
114
- const contents = _utils.fs.readFileSync(args.path, 'utf-8');
115
- return {
116
- contents: contents.replace(/\b__filename\b/g, JSON.stringify(args.path)).replace(/\b__dirname\b/g, JSON.stringify(_path.default.dirname(args.path))).replace(/\bimport\.meta\.url\b/g, JSON.stringify(`file://${args.path}`)),
117
- loader: inferLoader(_path.default.extname(args.path))
118
- };
119
- });
120
- }
121
- },
122
- // https://github.com/evanw/esbuild/issues/619#issuecomment-751995294
123
- {
124
- name: 'make-all-packages-external',
125
- setup(_build) {
126
- _build.onResolve({
127
- filter: EXTERNAL_REGEXP
128
- }, async args => {
129
- let external = true;
130
- // FIXME: windows external entrypoint
131
- if (args.kind === 'entry-point') {
132
- external = false;
128
+ }));
129
+ build2.onResolve(
130
+ { filter: /\.node$/, namespace: "node-file" },
131
+ (args) => ({
132
+ path: args.path,
133
+ namespace: "file"
134
+ })
135
+ );
136
+ const opts = build2.initialOptions;
137
+ opts.loader = opts.loader || {};
138
+ opts.loader[".node"] = "file";
133
139
  }
134
- try {
135
- const resolvedPath = require.resolve(args.path, {
136
- paths: [args.resolveDir]
137
- });
138
- // If it is a typescript or esm package, we should bundle it.
139
- if (BUNDLED_EXT_RE.test(resolvedPath) || (await isTypeModulePkg(resolvedPath))) {
140
+ },
141
+ {
142
+ name: "replace-path",
143
+ setup(ctx) {
144
+ ctx.onLoad({ filter: JS_EXT_RE }, (args) => __async(this, null, function* () {
145
+ const contents = import_utils.fs.readFileSync(args.path, "utf-8");
140
146
  return {
141
- external: false
147
+ contents: contents.replace(/\b__filename\b/g, JSON.stringify(args.path)).replace(
148
+ /\b__dirname\b/g,
149
+ JSON.stringify(import_path.default.dirname(args.path))
150
+ ).replace(
151
+ /\bimport\.meta\.url\b/g,
152
+ JSON.stringify(`file://${args.path}`)
153
+ ),
154
+ loader: inferLoader(import_path.default.extname(args.path))
142
155
  };
143
- }
144
- } catch (err) {
145
- // If the package can not be resolved, do nothing.
156
+ }));
146
157
  }
147
- return {
148
- path: args.path,
149
- external
150
- };
151
- });
152
- }
153
- }]
154
- }));
155
- return outfile;
156
- }
158
+ },
159
+ {
160
+ name: "make-all-packages-external",
161
+ setup(_build) {
162
+ _build.onResolve({ filter: EXTERNAL_REGEXP }, (args) => __async(this, null, function* () {
163
+ let external = true;
164
+ if (args.kind === "entry-point") {
165
+ external = false;
166
+ }
167
+ try {
168
+ const resolvedPath = require.resolve(args.path, {
169
+ paths: [args.resolveDir]
170
+ });
171
+ if (BUNDLED_EXT_RE.test(resolvedPath) || (yield isTypeModulePkg(resolvedPath))) {
172
+ return {
173
+ external: false
174
+ };
175
+ }
176
+ } catch (err) {
177
+ }
178
+ return {
179
+ path: args.path,
180
+ external
181
+ };
182
+ }));
183
+ }
184
+ }
185
+ ]
186
+ }));
187
+ return outfile;
188
+ });
189
+ }
190
+ // Annotate the CommonJS export names for ESM import in node:
191
+ 0 && (module.exports = {
192
+ EXTERNAL_REGEXP,
193
+ bundle,
194
+ defaultGetOutputFile
195
+ });
@@ -1,47 +1,76 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- Object.defineProperty(exports, "bundle", {
7
- enumerable: true,
8
- get: function () {
9
- return _bundle.bundle;
10
- }
11
- });
12
- exports.bundleRequire = bundleRequire;
13
- Object.defineProperty(exports, "defaultGetOutputFile", {
14
- enumerable: true,
15
- get: function () {
16
- return _bundle.defaultGetOutputFile;
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
14
  }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var __async = (__this, __arguments, generator) => {
19
+ return new Promise((resolve, reject) => {
20
+ var fulfilled = (value) => {
21
+ try {
22
+ step(generator.next(value));
23
+ } catch (e) {
24
+ reject(e);
25
+ }
26
+ };
27
+ var rejected = (value) => {
28
+ try {
29
+ step(generator.throw(value));
30
+ } catch (e) {
31
+ reject(e);
32
+ }
33
+ };
34
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
35
+ step((generator = generator.apply(__this, __arguments)).next());
36
+ });
37
+ };
38
+ var src_exports = {};
39
+ __export(src_exports, {
40
+ bundle: () => import_bundle.bundle,
41
+ bundleRequire: () => bundleRequire,
42
+ defaultGetOutputFile: () => import_bundle.defaultGetOutputFile
18
43
  });
19
- var _utils = require("@modern-js/utils");
20
- var _bundle = require("./bundle");
44
+ module.exports = __toCommonJS(src_exports);
45
+ var import_utils = require("@modern-js/utils");
46
+ var import_bundle = require("./bundle");
21
47
  function deleteRequireCache(path) {
22
48
  if (require.cache[path]) {
23
49
  delete require.cache[path];
24
50
  }
25
51
  if (module.children) {
26
- module.children = module.children.filter(item => item.filename !== path);
52
+ module.children = module.children.filter((item) => item.filename !== path);
27
53
  }
28
54
  }
29
- async function bundleRequire(filepath, options) {
30
- const configFile = await (0, _bundle.bundle)(filepath, options);
31
- let mod;
32
- const req = (options === null || options === void 0 ? void 0 : options.require) || require;
33
- try {
34
- mod = await req(configFile);
35
-
36
- // Webpack will check require history for persistent cache.
37
- // If webpack can not resolve the file, the previous cache pack will become invalid.
38
- // The bundled file is temporary, so we should clear the require history to avoid breaking the webpack cache.
39
- deleteRequireCache(configFile);
40
- } finally {
41
- // default auto clear configFile
42
- if ((options === null || options === void 0 ? void 0 : options.autoClear) === undefined || options.autoClear) {
43
- _utils.fs.unlinkSync(configFile);
55
+ function bundleRequire(filepath, options) {
56
+ return __async(this, null, function* () {
57
+ const configFile = yield (0, import_bundle.bundle)(filepath, options);
58
+ let mod;
59
+ const req = (options == null ? void 0 : options.require) || require;
60
+ try {
61
+ mod = yield req(configFile);
62
+ deleteRequireCache(configFile);
63
+ } finally {
64
+ if ((options == null ? void 0 : options.autoClear) === void 0 || options.autoClear) {
65
+ import_utils.fs.unlinkSync(configFile);
66
+ }
44
67
  }
45
- }
46
- return mod;
47
- }
68
+ return mod;
69
+ });
70
+ }
71
+ // Annotate the CommonJS export names for ESM import in node:
72
+ 0 && (module.exports = {
73
+ bundle,
74
+ bundleRequire,
75
+ defaultGetOutputFile
76
+ });
File without changes
@@ -10,19 +10,23 @@ export interface Options {
10
10
  /**
11
11
  * esbuild options
12
12
  */
13
+
13
14
  esbuildOptions?: BuildOptions;
14
15
  /**
15
16
  * esbuild plugin
16
17
  */
18
+
17
19
  esbuildPlugins?: Plugin[];
18
20
  /**
19
21
  * Get the path to the output file
20
22
  * By default we simply replace the extension with `.bundled.cjs`
21
23
  */
24
+
22
25
  getOutputFile?: (filepath: string) => Promise<string>;
23
26
  /**
24
27
  * auto clear bundle file
25
28
  */
29
+
26
30
  autoClear?: boolean;
27
31
  }
28
32
  export declare const defaultGetOutputFile: (filepath: string) => Promise<string>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@modern-js/node-bundle-require",
3
- "version": "2.0.0-beta.3",
3
+ "version": "2.0.0-beta.6",
4
4
  "description": "The meta-framework suite designed from scratch for frontend-focused modern web development.",
5
5
  "homepage": "https://modernjs.dev",
6
6
  "bugs": "https://github.com/modern-js-dev/modern.js/issues",
@@ -40,15 +40,15 @@
40
40
  "dependencies": {
41
41
  "@babel/runtime": "^7.18.0",
42
42
  "esbuild": "0.15.7",
43
- "@modern-js/utils": "2.0.0-beta.3"
43
+ "@modern-js/utils": "2.0.0-beta.6"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@types/jest": "^27",
47
47
  "@types/node": "^14",
48
48
  "jest": "^27",
49
49
  "typescript": "^4",
50
- "@scripts/build": "2.0.0-beta.3",
51
- "@scripts/jest-config": "2.0.0-beta.3"
50
+ "@scripts/build": "2.0.0-beta.6",
51
+ "@scripts/jest-config": "2.0.0-beta.6"
52
52
  },
53
53
  "sideEffects": false,
54
54
  "publishConfig": {