vite-node 0.1.16 → 0.1.20

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/client.d.ts CHANGED
@@ -2,6 +2,7 @@ declare type FetchFunction = (id: string) => Promise<{
2
2
  code?: string;
3
3
  externalize?: string;
4
4
  }>;
5
+ declare type ResolveIdFunction = (id: string, importer?: string) => Promise<ViteNodeResolveId | null>;
5
6
  interface ModuleCache {
6
7
  promise?: Promise<any>;
7
8
  exports?: any;
@@ -9,12 +10,20 @@ interface ModuleCache {
9
10
  }
10
11
  interface ViteNodeRunnerOptions {
11
12
  fetchModule: FetchFunction;
13
+ resolveId: ResolveIdFunction;
12
14
  root: string;
13
15
  base?: string;
14
16
  moduleCache?: Map<string, ModuleCache>;
15
17
  interpretDefault?: boolean;
16
18
  requestStubs?: Record<string, any>;
17
19
  }
20
+ interface ViteNodeResolveId {
21
+ external?: boolean | 'absolute' | 'relative';
22
+ id: string;
23
+ meta?: Record<string, any> | null;
24
+ moduleSideEffects?: boolean | 'no-treeshake' | null;
25
+ syntheticNamedExports?: boolean | string | null;
26
+ }
18
27
 
19
28
  declare class ViteNodeRunner {
20
29
  options: ViteNodeRunnerOptions;
package/dist/cli.cjs ADDED
@@ -0,0 +1,406 @@
1
+ 'use strict';
2
+
3
+ var minimist = require('minimist');
4
+ var kolorist = require('kolorist');
5
+ var vite = require('vite');
6
+ var fs = require('fs');
7
+ var mlly = require('mlly');
8
+ var url = require('url');
9
+ var pathe = require('pathe');
10
+ var module$1 = require('module');
11
+ var vm = require('vm');
12
+
13
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
+
15
+ function _interopNamespace(e) {
16
+ if (e && e.__esModule) return e;
17
+ var n = Object.create(null);
18
+ if (e) {
19
+ Object.keys(e).forEach(function (k) {
20
+ if (k !== 'default') {
21
+ var d = Object.getOwnPropertyDescriptor(e, k);
22
+ Object.defineProperty(n, k, d.get ? d : {
23
+ enumerable: true,
24
+ get: function () { return e[k]; }
25
+ });
26
+ }
27
+ });
28
+ }
29
+ n["default"] = e;
30
+ return Object.freeze(n);
31
+ }
32
+
33
+ var minimist__default = /*#__PURE__*/_interopDefaultLegacy(minimist);
34
+ var vm__default = /*#__PURE__*/_interopDefaultLegacy(vm);
35
+
36
+ const isWindows = process.platform === "win32";
37
+ function slash(str) {
38
+ return str.replace(/\\/g, "/");
39
+ }
40
+ function normalizeId(id, base) {
41
+ if (base && id.startsWith(base))
42
+ id = `/${id.slice(base.length)}`;
43
+ return id.replace(/^\/@id\/__x00__/, "\0").replace(/^\/@id\//, "").replace(/^__vite-browser-external:/, "").replace(/^node:/, "").replace(/[?&]v=\w+/, "?").replace(/\?$/, "");
44
+ }
45
+ function isPrimitive(v) {
46
+ return v !== Object(v);
47
+ }
48
+ function toFilePath(id, root) {
49
+ let absolute = slash(id).startsWith("/@fs/") ? id.slice(4) : id.startsWith(pathe.dirname(root)) && pathe.dirname(root) !== "/" ? id : id.startsWith("/") ? slash(pathe.resolve(root, id.slice(1))) : id;
50
+ if (absolute.startsWith("//"))
51
+ absolute = absolute.slice(1);
52
+ return isWindows && absolute.startsWith("/") ? url.fileURLToPath(url.pathToFileURL(absolute.slice(1)).href) : absolute;
53
+ }
54
+
55
+ const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
56
+ const ESM_FOLDER_RE = /\/esm\/(.*\.js)$/;
57
+ const defaultInline = [
58
+ /\/vitest\/dist\//,
59
+ /vitest-virtual-\w+\/dist/,
60
+ /virtual:/,
61
+ /\.ts$/,
62
+ ESM_EXT_RE,
63
+ ESM_FOLDER_RE
64
+ ];
65
+ const depsExternal = [
66
+ /\.cjs.js$/,
67
+ /\.mjs$/
68
+ ];
69
+ function guessCJSversion(id) {
70
+ if (id.match(ESM_EXT_RE)) {
71
+ for (const i of [
72
+ id.replace(ESM_EXT_RE, ".mjs"),
73
+ id.replace(ESM_EXT_RE, ".umd.js"),
74
+ id.replace(ESM_EXT_RE, ".cjs.js"),
75
+ id.replace(ESM_EXT_RE, ".js")
76
+ ]) {
77
+ if (fs.existsSync(i))
78
+ return i;
79
+ }
80
+ }
81
+ if (id.match(ESM_FOLDER_RE)) {
82
+ for (const i of [
83
+ id.replace(ESM_FOLDER_RE, "/umd/$1"),
84
+ id.replace(ESM_FOLDER_RE, "/cjs/$1"),
85
+ id.replace(ESM_FOLDER_RE, "/$1")
86
+ ]) {
87
+ if (fs.existsSync(i))
88
+ return i;
89
+ }
90
+ }
91
+ }
92
+ async function shouldExternalize(id, options, cache = new Map()) {
93
+ if (!cache.has(id))
94
+ cache.set(id, _shouldExternalize(id, options));
95
+ return cache.get(id);
96
+ }
97
+ async function _shouldExternalize(id, options) {
98
+ if (mlly.isNodeBuiltin(id))
99
+ return id;
100
+ id = patchWindowsImportPath(id);
101
+ if (matchExternalizePattern(id, options == null ? void 0 : options.inline))
102
+ return false;
103
+ if (matchExternalizePattern(id, options == null ? void 0 : options.external))
104
+ return id;
105
+ const isNodeModule = id.includes("/node_modules/");
106
+ id = isNodeModule ? guessCJSversion(id) || id : id;
107
+ if (matchExternalizePattern(id, defaultInline))
108
+ return false;
109
+ if (matchExternalizePattern(id, depsExternal))
110
+ return id;
111
+ if (isNodeModule && await mlly.isValidNodeImport(id))
112
+ return id;
113
+ return false;
114
+ }
115
+ function matchExternalizePattern(id, patterns) {
116
+ if (!patterns)
117
+ return false;
118
+ for (const ex of patterns) {
119
+ if (typeof ex === "string") {
120
+ if (id.includes(`/node_modules/${ex}/`))
121
+ return true;
122
+ } else {
123
+ if (ex.test(id))
124
+ return true;
125
+ }
126
+ }
127
+ return false;
128
+ }
129
+ function patchWindowsImportPath(path) {
130
+ if (path.match(/^\w:\\/))
131
+ return `file:///${slash(path)}`;
132
+ else if (path.match(/^\w:\//))
133
+ return `file:///${path}`;
134
+ else
135
+ return path;
136
+ }
137
+
138
+ let SOURCEMAPPING_URL = "sourceMa";
139
+ SOURCEMAPPING_URL += "ppingURL";
140
+ class ViteNodeServer {
141
+ constructor(server, options = {}) {
142
+ this.server = server;
143
+ this.options = options;
144
+ this.promiseMap = new Map();
145
+ }
146
+ shouldExternalize(id) {
147
+ return shouldExternalize(id, this.options.deps);
148
+ }
149
+ async fetchModule(id) {
150
+ const externalize = await this.shouldExternalize(toFilePath(id, this.server.config.root));
151
+ if (externalize)
152
+ return { externalize };
153
+ const r = await this.transformRequest(id);
154
+ return { code: r == null ? void 0 : r.code };
155
+ }
156
+ async resolveId(id, importer) {
157
+ return this.server.pluginContainer.resolveId(id, importer, { ssr: true });
158
+ }
159
+ async transformRequest(id) {
160
+ if (!this.promiseMap.has(id)) {
161
+ this.promiseMap.set(id, this._transformRequest(id).finally(() => {
162
+ this.promiseMap.delete(id);
163
+ }));
164
+ }
165
+ return this.promiseMap.get(id);
166
+ }
167
+ getTransformMode(id) {
168
+ var _a, _b, _c, _d;
169
+ const withoutQuery = id.split("?")[0];
170
+ if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r)))
171
+ return "web";
172
+ if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r)))
173
+ return "ssr";
174
+ if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/))
175
+ return "ssr";
176
+ return "web";
177
+ }
178
+ async _transformRequest(id) {
179
+ let result = null;
180
+ const mode = this.getTransformMode(id);
181
+ if (mode === "web") {
182
+ result = await this.server.transformRequest(id);
183
+ if (result)
184
+ result = await this.server.ssrTransform(result.code, result.map, id);
185
+ } else {
186
+ result = await this.server.transformRequest(id, { ssr: true });
187
+ }
188
+ if (this.options.sourcemap !== false && result && !id.includes("node_modules"))
189
+ withInlineSourcemap(result);
190
+ return result;
191
+ }
192
+ }
193
+ async function withInlineSourcemap(result) {
194
+ const { code, map } = result;
195
+ if (code.includes(`${SOURCEMAPPING_URL}=`))
196
+ return result;
197
+ if (map)
198
+ result.code = `${code}
199
+
200
+ //# ${SOURCEMAPPING_URL}=data:application/json;charset=utf-8;base64,${Buffer.from(JSON.stringify(map), "utf-8").toString("base64")}
201
+ `;
202
+ return result;
203
+ }
204
+
205
+ class ViteNodeRunner {
206
+ constructor(options) {
207
+ this.options = options;
208
+ this.root = options.root || process.cwd();
209
+ this.moduleCache = options.moduleCache || new Map();
210
+ this.externalCache = new Map();
211
+ module$1.builtinModules.forEach((m) => this.externalCache.set(m, m));
212
+ }
213
+ async executeFile(file) {
214
+ return await this.cachedRequest(`/@fs/${slash(pathe.resolve(file))}`, []);
215
+ }
216
+ async executeId(id) {
217
+ return await this.cachedRequest(id, []);
218
+ }
219
+ async cachedRequest(rawId, callstack) {
220
+ var _a, _b;
221
+ const id = normalizeId(rawId, this.options.base);
222
+ const fsPath = toFilePath(id, this.root);
223
+ if ((_a = this.moduleCache.get(fsPath)) == null ? void 0 : _a.promise)
224
+ return (_b = this.moduleCache.get(fsPath)) == null ? void 0 : _b.promise;
225
+ const promise = this.directRequest(id, fsPath, callstack);
226
+ this.setCache(fsPath, { promise });
227
+ return await promise;
228
+ }
229
+ async directRequest(id, fsPath, callstack) {
230
+ callstack = [...callstack, id];
231
+ const request = async (dep) => {
232
+ var _a;
233
+ if (callstack.includes(dep)) {
234
+ const cacheKey = toFilePath(dep, this.root);
235
+ if (!((_a = this.moduleCache.get(cacheKey)) == null ? void 0 : _a.exports))
236
+ throw new Error(`Circular dependency detected
237
+ Stack:
238
+ ${[...callstack, dep].reverse().map((p) => `- ${p}`).join("\n")}`);
239
+ return this.moduleCache.get(cacheKey).exports;
240
+ }
241
+ return this.cachedRequest(dep, callstack);
242
+ };
243
+ if (this.options.requestStubs && id in this.options.requestStubs)
244
+ return this.options.requestStubs[id];
245
+ const { code: transformed, externalize } = await this.options.fetchModule(id);
246
+ if (externalize) {
247
+ const mod = await interpretedImport(externalize, this.options.interpretDefault ?? true);
248
+ this.setCache(fsPath, { exports: mod });
249
+ return mod;
250
+ }
251
+ if (transformed == null)
252
+ throw new Error(`failed to load ${id}`);
253
+ const url$1 = url.pathToFileURL(fsPath).href;
254
+ const exports = {};
255
+ this.setCache(fsPath, { code: transformed, exports });
256
+ const __filename = url.fileURLToPath(url$1);
257
+ const moduleProxy = {
258
+ set exports(value) {
259
+ exportAll(exports, value);
260
+ exports.default = value;
261
+ },
262
+ get exports() {
263
+ return exports.default;
264
+ }
265
+ };
266
+ const context = this.prepareContext({
267
+ __vite_ssr_import__: request,
268
+ __vite_ssr_dynamic_import__: request,
269
+ __vite_ssr_exports__: exports,
270
+ __vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
271
+ __vite_ssr_import_meta__: { url: url$1 },
272
+ require: module$1.createRequire(url$1),
273
+ exports,
274
+ module: moduleProxy,
275
+ __filename,
276
+ __dirname: pathe.dirname(__filename)
277
+ });
278
+ const fn = vm__default["default"].runInThisContext(`async (${Object.keys(context).join(",")})=>{{${transformed}
279
+ }}`, {
280
+ filename: fsPath,
281
+ lineOffset: 0
282
+ });
283
+ await fn(...Object.values(context));
284
+ return exports;
285
+ }
286
+ prepareContext(context) {
287
+ return context;
288
+ }
289
+ setCache(id, mod) {
290
+ if (!this.moduleCache.has(id))
291
+ this.moduleCache.set(id, mod);
292
+ else
293
+ Object.assign(this.moduleCache.get(id), mod);
294
+ }
295
+ }
296
+ function hasNestedDefault(target) {
297
+ return "__esModule" in target && target.__esModule && "default" in target.default;
298
+ }
299
+ function proxyMethod(name, tryDefault) {
300
+ return function(target, key, ...args) {
301
+ const result = Reflect[name](target, key, ...args);
302
+ if (isPrimitive(target.default))
303
+ return result;
304
+ if (tryDefault && key === "default" || typeof result === "undefined")
305
+ return Reflect[name](target.default, key, ...args);
306
+ return result;
307
+ };
308
+ }
309
+ async function interpretedImport(path, interpretDefault) {
310
+ const mod = await (function (t) { return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require(t)); }); })(path);
311
+ if (interpretDefault && "default" in mod) {
312
+ const tryDefault = hasNestedDefault(mod);
313
+ return new Proxy(mod, {
314
+ get: proxyMethod("get", tryDefault),
315
+ set: proxyMethod("set", tryDefault),
316
+ has: proxyMethod("has", tryDefault),
317
+ deleteProperty: proxyMethod("deleteProperty", tryDefault)
318
+ });
319
+ }
320
+ return mod;
321
+ }
322
+ function exportAll(exports, sourceModule) {
323
+ for (const key in sourceModule) {
324
+ if (key !== "default") {
325
+ try {
326
+ Object.defineProperty(exports, key, {
327
+ enumerable: true,
328
+ configurable: true,
329
+ get() {
330
+ return sourceModule[key];
331
+ }
332
+ });
333
+ } catch (_err) {
334
+ }
335
+ }
336
+ }
337
+ }
338
+
339
+ const argv = minimist__default["default"](process.argv.slice(2), {
340
+ "alias": {
341
+ r: "root",
342
+ c: "config",
343
+ h: "help",
344
+ w: "watch",
345
+ s: "silent"
346
+ },
347
+ "--": true,
348
+ "string": ["root", "config"],
349
+ "boolean": ["help", "watch", "silent"],
350
+ unknown(name) {
351
+ if (name[0] === "-") {
352
+ console.error(kolorist.red(`Unknown argument: ${name}`));
353
+ help();
354
+ process.exit(1);
355
+ }
356
+ return true;
357
+ }
358
+ });
359
+ if (argv.help) {
360
+ help();
361
+ process.exit(0);
362
+ }
363
+ if (!argv._.length) {
364
+ console.error(kolorist.red("No files specified."));
365
+ help();
366
+ process.exit(1);
367
+ }
368
+ process.argv = [...process.argv.slice(0, 2), ...argv["--"] || []];
369
+ run(argv);
370
+ function help() {
371
+ console.log(`
372
+ Usage:
373
+ $ vite-node [options] [files]
374
+
375
+ Options:
376
+ -r, --root <path> ${kolorist.dim("[string]")} use specified root directory
377
+ -c, --config <file> ${kolorist.dim("[string]")} use specified config file
378
+ -w, --watch ${kolorist.dim("[boolean]")} restart on file changes, similar to "nodemon"
379
+ -s, --silent ${kolorist.dim("[boolean]")} do not emit errors and logs
380
+ --vue ${kolorist.dim("[boolean]")} support for importing Vue component
381
+ `);
382
+ }
383
+ async function run(options = {}) {
384
+ const files = options.files || options._ || [];
385
+ const server = await vite.createServer({
386
+ logLevel: "error",
387
+ clearScreen: false,
388
+ configFile: options.config,
389
+ root: options.root
390
+ });
391
+ await server.pluginContainer.buildStart({});
392
+ const node = new ViteNodeServer(server);
393
+ const runner = new ViteNodeRunner({
394
+ root: server.config.root,
395
+ base: server.config.base,
396
+ fetchModule(id) {
397
+ return node.fetchModule(id);
398
+ },
399
+ resolveId(id, importer) {
400
+ return node.resolveId(id, importer);
401
+ }
402
+ });
403
+ for (const file of files)
404
+ await runner.executeFile(file);
405
+ await server.close();
406
+ }