1 | 'use strict';
|
2 |
|
3 | var path = require('path');
|
4 | var pluginutils = require('@rollup/pluginutils');
|
5 | var defaultTs = require('typescript');
|
6 | var resolveId = require('resolve');
|
7 | var fs = require('fs');
|
8 |
|
9 | function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
10 |
|
11 | function _interopNamespace(e) {
|
12 | if (e && e.__esModule) return e;
|
13 | var n = Object.create(null);
|
14 | if (e) {
|
15 | Object.keys(e).forEach(function (k) {
|
16 | if (k !== 'default') {
|
17 | var d = Object.getOwnPropertyDescriptor(e, k);
|
18 | Object.defineProperty(n, k, d.get ? d : {
|
19 | enumerable: true,
|
20 | get: function () {
|
21 | return e[k];
|
22 | }
|
23 | });
|
24 | }
|
25 | });
|
26 | }
|
27 | n['default'] = e;
|
28 | return Object.freeze(n);
|
29 | }
|
30 |
|
31 | var path__default = _interopDefaultLegacy(path);
|
32 | var defaultTs__namespace = _interopNamespace(defaultTs);
|
33 | var resolveId__default = _interopDefaultLegacy(resolveId);
|
34 | var fs__default = _interopDefaultLegacy(fs);
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 | function createFormattingHost(ts, compilerOptions) {
|
44 | return {
|
45 |
|
46 | getCompilationSettings: () => compilerOptions,
|
47 |
|
48 | getCurrentDirectory: () => process.cwd(),
|
49 |
|
50 | getNewLine() {
|
51 | switch (compilerOptions.newLine) {
|
52 | case ts.NewLineKind.CarriageReturnLineFeed:
|
53 | return '\r\n';
|
54 | case ts.NewLineKind.LineFeed:
|
55 | return '\n';
|
56 | default:
|
57 | return ts.sys.newLine;
|
58 | }
|
59 | },
|
60 |
|
61 | getCanonicalFileName: (fileName) => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase()
|
62 | };
|
63 | }
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 | function createModuleResolver(ts, host) {
|
71 | const compilerOptions = host.getCompilationSettings();
|
72 | const cache = ts.createModuleResolutionCache(process.cwd(), host.getCanonicalFileName, compilerOptions);
|
73 | const moduleHost = Object.assign(Object.assign({}, ts.sys), host);
|
74 | return (moduleName, containingFile) => {
|
75 | const resolved = ts.nodeModuleNameResolver(moduleName, containingFile, compilerOptions, moduleHost, cache);
|
76 | return resolved.resolvedModule;
|
77 | };
|
78 | }
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 | function __rest(s, e) {
|
96 | var t = {};
|
97 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
98 | t[p] = s[p];
|
99 | if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
100 | for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
101 | if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
102 | t[p[i]] = s[p[i]];
|
103 | }
|
104 | return t;
|
105 | }
|
106 |
|
107 | const resolveIdAsync = (file, opts) => new Promise((fulfil, reject) => resolveId__default['default'](file, opts, (err, contents) => (err || typeof contents === 'undefined' ? reject(err) : fulfil(contents))));
|
108 |
|
109 |
|
110 |
|
111 | function getTsLibPath() {
|
112 | return resolveIdAsync('tslib/tslib.es6.js', { basedir: __dirname });
|
113 | }
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 |
|
125 | function getPluginOptions(options) {
|
126 | const { cacheDir, exclude, include, transformers, tsconfig, tslib, typescript } = options, compilerOptions = __rest(options, ["cacheDir", "exclude", "include", "transformers", "tsconfig", "tslib", "typescript"]);
|
127 | const filter = pluginutils.createFilter(include || ['*.ts+(|x)', '**/*.ts+(|x)'], exclude);
|
128 | return {
|
129 | cacheDir,
|
130 | filter,
|
131 | tsconfig,
|
132 | compilerOptions: compilerOptions,
|
133 | typescript: typescript || defaultTs__namespace,
|
134 | tslib: tslib || getTsLibPath(),
|
135 | transformers
|
136 | };
|
137 | }
|
138 |
|
139 |
|
140 |
|
141 |
|
142 | function diagnosticToWarning(ts, host, diagnostic) {
|
143 | const pluginCode = `TS${diagnostic.code}`;
|
144 | const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
|
145 |
|
146 | const warning = {
|
147 | pluginCode,
|
148 | message: `@rollup/plugin-typescript ${pluginCode}: ${message}`
|
149 | };
|
150 | if (diagnostic.file) {
|
151 |
|
152 | const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
|
153 | warning.loc = {
|
154 | column: character + 1,
|
155 | line: line + 1,
|
156 | file: diagnostic.file.fileName
|
157 | };
|
158 | if (host) {
|
159 |
|
160 | const formatted = ts.formatDiagnosticsWithColorAndContext([diagnostic], host);
|
161 |
|
162 |
|
163 | let frame = formatted.slice(formatted.indexOf(message) + message.length);
|
164 | const newLine = host.getNewLine();
|
165 | if (frame.startsWith(newLine)) {
|
166 | frame = frame.slice(frame.indexOf(newLine) + newLine.length);
|
167 | }
|
168 | warning.frame = frame;
|
169 | }
|
170 | }
|
171 | return warning;
|
172 | }
|
173 |
|
174 | const DEFAULT_COMPILER_OPTIONS = {
|
175 | module: 'esnext',
|
176 | skipLibCheck: true
|
177 | };
|
178 | const FORCED_COMPILER_OPTIONS = {
|
179 |
|
180 | noEmitHelpers: true,
|
181 | importHelpers: true,
|
182 |
|
183 | noEmit: false,
|
184 | emitDeclarationOnly: false,
|
185 |
|
186 | noResolve: false
|
187 | };
|
188 |
|
189 |
|
190 | const DIRECTORY_PROPS = ['outDir', 'declarationDir'];
|
191 |
|
192 |
|
193 |
|
194 |
|
195 |
|
196 |
|
197 |
|
198 | function makePathsAbsolute(compilerOptions, relativeTo) {
|
199 | for (const pathProp of DIRECTORY_PROPS) {
|
200 | if (compilerOptions[pathProp]) {
|
201 | compilerOptions[pathProp] = path.resolve(relativeTo, compilerOptions[pathProp]);
|
202 | }
|
203 | }
|
204 | }
|
205 |
|
206 |
|
207 |
|
208 |
|
209 |
|
210 | function normalizeCompilerOptions(ts, compilerOptions) {
|
211 | let autoSetSourceMap = false;
|
212 | if (compilerOptions.inlineSourceMap) {
|
213 |
|
214 | compilerOptions.sourceMap = true;
|
215 | compilerOptions.inlineSourceMap = false;
|
216 | }
|
217 | else if (typeof compilerOptions.sourceMap !== 'boolean') {
|
218 |
|
219 |
|
220 | compilerOptions.sourceMap = true;
|
221 |
|
222 |
|
223 | compilerOptions.inlineSources = true;
|
224 | autoSetSourceMap = true;
|
225 | }
|
226 | switch (compilerOptions.module) {
|
227 | case ts.ModuleKind.ES2015:
|
228 | case ts.ModuleKind.ESNext:
|
229 | case ts.ModuleKind.CommonJS:
|
230 |
|
231 | return autoSetSourceMap;
|
232 | case ts.ModuleKind.None:
|
233 | case ts.ModuleKind.AMD:
|
234 | case ts.ModuleKind.UMD:
|
235 | case ts.ModuleKind.System: {
|
236 |
|
237 | const moduleType = ts.ModuleKind[compilerOptions.module];
|
238 | throw new Error(`@rollup/plugin-typescript: The module kind should be 'ES2015' or 'ESNext, found: '${moduleType}'`);
|
239 | }
|
240 | default:
|
241 |
|
242 | compilerOptions.module = ts.ModuleKind.ESNext;
|
243 | }
|
244 | return autoSetSourceMap;
|
245 | }
|
246 |
|
247 |
|
248 |
|
249 |
|
250 |
|
251 |
|
252 |
|
253 | function getTsConfigPath(ts, relativePath) {
|
254 | if (relativePath === false)
|
255 | return null;
|
256 |
|
257 | const tsConfigPath = path.resolve(process.cwd(), relativePath || 'tsconfig.json');
|
258 | if (!ts.sys.fileExists(tsConfigPath)) {
|
259 | if (relativePath) {
|
260 |
|
261 | throw new Error(`Could not find specified tsconfig.json at ${tsConfigPath}`);
|
262 | }
|
263 | else {
|
264 | return null;
|
265 | }
|
266 | }
|
267 | return tsConfigPath;
|
268 | }
|
269 |
|
270 |
|
271 |
|
272 |
|
273 |
|
274 |
|
275 | function readTsConfigFile(ts, tsConfigPath) {
|
276 | const { config, error } = ts.readConfigFile(tsConfigPath, (path) => fs.readFileSync(path, 'utf8'));
|
277 | if (error) {
|
278 | throw Object.assign(Error(), diagnosticToWarning(ts, null, error));
|
279 | }
|
280 | return config || {};
|
281 | }
|
282 |
|
283 |
|
284 |
|
285 |
|
286 | function containsEnumOptions(compilerOptions) {
|
287 | const enums = [
|
288 | 'module',
|
289 | 'target',
|
290 | 'jsx',
|
291 | 'moduleResolution',
|
292 | 'newLine'
|
293 | ];
|
294 | return enums.some((prop) => prop in compilerOptions && typeof compilerOptions[prop] === 'number');
|
295 | }
|
296 | const configCache = new Map();
|
297 |
|
298 |
|
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 |
|
306 |
|
307 |
|
308 | function parseTypescriptConfig(ts, tsconfig, compilerOptions) {
|
309 |
|
310 | const cwd = process.cwd();
|
311 | makePathsAbsolute(compilerOptions, cwd);
|
312 | let parsedConfig;
|
313 |
|
314 |
|
315 | const tsConfigPath = getTsConfigPath(ts, tsconfig) || undefined;
|
316 | const tsConfigFile = tsConfigPath ? readTsConfigFile(ts, tsConfigPath) : {};
|
317 | const basePath = tsConfigPath ? path.dirname(tsConfigPath) : cwd;
|
318 |
|
319 |
|
320 | if (containsEnumOptions(compilerOptions)) {
|
321 | parsedConfig = ts.parseJsonConfigFileContent(Object.assign(Object.assign({}, tsConfigFile), { compilerOptions: Object.assign(Object.assign({}, DEFAULT_COMPILER_OPTIONS), tsConfigFile.compilerOptions) }), ts.sys, basePath, Object.assign(Object.assign({}, compilerOptions), FORCED_COMPILER_OPTIONS), tsConfigPath, undefined, undefined, configCache);
|
322 | }
|
323 | else {
|
324 | parsedConfig = ts.parseJsonConfigFileContent(Object.assign(Object.assign({}, tsConfigFile), { compilerOptions: Object.assign(Object.assign(Object.assign({}, DEFAULT_COMPILER_OPTIONS), tsConfigFile.compilerOptions), compilerOptions) }), ts.sys, basePath, FORCED_COMPILER_OPTIONS, tsConfigPath, undefined, undefined, configCache);
|
325 | }
|
326 | const autoSetSourceMap = normalizeCompilerOptions(ts, parsedConfig.options);
|
327 | return Object.assign(Object.assign({}, parsedConfig), { autoSetSourceMap });
|
328 | }
|
329 |
|
330 |
|
331 |
|
332 |
|
333 | function emitParsedOptionsErrors(ts, context, parsedOptions) {
|
334 | if (parsedOptions.errors.length > 0) {
|
335 | parsedOptions.errors.forEach((error) => context.warn(diagnosticToWarning(ts, null, error)));
|
336 | context.error(`@rollup/plugin-typescript: Couldn't process compiler options`);
|
337 | }
|
338 | }
|
339 |
|
340 |
|
341 |
|
342 |
|
343 |
|
344 |
|
345 |
|
346 |
|
347 |
|
348 | function validateSourceMap(context, compilerOptions, outputOptions, autoSetSourceMap) {
|
349 | if (compilerOptions.sourceMap && !outputOptions.sourcemap && !autoSetSourceMap) {
|
350 | context.warn(`@rollup/plugin-typescript: Rollup 'sourcemap' option must be set to generate source maps.`);
|
351 | }
|
352 | else if (!compilerOptions.sourceMap && outputOptions.sourcemap) {
|
353 | context.warn(`@rollup/plugin-typescript: Typescript 'sourceMap' compiler option must be set to generate source maps.`);
|
354 | }
|
355 | }
|
356 |
|
357 |
|
358 |
|
359 |
|
360 |
|
361 |
|
362 | function validatePaths(ts, context, compilerOptions, outputOptions) {
|
363 | if (compilerOptions.out) {
|
364 | context.error(`@rollup/plugin-typescript: Deprecated Typescript compiler option 'out' is not supported. Use 'outDir' instead.`);
|
365 | }
|
366 | else if (compilerOptions.outFile) {
|
367 | context.error(`@rollup/plugin-typescript: Typescript compiler option 'outFile' is not supported. Use 'outDir' instead.`);
|
368 | }
|
369 | for (const dirProperty of DIRECTORY_PROPS) {
|
370 | if (compilerOptions[dirProperty] && outputOptions.dir) {
|
371 |
|
372 | const fromRollupDirToTs = path.relative(outputOptions.dir, compilerOptions[dirProperty]);
|
373 | if (fromRollupDirToTs.startsWith('..')) {
|
374 | context.error(`@rollup/plugin-typescript: Path of Typescript compiler option '${dirProperty}' must be located inside Rollup 'dir' option.`);
|
375 | }
|
376 | }
|
377 | }
|
378 | const tsBuildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
|
379 | if (tsBuildInfoPath && compilerOptions.incremental) {
|
380 | if (!outputOptions.dir) {
|
381 | context.error(`@rollup/plugin-typescript: Rollup 'dir' option must be used when Typescript compiler options 'tsBuildInfoFile' or 'incremental' are specified.`);
|
382 | }
|
383 |
|
384 | const fromRollupDirToTs = path.relative(outputOptions.dir, tsBuildInfoPath);
|
385 | if (fromRollupDirToTs.startsWith('..')) {
|
386 | context.error(`@rollup/plugin-typescript: Path of Typescript compiler option 'tsBuildInfoFile' must be located inside Rollup 'dir' option.`);
|
387 | }
|
388 | }
|
389 | if (compilerOptions.declaration || compilerOptions.declarationMap || compilerOptions.composite) {
|
390 | if (DIRECTORY_PROPS.every((dirProperty) => !compilerOptions[dirProperty])) {
|
391 | context.error(`@rollup/plugin-typescript: You are using one of Typescript's compiler options 'declaration', 'declarationMap' or 'composite'. ` +
|
392 | `In this case 'outDir' or 'declarationDir' must be specified to generate declaration files.`);
|
393 | }
|
394 | }
|
395 | }
|
396 |
|
397 |
|
398 |
|
399 |
|
400 | function isCodeOutputFile(name) {
|
401 | return !isMapOutputFile(name) && !name.endsWith('.d.ts');
|
402 | }
|
403 |
|
404 |
|
405 |
|
406 | function isMapOutputFile(name) {
|
407 | return name.endsWith('.map');
|
408 | }
|
409 |
|
410 |
|
411 |
|
412 |
|
413 |
|
414 |
|
415 |
|
416 | function getEmittedFile(fileName, emittedFiles, tsCache) {
|
417 | let code;
|
418 | if (fileName) {
|
419 | if (emittedFiles.has(fileName)) {
|
420 | code = emittedFiles.get(fileName);
|
421 | }
|
422 | else {
|
423 | code = tsCache.getCached(fileName);
|
424 | }
|
425 | }
|
426 | return code;
|
427 | }
|
428 |
|
429 |
|
430 |
|
431 |
|
432 |
|
433 |
|
434 | function findTypescriptOutput(ts, parsedOptions, id, emittedFiles, tsCache) {
|
435 | const emittedFileNames = ts.getOutputFileNames(parsedOptions, id, !ts.sys.useCaseSensitiveFileNames);
|
436 | const codeFile = emittedFileNames.find(isCodeOutputFile);
|
437 | const mapFile = emittedFileNames.find(isMapOutputFile);
|
438 | return {
|
439 | code: getEmittedFile(codeFile, emittedFiles, tsCache),
|
440 | map: getEmittedFile(mapFile, emittedFiles, tsCache),
|
441 | declarations: emittedFileNames.filter((name) => name !== codeFile && name !== mapFile)
|
442 | };
|
443 | }
|
444 |
|
445 |
|
446 | const CANNOT_COMPILE_ESM = 1204;
|
447 |
|
448 |
|
449 |
|
450 | function emitDiagnostic(ts, context, host, diagnostic) {
|
451 | if (diagnostic.code === CANNOT_COMPILE_ESM)
|
452 | return;
|
453 | const { noEmitOnError } = host.getCompilationSettings();
|
454 |
|
455 | const warning = diagnosticToWarning(ts, host, diagnostic);
|
456 |
|
457 | if (noEmitOnError && diagnostic.category === ts.DiagnosticCategory.Error) {
|
458 | context.error(warning);
|
459 | }
|
460 | else {
|
461 | context.warn(warning);
|
462 | }
|
463 | }
|
464 | function buildDiagnosticReporter(ts, context, host) {
|
465 | return function reportDiagnostics(diagnostic) {
|
466 | emitDiagnostic(ts, context, host, diagnostic);
|
467 | };
|
468 | }
|
469 |
|
470 |
|
471 |
|
472 |
|
473 | function mergeTransformers(builder, ...input) {
|
474 |
|
475 | const transformerTypes = ['after', 'afterDeclarations', 'before'];
|
476 | const accumulator = {
|
477 | after: [],
|
478 | afterDeclarations: [],
|
479 | before: []
|
480 | };
|
481 | let program;
|
482 | let typeChecker;
|
483 | input.forEach((transformers) => {
|
484 | if (!transformers) {
|
485 |
|
486 | return;
|
487 | }
|
488 | transformerTypes.forEach((stage) => {
|
489 | getTransformers(transformers[stage]).forEach((transformer) => {
|
490 | if (!transformer) {
|
491 |
|
492 | return;
|
493 | }
|
494 | if ('type' in transformer) {
|
495 | if (typeof transformer.factory === 'function') {
|
496 |
|
497 | program = program || builder.getProgram();
|
498 | typeChecker = typeChecker || program.getTypeChecker();
|
499 | let factory;
|
500 | if (transformer.type === 'program') {
|
501 | program = program || builder.getProgram();
|
502 | factory = transformer.factory(program);
|
503 | }
|
504 | else {
|
505 | program = program || builder.getProgram();
|
506 | typeChecker = typeChecker || program.getTypeChecker();
|
507 | factory = transformer.factory(typeChecker);
|
508 | }
|
509 |
|
510 | if (factory) {
|
511 | accumulator[stage].push(factory);
|
512 | }
|
513 | }
|
514 | }
|
515 | else {
|
516 |
|
517 | accumulator[stage].push(transformer);
|
518 | }
|
519 | });
|
520 | });
|
521 | });
|
522 | return accumulator;
|
523 | }
|
524 | function getTransformers(transformers) {
|
525 | return transformers || [];
|
526 | }
|
527 |
|
528 |
|
529 | var DiagnosticCode;
|
530 | (function (DiagnosticCode) {
|
531 | DiagnosticCode[DiagnosticCode["FILE_CHANGE_DETECTED"] = 6032] = "FILE_CHANGE_DETECTED";
|
532 | DiagnosticCode[DiagnosticCode["FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES"] = 6193] = "FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES";
|
533 | DiagnosticCode[DiagnosticCode["FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES"] = 6194] = "FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES";
|
534 | })(DiagnosticCode || (DiagnosticCode = {}));
|
535 | function createDeferred(timeout) {
|
536 | let promise;
|
537 | let resolve = () => { };
|
538 | if (timeout) {
|
539 | promise = Promise.race([
|
540 | new Promise((r) => setTimeout(r, timeout, true)),
|
541 | new Promise((r) => (resolve = r))
|
542 | ]);
|
543 | }
|
544 | else {
|
545 | promise = new Promise((r) => (resolve = r));
|
546 | }
|
547 | return { promise, resolve };
|
548 | }
|
549 |
|
550 |
|
551 |
|
552 | class WatchProgramHelper {
|
553 | constructor() {
|
554 | this._startDeferred = null;
|
555 | this._finishDeferred = null;
|
556 | }
|
557 | watch(timeout = 1000) {
|
558 |
|
559 | this._startDeferred = createDeferred(timeout);
|
560 | this._finishDeferred = createDeferred();
|
561 | }
|
562 | handleStatus(diagnostic) {
|
563 |
|
564 | if (diagnostic.category === defaultTs.DiagnosticCategory.Message) {
|
565 | switch (diagnostic.code) {
|
566 | case DiagnosticCode.FILE_CHANGE_DETECTED:
|
567 | this.resolveStart();
|
568 | break;
|
569 | case DiagnosticCode.FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES:
|
570 | case DiagnosticCode.FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES:
|
571 | this.resolveFinish();
|
572 | break;
|
573 | }
|
574 | }
|
575 | }
|
576 | resolveStart() {
|
577 | if (this._startDeferred) {
|
578 | this._startDeferred.resolve(false);
|
579 | this._startDeferred = null;
|
580 | }
|
581 | }
|
582 | resolveFinish() {
|
583 | if (this._finishDeferred) {
|
584 | this._finishDeferred.resolve(false);
|
585 | this._finishDeferred = null;
|
586 | }
|
587 | }
|
588 | async wait() {
|
589 | var _a;
|
590 | if (this._startDeferred) {
|
591 | const timeout = await this._startDeferred.promise;
|
592 |
|
593 | if (timeout) {
|
594 | this._startDeferred = null;
|
595 | this._finishDeferred = null;
|
596 | }
|
597 | await ((_a = this._finishDeferred) === null || _a === void 0 ? void 0 : _a.promise);
|
598 | }
|
599 | }
|
600 | }
|
601 |
|
602 |
|
603 |
|
604 |
|
605 |
|
606 |
|
607 | function createWatchHost(ts, context, { formatHost, parsedOptions, writeFile, status, resolveModule, transformers }) {
|
608 | const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
|
609 | const baseHost = ts.createWatchCompilerHost(parsedOptions.fileNames, parsedOptions.options, ts.sys, createProgram, buildDiagnosticReporter(ts, context, formatHost), status, parsedOptions.projectReferences);
|
610 | return Object.assign(Object.assign({}, baseHost), {
|
611 |
|
612 | afterProgramCreate(program) {
|
613 | const origEmit = program.emit;
|
614 |
|
615 | program.emit = (targetSourceFile, _, ...args) => origEmit(targetSourceFile, writeFile,
|
616 |
|
617 | args[0],
|
618 |
|
619 | args[1], mergeTransformers(program, transformers, args[2]));
|
620 | return baseHost.afterProgramCreate(program);
|
621 | },
|
622 |
|
623 | resolveModuleNames(moduleNames, containingFile) {
|
624 | return moduleNames.map((moduleName) => resolveModule(moduleName, containingFile));
|
625 | } });
|
626 | }
|
627 | function createWatchProgram(ts, context, options) {
|
628 | return ts.createWatchProgram(createWatchHost(ts, context, options));
|
629 | }
|
630 |
|
631 |
|
632 | const createFileFolder = (filePath) => {
|
633 | const folderPath = path__default['default'].dirname(filePath);
|
634 | fs__default['default'].mkdirSync(folderPath, { recursive: true });
|
635 | };
|
636 | class TSCache {
|
637 | constructor(cacheFolder = '.rollup.cache') {
|
638 | this._cacheFolder = cacheFolder;
|
639 | }
|
640 |
|
641 | cachedFilename(fileName) {
|
642 | return path__default['default'].join(this._cacheFolder, fileName.replace(/^([A-Z]+):/, '$1'));
|
643 | }
|
644 |
|
645 | cacheCode(fileName, code) {
|
646 | const cachedPath = this.cachedFilename(fileName);
|
647 | createFileFolder(cachedPath);
|
648 | fs__default['default'].writeFileSync(cachedPath, code);
|
649 | }
|
650 |
|
651 | isCached(fileName) {
|
652 | return fs__default['default'].existsSync(this.cachedFilename(fileName));
|
653 | }
|
654 |
|
655 | getCached(fileName) {
|
656 | let code;
|
657 | if (this.isCached(fileName)) {
|
658 | code = fs__default['default'].readFileSync(this.cachedFilename(fileName), { encoding: 'utf-8' });
|
659 | }
|
660 | return code;
|
661 | }
|
662 | }
|
663 |
|
664 | function typescript(options = {}) {
|
665 | const { cacheDir, compilerOptions, filter, transformers, tsconfig, tslib, typescript: ts } = getPluginOptions(options);
|
666 | const tsCache = new TSCache(cacheDir);
|
667 | const emittedFiles = new Map();
|
668 | const watchProgramHelper = new WatchProgramHelper();
|
669 | const parsedOptions = parseTypescriptConfig(ts, tsconfig, compilerOptions);
|
670 | parsedOptions.fileNames = parsedOptions.fileNames.filter(filter);
|
671 | const formatHost = createFormattingHost(ts, parsedOptions.options);
|
672 | const resolveModule = createModuleResolver(ts, formatHost);
|
673 | let program = null;
|
674 | function normalizePath(fileName) {
|
675 | return fileName.split(path.win32.sep).join(path.posix.sep);
|
676 | }
|
677 | return {
|
678 | name: 'typescript',
|
679 | buildStart() {
|
680 | emitParsedOptionsErrors(ts, this, parsedOptions);
|
681 |
|
682 | if (!program) {
|
683 | program = createWatchProgram(ts, this, {
|
684 | formatHost,
|
685 | resolveModule,
|
686 | parsedOptions,
|
687 | writeFile(fileName, data) {
|
688 | if (parsedOptions.options.composite || parsedOptions.options.incremental) {
|
689 | tsCache.cacheCode(fileName, data);
|
690 | }
|
691 | emittedFiles.set(fileName, data);
|
692 | },
|
693 | status(diagnostic) {
|
694 | watchProgramHelper.handleStatus(diagnostic);
|
695 | },
|
696 | transformers
|
697 | });
|
698 | }
|
699 | },
|
700 | watchChange(id) {
|
701 | if (!filter(id))
|
702 | return;
|
703 | watchProgramHelper.watch();
|
704 | },
|
705 | buildEnd() {
|
706 | if (this.meta.watchMode !== true) {
|
707 |
|
708 |
|
709 | program === null || program === void 0 ? void 0 : program.close();
|
710 | }
|
711 | },
|
712 | renderStart(outputOptions) {
|
713 | validateSourceMap(this, parsedOptions.options, outputOptions, parsedOptions.autoSetSourceMap);
|
714 | validatePaths(ts, this, parsedOptions.options, outputOptions);
|
715 | },
|
716 | resolveId(importee, importer) {
|
717 | if (importee === 'tslib') {
|
718 | return tslib;
|
719 | }
|
720 | if (!importer)
|
721 | return null;
|
722 |
|
723 | const containingFile = normalizePath(importer);
|
724 | const resolved = resolveModule(importee, containingFile);
|
725 | if (resolved) {
|
726 | if (resolved.extension === '.d.ts')
|
727 | return null;
|
728 | return path.normalize(resolved.resolvedFileName);
|
729 | }
|
730 | return null;
|
731 | },
|
732 | async load(id) {
|
733 | if (!filter(id))
|
734 | return null;
|
735 | await watchProgramHelper.wait();
|
736 | const fileName = normalizePath(id);
|
737 | if (!parsedOptions.fileNames.includes(fileName)) {
|
738 |
|
739 | parsedOptions.fileNames.push(fileName);
|
740 | }
|
741 | const output = findTypescriptOutput(ts, parsedOptions, id, emittedFiles, tsCache);
|
742 | return output.code != null ? output : null;
|
743 | },
|
744 | generateBundle(outputOptions) {
|
745 | parsedOptions.fileNames.forEach((fileName) => {
|
746 | const output = findTypescriptOutput(ts, parsedOptions, fileName, emittedFiles, tsCache);
|
747 | output.declarations.forEach((id) => {
|
748 | const code = getEmittedFile(id, emittedFiles, tsCache);
|
749 | let baseDir = outputOptions.dir;
|
750 | if (!baseDir && tsconfig) {
|
751 | baseDir = tsconfig.substring(0, tsconfig.lastIndexOf('/'));
|
752 | }
|
753 | if (!code || !baseDir)
|
754 | return;
|
755 | this.emitFile({
|
756 | type: 'asset',
|
757 | fileName: normalizePath(path.relative(baseDir, id)),
|
758 | source: code
|
759 | });
|
760 | });
|
761 | });
|
762 | const tsBuildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(parsedOptions.options);
|
763 | if (tsBuildInfoPath) {
|
764 | const tsBuildInfoSource = emittedFiles.get(tsBuildInfoPath);
|
765 |
|
766 | if (tsBuildInfoSource) {
|
767 | this.emitFile({
|
768 | type: 'asset',
|
769 | fileName: normalizePath(path.relative(outputOptions.dir, tsBuildInfoPath)),
|
770 | source: tsBuildInfoSource
|
771 | });
|
772 | }
|
773 | }
|
774 | }
|
775 | };
|
776 | }
|
777 |
|
778 | module.exports = typescript;
|