@stencil/cli 5.0.0-alpha.3 → 5.0.0-alpha.30
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/README.md +76 -0
- package/dist/index.d.mts +317 -10
- package/dist/index.mjs +2817 -440
- package/package.json +14 -9
- /package/{LICENSE.md → LICENSE} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,19 @@
|
|
|
1
1
|
import { LOG_LEVELS } from "@stencil/core/compiler";
|
|
2
|
-
import { buildError, catchError, hasError, isFunction, isOutputTargetDocs,
|
|
3
|
-
import {
|
|
2
|
+
import { buildError, catchError, hasError, isFunction, isOutputTargetDistLazy, isOutputTargetDocs, isOutputTargetSsr, isOutputTargetStandalone, isOutputTargetWww, isString, normalizePath, readOnlyArrayHasStringMember, result, shouldIgnoreError, toCamelCase, validateComponentTag } from "@stencil/core/compiler/utils";
|
|
3
|
+
import { basename, dirname, join, parse, relative, resolve } from "node:path";
|
|
4
|
+
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
5
|
+
import * as p from "@clack/prompts";
|
|
6
|
+
import { cancel, isCancel, select } from "@clack/prompts";
|
|
7
|
+
import * as nypm from "nypm";
|
|
8
|
+
import { addDevDependency, detectPackageManager } from "nypm";
|
|
9
|
+
import { isCI } from "std-env";
|
|
4
10
|
import ts from "typescript";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
import { getPackageInfo } from "local-pkg";
|
|
13
|
+
import { existsSync } from "node:fs";
|
|
14
|
+
import { homedir } from "node:os";
|
|
15
|
+
import { dirname as dirname$1, isAbsolute, join as join$1, relative as relative$1 } from "path";
|
|
16
|
+
import { generateIndexHtml, generatePackageJsonFields, generateStencilConfig, getComponentBoilerplate, getPreviewHtmlBoilerplate, getStyleBoilerplate, getTemplatePath, getUsageExampleBoilerplate, toPascalCase } from "@stencil/templates";
|
|
5
17
|
import { start } from "@stencil/dev-server";
|
|
6
18
|
//#region src/config-flags.ts
|
|
7
19
|
/**
|
|
@@ -18,13 +30,11 @@ const BOOLEAN_CLI_FLAGS = [
|
|
|
18
30
|
"devtools",
|
|
19
31
|
"docs",
|
|
20
32
|
"dryRun",
|
|
21
|
-
"esm",
|
|
22
33
|
"help",
|
|
23
34
|
"log",
|
|
24
35
|
"open",
|
|
25
36
|
"prerender",
|
|
26
37
|
"prerenderExternal",
|
|
27
|
-
"prod",
|
|
28
38
|
"profile",
|
|
29
39
|
"serviceWorker",
|
|
30
40
|
"serve",
|
|
@@ -188,8 +198,10 @@ const parseCLITerm = (flags, args) => {
|
|
|
188
198
|
const [originalArg, value] = parseEqualsArg(arg);
|
|
189
199
|
setCLIArg(flags, desugarRawAlias(originalArg), normalizeFlagName(originalArg), value);
|
|
190
200
|
} else if (CLI_FLAG_REGEX.test(arg)) setCLIArg(flags, desugarRawAlias(arg), normalizeFlagName(arg), parseCLIValue(args));
|
|
191
|
-
else if (arg.startsWith("--no-") && arg.length > 5)
|
|
192
|
-
|
|
201
|
+
else if (arg.startsWith("--no-") && arg.length > 5) {
|
|
202
|
+
const normalized = normalizeNegativeFlagName(arg);
|
|
203
|
+
setCLIArg(flags, arg, normalized, "");
|
|
204
|
+
} else if (arg.startsWith("--no") && (isNegatedBoolean || isNegatedBooleanOrString)) setCLIArg(flags, arg, normalizeNegativeFlagName(arg), "");
|
|
193
205
|
else if (arg.startsWith("--") && arg.length > 2) setCLIArg(flags, arg, normalizeFlagName(arg), parseCLIValue(args));
|
|
194
206
|
else flags.unknownArgs.push(arg);
|
|
195
207
|
};
|
|
@@ -242,52 +254,58 @@ const setCLIArg = (flags, rawArg, normalizedArg, value) => {
|
|
|
242
254
|
flags[normalizedArg] = typeof value === "string" ? value === "true" : true;
|
|
243
255
|
flags.knownArgs.push(rawArg);
|
|
244
256
|
if (typeof value === "string" && value !== "") flags.knownArgs.push(value);
|
|
245
|
-
} else if (readOnlyArrayHasStringMember(STRING_CLI_FLAGS, normalizedArg))
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
flags.knownArgs.push(value);
|
|
249
|
-
} else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
|
|
250
|
-
else if (STRING_ARRAY_CLI_FLAGS.length > 0 && readOnlyArrayHasStringMember(STRING_ARRAY_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
|
|
251
|
-
const flagsRecord = flags;
|
|
252
|
-
if (!Array.isArray(flagsRecord[normalizedArg])) flagsRecord[normalizedArg] = [];
|
|
253
|
-
const targetArray = flagsRecord[normalizedArg];
|
|
254
|
-
if (Array.isArray(targetArray)) {
|
|
255
|
-
targetArray.push(value);
|
|
257
|
+
} else if (readOnlyArrayHasStringMember(STRING_CLI_FLAGS, normalizedArg)) {
|
|
258
|
+
if (typeof value === "string") {
|
|
259
|
+
flags[normalizedArg] = value;
|
|
256
260
|
flags.knownArgs.push(rawArg);
|
|
257
261
|
flags.knownArgs.push(value);
|
|
258
|
-
}
|
|
259
|
-
} else
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
262
|
+
} else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
|
|
263
|
+
} else if (STRING_ARRAY_CLI_FLAGS.length > 0 && readOnlyArrayHasStringMember(STRING_ARRAY_CLI_FLAGS, normalizedArg)) {
|
|
264
|
+
if (typeof value === "string") {
|
|
265
|
+
const flagsRecord = flags;
|
|
266
|
+
if (!Array.isArray(flagsRecord[normalizedArg])) flagsRecord[normalizedArg] = [];
|
|
267
|
+
const targetArray = flagsRecord[normalizedArg];
|
|
268
|
+
if (Array.isArray(targetArray)) {
|
|
269
|
+
targetArray.push(value);
|
|
270
|
+
flags.knownArgs.push(rawArg);
|
|
271
|
+
flags.knownArgs.push(value);
|
|
272
|
+
}
|
|
273
|
+
} else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
|
|
274
|
+
} else if (readOnlyArrayHasStringMember(NUMBER_CLI_FLAGS, normalizedArg)) {
|
|
275
|
+
if (typeof value === "string") {
|
|
276
|
+
const parsed = parseInt(value, 10);
|
|
277
|
+
if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
|
|
278
|
+
else {
|
|
279
|
+
flags[normalizedArg] = parsed;
|
|
280
|
+
flags.knownArgs.push(rawArg);
|
|
281
|
+
flags.knownArgs.push(value);
|
|
282
|
+
}
|
|
283
|
+
} else throwCLIParsingError(rawArg, "expected a number argument but received nothing");
|
|
284
|
+
} else if (readOnlyArrayHasStringMember(STRING_NUMBER_CLI_FLAGS, normalizedArg)) {
|
|
285
|
+
if (typeof value === "string") {
|
|
286
|
+
if (CLI_ARG_STRING_REGEX.test(value)) flags[normalizedArg] = value;
|
|
287
|
+
else {
|
|
288
|
+
const parsed = Number(value);
|
|
289
|
+
if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
|
|
290
|
+
else flags[normalizedArg] = parsed;
|
|
291
|
+
}
|
|
265
292
|
flags.knownArgs.push(rawArg);
|
|
266
293
|
flags.knownArgs.push(value);
|
|
267
|
-
}
|
|
268
|
-
} else
|
|
269
|
-
else if (readOnlyArrayHasStringMember(STRING_NUMBER_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
|
|
270
|
-
if (CLI_ARG_STRING_REGEX.test(value)) flags[normalizedArg] = value;
|
|
271
|
-
else {
|
|
272
|
-
const parsed = Number(value);
|
|
273
|
-
if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
|
|
274
|
-
else flags[normalizedArg] = parsed;
|
|
275
|
-
}
|
|
276
|
-
flags.knownArgs.push(rawArg);
|
|
277
|
-
flags.knownArgs.push(value);
|
|
278
|
-
} else throwCLIParsingError(rawArg, "expected a string or a number but received nothing");
|
|
279
|
-
else if (readOnlyArrayHasStringMember(BOOLEAN_STRING_CLI_FLAGS, normalizedArg)) {
|
|
294
|
+
} else throwCLIParsingError(rawArg, "expected a string or a number but received nothing");
|
|
295
|
+
} else if (readOnlyArrayHasStringMember(BOOLEAN_STRING_CLI_FLAGS, normalizedArg)) {
|
|
280
296
|
const derivedValue = typeof value === "string" ? value ? value : false : true;
|
|
281
297
|
flags[normalizedArg] = derivedValue;
|
|
282
298
|
flags.knownArgs.push(rawArg);
|
|
283
299
|
if (typeof derivedValue === "string" && derivedValue) flags.knownArgs.push(derivedValue);
|
|
284
|
-
} else if (readOnlyArrayHasStringMember(LOG_LEVEL_CLI_FLAGS, normalizedArg))
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
300
|
+
} else if (readOnlyArrayHasStringMember(LOG_LEVEL_CLI_FLAGS, normalizedArg)) {
|
|
301
|
+
if (typeof value === "string") {
|
|
302
|
+
if (isLogLevel(value)) {
|
|
303
|
+
flags[normalizedArg] = value;
|
|
304
|
+
flags.knownArgs.push(rawArg);
|
|
305
|
+
flags.knownArgs.push(value);
|
|
306
|
+
} else throwCLIParsingError(rawArg, `expected to receive a valid log level but received "${String(value)}"`);
|
|
307
|
+
} else throwCLIParsingError(rawArg, "expected to receive a valid log level but received nothing");
|
|
308
|
+
} else {
|
|
291
309
|
flags.unknownArgs.push(rawArg);
|
|
292
310
|
if (typeof value === "string") flags.unknownArgs.push(value);
|
|
293
311
|
}
|
|
@@ -438,11 +456,12 @@ const findConfig = async (opts) => {
|
|
|
438
456
|
const cwd = sys.getCurrentDirectory();
|
|
439
457
|
const rootDir = normalizePath(cwd);
|
|
440
458
|
let configPath = opts.configPath;
|
|
441
|
-
if (isString(configPath))
|
|
442
|
-
|
|
443
|
-
|
|
459
|
+
if (isString(configPath)) {
|
|
460
|
+
if (!sys.platformPath.isAbsolute(configPath)) configPath = normalizePath(sys.platformPath.join(cwd, configPath));
|
|
461
|
+
else configPath = normalizePath(configPath);
|
|
462
|
+
} else configPath = rootDir;
|
|
444
463
|
const results = {
|
|
445
|
-
configPath,
|
|
464
|
+
configPath: null,
|
|
446
465
|
rootDir: normalizePath(cwd)
|
|
447
466
|
};
|
|
448
467
|
const stat = await sys.stat(configPath);
|
|
@@ -457,12 +476,15 @@ const findConfig = async (opts) => {
|
|
|
457
476
|
if (stat.isFile) {
|
|
458
477
|
results.configPath = configPath;
|
|
459
478
|
results.rootDir = sys.platformPath.dirname(configPath);
|
|
460
|
-
} else if (stat.isDirectory)
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
479
|
+
} else if (stat.isDirectory) {
|
|
480
|
+
results.rootDir = configPath;
|
|
481
|
+
for (const configName of ["stencil.config.ts", "stencil.config.js"]) {
|
|
482
|
+
const testConfigFilePath = sys.platformPath.join(configPath, configName);
|
|
483
|
+
if ((await sys.stat(testConfigFilePath)).isFile) {
|
|
484
|
+
results.configPath = testConfigFilePath;
|
|
485
|
+
results.rootDir = sys.platformPath.dirname(testConfigFilePath);
|
|
486
|
+
break;
|
|
487
|
+
}
|
|
466
488
|
}
|
|
467
489
|
}
|
|
468
490
|
return result.ok(results);
|
|
@@ -561,7 +583,7 @@ const startupCompilerLog = (coreCompiler, config) => {
|
|
|
561
583
|
*
|
|
562
584
|
* This function applies command-line flags to the config, with CLI flags
|
|
563
585
|
* taking precedence over config file values. This is the canonical place
|
|
564
|
-
* where flag values are translated into config properties
|
|
586
|
+
* where flag values are translated into config properties.
|
|
565
587
|
*
|
|
566
588
|
* @param config The config object (from stencil.config.ts or empty)
|
|
567
589
|
* @param flags The parsed CLI flags
|
|
@@ -569,13 +591,11 @@ const startupCompilerLog = (coreCompiler, config) => {
|
|
|
569
591
|
*/
|
|
570
592
|
const mergeFlags = (config, flags) => {
|
|
571
593
|
const merged = { ...config };
|
|
572
|
-
if (flags.
|
|
573
|
-
else if (flags.dev === true) merged.devMode = true;
|
|
594
|
+
if (flags.dev === true) merged.devMode = true;
|
|
574
595
|
if (flags.debug === true || flags.verbose === true) merged.logLevel = "debug";
|
|
575
596
|
else if (flags.logLevel) merged.logLevel = flags.logLevel;
|
|
576
597
|
if (typeof flags.watch === "boolean") merged.watch = flags.watch;
|
|
577
|
-
if (
|
|
578
|
-
if (typeof flags.esm === "boolean") merged.buildDist = flags.esm;
|
|
598
|
+
if (flags.docs === true) merged._docsFlag = true;
|
|
579
599
|
if (typeof flags.profile === "boolean") merged.profile = flags.profile;
|
|
580
600
|
if (typeof flags.log === "boolean") merged.writeLog = flags.log;
|
|
581
601
|
if (typeof flags.cache === "boolean") merged.enableCache = flags.cache;
|
|
@@ -592,6 +612,739 @@ const mergeFlags = (config, flags) => {
|
|
|
592
612
|
return merged;
|
|
593
613
|
};
|
|
594
614
|
//#endregion
|
|
615
|
+
//#region src/wizard/config-editor.ts
|
|
616
|
+
async function openStencilConfig(configPath) {
|
|
617
|
+
let text = await readFile(configPath, "utf8");
|
|
618
|
+
const parse = () => ts.createSourceFile(configPath, text, ts.ScriptTarget.Latest, true);
|
|
619
|
+
function findArray(sf, propName) {
|
|
620
|
+
let found;
|
|
621
|
+
const visit = (node) => {
|
|
622
|
+
if (!found && ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === propName && ts.isArrayLiteralExpression(node.initializer)) found = node.initializer;
|
|
623
|
+
else ts.forEachChild(node, visit);
|
|
624
|
+
};
|
|
625
|
+
visit(sf);
|
|
626
|
+
return found;
|
|
627
|
+
}
|
|
628
|
+
function findConfigObject(sf) {
|
|
629
|
+
for (const stmt of sf.statements) if (ts.isVariableStatement(stmt)) {
|
|
630
|
+
for (const decl of stmt.declarationList.declarations) if (ts.isIdentifier(decl.name) && decl.name.text === "config" && decl.initializer && ts.isObjectLiteralExpression(decl.initializer)) return decl.initializer;
|
|
631
|
+
}
|
|
632
|
+
let found;
|
|
633
|
+
const visit = (node) => {
|
|
634
|
+
if (found) return;
|
|
635
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
636
|
+
if (node.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "namespace")) {
|
|
637
|
+
found = node;
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
ts.forEachChild(node, visit);
|
|
642
|
+
};
|
|
643
|
+
visit(sf);
|
|
644
|
+
return found;
|
|
645
|
+
}
|
|
646
|
+
function replaceInArray(arr, substring, expression) {
|
|
647
|
+
for (const element of arr.elements) if (text.slice(element.getStart(), element.getEnd()).includes(substring)) {
|
|
648
|
+
const lineStart = text.lastIndexOf("\n", element.getStart()) + 1;
|
|
649
|
+
const indent = text.slice(lineStart, element.getStart()).match(/^\s+/)?.[0] ?? "";
|
|
650
|
+
const indentedExpression = indent ? expression.replace(/\n/g, `\n${indent}`) : expression;
|
|
651
|
+
text = text.slice(0, element.getStart()) + indentedExpression + text.slice(element.getEnd());
|
|
652
|
+
return true;
|
|
653
|
+
}
|
|
654
|
+
return false;
|
|
655
|
+
}
|
|
656
|
+
function removeFromArray(arr, substring) {
|
|
657
|
+
const idx = arr.elements.findIndex((element) => text.slice(element.getStart(), element.getEnd()).includes(substring));
|
|
658
|
+
if (idx === -1) return false;
|
|
659
|
+
const element = arr.elements[idx];
|
|
660
|
+
if (arr.elements.length > 0 && text.slice(arr.getStart(), arr.elements[0].getStart()).includes("\n")) {
|
|
661
|
+
const lineStart = text.lastIndexOf("\n", element.getStart());
|
|
662
|
+
let end = element.getEnd();
|
|
663
|
+
const trailingComma = text.slice(end).match(/^\s*,/);
|
|
664
|
+
if (trailingComma) end += trailingComma[0].length;
|
|
665
|
+
text = text.slice(0, lineStart) + text.slice(end);
|
|
666
|
+
} else {
|
|
667
|
+
let start = element.getStart();
|
|
668
|
+
let end = element.getEnd();
|
|
669
|
+
if (idx < arr.elements.length - 1) {
|
|
670
|
+
const trailingMatch = text.slice(end).match(/^,\s*/);
|
|
671
|
+
if (trailingMatch) end += trailingMatch[0].length;
|
|
672
|
+
} else if (idx > 0) {
|
|
673
|
+
const precedingMatch = text.slice(0, start).match(/,\s*$/);
|
|
674
|
+
if (precedingMatch) start -= precedingMatch[0].length;
|
|
675
|
+
}
|
|
676
|
+
text = text.slice(0, start) + text.slice(end);
|
|
677
|
+
}
|
|
678
|
+
return true;
|
|
679
|
+
}
|
|
680
|
+
function appendToArray(arr, code) {
|
|
681
|
+
if (arr.elements.length === 0) {
|
|
682
|
+
const insertPos = arr.getEnd() - 1;
|
|
683
|
+
text = text.slice(0, insertPos) + code + text.slice(insertPos);
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
let insertPos = arr.elements[arr.elements.length - 1].getEnd();
|
|
687
|
+
const trailingComma = text.slice(insertPos).match(/^\s*,/);
|
|
688
|
+
if (trailingComma) insertPos += trailingComma[0].length;
|
|
689
|
+
const separator = trailingComma ? "" : ",";
|
|
690
|
+
const firstElemStart = arr.elements[0].getStart();
|
|
691
|
+
if (text.slice(arr.getStart(), firstElemStart).includes("\n")) {
|
|
692
|
+
const lineStart = text.lastIndexOf("\n", firstElemStart) + 1;
|
|
693
|
+
const indent = text.slice(lineStart, firstElemStart).match(/^\s+/)?.[0] ?? " ";
|
|
694
|
+
const indentedCode = code.replace(/\n/g, `\n${indent}`);
|
|
695
|
+
text = `${text.slice(0, insertPos)}${separator}\n${indent}${indentedCode}${text.slice(insertPos)}`;
|
|
696
|
+
} else text = `${text.slice(0, insertPos)}${separator} ${code}${text.slice(insertPos)}`;
|
|
697
|
+
}
|
|
698
|
+
function addArrayProp(sf, propName, code) {
|
|
699
|
+
const configObj = findConfigObject(sf);
|
|
700
|
+
if (!configObj) throw new Error("Could not find Stencil config object in stencil.config.ts");
|
|
701
|
+
let propIndent = " ";
|
|
702
|
+
if (configObj.properties.length > 0) {
|
|
703
|
+
const firstPropStart = configObj.properties[0].getStart();
|
|
704
|
+
const lineStart = text.lastIndexOf("\n", firstPropStart) + 1;
|
|
705
|
+
propIndent = text.slice(lineStart, firstPropStart).match(/^\s+/)?.[0] ?? " ";
|
|
706
|
+
}
|
|
707
|
+
const elemIndent = propIndent + " ";
|
|
708
|
+
const newProp = `${propName}: [\n${elemIndent}${code.replace(/\n/g, `\n${elemIndent}`)},\n${propIndent}]`;
|
|
709
|
+
const lastProp = configObj.properties[configObj.properties.length - 1];
|
|
710
|
+
if (lastProp) {
|
|
711
|
+
let insertPos = lastProp.getEnd();
|
|
712
|
+
const trailingComma = text.slice(insertPos).match(/^\s*,/);
|
|
713
|
+
const separator = trailingComma ? "" : ",";
|
|
714
|
+
if (trailingComma) insertPos += trailingComma[0].length;
|
|
715
|
+
text = `${text.slice(0, insertPos)}${separator}\n${propIndent}${newProp}${text.slice(insertPos)}`;
|
|
716
|
+
} else {
|
|
717
|
+
const insertPos = configObj.getEnd() - 1;
|
|
718
|
+
text = `${text.slice(0, insertPos)}\n${propIndent}${newProp},\n${text.slice(insertPos)}`;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
return {
|
|
722
|
+
hasImport(moduleSpecifier) {
|
|
723
|
+
return parse().statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier);
|
|
724
|
+
},
|
|
725
|
+
addImport(moduleSpecifier, namedImports) {
|
|
726
|
+
const sf = parse();
|
|
727
|
+
if (sf.statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier)) return;
|
|
728
|
+
let insertPos = 0;
|
|
729
|
+
for (const s of sf.statements) if (ts.isImportDeclaration(s)) insertPos = s.getEnd();
|
|
730
|
+
const decl = `\nimport { ${namedImports.join(", ")} } from '${moduleSpecifier}';`;
|
|
731
|
+
text = insertPos > 0 ? text.slice(0, insertPos) + decl + text.slice(insertPos) : decl + "\n" + text;
|
|
732
|
+
},
|
|
733
|
+
outputTargetsContains(substring) {
|
|
734
|
+
const arr = findArray(parse(), "outputTargets");
|
|
735
|
+
return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
|
|
736
|
+
},
|
|
737
|
+
addOutputTarget(expression) {
|
|
738
|
+
const sf = parse();
|
|
739
|
+
const arr = findArray(sf, "outputTargets");
|
|
740
|
+
if (arr) appendToArray(arr, expression);
|
|
741
|
+
else addArrayProp(sf, "outputTargets", expression);
|
|
742
|
+
},
|
|
743
|
+
replaceOutputTarget(substring, expression) {
|
|
744
|
+
const arr = findArray(parse(), "outputTargets");
|
|
745
|
+
return arr ? replaceInArray(arr, substring, expression) : false;
|
|
746
|
+
},
|
|
747
|
+
removeOutputTarget(substring) {
|
|
748
|
+
const arr = findArray(parse(), "outputTargets");
|
|
749
|
+
return arr ? removeFromArray(arr, substring) : false;
|
|
750
|
+
},
|
|
751
|
+
pluginsContains(substring) {
|
|
752
|
+
const arr = findArray(parse(), "plugins");
|
|
753
|
+
return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
|
|
754
|
+
},
|
|
755
|
+
addPlugin(expression) {
|
|
756
|
+
const sf = parse();
|
|
757
|
+
const arr = findArray(sf, "plugins");
|
|
758
|
+
if (arr) appendToArray(arr, expression);
|
|
759
|
+
else addArrayProp(sf, "plugins", expression);
|
|
760
|
+
},
|
|
761
|
+
replacePlugin(substring, expression) {
|
|
762
|
+
const arr = findArray(parse(), "plugins");
|
|
763
|
+
return arr ? replaceInArray(arr, substring, expression) : false;
|
|
764
|
+
},
|
|
765
|
+
removePlugin(substring) {
|
|
766
|
+
const arr = findArray(parse(), "plugins");
|
|
767
|
+
return arr ? removeFromArray(arr, substring) : false;
|
|
768
|
+
},
|
|
769
|
+
async save() {
|
|
770
|
+
await writeFile(configPath, text, "utf8");
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
//#endregion
|
|
775
|
+
//#region src/wizard/discover.ts
|
|
776
|
+
function toStringRecord(val) {
|
|
777
|
+
return val !== null && typeof val === "object" ? val : {};
|
|
778
|
+
}
|
|
779
|
+
async function readJson$1(filePath) {
|
|
780
|
+
try {
|
|
781
|
+
return JSON.parse(await readFile(filePath, "utf8"));
|
|
782
|
+
} catch {
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
async function loadOne(rootDir, packageName, loader) {
|
|
787
|
+
const info = await getPackageInfo(packageName, { paths: [rootDir] });
|
|
788
|
+
if (!info) return null;
|
|
789
|
+
const wizardEntry = info.packageJson.stencil?.wizard;
|
|
790
|
+
if (!wizardEntry) return null;
|
|
791
|
+
const wizardPath = join(info.rootPath, wizardEntry);
|
|
792
|
+
let mod;
|
|
793
|
+
try {
|
|
794
|
+
mod = await loader(pathToFileURL(wizardPath).href);
|
|
795
|
+
} catch {
|
|
796
|
+
console.warn(`[stencil] ${packageName} declares stencil.wizard but the module failed to load: ${wizardPath}`);
|
|
797
|
+
return null;
|
|
798
|
+
}
|
|
799
|
+
const plugin = mod.wizard;
|
|
800
|
+
if (!plugin || typeof plugin !== "object") {
|
|
801
|
+
console.warn(`[stencil] ${packageName} declares stencil.wizard but does not export a 'wizard' object`);
|
|
802
|
+
return null;
|
|
803
|
+
}
|
|
804
|
+
return {
|
|
805
|
+
packageName,
|
|
806
|
+
plugin
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Scans the project's declared dependencies for packages that expose a
|
|
811
|
+
* `stencil.wizard` entry in their `package.json` and dynamically imports
|
|
812
|
+
* each matching module.
|
|
813
|
+
*
|
|
814
|
+
* @param rootDir - Absolute path to the project root (where `package.json` lives).
|
|
815
|
+
* @param loader - Module loader; injectable for testing. Defaults to `import()`.
|
|
816
|
+
* @returns Array of successfully loaded plugins, in dependency declaration order.
|
|
817
|
+
*/
|
|
818
|
+
async function discoverPlugins(rootDir, loader = (url) => import(url)) {
|
|
819
|
+
const pkg = await readJson$1(join(rootDir, "package.json"));
|
|
820
|
+
if (!pkg) return [];
|
|
821
|
+
const depNames = [.../* @__PURE__ */ new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
|
|
822
|
+
const plugins = (await Promise.allSettled(depNames.map((name) => loadOne(rootDir, name, loader)))).filter((r) => r.status === "fulfilled" && r.value !== null).map((r) => r.value);
|
|
823
|
+
const devEnv = process.env.STENCIL_WIZARD_DEV;
|
|
824
|
+
if (devEnv) {
|
|
825
|
+
const devPaths = devEnv.split(",").map((s) => s.trim()).filter(Boolean);
|
|
826
|
+
for (const devPath of devPaths) {
|
|
827
|
+
const devPlugin = await loadDevPlugin(resolve(rootDir, devPath), loader);
|
|
828
|
+
if (devPlugin) {
|
|
829
|
+
const idx = plugins.findIndex((p) => p.packageName === devPlugin.packageName);
|
|
830
|
+
if (idx >= 0) plugins.splice(idx, 1, devPlugin);
|
|
831
|
+
else plugins.unshift(devPlugin);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
return plugins;
|
|
836
|
+
}
|
|
837
|
+
async function findDevPackageName(wizardPath) {
|
|
838
|
+
const dir = dirname(wizardPath);
|
|
839
|
+
for (const candidate of [dir, resolve(dir, "..")]) {
|
|
840
|
+
const pkg = await readJson$1(join(candidate, "package.json"));
|
|
841
|
+
if (typeof pkg?.name === "string") return pkg.name;
|
|
842
|
+
}
|
|
843
|
+
return basename(dir);
|
|
844
|
+
}
|
|
845
|
+
async function loadDevPlugin(wizardPath, loader) {
|
|
846
|
+
const packageName = await findDevPackageName(wizardPath);
|
|
847
|
+
let mod;
|
|
848
|
+
try {
|
|
849
|
+
mod = await loader(pathToFileURL(wizardPath).href);
|
|
850
|
+
} catch {
|
|
851
|
+
console.warn(`[stencil] STENCIL_WIZARD_DEV: failed to load ${wizardPath}`);
|
|
852
|
+
return null;
|
|
853
|
+
}
|
|
854
|
+
const plugin = mod.wizard;
|
|
855
|
+
if (!plugin || typeof plugin !== "object") {
|
|
856
|
+
console.warn(`[stencil] STENCIL_WIZARD_DEV: ${wizardPath} does not export a 'wizard' object`);
|
|
857
|
+
return null;
|
|
858
|
+
}
|
|
859
|
+
return {
|
|
860
|
+
packageName,
|
|
861
|
+
plugin
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
//#endregion
|
|
865
|
+
//#region src/wizard/clack.ts
|
|
866
|
+
/**
|
|
867
|
+
* Exits cleanly if the user cancelled a prompt (Ctrl+C).
|
|
868
|
+
* Narrows the type from `T | symbol` to `T` for callers.
|
|
869
|
+
*
|
|
870
|
+
* @param value - Return value from a `@clack/prompts` prompt call.
|
|
871
|
+
*/
|
|
872
|
+
function cancelIfAborted(value) {
|
|
873
|
+
if (isCancel(value)) {
|
|
874
|
+
cancel("Cancelled.");
|
|
875
|
+
process.exit(0);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
//#endregion
|
|
879
|
+
//#region src/wizard/init/steps.ts
|
|
880
|
+
/** Well-known integrations the CLI can offer before any packages are installed. */
|
|
881
|
+
const KNOWN_INTEGRATIONS = [
|
|
882
|
+
{
|
|
883
|
+
package: "@stencil/vitest",
|
|
884
|
+
displayName: "Vitest",
|
|
885
|
+
description: "Unit / Spec / Integration / Browser testing",
|
|
886
|
+
group: "Testing"
|
|
887
|
+
},
|
|
888
|
+
{
|
|
889
|
+
package: "@stencil/playwright",
|
|
890
|
+
displayName: "Playwright",
|
|
891
|
+
description: "E2E testing",
|
|
892
|
+
group: "Testing"
|
|
893
|
+
},
|
|
894
|
+
{
|
|
895
|
+
package: "@stencil/sass",
|
|
896
|
+
displayName: "Sass",
|
|
897
|
+
description: "Sass/SCSS styles",
|
|
898
|
+
group: "Styling",
|
|
899
|
+
requiresStencilConfig: true
|
|
900
|
+
},
|
|
901
|
+
{
|
|
902
|
+
package: "@stencil/eslint-plugin",
|
|
903
|
+
displayName: "ESLint Plugin",
|
|
904
|
+
description: "Stencil-aware lint rules (ESLint or oxlint)",
|
|
905
|
+
group: "Tooling"
|
|
906
|
+
},
|
|
907
|
+
{
|
|
908
|
+
package: "@stencil/storybook-plugin",
|
|
909
|
+
displayName: "Storybook",
|
|
910
|
+
description: "Component development & documentation",
|
|
911
|
+
group: "Tooling",
|
|
912
|
+
versionRange: ">=1.0.0-0"
|
|
913
|
+
},
|
|
914
|
+
{
|
|
915
|
+
package: "@stencil/types-output-target",
|
|
916
|
+
displayName: "Types",
|
|
917
|
+
description: "TypeScript types for React, Vue, Solid, Svelte, Preact",
|
|
918
|
+
group: "Framework integrations",
|
|
919
|
+
requiresStencilConfig: true
|
|
920
|
+
},
|
|
921
|
+
{
|
|
922
|
+
package: "@stencil/react-output-target",
|
|
923
|
+
displayName: "React",
|
|
924
|
+
description: "React component wrappers",
|
|
925
|
+
group: "Framework integrations",
|
|
926
|
+
requiresStencilConfig: true,
|
|
927
|
+
needsWorkspace: true
|
|
928
|
+
},
|
|
929
|
+
{
|
|
930
|
+
package: "@stencil/angular-output-target",
|
|
931
|
+
displayName: "Angular",
|
|
932
|
+
description: "Angular component wrappers",
|
|
933
|
+
group: "Framework integrations",
|
|
934
|
+
requiresStencilConfig: true,
|
|
935
|
+
needsWorkspace: true
|
|
936
|
+
},
|
|
937
|
+
{
|
|
938
|
+
package: "@stencil/vue-output-target",
|
|
939
|
+
displayName: "Vue",
|
|
940
|
+
description: "Vue component wrappers",
|
|
941
|
+
group: "Framework integrations",
|
|
942
|
+
requiresStencilConfig: true,
|
|
943
|
+
needsWorkspace: true
|
|
944
|
+
}
|
|
945
|
+
];
|
|
946
|
+
const versionRangeByPackage = new Map(KNOWN_INTEGRATIONS.filter((i) => i.versionRange).map((i) => [i.package, i.versionRange]));
|
|
947
|
+
function withVersionRanges(packages) {
|
|
948
|
+
return packages.map((pkg) => {
|
|
949
|
+
const range = versionRangeByPackage.get(pkg);
|
|
950
|
+
return range ? `${pkg}@${range}` : pkg;
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
async function promptOutputs() {
|
|
954
|
+
const picks = await p.multiselect({
|
|
955
|
+
message: "Outputs:",
|
|
956
|
+
options: [
|
|
957
|
+
{
|
|
958
|
+
value: "loader",
|
|
959
|
+
label: "Loader",
|
|
960
|
+
hint: "performant lazy-loader; browser & bundler ready"
|
|
961
|
+
},
|
|
962
|
+
{
|
|
963
|
+
value: "standalone",
|
|
964
|
+
label: "Standalone",
|
|
965
|
+
hint: "per-component modules, import only what you need"
|
|
966
|
+
},
|
|
967
|
+
{
|
|
968
|
+
value: "ssr",
|
|
969
|
+
label: "SSR",
|
|
970
|
+
hint: "pre-render components in any JS server environment"
|
|
971
|
+
},
|
|
972
|
+
{
|
|
973
|
+
value: "ssr-wasm",
|
|
974
|
+
label: "SSR WASM",
|
|
975
|
+
hint: "experimental: compile SSR to a portable WASM binary"
|
|
976
|
+
},
|
|
977
|
+
{
|
|
978
|
+
value: "www",
|
|
979
|
+
label: "WWW",
|
|
980
|
+
hint: "app mode with dev server and optional PWA support"
|
|
981
|
+
}
|
|
982
|
+
],
|
|
983
|
+
required: false
|
|
984
|
+
});
|
|
985
|
+
cancelIfAborted(picks);
|
|
986
|
+
return picks;
|
|
987
|
+
}
|
|
988
|
+
async function promptFeatures() {
|
|
989
|
+
const picks = await p.multiselect({
|
|
990
|
+
message: "Features:",
|
|
991
|
+
options: [
|
|
992
|
+
{
|
|
993
|
+
value: "signals",
|
|
994
|
+
label: "Signals",
|
|
995
|
+
hint: "signal-backed @Prop/@State for cross-framework reactive interop"
|
|
996
|
+
},
|
|
997
|
+
{
|
|
998
|
+
value: "globalStyle",
|
|
999
|
+
label: "Global style",
|
|
1000
|
+
hint: "Global stylesheet for font definitions, CSS variables, pre-load styles etc"
|
|
1001
|
+
},
|
|
1002
|
+
{
|
|
1003
|
+
value: "globalScript",
|
|
1004
|
+
label: "Global script",
|
|
1005
|
+
hint: "Global script for initializing application-wide logic before components load"
|
|
1006
|
+
}
|
|
1007
|
+
],
|
|
1008
|
+
required: false
|
|
1009
|
+
});
|
|
1010
|
+
cancelIfAborted(picks);
|
|
1011
|
+
const set = new Set(picks);
|
|
1012
|
+
return {
|
|
1013
|
+
signals: set.has("signals"),
|
|
1014
|
+
globalStyle: set.has("globalStyle"),
|
|
1015
|
+
globalScript: set.has("globalScript")
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
async function promptDocs() {
|
|
1019
|
+
const picks = await p.multiselect({
|
|
1020
|
+
message: "Docs:",
|
|
1021
|
+
options: [
|
|
1022
|
+
{
|
|
1023
|
+
value: "cem",
|
|
1024
|
+
label: "CEM",
|
|
1025
|
+
hint: "custom-elements.json - preferred format for interop with tools like Storybook, Styleguidist, etc"
|
|
1026
|
+
},
|
|
1027
|
+
{
|
|
1028
|
+
value: "json",
|
|
1029
|
+
label: "JSON",
|
|
1030
|
+
hint: "docs.json - Stencil / Ionic centric schema"
|
|
1031
|
+
},
|
|
1032
|
+
{
|
|
1033
|
+
value: "skill",
|
|
1034
|
+
label: "AI Skill",
|
|
1035
|
+
hint: "dist/skill/SKILL.md - Agent Skill (agentskills.io) reference for AI coding agents"
|
|
1036
|
+
},
|
|
1037
|
+
{
|
|
1038
|
+
value: "vscode",
|
|
1039
|
+
label: "VS Code",
|
|
1040
|
+
hint: "vscode-data.json - editor autocomplete for your components"
|
|
1041
|
+
}
|
|
1042
|
+
],
|
|
1043
|
+
required: false
|
|
1044
|
+
});
|
|
1045
|
+
cancelIfAborted(picks);
|
|
1046
|
+
return picks;
|
|
1047
|
+
}
|
|
1048
|
+
async function promptProjectName() {
|
|
1049
|
+
const name = await p.text({
|
|
1050
|
+
message: "Project name:",
|
|
1051
|
+
defaultValue: "my-stencil-library",
|
|
1052
|
+
validate: (v) => {
|
|
1053
|
+
if (!v?.trim()) return "Project name is required";
|
|
1054
|
+
}
|
|
1055
|
+
});
|
|
1056
|
+
cancelIfAborted(name);
|
|
1057
|
+
return name;
|
|
1058
|
+
}
|
|
1059
|
+
function buildGroupedOptions(integrations) {
|
|
1060
|
+
const groups = {};
|
|
1061
|
+
for (const i of integrations) (groups[i.group] ??= []).push({
|
|
1062
|
+
value: i.package,
|
|
1063
|
+
label: i.displayName,
|
|
1064
|
+
hint: i.description
|
|
1065
|
+
});
|
|
1066
|
+
return groups;
|
|
1067
|
+
}
|
|
1068
|
+
async function promptCustomPackages() {
|
|
1069
|
+
const input = await p.text({
|
|
1070
|
+
message: "Additional packages to install:",
|
|
1071
|
+
placeholder: "e.g. my-plugin another-package (leave blank to skip)"
|
|
1072
|
+
});
|
|
1073
|
+
cancelIfAborted(input);
|
|
1074
|
+
if (typeof input !== "string" || !input.trim()) return [];
|
|
1075
|
+
return input.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
|
|
1076
|
+
}
|
|
1077
|
+
async function promptIntegrations() {
|
|
1078
|
+
const picks = await p.groupMultiselect({
|
|
1079
|
+
message: "Add integrations (optional):",
|
|
1080
|
+
options: buildGroupedOptions(KNOWN_INTEGRATIONS),
|
|
1081
|
+
required: false
|
|
1082
|
+
});
|
|
1083
|
+
cancelIfAborted(picks);
|
|
1084
|
+
return KNOWN_INTEGRATIONS.filter((i) => picks.includes(i.package));
|
|
1085
|
+
}
|
|
1086
|
+
function hasFrameworkTargets(integrations) {
|
|
1087
|
+
return integrations.some((i) => i.needsWorkspace);
|
|
1088
|
+
}
|
|
1089
|
+
function needsStencilConfig(integrations) {
|
|
1090
|
+
return integrations.some((i) => i.requiresStencilConfig);
|
|
1091
|
+
}
|
|
1092
|
+
async function promptMonorepo() {
|
|
1093
|
+
const answer = await p.confirm({
|
|
1094
|
+
message: "Set up as a monorepo workspace? (recommended for publishing framework wrappers)",
|
|
1095
|
+
initialValue: true
|
|
1096
|
+
});
|
|
1097
|
+
cancelIfAborted(answer);
|
|
1098
|
+
return answer;
|
|
1099
|
+
}
|
|
1100
|
+
async function promptWorkspaceCoreName() {
|
|
1101
|
+
const name = await p.text({
|
|
1102
|
+
message: "Core package directory name:",
|
|
1103
|
+
defaultValue: "core",
|
|
1104
|
+
placeholder: "core"
|
|
1105
|
+
});
|
|
1106
|
+
cancelIfAborted(name);
|
|
1107
|
+
return name || "core";
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Prompt for actions on an existing project: install new integrations and/or
|
|
1111
|
+
* run init wizards for already-installed packages with wizard contributions.
|
|
1112
|
+
*
|
|
1113
|
+
* @param installable - KNOWN_INTEGRATIONS not yet present in the project.
|
|
1114
|
+
* @param configurable - Already-installed plugins that declare an `init` contribution.
|
|
1115
|
+
* @returns Selected integrations to install and plugins to configure.
|
|
1116
|
+
*/
|
|
1117
|
+
async function promptAddCapabilities(installable, configurable) {
|
|
1118
|
+
const options = {};
|
|
1119
|
+
if (installable.length > 0) options["Install new integrations"] = installable.map((i) => ({
|
|
1120
|
+
value: `install:${i.package}`,
|
|
1121
|
+
label: i.displayName,
|
|
1122
|
+
hint: i.description
|
|
1123
|
+
}));
|
|
1124
|
+
if (configurable.length > 0) options["Configure existing integrations"] = configurable.map((d) => ({
|
|
1125
|
+
value: `configure:${d.packageName}`,
|
|
1126
|
+
label: d.plugin.init.displayName,
|
|
1127
|
+
hint: d.plugin.init.description
|
|
1128
|
+
}));
|
|
1129
|
+
const picks = await p.groupMultiselect({
|
|
1130
|
+
message: "What would you like to do?",
|
|
1131
|
+
options,
|
|
1132
|
+
required: false
|
|
1133
|
+
});
|
|
1134
|
+
cancelIfAborted(picks);
|
|
1135
|
+
const pickedSet = new Set(picks);
|
|
1136
|
+
return {
|
|
1137
|
+
toInstall: installable.filter((i) => pickedSet.has(`install:${i.package}`)),
|
|
1138
|
+
toConfigure: configurable.filter((d) => pickedSet.has(`configure:${d.packageName}`))
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
//#endregion
|
|
1142
|
+
//#region src/wizard/project.ts
|
|
1143
|
+
/**
|
|
1144
|
+
* Extracts the stable, plugin-relevant fields from a fully-resolved compiler config.
|
|
1145
|
+
* @param validated The fully-resolved compiler config.
|
|
1146
|
+
* @returns A ProjectConfig with only the fields relevant to plugins and the wizard.
|
|
1147
|
+
* This is a stable subset of the compiler config that won't change between versions.
|
|
1148
|
+
*/
|
|
1149
|
+
function toProjectConfig(validated) {
|
|
1150
|
+
return {
|
|
1151
|
+
rootDir: validated.rootDir,
|
|
1152
|
+
srcDir: validated.srcDir,
|
|
1153
|
+
namespace: validated.namespace,
|
|
1154
|
+
fsNamespace: validated.fsNamespace,
|
|
1155
|
+
outputTargets: validated.outputTargets ?? [],
|
|
1156
|
+
globalScript: validated.globalScript,
|
|
1157
|
+
globalStyle: validated.globalStyle,
|
|
1158
|
+
compat: validated.compat,
|
|
1159
|
+
signalBacking: validated.signalBacking
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
/**
|
|
1163
|
+
* Builds a minimal ProjectConfig when no validated config is available (e.g. new project, no compiler).
|
|
1164
|
+
* @param rootDir The root directory of the project.
|
|
1165
|
+
* @param overrides Optional fields to override the defaults.
|
|
1166
|
+
* @returns A ProjectConfig with reasonable defaults for a new project.
|
|
1167
|
+
* */
|
|
1168
|
+
function defaultProjectConfig(rootDir, overrides) {
|
|
1169
|
+
const namespace = overrides?.namespace ?? "";
|
|
1170
|
+
return {
|
|
1171
|
+
rootDir,
|
|
1172
|
+
srcDir: join(rootDir, "src"),
|
|
1173
|
+
namespace,
|
|
1174
|
+
fsNamespace: overrides?.fsNamespace ?? namespace.toLowerCase(),
|
|
1175
|
+
outputTargets: [],
|
|
1176
|
+
...overrides
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* Walk up from `startDir` looking for a monorepo workspace root — a directory
|
|
1181
|
+
* containing `pnpm-workspace.yaml` or a `package.json` with a `workspaces` field.
|
|
1182
|
+
* Stops at the home directory or filesystem root. Returns `undefined` if none found.
|
|
1183
|
+
* @param startDir The directory to start searching from.
|
|
1184
|
+
* @returns A promise that resolves to the workspace root directory, or undefined if none found.
|
|
1185
|
+
*/
|
|
1186
|
+
async function detectWorkspaceRoot(startDir) {
|
|
1187
|
+
const home = homedir();
|
|
1188
|
+
let dir = startDir;
|
|
1189
|
+
while (true) {
|
|
1190
|
+
if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
|
|
1191
|
+
try {
|
|
1192
|
+
const pkg = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
|
|
1193
|
+
if (Array.isArray(pkg.workspaces)) return dir;
|
|
1194
|
+
} catch {}
|
|
1195
|
+
const parent = dirname(dir);
|
|
1196
|
+
if (parent === dir || dir === home) return void 0;
|
|
1197
|
+
dir = parent;
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* Returns true if the directory looks like an existing Stencil project:
|
|
1202
|
+
* - has an explicit `stencil.config.ts`, OR
|
|
1203
|
+
* - has `.tsx` files under `src/` (zero-config project).
|
|
1204
|
+
* @param dir The directory to check for an existing Stencil project.
|
|
1205
|
+
* @returns A promise that resolves to true if the directory looks like an existing Stencil project, false otherwise.
|
|
1206
|
+
*/
|
|
1207
|
+
async function isExistingStencilProject(dir) {
|
|
1208
|
+
if (existsSync(join(dir, "stencil.config.ts"))) return true;
|
|
1209
|
+
try {
|
|
1210
|
+
return (await readdir(join(dir, "src"), {
|
|
1211
|
+
recursive: true,
|
|
1212
|
+
withFileTypes: true
|
|
1213
|
+
})).some((e) => e.isFile() && e.name.endsWith(".tsx"));
|
|
1214
|
+
} catch {
|
|
1215
|
+
return false;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
//#endregion
|
|
1219
|
+
//#region src/wizard/splash.ts
|
|
1220
|
+
const CLI_VERSION = "5.0.0-alpha.30";
|
|
1221
|
+
const isTTY = process.stdout.isTTY;
|
|
1222
|
+
const noColor = !isTTY || "NO_COLOR" in process.env;
|
|
1223
|
+
const RESET = noColor ? "" : "\x1B[0m";
|
|
1224
|
+
const BOLD = noColor ? "" : "\x1B[1m";
|
|
1225
|
+
const DIM = noColor ? "" : "\x1B[2m";
|
|
1226
|
+
const BLUE = noColor ? "" : "\x1B[38;2;60;44;255m";
|
|
1227
|
+
const RAW = `\
|
|
1228
|
+
.............
|
|
1229
|
+
...................
|
|
1230
|
+
.........................
|
|
1231
|
+
..............................
|
|
1232
|
+
.................................
|
|
1233
|
+
..............████████████.........
|
|
1234
|
+
.............████████████............
|
|
1235
|
+
............████████████...............
|
|
1236
|
+
...........*************.................
|
|
1237
|
+
.........████████████████████████████....
|
|
1238
|
+
.......████████████████████████████......
|
|
1239
|
+
.....████████████████████████████........
|
|
1240
|
+
...████████████████████████████..........
|
|
1241
|
+
................*************............
|
|
1242
|
+
..............████████████.............
|
|
1243
|
+
............████████████..............
|
|
1244
|
+
.........████████████...............
|
|
1245
|
+
.................................
|
|
1246
|
+
..............................
|
|
1247
|
+
..........................
|
|
1248
|
+
......................
|
|
1249
|
+
................`;
|
|
1250
|
+
function colorize(raw) {
|
|
1251
|
+
if (noColor) return raw;
|
|
1252
|
+
let out = "";
|
|
1253
|
+
let style = "";
|
|
1254
|
+
for (const ch of raw) {
|
|
1255
|
+
const next = ".*".includes(ch) ? BLUE : "";
|
|
1256
|
+
if (next !== style) {
|
|
1257
|
+
if (style) out += RESET;
|
|
1258
|
+
if (next) out += next;
|
|
1259
|
+
style = next;
|
|
1260
|
+
}
|
|
1261
|
+
out += ch;
|
|
1262
|
+
}
|
|
1263
|
+
return style ? out + RESET : out;
|
|
1264
|
+
}
|
|
1265
|
+
const SPLASH = colorize(RAW);
|
|
1266
|
+
function printSplash() {
|
|
1267
|
+
if (!isTTY) return;
|
|
1268
|
+
const header = ` ${BOLD}Stencil${RESET} ${BLUE}v${CLI_VERSION}${RESET}`;
|
|
1269
|
+
const tagline = ` ${DIM}The Custom Element Compiler${RESET}`;
|
|
1270
|
+
process.stdout.write(`\n${SPLASH}\n\n${header}\n${tagline}\n\n`);
|
|
1271
|
+
}
|
|
1272
|
+
//#endregion
|
|
1273
|
+
//#region src/task-add.ts
|
|
1274
|
+
async function getInstalledPackageNames(rootDir) {
|
|
1275
|
+
try {
|
|
1276
|
+
const pkg = JSON.parse(await readFile(join(rootDir, "package.json"), "utf8"));
|
|
1277
|
+
const keys = (v) => Object.keys(v !== null && typeof v === "object" ? v : {});
|
|
1278
|
+
return /* @__PURE__ */ new Set([...keys(pkg.dependencies), ...keys(pkg.devDependencies)]);
|
|
1279
|
+
} catch {
|
|
1280
|
+
return /* @__PURE__ */ new Set();
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
async function selectInteractive(cwd) {
|
|
1284
|
+
const discovered = await discoverPlugins(cwd);
|
|
1285
|
+
const installed = await getInstalledPackageNames(cwd);
|
|
1286
|
+
const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
|
|
1287
|
+
const configurable = discovered.filter((d) => d.plugin.init != null);
|
|
1288
|
+
let toInstall = [];
|
|
1289
|
+
let toConfigure = [];
|
|
1290
|
+
if (installable.length > 0 || configurable.length > 0) {
|
|
1291
|
+
const result = await promptAddCapabilities(installable, configurable);
|
|
1292
|
+
toInstall = result.toInstall;
|
|
1293
|
+
toConfigure = result.toConfigure;
|
|
1294
|
+
} else p.log.info("All known integrations are already installed.");
|
|
1295
|
+
const customPackages = await promptCustomPackages();
|
|
1296
|
+
return {
|
|
1297
|
+
packagesToInstall: [...toInstall.map((i) => i.package), ...customPackages],
|
|
1298
|
+
pluginsToReconfigure: toConfigure
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
async function taskAdd(packages, strictConfig) {
|
|
1302
|
+
const cwd = process.cwd();
|
|
1303
|
+
printSplash();
|
|
1304
|
+
p.intro("stencil add");
|
|
1305
|
+
if (isCI) {
|
|
1306
|
+
p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil add`.");
|
|
1307
|
+
process.exit(1);
|
|
1308
|
+
}
|
|
1309
|
+
let packagesToInstall = packages;
|
|
1310
|
+
let pluginsToReconfigure = [];
|
|
1311
|
+
if (packages.length === 0) ({packagesToInstall, pluginsToReconfigure} = await selectInteractive(cwd));
|
|
1312
|
+
if (packagesToInstall.length === 0 && pluginsToReconfigure.length === 0) {
|
|
1313
|
+
p.outro("Nothing to do.");
|
|
1314
|
+
return;
|
|
1315
|
+
}
|
|
1316
|
+
if (packagesToInstall.length > 0) {
|
|
1317
|
+
if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: skipping install, loading wizard from ${process.env.STENCIL_WIZARD_DEV}`);
|
|
1318
|
+
else {
|
|
1319
|
+
const s = p.spinner();
|
|
1320
|
+
s.start(`Installing ${packagesToInstall.join(", ")}`);
|
|
1321
|
+
await addDevDependency(withVersionRanges(packagesToInstall), {
|
|
1322
|
+
cwd,
|
|
1323
|
+
silent: true
|
|
1324
|
+
});
|
|
1325
|
+
s.stop("Installed");
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
const config = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
|
|
1329
|
+
const workspaceRoot = await detectWorkspaceRoot(cwd);
|
|
1330
|
+
const context = {
|
|
1331
|
+
isNewProject: false,
|
|
1332
|
+
prompts: p,
|
|
1333
|
+
nypm,
|
|
1334
|
+
config,
|
|
1335
|
+
workspaceRoot,
|
|
1336
|
+
ts,
|
|
1337
|
+
openStencilConfig: () => openStencilConfig(join(config.rootDir, "stencil.config.ts"))
|
|
1338
|
+
};
|
|
1339
|
+
if (packagesToInstall.length > 0) {
|
|
1340
|
+
const discovered = await discoverPlugins(cwd);
|
|
1341
|
+
const installedSet = new Set(packagesToInstall);
|
|
1342
|
+
for (const d of discovered) if (installedSet.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run(context);
|
|
1343
|
+
}
|
|
1344
|
+
for (const d of pluginsToReconfigure) if (d.plugin.init?.run) await d.plugin.init.run(context);
|
|
1345
|
+
p.outro("Done!");
|
|
1346
|
+
}
|
|
1347
|
+
//#endregion
|
|
595
1348
|
//#region src/check-version.ts
|
|
596
1349
|
/**
|
|
597
1350
|
* Retrieve a reference to the active `CompilerSystem`'s `checkVersion` function
|
|
@@ -618,43 +1371,36 @@ const printCheckVersionResults = async (versionChecker) => {
|
|
|
618
1371
|
}
|
|
619
1372
|
};
|
|
620
1373
|
//#endregion
|
|
621
|
-
//#region src/migrations/rules/
|
|
1374
|
+
//#region src/migrations/rules/build-dist-docs.ts
|
|
622
1375
|
/**
|
|
623
|
-
* Migration rule for
|
|
1376
|
+
* Migration rule for buildDist and buildDocs removal.
|
|
624
1377
|
*
|
|
625
|
-
*
|
|
626
|
-
*
|
|
627
|
-
* -
|
|
628
|
-
* -
|
|
1378
|
+
* In Stencil v5, these global config options are replaced with per-output-target
|
|
1379
|
+
* `skipInDev` property. This migration:
|
|
1380
|
+
* - Detects `buildDist` or `buildDocs` in stencil.config.ts
|
|
1381
|
+
* - Removes the property
|
|
1382
|
+
* - For `buildDist: true` or `buildDocs: true`, adds `skipInDev: false` to relevant output targets
|
|
629
1383
|
*/
|
|
630
|
-
const
|
|
631
|
-
id: "
|
|
632
|
-
name: "
|
|
633
|
-
description: "
|
|
1384
|
+
const buildDistDocsRule = {
|
|
1385
|
+
id: "build-dist-docs",
|
|
1386
|
+
name: "buildDist/buildDocs Removal",
|
|
1387
|
+
description: "Remove deprecated buildDist and buildDocs config options",
|
|
634
1388
|
fromVersion: "4.x",
|
|
635
1389
|
toVersion: "5.x",
|
|
636
1390
|
detect(sourceFile) {
|
|
637
1391
|
const matches = [];
|
|
638
|
-
const importMap = getStencilCoreImportMap(sourceFile);
|
|
639
1392
|
const visit = (node) => {
|
|
640
|
-
if (ts.
|
|
641
|
-
const
|
|
642
|
-
if (
|
|
643
|
-
const
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
message: `Deprecated '${propName}' property found - migrate to 'encapsulation' API`,
|
|
652
|
-
line: line + 1,
|
|
653
|
-
column: character + 1
|
|
654
|
-
});
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
}
|
|
1393
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
|
|
1394
|
+
const propName = node.name.text;
|
|
1395
|
+
if (propName === "buildDist" || propName === "buildDocs") {
|
|
1396
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
1397
|
+
const isTrue = node.initializer.kind === ts.SyntaxKind.TrueKeyword;
|
|
1398
|
+
matches.push({
|
|
1399
|
+
node,
|
|
1400
|
+
message: `Deprecated '${propName}' found${isTrue ? " (set to true)" : ""} - will be removed and skipInDev added to output targets`,
|
|
1401
|
+
line: line + 1,
|
|
1402
|
+
column: character + 1
|
|
1403
|
+
});
|
|
658
1404
|
}
|
|
659
1405
|
}
|
|
660
1406
|
ts.forEachChild(node, visit);
|
|
@@ -665,38 +1411,375 @@ const encapsulationApiRule = {
|
|
|
665
1411
|
transform(sourceFile, matches) {
|
|
666
1412
|
if (matches.length === 0) return sourceFile.getFullText();
|
|
667
1413
|
let text = sourceFile.getFullText();
|
|
668
|
-
const
|
|
669
|
-
|
|
670
|
-
return b.node.getStart() - posA;
|
|
671
|
-
});
|
|
672
|
-
for (const match of sortedMatches) {
|
|
1414
|
+
const targetTypesNeedingSkipInDev = [];
|
|
1415
|
+
for (const match of matches) {
|
|
673
1416
|
const prop = match.node;
|
|
674
1417
|
const propName = prop.name.text;
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
1418
|
+
if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
|
|
1419
|
+
if (propName === "buildDist") targetTypesNeedingSkipInDev.push("dist", "dist-custom-elements", "dist-hydrate-script", "loader-bundle", "standalone", "ssr");
|
|
1420
|
+
else if (propName === "buildDocs") targetTypesNeedingSkipInDev.push("docs-readme", "docs-json", "docs-custom", "docs-vscode", "docs-custom-elements-manifest");
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
const outputTargetsToModify = [];
|
|
1424
|
+
const findOutputTargets = (node) => {
|
|
1425
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
|
|
1426
|
+
for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
|
|
1427
|
+
const typeProp = element.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type");
|
|
1428
|
+
if (typeProp && ts.isStringLiteral(typeProp.initializer)) {
|
|
1429
|
+
const targetType = typeProp.initializer.text;
|
|
1430
|
+
if (targetTypesNeedingSkipInDev.includes(targetType)) {
|
|
1431
|
+
if (!element.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "skipInDev")) outputTargetsToModify.push(element);
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
685
1434
|
}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
1435
|
+
}
|
|
1436
|
+
ts.forEachChild(node, findOutputTargets);
|
|
1437
|
+
};
|
|
1438
|
+
findOutputTargets(sourceFile);
|
|
1439
|
+
const allModifications = [];
|
|
1440
|
+
for (const match of matches) {
|
|
1441
|
+
const prop = match.node;
|
|
1442
|
+
const start = prop.getStart();
|
|
1443
|
+
let end = prop.getEnd();
|
|
693
1444
|
const afterProp = text.slice(end).match(/^\s*,/);
|
|
694
|
-
if (afterProp
|
|
695
|
-
|
|
696
|
-
|
|
1445
|
+
if (afterProp) end = end + afterProp[0].length;
|
|
1446
|
+
allModifications.push({
|
|
1447
|
+
type: "remove",
|
|
1448
|
+
start,
|
|
1449
|
+
end,
|
|
1450
|
+
node: prop
|
|
1451
|
+
});
|
|
697
1452
|
}
|
|
698
|
-
|
|
699
|
-
|
|
1453
|
+
for (const target of outputTargetsToModify) {
|
|
1454
|
+
const lastProp = target.properties[target.properties.length - 1];
|
|
1455
|
+
if (lastProp) allModifications.push({
|
|
1456
|
+
type: "addSkipInDev",
|
|
1457
|
+
start: lastProp.getEnd(),
|
|
1458
|
+
end: lastProp.getEnd(),
|
|
1459
|
+
node: target
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
allModifications.sort((a, b) => b.start - a.start);
|
|
1463
|
+
for (const mod of allModifications) if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
|
|
1464
|
+
else if (mod.type === "addSkipInDev") {
|
|
1465
|
+
const firstProp = mod.node.properties[0];
|
|
1466
|
+
let indent = " ";
|
|
1467
|
+
if (firstProp) {
|
|
1468
|
+
const propStart = firstProp.getStart();
|
|
1469
|
+
const lineStart = text.lastIndexOf("\n", propStart) + 1;
|
|
1470
|
+
const leadingWhitespace = text.slice(lineStart, propStart);
|
|
1471
|
+
if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
|
|
1472
|
+
}
|
|
1473
|
+
const afterLastProp = text.slice(mod.start).match(/^(\s*,)?/);
|
|
1474
|
+
const skipLength = afterLastProp && afterLastProp[1] ? afterLastProp[0].length : 0;
|
|
1475
|
+
text = text.slice(0, mod.start) + `,\n${indent}skipInDev: false,` + text.slice(mod.start + skipLength);
|
|
1476
|
+
}
|
|
1477
|
+
text = text.replace(/,\s*\n\s*\n/g, ",\n");
|
|
1478
|
+
text = text.replace(/{\s*\n\s*\n/g, "{\n");
|
|
1479
|
+
return text;
|
|
1480
|
+
}
|
|
1481
|
+
};
|
|
1482
|
+
//#endregion
|
|
1483
|
+
//#region src/migrations/rules/css-import-query-param.ts
|
|
1484
|
+
/**
|
|
1485
|
+
* Ambient module extensions Stencil declares its own type for. In v5 these
|
|
1486
|
+
* now require a `?stencil` query-param marker (see `stencil-ext-modules.d.ts`)
|
|
1487
|
+
* so the ambient declaration doesn't clash with other `*.css` etc. typings in
|
|
1488
|
+
* a monorepo.
|
|
1489
|
+
*/
|
|
1490
|
+
const AMBIENT_ASSET_EXTS = [
|
|
1491
|
+
".css",
|
|
1492
|
+
".svg",
|
|
1493
|
+
".txt",
|
|
1494
|
+
".frag",
|
|
1495
|
+
".vert"
|
|
1496
|
+
];
|
|
1497
|
+
const needsStencilMarker = (specifier) => {
|
|
1498
|
+
if (specifier.includes("?")) return false;
|
|
1499
|
+
const lower = specifier.toLowerCase();
|
|
1500
|
+
return AMBIENT_ASSET_EXTS.some((ext) => lower.endsWith(ext));
|
|
1501
|
+
};
|
|
1502
|
+
/**
|
|
1503
|
+
* Migration rule appending `?stencil` to raw asset import specifiers.
|
|
1504
|
+
*
|
|
1505
|
+
* Migrates:
|
|
1506
|
+
* - `import styles from './my-component.css'` → `import styles from './my-component.css?stencil'`
|
|
1507
|
+
* - `import logo from './logo.svg'` → `import logo from './logo.svg?stencil'`
|
|
1508
|
+
*
|
|
1509
|
+
* Does not touch `styleUrl`/`styleUrls` values in `@Component()` options - those are
|
|
1510
|
+
* compiler-resolved filenames, not import specifiers, and are never typed against the
|
|
1511
|
+
* ambient module declarations.
|
|
1512
|
+
*/
|
|
1513
|
+
const cssImportQueryParamRule = {
|
|
1514
|
+
id: "css-import-query-param",
|
|
1515
|
+
name: "Asset Import Query Param",
|
|
1516
|
+
description: "Append '?stencil' to raw *.css/*.svg/*.txt/*.frag/*.vert imports so they match Stencil's ambient module types",
|
|
1517
|
+
fromVersion: "4.x",
|
|
1518
|
+
toVersion: "5.x",
|
|
1519
|
+
detect(sourceFile) {
|
|
1520
|
+
const matches = [];
|
|
1521
|
+
const visit = (node) => {
|
|
1522
|
+
let specifierNode;
|
|
1523
|
+
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) specifierNode = node.moduleSpecifier;
|
|
1524
|
+
else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) specifierNode = node.arguments[0];
|
|
1525
|
+
if (specifierNode && needsStencilMarker(specifierNode.text)) {
|
|
1526
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(specifierNode.getStart());
|
|
1527
|
+
matches.push({
|
|
1528
|
+
node: specifierNode,
|
|
1529
|
+
message: `Raw asset import '${specifierNode.text}' needs a '?stencil' suffix to match Stencil's ambient module type`,
|
|
1530
|
+
line: line + 1,
|
|
1531
|
+
column: character + 1
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
ts.forEachChild(node, visit);
|
|
1535
|
+
};
|
|
1536
|
+
visit(sourceFile);
|
|
1537
|
+
return matches;
|
|
1538
|
+
},
|
|
1539
|
+
transform(sourceFile, matches) {
|
|
1540
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
1541
|
+
let text = sourceFile.getFullText();
|
|
1542
|
+
const sortedMatches = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
|
|
1543
|
+
for (const match of sortedMatches) {
|
|
1544
|
+
const node = match.node;
|
|
1545
|
+
const start = node.getStart();
|
|
1546
|
+
const end = node.getEnd();
|
|
1547
|
+
const quote = node.getText(sourceFile)[0];
|
|
1548
|
+
const updated = `${quote}${node.text}?stencil${quote}`;
|
|
1549
|
+
text = text.slice(0, start) + updated + text.slice(end);
|
|
1550
|
+
}
|
|
1551
|
+
return text;
|
|
1552
|
+
}
|
|
1553
|
+
};
|
|
1554
|
+
//#endregion
|
|
1555
|
+
//#region src/migrations/rules/dev-mode.ts
|
|
1556
|
+
/**
|
|
1557
|
+
* Migration rule for `devMode` config option removal.
|
|
1558
|
+
*
|
|
1559
|
+
* In Stencil v5, `devMode` is no longer a user-settable config option in `stencil.config.ts`.
|
|
1560
|
+
* Build mode is controlled exclusively by the `--dev` CLI flag (default is production).
|
|
1561
|
+
* This migration removes `devMode` from the config object.
|
|
1562
|
+
*/
|
|
1563
|
+
const devModeRule = {
|
|
1564
|
+
id: "dev-mode",
|
|
1565
|
+
name: "devMode Config Removal",
|
|
1566
|
+
description: "Remove deprecated devMode config option - use --dev CLI flag instead",
|
|
1567
|
+
fromVersion: "4.x",
|
|
1568
|
+
toVersion: "5.x",
|
|
1569
|
+
detect(sourceFile) {
|
|
1570
|
+
const matches = [];
|
|
1571
|
+
const visit = (node) => {
|
|
1572
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
|
|
1573
|
+
if (node.name.text === "devMode") {
|
|
1574
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
1575
|
+
matches.push({
|
|
1576
|
+
node,
|
|
1577
|
+
message: `Deprecated 'devMode' config option found - build mode is now set via the --dev CLI flag (production is the default)`,
|
|
1578
|
+
line: line + 1,
|
|
1579
|
+
column: character + 1
|
|
1580
|
+
});
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
ts.forEachChild(node, visit);
|
|
1584
|
+
};
|
|
1585
|
+
visit(sourceFile);
|
|
1586
|
+
return matches;
|
|
1587
|
+
},
|
|
1588
|
+
transform(sourceFile, matches) {
|
|
1589
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
1590
|
+
let text = sourceFile.getFullText();
|
|
1591
|
+
for (const match of [...matches].reverse()) {
|
|
1592
|
+
const node = match.node;
|
|
1593
|
+
const start = node.getFullStart();
|
|
1594
|
+
const end = node.getEnd();
|
|
1595
|
+
let removeEnd = end;
|
|
1596
|
+
const trailingComma = text.slice(end).match(/^\s*,/);
|
|
1597
|
+
if (trailingComma) removeEnd = end + trailingComma[0].length;
|
|
1598
|
+
text = text.slice(0, start) + text.slice(removeEnd);
|
|
1599
|
+
}
|
|
1600
|
+
return text;
|
|
1601
|
+
}
|
|
1602
|
+
};
|
|
1603
|
+
//#endregion
|
|
1604
|
+
//#region src/migrations/rules/encapsulation-api.ts
|
|
1605
|
+
/**
|
|
1606
|
+
* Migration rule for the @Component encapsulation API change.
|
|
1607
|
+
*
|
|
1608
|
+
* Migrates:
|
|
1609
|
+
* - `shadow: true` → `encapsulation: { type: 'shadow' }`
|
|
1610
|
+
* - `shadow: { delegatesFocus: true }` → `encapsulation: { type: 'shadow', delegatesFocus: true }`
|
|
1611
|
+
* - `scoped: true` → `encapsulation: { type: 'scoped' }`
|
|
1612
|
+
*/
|
|
1613
|
+
const encapsulationApiRule = {
|
|
1614
|
+
id: "encapsulation-api",
|
|
1615
|
+
name: "Encapsulation API",
|
|
1616
|
+
description: "Migrate shadow/scoped properties to new encapsulation API",
|
|
1617
|
+
fromVersion: "4.x",
|
|
1618
|
+
toVersion: "5.x",
|
|
1619
|
+
detect(sourceFile) {
|
|
1620
|
+
const matches = [];
|
|
1621
|
+
const importMap = getStencilCoreImportMap(sourceFile);
|
|
1622
|
+
const visit = (node) => {
|
|
1623
|
+
if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {
|
|
1624
|
+
const decoratorName = node.expression.expression;
|
|
1625
|
+
if (ts.isIdentifier(decoratorName) && isStencilDecorator(decoratorName.text, "Component", importMap)) {
|
|
1626
|
+
const [arg] = node.expression.arguments;
|
|
1627
|
+
if (arg && ts.isObjectLiteralExpression(arg)) {
|
|
1628
|
+
for (const prop of arg.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
|
|
1629
|
+
const propName = prop.name.text;
|
|
1630
|
+
if (propName === "shadow" || propName === "scoped") {
|
|
1631
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(prop.getStart());
|
|
1632
|
+
matches.push({
|
|
1633
|
+
node: prop,
|
|
1634
|
+
message: `Deprecated '${propName}' property found - migrate to 'encapsulation' API`,
|
|
1635
|
+
line: line + 1,
|
|
1636
|
+
column: character + 1
|
|
1637
|
+
});
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
ts.forEachChild(node, visit);
|
|
1644
|
+
};
|
|
1645
|
+
visit(sourceFile);
|
|
1646
|
+
return matches;
|
|
1647
|
+
},
|
|
1648
|
+
transform(sourceFile, matches) {
|
|
1649
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
1650
|
+
let text = sourceFile.getFullText();
|
|
1651
|
+
const sortedMatches = [...matches].sort((a, b) => {
|
|
1652
|
+
const posA = a.node.getStart();
|
|
1653
|
+
return b.node.getStart() - posA;
|
|
1654
|
+
});
|
|
1655
|
+
for (const match of sortedMatches) {
|
|
1656
|
+
const prop = match.node;
|
|
1657
|
+
const propName = prop.name.text;
|
|
1658
|
+
const start = prop.getStart();
|
|
1659
|
+
const end = prop.getEnd();
|
|
1660
|
+
let replacement;
|
|
1661
|
+
if (propName === "shadow") {
|
|
1662
|
+
if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'shadow' }";
|
|
1663
|
+
else if (ts.isObjectLiteralExpression(prop.initializer)) {
|
|
1664
|
+
const options = [];
|
|
1665
|
+
for (const innerProp of prop.initializer.properties) if (ts.isPropertyAssignment(innerProp) && ts.isIdentifier(innerProp.name)) {
|
|
1666
|
+
const optName = innerProp.name.text;
|
|
1667
|
+
const optValue = innerProp.initializer.getText();
|
|
1668
|
+
options.push(`${optName}: ${optValue}`);
|
|
1669
|
+
}
|
|
1670
|
+
if (options.length > 0) replacement = `encapsulation: { type: 'shadow', ${options.join(", ")} }`;
|
|
1671
|
+
else replacement = "encapsulation: { type: 'shadow' }";
|
|
1672
|
+
} else replacement = "";
|
|
1673
|
+
} else if (propName === "scoped") {
|
|
1674
|
+
if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'scoped' }";
|
|
1675
|
+
else replacement = "";
|
|
1676
|
+
} else continue;
|
|
1677
|
+
let endPos = end;
|
|
1678
|
+
const afterProp = text.slice(end).match(/^\s*,/);
|
|
1679
|
+
if (afterProp && replacement === "") endPos = end + afterProp[0].length;
|
|
1680
|
+
else if (afterProp && replacement !== "") {} else if (!afterProp && replacement !== "") {}
|
|
1681
|
+
text = text.slice(0, start) + replacement + text.slice(endPos);
|
|
1682
|
+
}
|
|
1683
|
+
return text;
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
//#endregion
|
|
1687
|
+
//#region src/migrations/rules/external-runtime.ts
|
|
1688
|
+
/**
|
|
1689
|
+
* Migration rule for `externalRuntime` on `standalone` output targets.
|
|
1690
|
+
*
|
|
1691
|
+
* In Stencil v5, `externalRuntime` defaults to `false` (was `true` in v4).
|
|
1692
|
+
* Explicit `externalRuntime: false` is now redundant and can be removed.
|
|
1693
|
+
*/
|
|
1694
|
+
const externalRuntimeRule = {
|
|
1695
|
+
id: "external-runtime",
|
|
1696
|
+
name: "externalRuntime Default Change",
|
|
1697
|
+
description: "Remove redundant 'externalRuntime: false' from standalone output targets - false is now the default",
|
|
1698
|
+
fromVersion: "4.x",
|
|
1699
|
+
toVersion: "5.x",
|
|
1700
|
+
detect(sourceFile) {
|
|
1701
|
+
const matches = [];
|
|
1702
|
+
const visit = (node) => {
|
|
1703
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "externalRuntime" && node.initializer.kind === ts.SyntaxKind.FalseKeyword) {
|
|
1704
|
+
const parent = node.parent;
|
|
1705
|
+
if (ts.isObjectLiteralExpression(parent)) {
|
|
1706
|
+
if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && p.initializer.text === "standalone")) {
|
|
1707
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
1708
|
+
matches.push({
|
|
1709
|
+
node,
|
|
1710
|
+
message: "'externalRuntime: false' is now the default - this property can be removed",
|
|
1711
|
+
line: line + 1,
|
|
1712
|
+
column: character + 1
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
ts.forEachChild(node, visit);
|
|
1718
|
+
};
|
|
1719
|
+
visit(sourceFile);
|
|
1720
|
+
return matches;
|
|
1721
|
+
},
|
|
1722
|
+
transform(sourceFile, matches) {
|
|
1723
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
1724
|
+
let text = sourceFile.getFullText();
|
|
1725
|
+
for (const match of [...matches].reverse()) {
|
|
1726
|
+
const node = match.node;
|
|
1727
|
+
const start = node.getFullStart();
|
|
1728
|
+
const end = node.getEnd();
|
|
1729
|
+
let removeEnd = end;
|
|
1730
|
+
const trailingComma = text.slice(end).match(/^\s*,/);
|
|
1731
|
+
if (trailingComma) removeEnd = end + trailingComma[0].length;
|
|
1732
|
+
text = text.slice(0, start) + text.slice(removeEnd);
|
|
1733
|
+
}
|
|
1734
|
+
return text;
|
|
1735
|
+
}
|
|
1736
|
+
};
|
|
1737
|
+
//#endregion
|
|
1738
|
+
//#region src/migrations/rules/extras-to-compat.ts
|
|
1739
|
+
/**
|
|
1740
|
+
* Migration rule: rename the top-level `extras` config key to `compat`.
|
|
1741
|
+
*
|
|
1742
|
+
* In v5, `extras` is replaced by `compat` (framework/bundler compatibility flags).
|
|
1743
|
+
*/
|
|
1744
|
+
const extrasToCompatRule = {
|
|
1745
|
+
id: "extras-to-compat",
|
|
1746
|
+
name: "Extras → Compat Rename",
|
|
1747
|
+
description: "Rename top-level 'extras' config key to 'compat'",
|
|
1748
|
+
fromVersion: "4.x",
|
|
1749
|
+
toVersion: "5.x",
|
|
1750
|
+
detect(sourceFile) {
|
|
1751
|
+
const matches = [];
|
|
1752
|
+
const visit = (node) => {
|
|
1753
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
|
|
1754
|
+
if (node.name.text === "extras") {
|
|
1755
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
1756
|
+
matches.push({
|
|
1757
|
+
node,
|
|
1758
|
+
message: "'extras' has been renamed to 'compat'",
|
|
1759
|
+
line: line + 1,
|
|
1760
|
+
column: character + 1
|
|
1761
|
+
});
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
ts.forEachChild(node, visit);
|
|
1765
|
+
};
|
|
1766
|
+
visit(sourceFile);
|
|
1767
|
+
return matches;
|
|
1768
|
+
},
|
|
1769
|
+
transform(sourceFile, matches) {
|
|
1770
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
1771
|
+
let text = sourceFile.getFullText();
|
|
1772
|
+
const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
|
|
1773
|
+
for (const match of sorted) {
|
|
1774
|
+
const node = match.node;
|
|
1775
|
+
if (node.name.text === "extras") {
|
|
1776
|
+
const keyStart = node.name.getStart();
|
|
1777
|
+
const keyEnd = node.name.getEnd();
|
|
1778
|
+
text = text.slice(0, keyStart) + "compat" + text.slice(keyEnd);
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
return text;
|
|
1782
|
+
}
|
|
700
1783
|
};
|
|
701
1784
|
//#endregion
|
|
702
1785
|
//#region src/migrations/rules/form-associated.ts
|
|
@@ -763,25 +1846,838 @@ const formAssociatedRule = {
|
|
|
763
1846
|
ts.forEachChild(node, visit);
|
|
764
1847
|
return;
|
|
765
1848
|
}
|
|
766
|
-
const classBodyStart = searchStart + braceMatch[0].length;
|
|
767
|
-
let indent = " ";
|
|
768
|
-
if (node.members.length > 0) {
|
|
769
|
-
const memberStart = node.members[0].getStart(sourceFile);
|
|
770
|
-
const indentMatch = sourceFile.getFullText().slice(classBodyStart, memberStart).match(/\n(\s+)/);
|
|
771
|
-
if (indentMatch) indent = indentMatch[1];
|
|
1849
|
+
const classBodyStart = searchStart + braceMatch[0].length;
|
|
1850
|
+
let indent = " ";
|
|
1851
|
+
if (node.members.length > 0) {
|
|
1852
|
+
const memberStart = node.members[0].getStart(sourceFile);
|
|
1853
|
+
const indentMatch = sourceFile.getFullText().slice(classBodyStart, memberStart).match(/\n(\s+)/);
|
|
1854
|
+
if (indentMatch) indent = indentMatch[1];
|
|
1855
|
+
}
|
|
1856
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(formAssociatedProp.getStart());
|
|
1857
|
+
matches.push({
|
|
1858
|
+
node: formAssociatedProp,
|
|
1859
|
+
message: hasAttachInternals ? "Remove 'formAssociated' (already has @AttachInternals)" : "Migrate 'formAssociated' to @AttachInternals decorator",
|
|
1860
|
+
line: line + 1,
|
|
1861
|
+
column: character + 1,
|
|
1862
|
+
classBodyStart,
|
|
1863
|
+
hasAttachInternals,
|
|
1864
|
+
indent,
|
|
1865
|
+
needsImport: !hasAttachInternalsImport && !hasAttachInternals,
|
|
1866
|
+
stencilImportEnd
|
|
1867
|
+
});
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
ts.forEachChild(node, visit);
|
|
1871
|
+
};
|
|
1872
|
+
visit(sourceFile);
|
|
1873
|
+
return matches;
|
|
1874
|
+
},
|
|
1875
|
+
transform(sourceFile, matches) {
|
|
1876
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
1877
|
+
let text = sourceFile.getFullText();
|
|
1878
|
+
const typedMatches = matches;
|
|
1879
|
+
const sortedMatches = [...typedMatches].sort((a, b) => {
|
|
1880
|
+
return b.classBodyStart - a.classBodyStart;
|
|
1881
|
+
});
|
|
1882
|
+
for (const match of sortedMatches) {
|
|
1883
|
+
if (!match.hasAttachInternals) {
|
|
1884
|
+
const newMember = `\n${match.indent}@AttachInternals() internals: ElementInternals;\n`;
|
|
1885
|
+
text = text.slice(0, match.classBodyStart) + newMember + text.slice(match.classBodyStart);
|
|
1886
|
+
}
|
|
1887
|
+
const prop = match.node;
|
|
1888
|
+
const start = prop.getStart();
|
|
1889
|
+
let end = prop.getEnd();
|
|
1890
|
+
const afterProp = text.slice(end).match(/^\s*,/);
|
|
1891
|
+
if (afterProp) end = end + afterProp[0].length;
|
|
1892
|
+
text = text.slice(0, start) + text.slice(end);
|
|
1893
|
+
}
|
|
1894
|
+
const firstMatch = typedMatches[0];
|
|
1895
|
+
if (firstMatch?.needsImport && firstMatch.stencilImportEnd > 0) {
|
|
1896
|
+
const importMatch = text.match(/import\s*\{([^}]*)\}\s*from\s*['"]@stencil\/core['"]/);
|
|
1897
|
+
if (importMatch) {
|
|
1898
|
+
const newImports = importMatch[1].trimEnd() + ", AttachInternals";
|
|
1899
|
+
text = text.replace(importMatch[0], `import {${newImports}} from '@stencil/core'`);
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
return text;
|
|
1903
|
+
}
|
|
1904
|
+
};
|
|
1905
|
+
//#endregion
|
|
1906
|
+
//#region src/migrations/rules/global-style-inject.ts
|
|
1907
|
+
/**
|
|
1908
|
+
* Migration rule for `extras.addGlobalStyleToComponents` → `global-style` output target `inject`.
|
|
1909
|
+
*
|
|
1910
|
+
* In v5, the `addGlobalStyleToComponents` extras option is removed. Instead, configure
|
|
1911
|
+
* the `inject` option on the `global-style` output target.
|
|
1912
|
+
*
|
|
1913
|
+
* Migration mapping:
|
|
1914
|
+
* - `addGlobalStyleToComponents: true` → `inject: 'all'`
|
|
1915
|
+
* - `addGlobalStyleToComponents: 'client'` → `inject: 'client'`
|
|
1916
|
+
* - `addGlobalStyleToComponents: false` → omit (default is 'none')
|
|
1917
|
+
*
|
|
1918
|
+
* Note: This migration only acts on explicitly set `addGlobalStyleToComponents`.
|
|
1919
|
+
* Users who relied on the implicit v4 default ('client') will need to manually
|
|
1920
|
+
* add `inject: 'client'` to their global-style output target if desired.
|
|
1921
|
+
*/
|
|
1922
|
+
const globalStyleInjectRule = {
|
|
1923
|
+
id: "global-style-inject",
|
|
1924
|
+
name: "Global Style Inject Migration",
|
|
1925
|
+
description: "Migrate extras.addGlobalStyleToComponents to global-style output target inject option",
|
|
1926
|
+
fromVersion: "4.x",
|
|
1927
|
+
toVersion: "5.x",
|
|
1928
|
+
detect(sourceFile) {
|
|
1929
|
+
const matches = [];
|
|
1930
|
+
const visit = (node) => {
|
|
1931
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "addGlobalStyleToComponents") {
|
|
1932
|
+
const parent = node.parent;
|
|
1933
|
+
if (ts.isObjectLiteralExpression(parent)) {
|
|
1934
|
+
const grandparent = parent.parent;
|
|
1935
|
+
if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
|
|
1936
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
1937
|
+
matches.push({
|
|
1938
|
+
node,
|
|
1939
|
+
message: `extras.addGlobalStyleToComponents is removed. Use 'inject' on global-style output target instead.`,
|
|
1940
|
+
line: line + 1,
|
|
1941
|
+
column: character + 1
|
|
1942
|
+
});
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
ts.forEachChild(node, visit);
|
|
1947
|
+
};
|
|
1948
|
+
visit(sourceFile);
|
|
1949
|
+
return matches;
|
|
1950
|
+
},
|
|
1951
|
+
transform(sourceFile, matches) {
|
|
1952
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
1953
|
+
let text = sourceFile.getFullText();
|
|
1954
|
+
const matchNode = matches[0].node;
|
|
1955
|
+
if (!ts.isPropertyAssignment(matchNode)) return text;
|
|
1956
|
+
let injectValue = null;
|
|
1957
|
+
if (matchNode.initializer.kind === ts.SyntaxKind.TrueKeyword) injectValue = "all";
|
|
1958
|
+
else if (ts.isStringLiteral(matchNode.initializer) && matchNode.initializer.text === "client") injectValue = "client";
|
|
1959
|
+
let insertionOffset = 0;
|
|
1960
|
+
if (injectValue) {
|
|
1961
|
+
const result = addGlobalStyleOutputTarget(text, sourceFile, injectValue);
|
|
1962
|
+
insertionOffset = result.length - text.length;
|
|
1963
|
+
text = result;
|
|
1964
|
+
}
|
|
1965
|
+
let start = matchNode.getStart();
|
|
1966
|
+
let end = matchNode.getEnd();
|
|
1967
|
+
const outputTargetsEnd = findOutputTargetsEnd(sourceFile);
|
|
1968
|
+
if (insertionOffset !== 0 && outputTargetsEnd !== null && matchNode.getStart() > outputTargetsEnd) {
|
|
1969
|
+
start += insertionOffset;
|
|
1970
|
+
end += insertionOffset;
|
|
1971
|
+
}
|
|
1972
|
+
const afterProp = text.slice(end).match(/^\s*,/);
|
|
1973
|
+
if (afterProp) end = end + afterProp[0].length;
|
|
1974
|
+
else {
|
|
1975
|
+
const beforeProp = text.slice(0, start).match(/,\s*$/);
|
|
1976
|
+
if (beforeProp) {
|
|
1977
|
+
text = text.slice(0, start - beforeProp[0].length) + text.slice(end);
|
|
1978
|
+
end = -1;
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
if (end !== -1) text = text.slice(0, start) + text.slice(end);
|
|
1982
|
+
text = cleanupEmptyExtras$1(text);
|
|
1983
|
+
return text;
|
|
1984
|
+
}
|
|
1985
|
+
};
|
|
1986
|
+
/**
|
|
1987
|
+
* Find the end position of the outputTargets array in the source file.
|
|
1988
|
+
* @param sourceFile The source file to search
|
|
1989
|
+
* @returns The end position of the outputTargets array, or null if not found
|
|
1990
|
+
*/
|
|
1991
|
+
function findOutputTargetsEnd(sourceFile) {
|
|
1992
|
+
let endPos = null;
|
|
1993
|
+
const visit = (node) => {
|
|
1994
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets") endPos = node.getEnd();
|
|
1995
|
+
ts.forEachChild(node, visit);
|
|
1996
|
+
};
|
|
1997
|
+
visit(sourceFile);
|
|
1998
|
+
return endPos;
|
|
1999
|
+
}
|
|
2000
|
+
/**
|
|
2001
|
+
* Clean up empty extras object after removing addGlobalStyleToComponents.
|
|
2002
|
+
* @param text The source text to clean up
|
|
2003
|
+
* @returns The cleaned up text with empty extras removed
|
|
2004
|
+
*/
|
|
2005
|
+
function cleanupEmptyExtras$1(text) {
|
|
2006
|
+
return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
|
|
2007
|
+
}
|
|
2008
|
+
/**
|
|
2009
|
+
* Add a global-style output target with the specified inject value.
|
|
2010
|
+
* @param text The source text to modify
|
|
2011
|
+
* @param sourceFile The source file for position info
|
|
2012
|
+
* @param injectValue The inject value to set on the new global-style output target
|
|
2013
|
+
* @returns The modified text with the new global-style output target added
|
|
2014
|
+
*/
|
|
2015
|
+
function addGlobalStyleOutputTarget(text, sourceFile, injectValue) {
|
|
2016
|
+
if (text.includes("type: 'global-style'")) return text;
|
|
2017
|
+
let outputTargetsArray = null;
|
|
2018
|
+
const findOutputTargets = (node) => {
|
|
2019
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) outputTargetsArray = node.initializer;
|
|
2020
|
+
ts.forEachChild(node, findOutputTargets);
|
|
2021
|
+
};
|
|
2022
|
+
findOutputTargets(sourceFile);
|
|
2023
|
+
if (!outputTargetsArray) return text;
|
|
2024
|
+
const array = outputTargetsArray;
|
|
2025
|
+
let indent = " ";
|
|
2026
|
+
if (array.elements.length > 0) {
|
|
2027
|
+
const elemStart = array.elements[0].getStart();
|
|
2028
|
+
const lineStart = text.lastIndexOf("\n", elemStart) + 1;
|
|
2029
|
+
const leadingWhitespace = text.slice(lineStart, elemStart);
|
|
2030
|
+
if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
|
|
2031
|
+
}
|
|
2032
|
+
const lastElement = array.elements[array.elements.length - 1];
|
|
2033
|
+
if (!lastElement) {
|
|
2034
|
+
const arrayStart = array.getStart() + 1;
|
|
2035
|
+
const newTarget = `\n${indent}{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}\n${indent.slice(2)}`;
|
|
2036
|
+
return text.slice(0, arrayStart) + newTarget + text.slice(arrayStart);
|
|
2037
|
+
}
|
|
2038
|
+
let insertPos = lastElement.getEnd();
|
|
2039
|
+
const afterLastElement = text.slice(insertPos).match(/^(\s*,)?/);
|
|
2040
|
+
const hasTrailingComma = afterLastElement && afterLastElement[1];
|
|
2041
|
+
if (hasTrailingComma) insertPos += afterLastElement[0].length;
|
|
2042
|
+
const newTarget = `{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}`;
|
|
2043
|
+
const insertion = (hasTrailingComma ? "" : ",") + "\n" + indent + newTarget;
|
|
2044
|
+
return text.slice(0, insertPos) + insertion + text.slice(insertPos);
|
|
2045
|
+
}
|
|
2046
|
+
//#endregion
|
|
2047
|
+
//#region src/migrations/rules/hash-file-names.ts
|
|
2048
|
+
/**
|
|
2049
|
+
* Migration rule for `hashFileNames` and `hashedFileNameLength` config options.
|
|
2050
|
+
*
|
|
2051
|
+
* In Stencil v5, these are no longer top-level config options. They belong on
|
|
2052
|
+
* the `loader-bundle` and `www` output targets, which are the only outputs that
|
|
2053
|
+
* are served directly in the browser and benefit from content-hash caching.
|
|
2054
|
+
*
|
|
2055
|
+
* This migration:
|
|
2056
|
+
* 1. Removes them from the top-level config
|
|
2057
|
+
* 2. Injects them into any `loader-bundle` and `www` output targets found in the same file
|
|
2058
|
+
*/
|
|
2059
|
+
const hashFileNamesRule = {
|
|
2060
|
+
id: "hash-file-names",
|
|
2061
|
+
name: "Hash File Names Config Move",
|
|
2062
|
+
description: "Move hashFileNames and hashedFileNameLength from top-level config to loader-bundle and www output targets",
|
|
2063
|
+
fromVersion: "4.x",
|
|
2064
|
+
toVersion: "5.x",
|
|
2065
|
+
detect(sourceFile) {
|
|
2066
|
+
const matches = [];
|
|
2067
|
+
const visit = (node) => {
|
|
2068
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "hashFileNames" || node.name.text === "hashedFileNameLength")) {
|
|
2069
|
+
const parent = node.parent;
|
|
2070
|
+
if (ts.isObjectLiteralExpression(parent)) {
|
|
2071
|
+
if (!parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
|
|
2072
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2073
|
+
matches.push({
|
|
2074
|
+
node,
|
|
2075
|
+
message: `'${node.name.text}' is no longer a top-level config option. Move it to your 'loader-bundle' and/or 'www' output targets.`,
|
|
2076
|
+
line: line + 1,
|
|
2077
|
+
column: character + 1
|
|
2078
|
+
});
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
ts.forEachChild(node, visit);
|
|
2083
|
+
};
|
|
2084
|
+
visit(sourceFile);
|
|
2085
|
+
return matches;
|
|
2086
|
+
},
|
|
2087
|
+
transform(sourceFile, matches) {
|
|
2088
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
2089
|
+
const fullText = sourceFile.getFullText();
|
|
2090
|
+
const propsToInject = matches.map((m) => {
|
|
2091
|
+
const node = m.node;
|
|
2092
|
+
return {
|
|
2093
|
+
name: node.name.text,
|
|
2094
|
+
value: node.initializer.getText(sourceFile)
|
|
2095
|
+
};
|
|
2096
|
+
});
|
|
2097
|
+
const TARGET_TYPES = /* @__PURE__ */ new Set(["loader-bundle", "www"]);
|
|
2098
|
+
const insertionsByPos = /* @__PURE__ */ new Map();
|
|
2099
|
+
const visit = (node) => {
|
|
2100
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
2101
|
+
if (node.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && TARGET_TYPES.has(p.initializer.text))) {
|
|
2102
|
+
const existingPropNames = new Set(node.properties.filter((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name)).map((p) => p.name.text));
|
|
2103
|
+
const objStart = node.getStart(sourceFile);
|
|
2104
|
+
const objLineStart = fullText.lastIndexOf("\n", objStart) + 1;
|
|
2105
|
+
const propIndent = (fullText.slice(objLineStart, objStart).match(/^(\s*)/)?.[1] ?? "") + " ";
|
|
2106
|
+
const closingBracePos = node.getEnd() - 1;
|
|
2107
|
+
const isMultiLine = fullText.slice(objStart, node.getEnd()).includes("\n");
|
|
2108
|
+
let insertPos;
|
|
2109
|
+
if (isMultiLine) insertPos = fullText.lastIndexOf("\n", closingBracePos - 1);
|
|
2110
|
+
else {
|
|
2111
|
+
insertPos = closingBracePos;
|
|
2112
|
+
while (insertPos > 0 && fullText[insertPos - 1] === " ") insertPos--;
|
|
2113
|
+
}
|
|
2114
|
+
const existing = insertionsByPos.get(insertPos) ?? [];
|
|
2115
|
+
for (const prop of propsToInject) if (!existingPropNames.has(prop.name)) existing.push(isMultiLine ? `\n${propIndent}${prop.name}: ${prop.value},` : `, ${prop.name}: ${prop.value}`);
|
|
2116
|
+
if (existing.length > 0) insertionsByPos.set(insertPos, existing);
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
ts.forEachChild(node, visit);
|
|
2120
|
+
};
|
|
2121
|
+
visit(sourceFile);
|
|
2122
|
+
const edits = [];
|
|
2123
|
+
for (const match of matches) {
|
|
2124
|
+
const node = match.node;
|
|
2125
|
+
const start = node.getFullStart();
|
|
2126
|
+
const end = node.getEnd();
|
|
2127
|
+
let removeEnd = end;
|
|
2128
|
+
const trailingComma = fullText.slice(end).match(/^\s*,/);
|
|
2129
|
+
if (trailingComma) removeEnd = end + trailingComma[0].length;
|
|
2130
|
+
edits.push({
|
|
2131
|
+
start,
|
|
2132
|
+
end: removeEnd,
|
|
2133
|
+
replacement: ""
|
|
2134
|
+
});
|
|
2135
|
+
}
|
|
2136
|
+
for (const [pos, insertions] of insertionsByPos) edits.push({
|
|
2137
|
+
start: pos,
|
|
2138
|
+
end: pos,
|
|
2139
|
+
replacement: insertions.join("")
|
|
2140
|
+
});
|
|
2141
|
+
edits.sort((a, b) => b.start - a.start);
|
|
2142
|
+
let text = fullText;
|
|
2143
|
+
for (const edit of edits) text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);
|
|
2144
|
+
return text;
|
|
2145
|
+
}
|
|
2146
|
+
};
|
|
2147
|
+
//#endregion
|
|
2148
|
+
//#region src/migrations/rules/light-dom-patches.ts
|
|
2149
|
+
/**
|
|
2150
|
+
* Migration rule for slot-fix extras → `lightDomPatches`.
|
|
2151
|
+
*
|
|
2152
|
+
* In v5, the individual slot-fix flags and `experimentalSlotFixes` umbrella are replaced
|
|
2153
|
+
* by a single `lightDomPatches` option which defaults to `true`.
|
|
2154
|
+
*
|
|
2155
|
+
* Migration mapping:
|
|
2156
|
+
* - `experimentalSlotFixes: true` → remove (new default is `true`)
|
|
2157
|
+
* - `experimentalSlotFixes: false` → `lightDomPatches: false`
|
|
2158
|
+
* - Individual flags only → `lightDomPatches: { <new names> }`
|
|
2159
|
+
*
|
|
2160
|
+
* Old → new individual key names:
|
|
2161
|
+
* appendChildSlotFix → domMutations
|
|
2162
|
+
* cloneNodeFix → cloneNode
|
|
2163
|
+
* scopedSlotTextContentFix → textContent
|
|
2164
|
+
* slotChildNodesFix → childNodes
|
|
2165
|
+
*/
|
|
2166
|
+
const lightDomPatchesRule = {
|
|
2167
|
+
id: "light-dom-patches",
|
|
2168
|
+
name: "Light DOM Patches Migration",
|
|
2169
|
+
description: "Migrate experimentalSlotFixes / individual slot-fix flags to lightDomPatches",
|
|
2170
|
+
fromVersion: "4.x",
|
|
2171
|
+
toVersion: "5.x",
|
|
2172
|
+
detect(sourceFile) {
|
|
2173
|
+
const matches = [];
|
|
2174
|
+
const oldKeys = /* @__PURE__ */ new Set([
|
|
2175
|
+
"experimentalSlotFixes",
|
|
2176
|
+
"appendChildSlotFix",
|
|
2177
|
+
"cloneNodeFix",
|
|
2178
|
+
"scopedSlotTextContentFix",
|
|
2179
|
+
"slotChildNodesFix"
|
|
2180
|
+
]);
|
|
2181
|
+
const visit = (node) => {
|
|
2182
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && oldKeys.has(node.name.text)) {
|
|
2183
|
+
const parent = node.parent;
|
|
2184
|
+
if (ts.isObjectLiteralExpression(parent)) {
|
|
2185
|
+
const grandparent = parent.parent;
|
|
2186
|
+
if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
|
|
2187
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2188
|
+
matches.push({
|
|
2189
|
+
node,
|
|
2190
|
+
message: `extras.${node.name.text} is removed. Use 'extras.lightDomPatches' instead.`,
|
|
2191
|
+
line: line + 1,
|
|
2192
|
+
column: character + 1
|
|
2193
|
+
});
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
ts.forEachChild(node, visit);
|
|
2198
|
+
};
|
|
2199
|
+
visit(sourceFile);
|
|
2200
|
+
return matches;
|
|
2201
|
+
},
|
|
2202
|
+
transform(sourceFile, matches) {
|
|
2203
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
2204
|
+
const oldKeyMap = {};
|
|
2205
|
+
for (const match of matches) {
|
|
2206
|
+
const node = match.node;
|
|
2207
|
+
const key = node.name.text;
|
|
2208
|
+
const init = node.initializer;
|
|
2209
|
+
oldKeyMap[key] = init.kind === ts.SyntaxKind.TrueKeyword ? true : init.kind === ts.SyntaxKind.FalseKeyword ? false : void 0;
|
|
2210
|
+
}
|
|
2211
|
+
const keyRename = {
|
|
2212
|
+
appendChildSlotFix: "domMutations",
|
|
2213
|
+
cloneNodeFix: "cloneNode",
|
|
2214
|
+
scopedSlotTextContentFix: "textContent",
|
|
2215
|
+
slotChildNodesFix: "childNodes"
|
|
2216
|
+
};
|
|
2217
|
+
const experimentalValue = oldKeyMap["experimentalSlotFixes"];
|
|
2218
|
+
const hasIndividualKeys = matches.some((m) => {
|
|
2219
|
+
return m.node.name.text !== "experimentalSlotFixes";
|
|
2220
|
+
});
|
|
2221
|
+
let replacement = null;
|
|
2222
|
+
if (experimentalValue === true && !hasIndividualKeys) replacement = null;
|
|
2223
|
+
else if (experimentalValue === false && !hasIndividualKeys) replacement = "lightDomPatches: false";
|
|
2224
|
+
else if (experimentalValue === true && hasIndividualKeys) replacement = null;
|
|
2225
|
+
else {
|
|
2226
|
+
const parts = [];
|
|
2227
|
+
for (const [oldKey, newKey] of Object.entries(keyRename)) {
|
|
2228
|
+
const val = oldKeyMap[oldKey];
|
|
2229
|
+
if (val === true) parts.push(`${newKey}: true`);
|
|
2230
|
+
else if (val === false) parts.push(`${newKey}: false`);
|
|
2231
|
+
}
|
|
2232
|
+
if (parts.length > 0) replacement = `lightDomPatches: { ${parts.join(", ")} }`;
|
|
2233
|
+
}
|
|
2234
|
+
const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
|
|
2235
|
+
let text = sourceFile.getFullText();
|
|
2236
|
+
let replacementInserted = false;
|
|
2237
|
+
for (const match of sorted) {
|
|
2238
|
+
const node = match.node;
|
|
2239
|
+
let start = node.getStart();
|
|
2240
|
+
let end = node.getEnd();
|
|
2241
|
+
const trailingComma = text.slice(end).match(/^(\s*,)/);
|
|
2242
|
+
if (trailingComma) end += trailingComma[1].length;
|
|
2243
|
+
else {
|
|
2244
|
+
const leadingComma = text.slice(0, start).match(/,\s*$/);
|
|
2245
|
+
if (leadingComma) start -= leadingComma[0].length;
|
|
2246
|
+
}
|
|
2247
|
+
if (!replacementInserted && replacement !== null) {
|
|
2248
|
+
text = text.slice(0, start) + replacement + text.slice(end);
|
|
2249
|
+
replacementInserted = true;
|
|
2250
|
+
} else text = text.slice(0, start) + text.slice(end);
|
|
2251
|
+
}
|
|
2252
|
+
text = cleanupEmptyExtras(text);
|
|
2253
|
+
return text;
|
|
2254
|
+
}
|
|
2255
|
+
};
|
|
2256
|
+
function cleanupEmptyExtras(text) {
|
|
2257
|
+
return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
|
|
2258
|
+
}
|
|
2259
|
+
//#endregion
|
|
2260
|
+
//#region src/migrations/rules/output-target-renames.ts
|
|
2261
|
+
/**
|
|
2262
|
+
* Migration rule for output target renames in Stencil v5.
|
|
2263
|
+
*
|
|
2264
|
+
* This migration:
|
|
2265
|
+
* - Renames `dist` → `loader-bundle`
|
|
2266
|
+
* - Renames `dist-custom-elements` → `standalone`
|
|
2267
|
+
* - Renames `dist-hydrate-script` → `ssr`
|
|
2268
|
+
* - Renames `dist-collection` → `collection`
|
|
2269
|
+
* - Renames `dist-types` → `types`
|
|
2270
|
+
* - Extracts `collectionDir` from loader-bundle into separate `collection` output
|
|
2271
|
+
* - Extracts `typesDir` from loader-bundle into separate `types` output
|
|
2272
|
+
* - Renames `esmLoaderPath` → `loaderPath` (applies to all module formats, not just ESM)
|
|
2273
|
+
* - Removes `isPrimaryPackageOutputTarget` (no longer needed, package.json validation auto-detects)
|
|
2274
|
+
* - Removes `generateTypeDeclarations` (types are now auto-generated via the `types` output target)
|
|
2275
|
+
*/
|
|
2276
|
+
const outputTargetRenamesRule = {
|
|
2277
|
+
id: "output-target-renames",
|
|
2278
|
+
name: "Output Target Renames",
|
|
2279
|
+
description: "Rename output targets to new v5 names",
|
|
2280
|
+
fromVersion: "4.x",
|
|
2281
|
+
toVersion: "5.x",
|
|
2282
|
+
detect(sourceFile) {
|
|
2283
|
+
const matches = [];
|
|
2284
|
+
const oldToNewNames = {
|
|
2285
|
+
dist: "loader-bundle",
|
|
2286
|
+
"dist-custom-elements": "standalone",
|
|
2287
|
+
"dist-hydrate-script": "ssr",
|
|
2288
|
+
"dist-collection": "collection",
|
|
2289
|
+
"dist-types": "types"
|
|
2290
|
+
};
|
|
2291
|
+
const visit = (node) => {
|
|
2292
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "type" && ts.isStringLiteral(node.initializer)) {
|
|
2293
|
+
const typeValue = node.initializer.text;
|
|
2294
|
+
if (typeValue in oldToNewNames) {
|
|
2295
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2296
|
+
matches.push({
|
|
2297
|
+
node,
|
|
2298
|
+
message: `Output target type '${typeValue}' → '${oldToNewNames[typeValue]}'`,
|
|
2299
|
+
line: line + 1,
|
|
2300
|
+
column: character + 1
|
|
2301
|
+
});
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "collectionDir" || node.name.text === "typesDir")) {
|
|
2305
|
+
const parent = node.parent;
|
|
2306
|
+
if (ts.isObjectLiteralExpression(parent)) {
|
|
2307
|
+
if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
|
|
2308
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2309
|
+
const propName = node.name.text;
|
|
2310
|
+
const newType = propName === "collectionDir" ? "collection" : "types";
|
|
2311
|
+
matches.push({
|
|
2312
|
+
node,
|
|
2313
|
+
message: `Property '${propName}' will be extracted to separate '${newType}' output target`,
|
|
2314
|
+
line: line + 1,
|
|
2315
|
+
column: character + 1
|
|
2316
|
+
});
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
}
|
|
2320
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "esmLoaderPath") {
|
|
2321
|
+
const parent = node.parent;
|
|
2322
|
+
if (ts.isObjectLiteralExpression(parent)) {
|
|
2323
|
+
if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
|
|
2324
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2325
|
+
matches.push({
|
|
2326
|
+
node,
|
|
2327
|
+
message: `Property 'esmLoaderPath' renamed to 'loaderPath' (applies to all module formats)`,
|
|
2328
|
+
line: line + 1,
|
|
2329
|
+
column: character + 1
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "isPrimaryPackageOutputTarget" || node.name.text === "generateTypeDeclarations")) {
|
|
2335
|
+
const parent = node.parent;
|
|
2336
|
+
if (ts.isObjectLiteralExpression(parent)) {
|
|
2337
|
+
if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
|
|
2338
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2339
|
+
const propName = node.name.text;
|
|
2340
|
+
const reason = propName === "isPrimaryPackageOutputTarget" ? "Package.json validation now auto-detects based on configured outputs" : "Types are now auto-generated via the 'types' output target";
|
|
2341
|
+
matches.push({
|
|
2342
|
+
node,
|
|
2343
|
+
message: `Property '${propName}' is removed in v5. ${reason}`,
|
|
2344
|
+
line: line + 1,
|
|
2345
|
+
column: character + 1
|
|
2346
|
+
});
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
ts.forEachChild(node, visit);
|
|
2351
|
+
};
|
|
2352
|
+
visit(sourceFile);
|
|
2353
|
+
return matches;
|
|
2354
|
+
},
|
|
2355
|
+
transform(sourceFile, matches) {
|
|
2356
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
2357
|
+
let text = sourceFile.getFullText();
|
|
2358
|
+
const oldToNewNames = {
|
|
2359
|
+
dist: "loader-bundle",
|
|
2360
|
+
"dist-custom-elements": "standalone",
|
|
2361
|
+
"dist-hydrate-script": "ssr",
|
|
2362
|
+
"dist-collection": "collection",
|
|
2363
|
+
"dist-types": "types"
|
|
2364
|
+
};
|
|
2365
|
+
const outputTargetsToExtract = [];
|
|
2366
|
+
const findOutputTargetsToExtract = (node) => {
|
|
2367
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
|
|
2368
|
+
for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
|
|
2369
|
+
let collectionDir;
|
|
2370
|
+
let typesDir;
|
|
2371
|
+
for (const prop of element.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
|
|
2372
|
+
if (prop.name.text === "collectionDir" && ts.isStringLiteral(prop.initializer)) collectionDir = prop.initializer.text;
|
|
2373
|
+
else if (prop.name.text === "typesDir" && ts.isStringLiteral(prop.initializer)) typesDir = prop.initializer.text;
|
|
2374
|
+
}
|
|
2375
|
+
if (collectionDir || typesDir) outputTargetsToExtract.push({
|
|
2376
|
+
targetNode: element,
|
|
2377
|
+
collectionDir,
|
|
2378
|
+
typesDir
|
|
2379
|
+
});
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
ts.forEachChild(node, findOutputTargetsToExtract);
|
|
2383
|
+
};
|
|
2384
|
+
findOutputTargetsToExtract(sourceFile);
|
|
2385
|
+
const modifications = [];
|
|
2386
|
+
for (const match of matches) {
|
|
2387
|
+
const prop = match.node;
|
|
2388
|
+
const propName = prop.name.text;
|
|
2389
|
+
if (propName === "type" && ts.isStringLiteral(prop.initializer)) {
|
|
2390
|
+
const newType = oldToNewNames[prop.initializer.text];
|
|
2391
|
+
if (newType) {
|
|
2392
|
+
const start = prop.initializer.getStart() + 1;
|
|
2393
|
+
const end = prop.initializer.getEnd() - 1;
|
|
2394
|
+
modifications.push({
|
|
2395
|
+
type: "replace",
|
|
2396
|
+
start,
|
|
2397
|
+
end,
|
|
2398
|
+
replacement: newType
|
|
2399
|
+
});
|
|
2400
|
+
}
|
|
2401
|
+
} else if (propName === "esmLoaderPath") {
|
|
2402
|
+
const nameNode = prop.name;
|
|
2403
|
+
modifications.push({
|
|
2404
|
+
type: "replace",
|
|
2405
|
+
start: nameNode.getStart(),
|
|
2406
|
+
end: nameNode.getEnd(),
|
|
2407
|
+
replacement: "loaderPath"
|
|
2408
|
+
});
|
|
2409
|
+
if (ts.isStringLiteral(prop.initializer)) {
|
|
2410
|
+
const newPath = "../" + prop.initializer.text;
|
|
2411
|
+
modifications.push({
|
|
2412
|
+
type: "replace",
|
|
2413
|
+
start: prop.initializer.getStart() + 1,
|
|
2414
|
+
end: prop.initializer.getEnd() - 1,
|
|
2415
|
+
replacement: newPath
|
|
2416
|
+
});
|
|
2417
|
+
}
|
|
2418
|
+
} else if (propName === "collectionDir" || propName === "typesDir" || propName === "isPrimaryPackageOutputTarget" || propName === "generateTypeDeclarations") {
|
|
2419
|
+
const start = prop.getStart();
|
|
2420
|
+
let end = prop.getEnd();
|
|
2421
|
+
const beforeProp = text.slice(0, start).match(/,\s*$/);
|
|
2422
|
+
const afterProp = text.slice(end).match(/^\s*,/);
|
|
2423
|
+
if (afterProp) end = end + afterProp[0].length;
|
|
2424
|
+
else if (beforeProp) {
|
|
2425
|
+
const commaStart = start - beforeProp[0].length;
|
|
2426
|
+
modifications.push({
|
|
2427
|
+
type: "remove",
|
|
2428
|
+
start: commaStart,
|
|
2429
|
+
end
|
|
2430
|
+
});
|
|
2431
|
+
continue;
|
|
2432
|
+
}
|
|
2433
|
+
modifications.push({
|
|
2434
|
+
type: "remove",
|
|
2435
|
+
start,
|
|
2436
|
+
end
|
|
2437
|
+
});
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
modifications.sort((a, b) => b.start - a.start);
|
|
2441
|
+
for (const mod of modifications) if (mod.type === "replace") text = text.slice(0, mod.start) + mod.replacement + text.slice(mod.end);
|
|
2442
|
+
else if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
|
|
2443
|
+
if (outputTargetsToExtract.length > 0) text = addExtractedOutputTargets(text, sourceFile, outputTargetsToExtract);
|
|
2444
|
+
text = text.replace(/,\s*\n\s*\n/g, ",\n");
|
|
2445
|
+
text = text.replace(/{\s*\n\s*\n/g, "{\n");
|
|
2446
|
+
text = text.replace(/,\s*,/g, ",");
|
|
2447
|
+
return text;
|
|
2448
|
+
}
|
|
2449
|
+
};
|
|
2450
|
+
/**
|
|
2451
|
+
* Add new output targets for extracted collectionDir and typesDir.
|
|
2452
|
+
* @param text The original source text
|
|
2453
|
+
* @param sourceFile The TypeScript source file object
|
|
2454
|
+
* @param toExtract An array of objects containing the output target nodes and their collectionDir/typesDir values to extract
|
|
2455
|
+
* @returns The modified source text with new output targets added
|
|
2456
|
+
*/
|
|
2457
|
+
function addExtractedOutputTargets(text, sourceFile, toExtract) {
|
|
2458
|
+
let outputTargetsArray = null;
|
|
2459
|
+
const findOutputTargets = (node) => {
|
|
2460
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) outputTargetsArray = node.initializer;
|
|
2461
|
+
ts.forEachChild(node, findOutputTargets);
|
|
2462
|
+
};
|
|
2463
|
+
findOutputTargets(sourceFile);
|
|
2464
|
+
if (!outputTargetsArray || toExtract.length === 0) return text;
|
|
2465
|
+
const array = outputTargetsArray;
|
|
2466
|
+
let indent = " ";
|
|
2467
|
+
if (array.elements.length > 0) {
|
|
2468
|
+
const elemStart = array.elements[0].getStart();
|
|
2469
|
+
const lineStart = text.lastIndexOf("\n", elemStart) + 1;
|
|
2470
|
+
const leadingWhitespace = text.slice(lineStart, elemStart);
|
|
2471
|
+
if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
|
|
2472
|
+
}
|
|
2473
|
+
const lastElement = array.elements[array.elements.length - 1];
|
|
2474
|
+
if (!lastElement) return text;
|
|
2475
|
+
let insertPos = lastElement.getEnd();
|
|
2476
|
+
const afterLastElement = text.slice(insertPos).match(/^(\s*,)?/);
|
|
2477
|
+
if (afterLastElement && afterLastElement[1]) insertPos += afterLastElement[0].length;
|
|
2478
|
+
const newTargets = [];
|
|
2479
|
+
for (const extracted of toExtract) {
|
|
2480
|
+
if (extracted.collectionDir) newTargets.push(`{\n${indent} type: 'collection',\n${indent} dir: '${extracted.collectionDir}',\n${indent}}`);
|
|
2481
|
+
if (extracted.typesDir) newTargets.push(`{\n${indent} type: 'types',\n${indent} dir: '${extracted.typesDir}',\n${indent}}`);
|
|
2482
|
+
}
|
|
2483
|
+
if (newTargets.length === 0) return text;
|
|
2484
|
+
const insertion = ",\n" + newTargets.map((t) => `${indent}${t}`).join(",\n");
|
|
2485
|
+
text = text.slice(0, insertPos) + insertion + text.slice(insertPos);
|
|
2486
|
+
return text;
|
|
2487
|
+
}
|
|
2488
|
+
//#endregion
|
|
2489
|
+
//#region src/migrations/rules/rolldown-config.ts
|
|
2490
|
+
/**
|
|
2491
|
+
* NodeResolve fields that were valid in @rollup/plugin-node-resolve but don't exist
|
|
2492
|
+
* in rolldown's native resolver and should be removed.
|
|
2493
|
+
*/
|
|
2494
|
+
const REMOVED_NODE_RESOLVE_FIELDS = /* @__PURE__ */ new Set([
|
|
2495
|
+
"browser",
|
|
2496
|
+
"modulePaths",
|
|
2497
|
+
"dedupe",
|
|
2498
|
+
"jail",
|
|
2499
|
+
"modulesOnly",
|
|
2500
|
+
"preferBuiltins",
|
|
2501
|
+
"resolveOnly",
|
|
2502
|
+
"rootDir",
|
|
2503
|
+
"allowExportsFolderMapping"
|
|
2504
|
+
]);
|
|
2505
|
+
/** Fields renamed between @rollup/plugin-node-resolve and rolldown's native resolver. */
|
|
2506
|
+
const RENAMED_NODE_RESOLVE_FIELDS = {
|
|
2507
|
+
exportConditions: "conditionNames",
|
|
2508
|
+
moduleDirectories: "modules"
|
|
2509
|
+
};
|
|
2510
|
+
function isInsideNodeResolve(node) {
|
|
2511
|
+
const parent = node.parent;
|
|
2512
|
+
if (!ts.isObjectLiteralExpression(parent)) return false;
|
|
2513
|
+
const grandParent = parent.parent;
|
|
2514
|
+
return ts.isPropertyAssignment(grandParent) && ts.isIdentifier(grandParent.name) && grandParent.name.text === "nodeResolve";
|
|
2515
|
+
}
|
|
2516
|
+
/**
|
|
2517
|
+
* Migration rule for rolldown-related config changes in Stencil v5.
|
|
2518
|
+
*
|
|
2519
|
+
* Handles:
|
|
2520
|
+
* - `rollupConfig` → `rolldownConfig` (key rename + flatten `inputOptions`)
|
|
2521
|
+
* - `rolldownConfig: { inputOptions: { ... } }` → `rolldownConfig: { ... }` (flatten)
|
|
2522
|
+
* - `rollupPlugins` → `rolldownPlugins`
|
|
2523
|
+
* - `nodeResolve.exportConditions` → `nodeResolve.conditionNames`
|
|
2524
|
+
* - `nodeResolve.moduleDirectories` → `nodeResolve.modules`
|
|
2525
|
+
* - Removes unsupported `nodeResolve` fields (`browser`, `dedupe`, `jail`, etc.)
|
|
2526
|
+
*/
|
|
2527
|
+
const rolldownConfigRule = {
|
|
2528
|
+
id: "rolldown-config",
|
|
2529
|
+
name: "Rolldown Config Migration",
|
|
2530
|
+
description: "Migrate rollup/rolldown config options to v5 rolldown-native API",
|
|
2531
|
+
fromVersion: "4.x",
|
|
2532
|
+
toVersion: "5.x",
|
|
2533
|
+
detect(sourceFile) {
|
|
2534
|
+
const matches = [];
|
|
2535
|
+
const visit = (node) => {
|
|
2536
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
|
|
2537
|
+
const name = node.name.text;
|
|
2538
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2539
|
+
if (name === "rollupPlugins") matches.push({
|
|
2540
|
+
node,
|
|
2541
|
+
message: `'rollupPlugins' renamed to 'rolldownPlugins'`,
|
|
2542
|
+
line: line + 1,
|
|
2543
|
+
column: character + 1
|
|
2544
|
+
});
|
|
2545
|
+
else if (name === "rollupConfig" || name === "rolldownConfig") {
|
|
2546
|
+
const value = node.initializer;
|
|
2547
|
+
if (name === "rollupConfig" || ts.isObjectLiteralExpression(value) && value.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "inputOptions")) matches.push({
|
|
2548
|
+
node,
|
|
2549
|
+
message: name === "rollupConfig" ? `'rollupConfig' renamed to 'rolldownConfig'; 'inputOptions' wrapper removed` : `'rolldownConfig.inputOptions' wrapper removed - options are now top-level`,
|
|
2550
|
+
line: line + 1,
|
|
2551
|
+
column: character + 1
|
|
2552
|
+
});
|
|
2553
|
+
} else if (name in RENAMED_NODE_RESOLVE_FIELDS && isInsideNodeResolve(node)) matches.push({
|
|
2554
|
+
node,
|
|
2555
|
+
message: `'nodeResolve.${name}' renamed to 'nodeResolve.${RENAMED_NODE_RESOLVE_FIELDS[name]}'`,
|
|
2556
|
+
line: line + 1,
|
|
2557
|
+
column: character + 1
|
|
2558
|
+
});
|
|
2559
|
+
else if (REMOVED_NODE_RESOLVE_FIELDS.has(name) && isInsideNodeResolve(node)) matches.push({
|
|
2560
|
+
node,
|
|
2561
|
+
message: `'nodeResolve.${name}' is not supported by rolldown's native resolver and will be removed`,
|
|
2562
|
+
line: line + 1,
|
|
2563
|
+
column: character + 1
|
|
2564
|
+
});
|
|
2565
|
+
}
|
|
2566
|
+
ts.forEachChild(node, visit);
|
|
2567
|
+
};
|
|
2568
|
+
visit(sourceFile);
|
|
2569
|
+
return matches;
|
|
2570
|
+
},
|
|
2571
|
+
transform(sourceFile, matches) {
|
|
2572
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
2573
|
+
const edits = [];
|
|
2574
|
+
const fullText = sourceFile.getFullText();
|
|
2575
|
+
for (const match of matches) {
|
|
2576
|
+
const node = match.node;
|
|
2577
|
+
const name = node.name.text;
|
|
2578
|
+
if (name === "rollupPlugins") {
|
|
2579
|
+
const nameStart = node.name.getStart(sourceFile);
|
|
2580
|
+
const nameEnd = node.name.getEnd();
|
|
2581
|
+
edits.push({
|
|
2582
|
+
start: nameStart,
|
|
2583
|
+
end: nameEnd,
|
|
2584
|
+
replacement: "rolldownPlugins"
|
|
2585
|
+
});
|
|
2586
|
+
continue;
|
|
2587
|
+
}
|
|
2588
|
+
if (name in RENAMED_NODE_RESOLVE_FIELDS && isInsideNodeResolve(node)) {
|
|
2589
|
+
const nameStart = node.name.getStart(sourceFile);
|
|
2590
|
+
const nameEnd = node.name.getEnd();
|
|
2591
|
+
edits.push({
|
|
2592
|
+
start: nameStart,
|
|
2593
|
+
end: nameEnd,
|
|
2594
|
+
replacement: RENAMED_NODE_RESOLVE_FIELDS[name]
|
|
2595
|
+
});
|
|
2596
|
+
continue;
|
|
2597
|
+
}
|
|
2598
|
+
if (REMOVED_NODE_RESOLVE_FIELDS.has(name) && isInsideNodeResolve(node)) {
|
|
2599
|
+
const start = node.getFullStart();
|
|
2600
|
+
const end = node.getEnd();
|
|
2601
|
+
const trailingComma = fullText.slice(end).match(/^\s*,/);
|
|
2602
|
+
edits.push({
|
|
2603
|
+
start,
|
|
2604
|
+
end: trailingComma ? end + trailingComma[0].length : end,
|
|
2605
|
+
replacement: ""
|
|
2606
|
+
});
|
|
2607
|
+
continue;
|
|
2608
|
+
}
|
|
2609
|
+
if (name === "rollupConfig" || name === "rolldownConfig") {
|
|
2610
|
+
const value = node.initializer;
|
|
2611
|
+
if (!ts.isObjectLiteralExpression(value)) {
|
|
2612
|
+
if (name === "rollupConfig") {
|
|
2613
|
+
const nameStart = node.name.getStart(sourceFile);
|
|
2614
|
+
edits.push({
|
|
2615
|
+
start: nameStart,
|
|
2616
|
+
end: node.name.getEnd(),
|
|
2617
|
+
replacement: "rolldownConfig"
|
|
2618
|
+
});
|
|
2619
|
+
}
|
|
2620
|
+
continue;
|
|
2621
|
+
}
|
|
2622
|
+
const inputOptionsProp = value.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "inputOptions");
|
|
2623
|
+
if (!inputOptionsProp) {
|
|
2624
|
+
if (name === "rollupConfig") {
|
|
2625
|
+
const nameStart = node.name.getStart(sourceFile);
|
|
2626
|
+
edits.push({
|
|
2627
|
+
start: nameStart,
|
|
2628
|
+
end: node.name.getEnd(),
|
|
2629
|
+
replacement: "rolldownConfig"
|
|
2630
|
+
});
|
|
2631
|
+
}
|
|
2632
|
+
continue;
|
|
2633
|
+
}
|
|
2634
|
+
const newValueText = inputOptionsProp.initializer.getText(sourceFile);
|
|
2635
|
+
const keyStart = node.name.getStart(sourceFile);
|
|
2636
|
+
edits.push({
|
|
2637
|
+
start: keyStart,
|
|
2638
|
+
end: node.getEnd(),
|
|
2639
|
+
replacement: `rolldownConfig: ${newValueText}`
|
|
2640
|
+
});
|
|
2641
|
+
}
|
|
2642
|
+
}
|
|
2643
|
+
edits.sort((a, b) => b.start - a.start);
|
|
2644
|
+
let text = fullText;
|
|
2645
|
+
for (const edit of edits) text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);
|
|
2646
|
+
return text;
|
|
2647
|
+
}
|
|
2648
|
+
};
|
|
2649
|
+
//#endregion
|
|
2650
|
+
//#region src/migrations/rules/service-worker-default.ts
|
|
2651
|
+
/**
|
|
2652
|
+
* Migration rule for `serviceWorker: null` / `serviceWorker: false` on `www` output targets.
|
|
2653
|
+
*
|
|
2654
|
+
* In Stencil v5, `serviceWorker` defaults to `null` (disabled). Explicit `null` or `false`
|
|
2655
|
+
* values on `www` output targets are now redundant and can be removed.
|
|
2656
|
+
*/
|
|
2657
|
+
const serviceWorkerDefaultRule = {
|
|
2658
|
+
id: "service-worker-default",
|
|
2659
|
+
name: "Service Worker Default Cleanup",
|
|
2660
|
+
description: "Remove redundant 'serviceWorker: null' / 'serviceWorker: false' from www output targets - null is now the default",
|
|
2661
|
+
fromVersion: "4.x",
|
|
2662
|
+
toVersion: "5.x",
|
|
2663
|
+
detect(sourceFile) {
|
|
2664
|
+
const matches = [];
|
|
2665
|
+
const visit = (node) => {
|
|
2666
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "serviceWorker") {
|
|
2667
|
+
const init = node.initializer;
|
|
2668
|
+
if (init.kind === ts.SyntaxKind.NullKeyword || init.kind === ts.SyntaxKind.FalseKeyword) {
|
|
2669
|
+
const parent = node.parent;
|
|
2670
|
+
if (ts.isObjectLiteralExpression(parent)) {
|
|
2671
|
+
if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && p.initializer.text === "www")) {
|
|
2672
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2673
|
+
matches.push({
|
|
2674
|
+
node,
|
|
2675
|
+
message: `'serviceWorker: ${init.kind === ts.SyntaxKind.NullKeyword ? "null" : "false"}' is now the default on www output targets and can be removed`,
|
|
2676
|
+
line: line + 1,
|
|
2677
|
+
column: character + 1
|
|
2678
|
+
});
|
|
2679
|
+
}
|
|
772
2680
|
}
|
|
773
|
-
const { line, character } = sourceFile.getLineAndCharacterOfPosition(formAssociatedProp.getStart());
|
|
774
|
-
matches.push({
|
|
775
|
-
node: formAssociatedProp,
|
|
776
|
-
message: hasAttachInternals ? "Remove 'formAssociated' (already has @AttachInternals)" : "Migrate 'formAssociated' to @AttachInternals decorator",
|
|
777
|
-
line: line + 1,
|
|
778
|
-
column: character + 1,
|
|
779
|
-
classBodyStart,
|
|
780
|
-
hasAttachInternals,
|
|
781
|
-
indent,
|
|
782
|
-
needsImport: !hasAttachInternalsImport && !hasAttachInternals,
|
|
783
|
-
stencilImportEnd
|
|
784
|
-
});
|
|
785
2681
|
}
|
|
786
2682
|
}
|
|
787
2683
|
ts.forEachChild(node, visit);
|
|
@@ -792,38 +2688,113 @@ const formAssociatedRule = {
|
|
|
792
2688
|
transform(sourceFile, matches) {
|
|
793
2689
|
if (matches.length === 0) return sourceFile.getFullText();
|
|
794
2690
|
let text = sourceFile.getFullText();
|
|
795
|
-
const
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
2691
|
+
for (const match of [...matches].reverse()) {
|
|
2692
|
+
const node = match.node;
|
|
2693
|
+
let start = node.getFullStart();
|
|
2694
|
+
const end = node.getEnd();
|
|
2695
|
+
let removeEnd = end;
|
|
2696
|
+
const trailingComma = text.slice(end).match(/^\s*,/);
|
|
2697
|
+
if (trailingComma) removeEnd = end + trailingComma[0].length;
|
|
2698
|
+
else {
|
|
2699
|
+
const leadingComma = text.slice(0, start).match(/,\s*$/);
|
|
2700
|
+
if (leadingComma) start -= leadingComma[0].length;
|
|
803
2701
|
}
|
|
804
|
-
|
|
805
|
-
const start = prop.getStart();
|
|
806
|
-
let end = prop.getEnd();
|
|
807
|
-
const afterProp = text.slice(end).match(/^\s*,/);
|
|
808
|
-
if (afterProp) end = end + afterProp[0].length;
|
|
809
|
-
text = text.slice(0, start) + text.slice(end);
|
|
2702
|
+
text = text.slice(0, start) + text.slice(removeEnd);
|
|
810
2703
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
2704
|
+
return text;
|
|
2705
|
+
}
|
|
2706
|
+
};
|
|
2707
|
+
//#endregion
|
|
2708
|
+
//#region src/migrations/rules/suppress-warnings-to-compat.ts
|
|
2709
|
+
/**
|
|
2710
|
+
* Migration rule: move `suppressReservedPublicNameWarnings` / `suppressReservedEventNameWarnings`
|
|
2711
|
+
* off the top level of the config and into `compat`, dropping `Reserved` from their names.
|
|
2712
|
+
*
|
|
2713
|
+
* In v5:
|
|
2714
|
+
* suppressReservedPublicNameWarnings → compat.suppressPublicNameWarnings
|
|
2715
|
+
* suppressReservedEventNameWarnings → compat.suppressEventNameWarnings
|
|
2716
|
+
*/
|
|
2717
|
+
const KEY_RENAME = {
|
|
2718
|
+
suppressReservedPublicNameWarnings: "suppressPublicNameWarnings",
|
|
2719
|
+
suppressReservedEventNameWarnings: "suppressEventNameWarnings"
|
|
2720
|
+
};
|
|
2721
|
+
const suppressWarningsToCompatRule = {
|
|
2722
|
+
id: "suppress-warnings-to-compat",
|
|
2723
|
+
name: "Suppress Warnings → Compat",
|
|
2724
|
+
description: "Move 'suppressReservedPublicNameWarnings' / 'suppressReservedEventNameWarnings' into 'compat'",
|
|
2725
|
+
fromVersion: "4.x",
|
|
2726
|
+
toVersion: "5.x",
|
|
2727
|
+
detect(sourceFile) {
|
|
2728
|
+
const matches = [];
|
|
2729
|
+
const visit = (node) => {
|
|
2730
|
+
if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text in KEY_RENAME) {
|
|
2731
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2732
|
+
matches.push({
|
|
2733
|
+
node,
|
|
2734
|
+
message: `'${node.name.text}' has moved to 'compat.${KEY_RENAME[node.name.text]}'`,
|
|
2735
|
+
line: line + 1,
|
|
2736
|
+
column: character + 1
|
|
2737
|
+
});
|
|
2738
|
+
}
|
|
2739
|
+
ts.forEachChild(node, visit);
|
|
2740
|
+
};
|
|
2741
|
+
visit(sourceFile);
|
|
2742
|
+
return matches;
|
|
2743
|
+
},
|
|
2744
|
+
transform(sourceFile, matches) {
|
|
2745
|
+
if (matches.length === 0) return sourceFile.getFullText();
|
|
2746
|
+
const text = sourceFile.getFullText();
|
|
2747
|
+
const edits = [];
|
|
2748
|
+
const newProps = [];
|
|
2749
|
+
for (const match of matches) {
|
|
2750
|
+
const node = match.node;
|
|
2751
|
+
const key = node.name.text;
|
|
2752
|
+
newProps.push(`${KEY_RENAME[key]}: ${node.initializer.getText(sourceFile)}`);
|
|
2753
|
+
let start = node.getStart();
|
|
2754
|
+
let end = node.getEnd();
|
|
2755
|
+
const trailingComma = text.slice(end).match(/^(\s*,)/);
|
|
2756
|
+
if (trailingComma) end += trailingComma[1].length;
|
|
2757
|
+
else {
|
|
2758
|
+
const leadingComma = text.slice(0, start).match(/,\s*$/);
|
|
2759
|
+
if (leadingComma) start -= leadingComma[0].length;
|
|
817
2760
|
}
|
|
2761
|
+
edits.push({
|
|
2762
|
+
start,
|
|
2763
|
+
end,
|
|
2764
|
+
replacement: ""
|
|
2765
|
+
});
|
|
818
2766
|
}
|
|
819
|
-
|
|
2767
|
+
const parentObject = matches[0].node.parent;
|
|
2768
|
+
const existingCompat = parentObject.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "compat" && ts.isObjectLiteralExpression(p.initializer));
|
|
2769
|
+
if (existingCompat) edits.push(insertIntoObjectLiteral(existingCompat.initializer, newProps));
|
|
2770
|
+
else edits.push(insertIntoObjectLiteral(parentObject, [`compat: { ${newProps.join(", ")} }`]));
|
|
2771
|
+
let result = text;
|
|
2772
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
|
|
2773
|
+
return result;
|
|
820
2774
|
}
|
|
821
2775
|
};
|
|
2776
|
+
function insertIntoObjectLiteral(obj, newProps) {
|
|
2777
|
+
if (obj.properties.length === 0) {
|
|
2778
|
+
const pos = obj.getStart() + 1;
|
|
2779
|
+
return {
|
|
2780
|
+
start: pos,
|
|
2781
|
+
end: pos,
|
|
2782
|
+
replacement: ` ${newProps.join(", ")} `
|
|
2783
|
+
};
|
|
2784
|
+
}
|
|
2785
|
+
const last = obj.properties[obj.properties.length - 1];
|
|
2786
|
+
return {
|
|
2787
|
+
start: last.getEnd(),
|
|
2788
|
+
end: last.getEnd(),
|
|
2789
|
+
replacement: `, ${newProps.join(", ")}`
|
|
2790
|
+
};
|
|
2791
|
+
}
|
|
822
2792
|
//#endregion
|
|
823
2793
|
//#region src/migrations/index.ts
|
|
824
2794
|
/**
|
|
825
2795
|
* Build a map of local import names to their original names from @stencil/core.
|
|
826
2796
|
* Handles aliased imports like `import { Component as Cmp } from '@stencil/core'`.
|
|
2797
|
+
* Also handles multiple imports from @stencil/core (e.g., separate type and value imports).
|
|
827
2798
|
*
|
|
828
2799
|
* @param sourceFile The TypeScript source file to analyze
|
|
829
2800
|
* @returns Map where keys are local names and values are original imported names
|
|
@@ -837,7 +2808,6 @@ const getStencilCoreImportMap = (sourceFile) => {
|
|
|
837
2808
|
const originalName = element.propertyName?.text ?? element.name.text;
|
|
838
2809
|
importMap.set(localName, originalName);
|
|
839
2810
|
}
|
|
840
|
-
break;
|
|
841
2811
|
}
|
|
842
2812
|
return importMap;
|
|
843
2813
|
};
|
|
@@ -857,7 +2827,22 @@ const isStencilDecorator = (decoratorName, expectedOriginalName, importMap) => {
|
|
|
857
2827
|
* Registry of all available migration rules.
|
|
858
2828
|
* Rules are applied in order, so add new rules at the end.
|
|
859
2829
|
*/
|
|
860
|
-
const migrationRules = [
|
|
2830
|
+
const migrationRules = [
|
|
2831
|
+
encapsulationApiRule,
|
|
2832
|
+
formAssociatedRule,
|
|
2833
|
+
buildDistDocsRule,
|
|
2834
|
+
outputTargetRenamesRule,
|
|
2835
|
+
devModeRule,
|
|
2836
|
+
globalStyleInjectRule,
|
|
2837
|
+
lightDomPatchesRule,
|
|
2838
|
+
extrasToCompatRule,
|
|
2839
|
+
suppressWarningsToCompatRule,
|
|
2840
|
+
externalRuntimeRule,
|
|
2841
|
+
hashFileNamesRule,
|
|
2842
|
+
rolldownConfigRule,
|
|
2843
|
+
serviceWorkerDefaultRule,
|
|
2844
|
+
cssImportQueryParamRule
|
|
2845
|
+
];
|
|
861
2846
|
/**
|
|
862
2847
|
* Get all migration rules for a specific version upgrade.
|
|
863
2848
|
* @param fromVersion Source version (e.g., '4')
|
|
@@ -905,7 +2890,7 @@ const taskMigrate = async (coreCompiler, config, flags) => {
|
|
|
905
2890
|
const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
|
|
906
2891
|
const matches = rule.detect(sourceFile);
|
|
907
2892
|
if (matches.length > 0) {
|
|
908
|
-
const relPath = relative(config.rootDir, filePath);
|
|
2893
|
+
const relPath = relative$1(config.rootDir, filePath);
|
|
909
2894
|
logger.info(`\n${logger.cyan(relPath)}`);
|
|
910
2895
|
logger.info(` ${logger.yellow(`[${rule.id}]`)} ${rule.name}`);
|
|
911
2896
|
for (const match of matches) logger.info(` Line ${match.line}: ${match.message}`);
|
|
@@ -966,7 +2951,8 @@ const detectMigrations = async (coreCompiler, config) => {
|
|
|
966
2951
|
const sys = config.sys;
|
|
967
2952
|
const logger = config.logger;
|
|
968
2953
|
const currentMajor = coreCompiler.version.split(".")[0];
|
|
969
|
-
const
|
|
2954
|
+
const fromVersion = String(Number(currentMajor) - 1);
|
|
2955
|
+
const rules = getRulesForVersionUpgrade(fromVersion, currentMajor);
|
|
970
2956
|
if (rules.length === 0) return {
|
|
971
2957
|
hasMigrations: false,
|
|
972
2958
|
totalMatches: 0,
|
|
@@ -1017,8 +3003,8 @@ const detectMigrations = async (coreCompiler, config) => {
|
|
|
1017
3003
|
*/
|
|
1018
3004
|
async function getTypeScriptFiles(config, sys, logger) {
|
|
1019
3005
|
let tsconfigPath;
|
|
1020
|
-
if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join(config.rootDir, config.tsconfig);
|
|
1021
|
-
else tsconfigPath = join(config.rootDir, "tsconfig.json");
|
|
3006
|
+
if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join$1(config.rootDir, config.tsconfig);
|
|
3007
|
+
else tsconfigPath = join$1(config.rootDir, "tsconfig.json");
|
|
1022
3008
|
logger.debug(`Using tsconfig: ${tsconfigPath}`);
|
|
1023
3009
|
const tsconfigContent = await sys.readFile(tsconfigPath);
|
|
1024
3010
|
if (!tsconfigContent) {
|
|
@@ -1041,27 +3027,49 @@ async function getTypeScriptFiles(config, sys, logger) {
|
|
|
1041
3027
|
return [];
|
|
1042
3028
|
}
|
|
1043
3029
|
if (results.errors && results.errors.length > 0) for (const err of results.errors) logger.warn(ts.flattenDiagnosticMessageText(err.messageText, "\n"));
|
|
1044
|
-
|
|
3030
|
+
const files = results.fileNames.filter((f) => (f.endsWith(".ts") || f.endsWith(".tsx")) && !f.endsWith(".d.ts"));
|
|
3031
|
+
const configFile = config.configPath;
|
|
3032
|
+
if (configFile && (configFile.endsWith(".ts") || configFile.endsWith(".mts"))) {
|
|
3033
|
+
if (!files.includes(configFile)) files.push(configFile);
|
|
3034
|
+
const configContent = await sys.readFile(configFile);
|
|
3035
|
+
if (configContent) {
|
|
3036
|
+
const configSourceFile = ts.createSourceFile(configFile, configContent, ts.ScriptTarget.Latest, true);
|
|
3037
|
+
const configDir = dirname$1(configFile);
|
|
3038
|
+
for (const statement of configSourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
|
|
3039
|
+
const specifier = statement.moduleSpecifier.text;
|
|
3040
|
+
if (!specifier.startsWith("./") && !specifier.startsWith("../")) continue;
|
|
3041
|
+
const basePath = join$1(configDir, specifier);
|
|
3042
|
+
const candidates = basePath.endsWith(".ts") || basePath.endsWith(".tsx") ? [basePath] : [`${basePath}.ts`, `${basePath}.tsx`];
|
|
3043
|
+
for (const candidate of candidates) if (!candidate.endsWith(".d.ts") && !files.includes(candidate) && candidate.startsWith(config.rootDir)) {
|
|
3044
|
+
if (await sys.readFile(candidate)) {
|
|
3045
|
+
files.push(candidate);
|
|
3046
|
+
break;
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
return files;
|
|
1045
3053
|
}
|
|
1046
3054
|
//#endregion
|
|
1047
3055
|
//#region src/task-prerender.ts
|
|
1048
3056
|
const taskPrerender = async (coreCompiler, config, flags) => {
|
|
1049
3057
|
startupCompilerLog(coreCompiler, config);
|
|
1050
|
-
const
|
|
1051
|
-
if (typeof
|
|
3058
|
+
const ssrAppFilePath = flags.unknownArgs[0];
|
|
3059
|
+
if (typeof ssrAppFilePath !== "string") {
|
|
1052
3060
|
config.logger.error(`Missing hydrate app script path`);
|
|
1053
3061
|
return config.sys.exit(1);
|
|
1054
3062
|
}
|
|
1055
3063
|
const srcIndexHtmlPath = config.srcIndexHtml;
|
|
1056
|
-
const diagnostics = await runPrerenderTask(coreCompiler, config,
|
|
3064
|
+
const diagnostics = await runPrerenderTask(coreCompiler, config, ssrAppFilePath, void 0, srcIndexHtmlPath);
|
|
1057
3065
|
config.logger.printDiagnostics(diagnostics);
|
|
1058
3066
|
if (diagnostics.some((d) => d.level === "error")) return config.sys.exit(1);
|
|
1059
3067
|
};
|
|
1060
|
-
const runPrerenderTask = async (coreCompiler, config,
|
|
3068
|
+
const runPrerenderTask = async (coreCompiler, config, ssrAppFilePath, componentGraph, srcIndexHtmlPath) => {
|
|
1061
3069
|
const diagnostics = [];
|
|
1062
3070
|
try {
|
|
1063
3071
|
const results = await (await coreCompiler.createPrerenderer(config)).start({
|
|
1064
|
-
|
|
3072
|
+
ssrAppFilePath,
|
|
1065
3073
|
componentGraph,
|
|
1066
3074
|
srcIndexHtmlPath
|
|
1067
3075
|
});
|
|
@@ -1166,8 +3174,8 @@ function hasVerbose(flags) {
|
|
|
1166
3174
|
}
|
|
1167
3175
|
//#endregion
|
|
1168
3176
|
//#region src/ionic-config.ts
|
|
1169
|
-
const isTest
|
|
1170
|
-
const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest
|
|
3177
|
+
const isTest = () => process.env.JEST_WORKER_ID !== void 0;
|
|
3178
|
+
const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest() ? "tmp-config.json" : "config.json"}`);
|
|
1171
3179
|
const defaultConfigDirectory = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic`);
|
|
1172
3180
|
/**
|
|
1173
3181
|
* Reads an Ionic configuration file from disk, parses it, and performs any necessary corrections to it if certain
|
|
@@ -1393,7 +3401,7 @@ const anonymizeConfigForTelemetry = (config) => {
|
|
|
1393
3401
|
if (OUTPUT_TARGET_KEYS_TO_KEEP.includes(key)) return value;
|
|
1394
3402
|
return "omitted";
|
|
1395
3403
|
}));
|
|
1396
|
-
if (
|
|
3404
|
+
if (isOutputTargetSsr(target) && target.external) anonymizedOT["external"] = target.external.concat();
|
|
1397
3405
|
return anonymizedOT;
|
|
1398
3406
|
});
|
|
1399
3407
|
for (const prop of CONFIG_PROPS_TO_DELETE) delete anonymizedConfig[prop];
|
|
@@ -1587,6 +3595,23 @@ const taskBuild = async (coreCompiler, config, flags) => {
|
|
|
1587
3595
|
let exitCode = 0;
|
|
1588
3596
|
try {
|
|
1589
3597
|
startupCompilerLog(coreCompiler, config);
|
|
3598
|
+
const preBuildMigrationResult = await detectMigrations(coreCompiler, config);
|
|
3599
|
+
if (preBuildMigrationResult.hasMigrations) {
|
|
3600
|
+
const action = await promptForMigration(config, preBuildMigrationResult, "pre-build");
|
|
3601
|
+
if (action === "run") {
|
|
3602
|
+
await taskMigrate(coreCompiler, config, {
|
|
3603
|
+
...flags,
|
|
3604
|
+
dryRun: false
|
|
3605
|
+
});
|
|
3606
|
+
config.logger.info("\nMigrations applied. Starting build...\n");
|
|
3607
|
+
} else if (action === "dry-run") {
|
|
3608
|
+
await taskMigrate(coreCompiler, config, {
|
|
3609
|
+
...flags,
|
|
3610
|
+
dryRun: true
|
|
3611
|
+
});
|
|
3612
|
+
return config.sys.exit(1);
|
|
3613
|
+
} else return config.sys.exit(1);
|
|
3614
|
+
}
|
|
1590
3615
|
const versionChecker = startCheckVersion(config, coreCompiler.version, flags);
|
|
1591
3616
|
const compiler = await coreCompiler.createCompiler(config);
|
|
1592
3617
|
const results = await compiler.build();
|
|
@@ -1595,7 +3620,7 @@ const taskBuild = async (coreCompiler, config, flags) => {
|
|
|
1595
3620
|
if (results.hasError) {
|
|
1596
3621
|
const migrationResult = await detectMigrations(coreCompiler, config);
|
|
1597
3622
|
if (migrationResult.hasMigrations) {
|
|
1598
|
-
const action = await
|
|
3623
|
+
const action = await promptForMigration(config, migrationResult, "post-error");
|
|
1599
3624
|
if (action === "run") {
|
|
1600
3625
|
await taskMigrate(coreCompiler, config, {
|
|
1601
3626
|
...flags,
|
|
@@ -1608,7 +3633,7 @@ const taskBuild = async (coreCompiler, config, flags) => {
|
|
|
1608
3633
|
if (!newResults.hasError) {
|
|
1609
3634
|
exitCode = 0;
|
|
1610
3635
|
if (flags.prerender) {
|
|
1611
|
-
const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, newResults.
|
|
3636
|
+
const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, newResults.ssrAppFilePath, newResults.componentGraph, void 0);
|
|
1612
3637
|
config.logger.printDiagnostics(prerenderDiagnostics);
|
|
1613
3638
|
if (prerenderDiagnostics.some((d) => d.level === "error")) exitCode = 1;
|
|
1614
3639
|
}
|
|
@@ -1622,7 +3647,7 @@ const taskBuild = async (coreCompiler, config, flags) => {
|
|
|
1622
3647
|
} else exitCode = 1;
|
|
1623
3648
|
} else exitCode = 1;
|
|
1624
3649
|
} else if (flags.prerender) {
|
|
1625
|
-
const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, results.
|
|
3650
|
+
const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, results.ssrAppFilePath, results.componentGraph, void 0);
|
|
1626
3651
|
config.logger.printDiagnostics(prerenderDiagnostics);
|
|
1627
3652
|
if (prerenderDiagnostics.some((d) => d.level === "error")) exitCode = 1;
|
|
1628
3653
|
}
|
|
@@ -1634,49 +3659,48 @@ const taskBuild = async (coreCompiler, config, flags) => {
|
|
|
1634
3659
|
if (exitCode > 0) return config.sys.exit(exitCode);
|
|
1635
3660
|
};
|
|
1636
3661
|
/**
|
|
1637
|
-
* Prompt the user about available migrations
|
|
3662
|
+
* Prompt the user about available migrations.
|
|
1638
3663
|
* Shows what migrations are available and lets them choose to run them.
|
|
1639
3664
|
* @param config the Stencil config
|
|
1640
3665
|
* @param migrationResult the result of migration detection with available migrations
|
|
3666
|
+
* @param context whether this is a pre-build check or post-error check
|
|
1641
3667
|
* @returns the user's chosen action for handling migrations
|
|
1642
3668
|
*/
|
|
1643
|
-
async function
|
|
3669
|
+
async function promptForMigration(config, migrationResult, context) {
|
|
1644
3670
|
const logger = config.logger;
|
|
1645
3671
|
logger.info("");
|
|
1646
|
-
logger.info(logger.bold(logger.yellow("Migrations
|
|
3672
|
+
logger.info(logger.bold(logger.yellow("Migrations Required")));
|
|
1647
3673
|
logger.info("─".repeat(40));
|
|
1648
|
-
logger.info(`Found ${migrationResult.totalMatches} item(s) in ${migrationResult.filesAffected} file(s) that
|
|
3674
|
+
logger.info(`Found ${migrationResult.totalMatches} item(s) in ${migrationResult.filesAffected} file(s) that need to be migrated for Stencil v5.`);
|
|
1649
3675
|
for (const migration of migrationResult.migrations) {
|
|
1650
|
-
const relPath = relative(config.rootDir, migration.filePath);
|
|
3676
|
+
const relPath = relative$1(config.rootDir, migration.filePath);
|
|
1651
3677
|
logger.info(` ${logger.cyan(relPath)}: ${migration.matches.length} item(s)`);
|
|
1652
3678
|
}
|
|
1653
3679
|
logger.info("");
|
|
1654
|
-
logger.info("
|
|
1655
|
-
|
|
1656
|
-
const
|
|
1657
|
-
name: "action",
|
|
1658
|
-
type: "select",
|
|
3680
|
+
if (context === "pre-build") logger.info("Your config contains deprecated options that must be migrated before building.");
|
|
3681
|
+
else logger.info("These migrations may help resolve the build errors above.");
|
|
3682
|
+
const action = await select({
|
|
1659
3683
|
message: "What would you like to do?",
|
|
1660
|
-
|
|
3684
|
+
options: [
|
|
1661
3685
|
{
|
|
1662
|
-
title: "Run migration",
|
|
1663
3686
|
value: "run",
|
|
1664
|
-
|
|
3687
|
+
label: "Run migration",
|
|
3688
|
+
hint: "Apply migrations and re-run build"
|
|
1665
3689
|
},
|
|
1666
3690
|
{
|
|
1667
|
-
title: "Dry run",
|
|
1668
3691
|
value: "dry-run",
|
|
1669
|
-
|
|
3692
|
+
label: "Dry run",
|
|
3693
|
+
hint: "Preview changes without modifying files"
|
|
1670
3694
|
},
|
|
1671
3695
|
{
|
|
1672
|
-
title: "Exit",
|
|
1673
3696
|
value: "exit",
|
|
1674
|
-
|
|
3697
|
+
label: "Exit",
|
|
3698
|
+
hint: "Exit without making changes"
|
|
1675
3699
|
}
|
|
1676
3700
|
]
|
|
1677
3701
|
});
|
|
1678
|
-
if (
|
|
1679
|
-
return
|
|
3702
|
+
if (isCancel(action)) return "exit";
|
|
3703
|
+
return action;
|
|
1680
3704
|
}
|
|
1681
3705
|
//#endregion
|
|
1682
3706
|
//#region src/task-docs.ts
|
|
@@ -1690,277 +3714,180 @@ const taskDocs = async (coreCompiler, config) => {
|
|
|
1690
3714
|
await compiler.destroy();
|
|
1691
3715
|
};
|
|
1692
3716
|
//#endregion
|
|
1693
|
-
//#region src/
|
|
3717
|
+
//#region src/resolve-entry-script.ts
|
|
1694
3718
|
/**
|
|
1695
|
-
*
|
|
1696
|
-
*
|
|
1697
|
-
*
|
|
1698
|
-
*
|
|
3719
|
+
* Resolves the server-relative src for the project's browser entry bundle, from validated
|
|
3720
|
+
* output targets alone (no build required) - the same dev-mode, unhashed filename conventions
|
|
3721
|
+
* the compiler itself uses (see `getAbsoluteBuildDir` in `packages/core/src/compiler/html/html-utils.ts`
|
|
3722
|
+
* and the dev server's `getLoaderUrl` in `packages/dev-server/src/server/dev-preview.ts`, which
|
|
3723
|
+
* this mirrors for use before a build has happened).
|
|
1699
3724
|
*
|
|
1700
|
-
*
|
|
1701
|
-
*
|
|
1702
|
-
*
|
|
3725
|
+
* Preference order matches what actually gets built:
|
|
3726
|
+
* 1. `www` - always emits its own entry bundle at `{buildDir}/{fsNamespace}.js`, regardless of
|
|
3727
|
+
* `bundleMode`, so it's resolved directly from the `www` target rather than the `dist-lazy` /
|
|
3728
|
+
* `standalone` target it internally synthesizes.
|
|
3729
|
+
* 2. `loader-bundle` (no `www`) - synthesizes a `dist-lazy` build for CDN usage, servable from
|
|
3730
|
+
* the project root when there's no `www` target to claim the server root instead.
|
|
3731
|
+
* 3. `standalone` with `autoLoader` enabled (the default) - falls back to its auto-loader script.
|
|
3732
|
+
*
|
|
3733
|
+
* Returns `null` if the project has no browser-loadable output target at all (e.g. an SSR-only
|
|
3734
|
+
* project) - the caller should omit the script tag in that case.
|
|
3735
|
+
*
|
|
3736
|
+
* @param config - Validated Stencil config.
|
|
3737
|
+
* @returns Server-relative script src, or `null` if none of the configured output targets
|
|
3738
|
+
* produce a browser-loadable entry.
|
|
1703
3739
|
*/
|
|
3740
|
+
function resolveEntryScriptSrc(config) {
|
|
3741
|
+
const outputTargets = config.outputTargets;
|
|
3742
|
+
const wwwTarget = outputTargets.find(isOutputTargetWww);
|
|
3743
|
+
if (wwwTarget?.dir && wwwTarget.buildDir) return toUrl(wwwTarget.dir, wwwTarget.buildDir, `${config.fsNamespace}.js`);
|
|
3744
|
+
const distLazyTarget = outputTargets.find(isOutputTargetDistLazy);
|
|
3745
|
+
const distLazyDir = distLazyTarget?.esmDir ?? distLazyTarget?.dir;
|
|
3746
|
+
if (distLazyDir) return toUrl(config.rootDir, distLazyDir, `${config.fsNamespace}.js`);
|
|
3747
|
+
const standaloneTarget = outputTargets.find(isOutputTargetStandalone);
|
|
3748
|
+
if (standaloneTarget?.dir && standaloneTarget.autoLoader !== false) {
|
|
3749
|
+
const fileName = typeof standaloneTarget.autoLoader === "object" ? standaloneTarget.autoLoader.fileName || "loader" : "loader";
|
|
3750
|
+
return toUrl(config.rootDir, standaloneTarget.dir, `${fileName}.js`);
|
|
3751
|
+
}
|
|
3752
|
+
return null;
|
|
3753
|
+
}
|
|
3754
|
+
function toUrl(base, dir, fileName) {
|
|
3755
|
+
const relativeDir = normalizePath(relative(base, dir), false);
|
|
3756
|
+
return `/${relativeDir ? `${relativeDir}/` : ""}${fileName}`;
|
|
3757
|
+
}
|
|
3758
|
+
//#endregion
|
|
3759
|
+
//#region src/task-generate.ts
|
|
3760
|
+
async function resolveFileTemplates(contrib, ctx) {
|
|
3761
|
+
const { fileTemplates } = contrib;
|
|
3762
|
+
if (!fileTemplates) return [];
|
|
3763
|
+
return typeof fileTemplates === "function" ? fileTemplates(ctx) : fileTemplates;
|
|
3764
|
+
}
|
|
1704
3765
|
const taskGenerate = async (config, flags) => {
|
|
1705
|
-
|
|
1706
|
-
|
|
3766
|
+
const srcDir = config.srcDir;
|
|
3767
|
+
if (!srcDir || !existsSync(srcDir)) {
|
|
3768
|
+
config.logger.error("Please run this command in your project root directory.");
|
|
1707
3769
|
return config.sys.exit(1);
|
|
1708
3770
|
}
|
|
1709
|
-
const
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
3771
|
+
const generateContribs = (await discoverPlugins(config.rootDir)).flatMap((d) => d.plugin.generate ? [d.plugin.generate] : []);
|
|
3772
|
+
p.intro("stencil generate");
|
|
3773
|
+
const rawInput = flags.unknownArgs.find((arg) => !arg.startsWith("-"));
|
|
3774
|
+
let input;
|
|
3775
|
+
if (rawInput) input = rawInput;
|
|
3776
|
+
else {
|
|
3777
|
+
const tagName = await p.text({
|
|
3778
|
+
message: "Component tag name (dash-case):",
|
|
3779
|
+
validate: (value) => validateComponentTag(value ?? "")
|
|
3780
|
+
});
|
|
3781
|
+
cancelIfAborted(tagName);
|
|
3782
|
+
input = tagName;
|
|
1713
3783
|
}
|
|
1714
|
-
const { prompt } = await import("prompts");
|
|
1715
|
-
const input = flags.unknownArgs.find((arg) => !arg.startsWith("-")) || (await prompt({
|
|
1716
|
-
name: "tagName",
|
|
1717
|
-
type: "text",
|
|
1718
|
-
message: "Component tag name (dash-case):"
|
|
1719
|
-
})).tagName;
|
|
1720
|
-
if (void 0 === input) return;
|
|
1721
3784
|
const { dir, base: componentName } = parse(input);
|
|
1722
3785
|
const tagError = validateComponentTag(componentName);
|
|
1723
3786
|
if (tagError) {
|
|
1724
3787
|
config.logger.error(tagError);
|
|
1725
3788
|
return config.sys.exit(1);
|
|
1726
3789
|
}
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
const
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
const
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
/**
|
|
1751
|
-
* Show a checkbox prompt to select the files to be generated.
|
|
1752
|
-
*
|
|
1753
|
-
* @param cssExtension the extension of the CSS file to be generated
|
|
1754
|
-
* @returns a read-only array of `GeneratableExtension`, the extensions that the user has decided
|
|
1755
|
-
* to generate
|
|
1756
|
-
*/
|
|
1757
|
-
const chooseFilesToGenerate = async (cssExtension) => {
|
|
1758
|
-
const { prompt } = await import("prompts");
|
|
1759
|
-
return (await prompt({
|
|
1760
|
-
name: "filesToGenerate",
|
|
1761
|
-
type: "multiselect",
|
|
1762
|
-
message: "Which additional files do you want to generate?",
|
|
1763
|
-
choices: [
|
|
3790
|
+
const styleOptions = [
|
|
3791
|
+
{
|
|
3792
|
+
value: "css",
|
|
3793
|
+
label: "CSS (.css)"
|
|
3794
|
+
},
|
|
3795
|
+
...[...new Set(generateContribs.flatMap((c) => c.styleExtensions ?? []))].map((ext) => ({
|
|
3796
|
+
value: ext,
|
|
3797
|
+
label: `${ext.toUpperCase()} (.${ext})`
|
|
3798
|
+
})),
|
|
3799
|
+
{
|
|
3800
|
+
value: "",
|
|
3801
|
+
label: "None"
|
|
3802
|
+
}
|
|
3803
|
+
];
|
|
3804
|
+
const stylePick = await p.select({
|
|
3805
|
+
message: "Stylesheet format:",
|
|
3806
|
+
options: styleOptions
|
|
3807
|
+
});
|
|
3808
|
+
cancelIfAborted(stylePick);
|
|
3809
|
+
const styleExtension = stylePick || void 0;
|
|
3810
|
+
const demoPick = await p.select({
|
|
3811
|
+
message: "Demo:",
|
|
3812
|
+
options: [
|
|
1764
3813
|
{
|
|
1765
|
-
value:
|
|
1766
|
-
|
|
1767
|
-
|
|
3814
|
+
value: "usage",
|
|
3815
|
+
label: "Usage example",
|
|
3816
|
+
hint: "usage/example.md - rendered in docs and the dev server auto-preview"
|
|
1768
3817
|
},
|
|
1769
3818
|
{
|
|
1770
|
-
value: "
|
|
1771
|
-
|
|
1772
|
-
|
|
3819
|
+
value: "preview",
|
|
3820
|
+
label: "Preview page",
|
|
3821
|
+
hint: "index.html - full control, opts out of the dev server auto-preview"
|
|
1773
3822
|
},
|
|
1774
3823
|
{
|
|
1775
|
-
value: "
|
|
1776
|
-
|
|
1777
|
-
selected: true
|
|
3824
|
+
value: "",
|
|
3825
|
+
label: "None"
|
|
1778
3826
|
}
|
|
1779
3827
|
]
|
|
1780
|
-
})
|
|
1781
|
-
|
|
1782
|
-
const
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
}
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
*
|
|
1804
|
-
* @param filePath path to where we're going to generate the component
|
|
1805
|
-
* @param componentName the user-supplied name for the generated component
|
|
1806
|
-
* @param extension the file extension
|
|
1807
|
-
* @returns the full filepath to the component (with a possible `test` directory
|
|
1808
|
-
* added)
|
|
1809
|
-
*/
|
|
1810
|
-
const getFilepathForFile = (filePath, componentName, extension) => isTest(extension) ? normalizePath(join(filePath, "test", `${componentName}.${extension}`)) : normalizePath(join(filePath, `${componentName}.${extension}`));
|
|
1811
|
-
/**
|
|
1812
|
-
* Get the boilerplate for a file and write it to disk
|
|
1813
|
-
*
|
|
1814
|
-
* @param config the current config, needed for file operations
|
|
1815
|
-
* @param componentName the component name (user-supplied)
|
|
1816
|
-
* @param withCss are we generating CSS?
|
|
1817
|
-
* @param file the file we want to write
|
|
1818
|
-
* @param styleExtension extension used for styles
|
|
1819
|
-
* @returns a `Promise<string>` which holds the full filepath we've written to,
|
|
1820
|
-
* used to print out a little summary of our activity to the user.
|
|
1821
|
-
*/
|
|
1822
|
-
const getBoilerplateAndWriteFile = async (config, componentName, withCss, file, styleExtension) => {
|
|
1823
|
-
const boilerplate = getBoilerplateByExtension(componentName, file.extension, withCss, styleExtension);
|
|
1824
|
-
await config.sys.writeFile(normalizePath(file.path), boilerplate);
|
|
1825
|
-
return file.path;
|
|
1826
|
-
};
|
|
1827
|
-
/**
|
|
1828
|
-
* Check to see if any of the files we plan to write already exist and would
|
|
1829
|
-
* therefore be overwritten if we proceed, because we'd like to not overwrite
|
|
1830
|
-
* people's code!
|
|
1831
|
-
*
|
|
1832
|
-
* This function will check all the filepaths and if it finds any files log an
|
|
1833
|
-
* error and exit with an error code. If it doesn't find anything it will just
|
|
1834
|
-
* peacefully return `Promise<void>`.
|
|
1835
|
-
*
|
|
1836
|
-
* @param files the files we want to check
|
|
1837
|
-
* @param config the Config object, used here to get access to `sys.readFile`
|
|
1838
|
-
*/
|
|
1839
|
-
const checkForOverwrite = async (files, config) => {
|
|
1840
|
-
const alreadyPresent = [];
|
|
1841
|
-
await Promise.all(files.map(async ({ path }) => {
|
|
1842
|
-
if (await config.sys.readFile(path) !== void 0) alreadyPresent.push(path);
|
|
1843
|
-
}));
|
|
1844
|
-
if (alreadyPresent.length > 0) {
|
|
1845
|
-
config.logger.error("Generating code would overwrite the following files:", ...alreadyPresent.map((path) => " " + normalizePath(path)));
|
|
1846
|
-
await config.sys.exit(1);
|
|
3828
|
+
});
|
|
3829
|
+
cancelIfAborted(demoPick);
|
|
3830
|
+
const generateCtx = {
|
|
3831
|
+
tagName: componentName,
|
|
3832
|
+
config: toProjectConfig(config),
|
|
3833
|
+
prompts: p,
|
|
3834
|
+
nypm
|
|
3835
|
+
};
|
|
3836
|
+
const allFileTemplates = [];
|
|
3837
|
+
for (const contrib of generateContribs) allFileTemplates.push(...await resolveFileTemplates(contrib, generateCtx));
|
|
3838
|
+
let pickedExtensions = [];
|
|
3839
|
+
if (allFileTemplates.length > 0) {
|
|
3840
|
+
const filePick = await p.multiselect({
|
|
3841
|
+
message: "Additional files:",
|
|
3842
|
+
options: allFileTemplates.map((ft) => ({
|
|
3843
|
+
value: ft.extension,
|
|
3844
|
+
label: ft.label
|
|
3845
|
+
})),
|
|
3846
|
+
initialValues: allFileTemplates.filter((ft) => ft.selectedByDefault !== false).map((ft) => ft.extension),
|
|
3847
|
+
required: false
|
|
3848
|
+
});
|
|
3849
|
+
cancelIfAborted(filePick);
|
|
3850
|
+
pickedExtensions = filePick;
|
|
1847
3851
|
}
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
*/
|
|
1867
|
-
const getBoilerplateByExtension = (tagName, extension, withCss, styleExtension) => {
|
|
1868
|
-
switch (extension) {
|
|
1869
|
-
case "tsx": return getComponentBoilerplate(tagName, withCss, styleExtension);
|
|
1870
|
-
case "css":
|
|
1871
|
-
case "less":
|
|
1872
|
-
case "sass":
|
|
1873
|
-
case "scss": return getStyleUrlBoilerplate(styleExtension);
|
|
1874
|
-
case "spec.tsx": return getSpecTestBoilerplate(tagName);
|
|
1875
|
-
case "e2e.ts": return getE2eTestBoilerplate(tagName);
|
|
1876
|
-
default: throw new Error(`Unkown extension "${extension}".`);
|
|
3852
|
+
const outDir = join(srcDir, "components", dir, componentName);
|
|
3853
|
+
const className = toPascalCase(componentName);
|
|
3854
|
+
const filesToWrite = [];
|
|
3855
|
+
filesToWrite.push({
|
|
3856
|
+
absPath: normalizePath(join(outDir, `${componentName}.tsx`)),
|
|
3857
|
+
content: getComponentBoilerplate(componentName, styleExtension)
|
|
3858
|
+
});
|
|
3859
|
+
if (styleExtension) filesToWrite.push({
|
|
3860
|
+
absPath: normalizePath(join(outDir, `${componentName}.${styleExtension}`)),
|
|
3861
|
+
content: getStyleBoilerplate(styleExtension)
|
|
3862
|
+
});
|
|
3863
|
+
for (const ext of pickedExtensions) {
|
|
3864
|
+
const tmpl = allFileTemplates.find((ft) => ft.extension === ext);
|
|
3865
|
+
const absPath = normalizePath(join(outDir, tmpl.subdirectory ?? "", `${componentName}.${ext}`));
|
|
3866
|
+
filesToWrite.push({
|
|
3867
|
+
absPath,
|
|
3868
|
+
content: tmpl.template(componentName, className)
|
|
3869
|
+
});
|
|
1877
3870
|
}
|
|
3871
|
+
if (demoPick === "usage") filesToWrite.push({
|
|
3872
|
+
absPath: normalizePath(join(outDir, "usage", "example.md")),
|
|
3873
|
+
content: getUsageExampleBoilerplate(componentName)
|
|
3874
|
+
});
|
|
3875
|
+
else if (demoPick === "preview") filesToWrite.push({
|
|
3876
|
+
absPath: normalizePath(join(outDir, "index.html")),
|
|
3877
|
+
content: getPreviewHtmlBoilerplate(componentName, resolveEntryScriptSrc(config))
|
|
3878
|
+
});
|
|
3879
|
+
const wouldOverwrite = (await Promise.all(filesToWrite.map(async ({ absPath }) => await config.sys.readFile(absPath) !== void 0 ? absPath : null))).filter((f) => f !== null);
|
|
3880
|
+
if (wouldOverwrite.length > 0) {
|
|
3881
|
+
config.logger.error("Generating code would overwrite the following files:", ...wouldOverwrite.map((path) => " " + normalizePath(path)));
|
|
3882
|
+
await config.sys.exit(1);
|
|
3883
|
+
return;
|
|
3884
|
+
}
|
|
3885
|
+
const dirs = [...new Set(filesToWrite.map(({ absPath }) => normalizePath(join(absPath, ".."))))];
|
|
3886
|
+
await Promise.all(dirs.map((d) => config.sys.createDir(d, { recursive: true })));
|
|
3887
|
+
await Promise.all(filesToWrite.map(({ absPath, content }) => config.sys.writeFile(absPath, content)));
|
|
3888
|
+
p.note(filesToWrite.map(({ absPath }) => relative(config.rootDir, absPath)).join("\n"), "Generated");
|
|
3889
|
+
p.outro(`stencil generate ${input}`);
|
|
1878
3890
|
};
|
|
1879
|
-
/**
|
|
1880
|
-
* Get the boilerplate for a file containing the definition of a component
|
|
1881
|
-
* @param tagName the name of the tag to give the component
|
|
1882
|
-
* @param hasStyle designates if the component has an external stylesheet or not
|
|
1883
|
-
* @param styleExtension extension used for styles
|
|
1884
|
-
* @returns the contents of a file that defines a component
|
|
1885
|
-
*/
|
|
1886
|
-
const getComponentBoilerplate = (tagName, hasStyle, styleExtension) => {
|
|
1887
|
-
const decorator = [`{`];
|
|
1888
|
-
decorator.push(` tag: '${tagName}',`);
|
|
1889
|
-
if (hasStyle) decorator.push(` styleUrl: '${tagName}.${styleExtension}',`);
|
|
1890
|
-
decorator.push(` shadow: true,`);
|
|
1891
|
-
decorator.push(`}`);
|
|
1892
|
-
return `import { Component, Host, h } from '@stencil/core';
|
|
1893
|
-
|
|
1894
|
-
@Component(${decorator.join("\n")})
|
|
1895
|
-
export class ${toPascalCase(tagName)} {
|
|
1896
|
-
render() {
|
|
1897
|
-
return (
|
|
1898
|
-
<Host>
|
|
1899
|
-
<slot></slot>
|
|
1900
|
-
</Host>
|
|
1901
|
-
);
|
|
1902
|
-
}
|
|
1903
|
-
}
|
|
1904
|
-
`;
|
|
1905
|
-
};
|
|
1906
|
-
/**
|
|
1907
|
-
* Get the boilerplate for style for a generated component
|
|
1908
|
-
* @param ext extension used for styles
|
|
1909
|
-
* @returns a boilerplate CSS block
|
|
1910
|
-
*/
|
|
1911
|
-
const getStyleUrlBoilerplate = (ext) => ext === "sass" ? `:host
|
|
1912
|
-
display: block
|
|
1913
|
-
` : `:host {
|
|
1914
|
-
display: block;
|
|
1915
|
-
}
|
|
1916
|
-
`;
|
|
1917
|
-
/**
|
|
1918
|
-
* Get the boilerplate for a file containing a spec (unit) test for a component
|
|
1919
|
-
* @param tagName the name of the tag associated with the component under test
|
|
1920
|
-
* @returns the contents of a file that unit tests a component
|
|
1921
|
-
*/
|
|
1922
|
-
const getSpecTestBoilerplate = (tagName) => `import { newSpecPage } from '@stencil/core/testing';
|
|
1923
|
-
import { ${toPascalCase(tagName)} } from '../${tagName}';
|
|
1924
|
-
|
|
1925
|
-
describe('${tagName}', () => {
|
|
1926
|
-
it('renders', async () => {
|
|
1927
|
-
const page = await newSpecPage({
|
|
1928
|
-
components: [${toPascalCase(tagName)}],
|
|
1929
|
-
html: \`<${tagName}></${tagName}>\`,
|
|
1930
|
-
});
|
|
1931
|
-
expect(page.root).toEqualHtml(\`
|
|
1932
|
-
<${tagName}>
|
|
1933
|
-
<mock:shadow-root>
|
|
1934
|
-
<slot></slot>
|
|
1935
|
-
</mock:shadow-root>
|
|
1936
|
-
</${tagName}>
|
|
1937
|
-
\`);
|
|
1938
|
-
});
|
|
1939
|
-
});
|
|
1940
|
-
`;
|
|
1941
|
-
/**
|
|
1942
|
-
* Get the boilerplate for a file containing an end-to-end (E2E) test for a component
|
|
1943
|
-
* @param tagName the name of the tag associated with the component under test
|
|
1944
|
-
* @returns the contents of a file that E2E tests a component
|
|
1945
|
-
*/
|
|
1946
|
-
const getE2eTestBoilerplate = (tagName) => `import { newE2EPage } from '@stencil/core/testing';
|
|
1947
|
-
|
|
1948
|
-
describe('${tagName}', () => {
|
|
1949
|
-
it('renders', async () => {
|
|
1950
|
-
const page = await newE2EPage();
|
|
1951
|
-
await page.setContent('<${tagName}></${tagName}>');
|
|
1952
|
-
|
|
1953
|
-
const element = await page.find('${tagName}');
|
|
1954
|
-
expect(element).toHaveClass('hydrated');
|
|
1955
|
-
});
|
|
1956
|
-
});
|
|
1957
|
-
`;
|
|
1958
|
-
/**
|
|
1959
|
-
* Convert a dash case string to pascal case.
|
|
1960
|
-
* @param str the string to convert
|
|
1961
|
-
* @returns the converted input as pascal case
|
|
1962
|
-
*/
|
|
1963
|
-
const toPascalCase = (str) => str.split("-").reduce((res, part) => res + part[0].toUpperCase() + part.slice(1), "");
|
|
1964
3891
|
//#endregion
|
|
1965
3892
|
//#region src/task-telemetry.ts
|
|
1966
3893
|
/**
|
|
@@ -2074,6 +4001,415 @@ const taskInfo = (coreCompiler, sys, logger) => {
|
|
|
2074
4001
|
console.log(``);
|
|
2075
4002
|
};
|
|
2076
4003
|
//#endregion
|
|
4004
|
+
//#region src/wizard/init/apply.ts
|
|
4005
|
+
/**
|
|
4006
|
+
* Copy component-starter template into rootDir, interpolating project name and namespace.
|
|
4007
|
+
*
|
|
4008
|
+
* @param rootDir - Destination directory (typically `process.cwd()`).
|
|
4009
|
+
* @param projectName - Value to substitute for `{{PROJECT_NAME}}` placeholders.
|
|
4010
|
+
* @param namespace - Value to substitute for `{{NAMESPACE}}` placeholders.
|
|
4011
|
+
* @param stencilVersion - Optional version to substitute for `{{STENCIL_VERSION}}` placeholders.
|
|
4012
|
+
*/
|
|
4013
|
+
async function copyTemplate(rootDir, projectName, namespace, stencilVersion) {
|
|
4014
|
+
const templateDir = getTemplatePath("component-starter");
|
|
4015
|
+
const entries = await readdir(templateDir, {
|
|
4016
|
+
recursive: true,
|
|
4017
|
+
withFileTypes: true
|
|
4018
|
+
});
|
|
4019
|
+
const resolvedStencilVersion = stencilVersion ?? "^5.0.0";
|
|
4020
|
+
for (const entry of entries) {
|
|
4021
|
+
if (!entry.isFile()) continue;
|
|
4022
|
+
const srcPath = join(entry.parentPath, entry.name);
|
|
4023
|
+
let relPath = relative(templateDir, srcPath);
|
|
4024
|
+
if (relPath === "_gitignore") relPath = ".gitignore";
|
|
4025
|
+
const destPath = join(rootDir, relPath);
|
|
4026
|
+
await mkdir(dirname(destPath), { recursive: true });
|
|
4027
|
+
const content = (await readFile(srcPath, "utf8")).replace(/\{\{PROJECT_NAME\}\}/g, projectName).replace(/\{\{NAMESPACE\}\}/g, namespace).replace(/\{\{STENCIL_VERSION\}\}/g, resolvedStencilVersion);
|
|
4028
|
+
if (relPath === "package.json") await mergePackageJson(destPath, content);
|
|
4029
|
+
else if (relPath === "tsconfig.json") await mergeTsConfig(destPath, content);
|
|
4030
|
+
else if (relPath === ".gitignore") await mergeGitignore(destPath, content);
|
|
4031
|
+
else await writeIfAbsent(destPath, content);
|
|
4032
|
+
}
|
|
4033
|
+
}
|
|
4034
|
+
const PARCEL_WATCHER_BUILD_ALLOWANCES = [
|
|
4035
|
+
`onlyBuiltDependencies:`,
|
|
4036
|
+
` - '@parcel/watcher'`,
|
|
4037
|
+
``,
|
|
4038
|
+
`allowBuilds:`,
|
|
4039
|
+
` '@parcel/watcher': true`
|
|
4040
|
+
].join("\n");
|
|
4041
|
+
async function mergePnpmWorkspaceYaml(yamlPath) {
|
|
4042
|
+
let existing = null;
|
|
4043
|
+
try {
|
|
4044
|
+
existing = await readFile(yamlPath, "utf8");
|
|
4045
|
+
} catch {}
|
|
4046
|
+
if (existing === null) {
|
|
4047
|
+
await writeFile(yamlPath, [
|
|
4048
|
+
`packages:`,
|
|
4049
|
+
` - 'packages/*'`,
|
|
4050
|
+
``,
|
|
4051
|
+
PARCEL_WATCHER_BUILD_ALLOWANCES,
|
|
4052
|
+
``
|
|
4053
|
+
].join("\n"), "utf8");
|
|
4054
|
+
return;
|
|
4055
|
+
}
|
|
4056
|
+
let toAppend = "";
|
|
4057
|
+
if (!existing.includes("packages/*")) toAppend += `\npackages:\n - 'packages/*'\n`;
|
|
4058
|
+
if (!existing.includes("onlyBuiltDependencies:")) toAppend += `\nonlyBuiltDependencies:\n - '@parcel/watcher'\n`;
|
|
4059
|
+
if (!existing.includes("allowBuilds:")) toAppend += `\nallowBuilds:\n '@parcel/watcher': true\n`;
|
|
4060
|
+
if (toAppend) {
|
|
4061
|
+
const separator = existing.endsWith("\n") ? "" : "\n";
|
|
4062
|
+
await writeFile(yamlPath, existing + separator + toAppend, "utf8");
|
|
4063
|
+
}
|
|
4064
|
+
}
|
|
4065
|
+
async function writeIfAbsent(destPath, content) {
|
|
4066
|
+
try {
|
|
4067
|
+
await writeFile(destPath, content, {
|
|
4068
|
+
encoding: "utf8",
|
|
4069
|
+
flag: "wx"
|
|
4070
|
+
});
|
|
4071
|
+
} catch (e) {
|
|
4072
|
+
if (e.code !== "EEXIST") throw e;
|
|
4073
|
+
}
|
|
4074
|
+
}
|
|
4075
|
+
async function mergePackageJson(destPath, templateContent) {
|
|
4076
|
+
const template = JSON.parse(templateContent);
|
|
4077
|
+
let existing;
|
|
4078
|
+
try {
|
|
4079
|
+
existing = JSON.parse(await readFile(destPath, "utf8"));
|
|
4080
|
+
} catch {
|
|
4081
|
+
await writeFile(destPath, templateContent, "utf8");
|
|
4082
|
+
return;
|
|
4083
|
+
}
|
|
4084
|
+
const dependencies = mergeStringRecord(template.dependencies, existing.dependencies);
|
|
4085
|
+
const devDependencies = mergeStringRecord(template.devDependencies, existing.devDependencies);
|
|
4086
|
+
for (const pkg of Object.keys(devDependencies)) if (pkg in dependencies) delete devDependencies[pkg];
|
|
4087
|
+
const merged = {
|
|
4088
|
+
...template,
|
|
4089
|
+
...existing,
|
|
4090
|
+
scripts: mergeStringRecord(template.scripts, existing.scripts),
|
|
4091
|
+
dependencies,
|
|
4092
|
+
devDependencies
|
|
4093
|
+
};
|
|
4094
|
+
await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
|
|
4095
|
+
}
|
|
4096
|
+
async function mergeTsConfig(destPath, templateContent) {
|
|
4097
|
+
const template = JSON.parse(templateContent);
|
|
4098
|
+
let existing;
|
|
4099
|
+
try {
|
|
4100
|
+
existing = JSON.parse(await readFile(destPath, "utf8"));
|
|
4101
|
+
} catch {
|
|
4102
|
+
await writeFile(destPath, templateContent, "utf8");
|
|
4103
|
+
return;
|
|
4104
|
+
}
|
|
4105
|
+
const merged = {
|
|
4106
|
+
...template,
|
|
4107
|
+
...existing,
|
|
4108
|
+
compilerOptions: mergeStringRecord(template.compilerOptions, existing.compilerOptions)
|
|
4109
|
+
};
|
|
4110
|
+
await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
|
|
4111
|
+
}
|
|
4112
|
+
async function mergeGitignore(destPath, templateContent) {
|
|
4113
|
+
let existing;
|
|
4114
|
+
try {
|
|
4115
|
+
existing = await readFile(destPath, "utf8");
|
|
4116
|
+
} catch {
|
|
4117
|
+
await writeFile(destPath, templateContent, "utf8");
|
|
4118
|
+
return;
|
|
4119
|
+
}
|
|
4120
|
+
const existingEntries = new Set(existing.split("\n").map((l) => l.trim()).filter(Boolean));
|
|
4121
|
+
const missing = templateContent.split("\n").filter((line) => line.trim() && !existingEntries.has(line.trim()));
|
|
4122
|
+
if (missing.length === 0) return;
|
|
4123
|
+
const separator = existing.endsWith("\n") ? "" : "\n";
|
|
4124
|
+
await writeFile(destPath, existing + separator + missing.join("\n") + "\n", "utf8");
|
|
4125
|
+
}
|
|
4126
|
+
function mergeStringRecord(base, override) {
|
|
4127
|
+
const toObj = (v) => v !== null && typeof v === "object" ? v : {};
|
|
4128
|
+
return {
|
|
4129
|
+
...toObj(base),
|
|
4130
|
+
...toObj(override)
|
|
4131
|
+
};
|
|
4132
|
+
}
|
|
4133
|
+
async function writeStencilConfig(rootDir, content) {
|
|
4134
|
+
await writeFile(join(rootDir, "stencil.config.ts"), content, "utf8");
|
|
4135
|
+
}
|
|
4136
|
+
async function writeGlobalStyle(rootDir) {
|
|
4137
|
+
const path = join(rootDir, "src", "global.css");
|
|
4138
|
+
await mkdir(dirname(path), { recursive: true });
|
|
4139
|
+
await writeIfAbsent(path, `@import "stencil-globals";\n@import "stencil-hydrate";\n`);
|
|
4140
|
+
}
|
|
4141
|
+
async function writeGlobalScript(rootDir) {
|
|
4142
|
+
const path = join(rootDir, "src", "global.ts");
|
|
4143
|
+
await mkdir(dirname(path), { recursive: true });
|
|
4144
|
+
await writeIfAbsent(path, `export default function (): void {}\n`);
|
|
4145
|
+
}
|
|
4146
|
+
async function writeIndexHtml(rootDir, content) {
|
|
4147
|
+
const path = join(rootDir, "src", "index.html");
|
|
4148
|
+
await mkdir(dirname(path), { recursive: true });
|
|
4149
|
+
await writeIfAbsent(path, content);
|
|
4150
|
+
}
|
|
4151
|
+
function workspaceBuildScript(pm, coreName) {
|
|
4152
|
+
switch (pm) {
|
|
4153
|
+
case "pnpm": return "pnpm -r build";
|
|
4154
|
+
case "yarn": return "yarn workspaces run build";
|
|
4155
|
+
case "bun": return "bun run --filter \"*\" build";
|
|
4156
|
+
default: return `npm run build -w packages/${coreName} && npm run build --workspaces --if-present`;
|
|
4157
|
+
}
|
|
4158
|
+
}
|
|
4159
|
+
/**
|
|
4160
|
+
* Scaffold a workspace root in `cwd`: creates `packages/`, writes the appropriate
|
|
4161
|
+
* workspace manifest (`pnpm-workspace.yaml` for pnpm, `workspaces` field in
|
|
4162
|
+
* `package.json` for npm / yarn / bun), and ensures a root `package.json` exists.
|
|
4163
|
+
* @param cwd - Absolute path to the workspace root (where `package.json` will be created).
|
|
4164
|
+
* @param projectName - Name to use for the root package.json (typically the project name).
|
|
4165
|
+
* @param coreName - Directory name of the core package under `packages/` (e.g. `core`).
|
|
4166
|
+
* @returns A promise that resolves when the workspace root has been scaffolded.
|
|
4167
|
+
*/
|
|
4168
|
+
async function scaffoldWorkspaceRoot(cwd, projectName, coreName) {
|
|
4169
|
+
await mkdir(join(cwd, "packages"), { recursive: true });
|
|
4170
|
+
const pm = await detectPackageManager(cwd);
|
|
4171
|
+
const usePnpmYaml = pm?.name === "pnpm";
|
|
4172
|
+
const pkgPath = join(cwd, "package.json");
|
|
4173
|
+
let pkg;
|
|
4174
|
+
try {
|
|
4175
|
+
pkg = JSON.parse(await readFile(pkgPath, "utf8"));
|
|
4176
|
+
} catch {
|
|
4177
|
+
pkg = {};
|
|
4178
|
+
}
|
|
4179
|
+
pkg.name ??= `${projectName}-workspace`;
|
|
4180
|
+
pkg.version ??= "0.0.1";
|
|
4181
|
+
pkg.private = true;
|
|
4182
|
+
pkg.scripts = {
|
|
4183
|
+
build: workspaceBuildScript(pm?.name, coreName),
|
|
4184
|
+
...pkg.scripts
|
|
4185
|
+
};
|
|
4186
|
+
if (!usePnpmYaml) pkg.workspaces = ["packages/*"];
|
|
4187
|
+
delete pkg.dependencies;
|
|
4188
|
+
delete pkg.devDependencies;
|
|
4189
|
+
await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
|
|
4190
|
+
if (usePnpmYaml) await mergePnpmWorkspaceYaml(join(cwd, "pnpm-workspace.yaml"));
|
|
4191
|
+
}
|
|
4192
|
+
/**
|
|
4193
|
+
* Write output-driven distributable fields (type, module, types) into package.json.
|
|
4194
|
+
* These fields depend on which outputs the user selected, so they cannot be static in the template.
|
|
4195
|
+
* Skips if fields is empty (e.g. www-only project).
|
|
4196
|
+
*
|
|
4197
|
+
* @param rootDir - Absolute path to the project root.
|
|
4198
|
+
* @param fields - Fields to write, from generatePackageJsonFields().
|
|
4199
|
+
*/
|
|
4200
|
+
async function applyPackageJsonFields(rootDir, fields) {
|
|
4201
|
+
if (Object.keys(fields).length === 0) return;
|
|
4202
|
+
const pkgPath = join(rootDir, "package.json");
|
|
4203
|
+
const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
|
|
4204
|
+
Object.assign(pkg, fields);
|
|
4205
|
+
await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
|
|
4206
|
+
}
|
|
4207
|
+
//#endregion
|
|
4208
|
+
//#region src/task-init.ts
|
|
4209
|
+
/**
|
|
4210
|
+
* Package managers can report success while silently failing to write to node_modules.
|
|
4211
|
+
* Confirms packages actually landed on disk instead of trusting the install call's exit code.
|
|
4212
|
+
*
|
|
4213
|
+
* @param rootDir - directory to resolve packages from.
|
|
4214
|
+
* @param packageNames - packages that were just supposed to be installed.
|
|
4215
|
+
*/
|
|
4216
|
+
async function verifyInstalled(rootDir, packageNames) {
|
|
4217
|
+
const missing = [];
|
|
4218
|
+
for (const name of packageNames) if (!await getPackageInfo(name, { paths: [rootDir] })) missing.push(name);
|
|
4219
|
+
if (missing.length === 0) return;
|
|
4220
|
+
p.log.error(`Install reported success but ${missing.join(", ")} could not be found in ${rootDir}. Your package manager may have silently failed to write to node_modules - check its logs and try again.`);
|
|
4221
|
+
process.exit(1);
|
|
4222
|
+
}
|
|
4223
|
+
/**
|
|
4224
|
+
* npm silently omits devDependencies when this CLI is itself running as a nested child
|
|
4225
|
+
* process (e.g. via `npx create-stencil` / `npm init stencil`). Root cause: npm/exec only
|
|
4226
|
+
* needs @stencil/cli's own regular dependencies to resolve+run it, so that install computes
|
|
4227
|
+
* `omit: ['dev']` - and per npm's own config flattening
|
|
4228
|
+
* (@npmcli/config/lib/definitions/definitions.js), whenever `omit` includes 'dev' npm sets
|
|
4229
|
+
* `process.env.NODE_ENV = 'production'` on itself. We inherit that env var from the outer
|
|
4230
|
+
* npm/npx process, and every child process we (or a wizard plugin) spawn from here would
|
|
4231
|
+
* inherit it right back, causing nested `npm install`s to also compute `omit: ['dev']` and
|
|
4232
|
+
* silently drop (or, worse, actively remove) every devDependency in the scaffolded project.
|
|
4233
|
+
* Clearing it once, up front, fixes every install call transitively - ours and every wizard
|
|
4234
|
+
* plugin's - without needing to special-case npm invocations one by one.
|
|
4235
|
+
*/
|
|
4236
|
+
function clearInheritedProductionEnv() {
|
|
4237
|
+
if (process.env.NODE_ENV === "production") delete process.env.NODE_ENV;
|
|
4238
|
+
}
|
|
4239
|
+
function outputKeysToTargets(keys) {
|
|
4240
|
+
const map = {
|
|
4241
|
+
loader: "loader-bundle",
|
|
4242
|
+
standalone: "standalone",
|
|
4243
|
+
ssr: "ssr",
|
|
4244
|
+
"ssr-wasm": "ssr-wasm",
|
|
4245
|
+
www: "www"
|
|
4246
|
+
};
|
|
4247
|
+
return keys.length > 0 ? keys.map((k) => ({ type: map[k] })) : [{ type: "loader-bundle" }];
|
|
4248
|
+
}
|
|
4249
|
+
async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
|
|
4250
|
+
clearInheritedProductionEnv();
|
|
4251
|
+
const cwd = process.cwd();
|
|
4252
|
+
const isExistingProject = await isExistingStencilProject(cwd);
|
|
4253
|
+
printSplash();
|
|
4254
|
+
p.intro(`stencil init`);
|
|
4255
|
+
if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: loading wizards from ${process.env.STENCIL_WIZARD_DEV}`);
|
|
4256
|
+
if (isCI) {
|
|
4257
|
+
p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil init`.");
|
|
4258
|
+
process.exit(1);
|
|
4259
|
+
}
|
|
4260
|
+
if (isExistingProject) {
|
|
4261
|
+
await addCapabilities(cwd, strictConfig);
|
|
4262
|
+
return;
|
|
4263
|
+
}
|
|
4264
|
+
const projectName = await promptProjectName();
|
|
4265
|
+
const namespace = toNamespace(projectName);
|
|
4266
|
+
const outputs = await promptOutputs();
|
|
4267
|
+
const features = await promptFeatures();
|
|
4268
|
+
const docs = await promptDocs();
|
|
4269
|
+
const selectedIntegrations = await promptIntegrations();
|
|
4270
|
+
let monorepo = false;
|
|
4271
|
+
let coreName = "";
|
|
4272
|
+
if (hasFrameworkTargets(selectedIntegrations)) {
|
|
4273
|
+
monorepo = await promptMonorepo();
|
|
4274
|
+
if (monorepo) coreName = await promptWorkspaceCoreName();
|
|
4275
|
+
}
|
|
4276
|
+
const configSource = generateStencilConfig({
|
|
4277
|
+
namespace,
|
|
4278
|
+
outputs,
|
|
4279
|
+
signals: features.signals,
|
|
4280
|
+
docs
|
|
4281
|
+
}) ?? (needsStencilConfig(selectedIntegrations) ? `import { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n outputTargets: [{ type: 'loader-bundle' }],\n};\n` : null);
|
|
4282
|
+
const summaryLines = [
|
|
4283
|
+
`Template: component-starter`,
|
|
4284
|
+
`Name: ${projectName}`,
|
|
4285
|
+
`Namespace: ${namespace}`,
|
|
4286
|
+
`Config: ${configSource ? "stencil.config.ts" : "zero-config (loader default)"}`
|
|
4287
|
+
];
|
|
4288
|
+
if (monorepo) {
|
|
4289
|
+
summaryLines.push(`Structure: monorepo workspace`);
|
|
4290
|
+
summaryLines.push(`Core: packages/${coreName}/`);
|
|
4291
|
+
}
|
|
4292
|
+
if (selectedIntegrations.length > 0) summaryLines.push(`Add: ${selectedIntegrations.map((i) => i.displayName).join(", ")}`);
|
|
4293
|
+
p.note(summaryLines.join("\n"), "Summary");
|
|
4294
|
+
const coreDir = monorepo ? join(cwd, "packages", coreName) : cwd;
|
|
4295
|
+
const s1 = p.spinner();
|
|
4296
|
+
s1.start("Scaffolding project files");
|
|
4297
|
+
if (monorepo) await scaffoldWorkspaceRoot(cwd, projectName, coreName);
|
|
4298
|
+
await copyTemplate(coreDir, projectName, namespace, coreCompiler?.version);
|
|
4299
|
+
await applyPackageJsonFields(coreDir, generatePackageJsonFields(outputs));
|
|
4300
|
+
if (configSource) await writeStencilConfig(coreDir, configSource);
|
|
4301
|
+
if (features.globalStyle) await writeGlobalStyle(coreDir);
|
|
4302
|
+
if (features.globalScript) await writeGlobalScript(coreDir);
|
|
4303
|
+
if (outputs.includes("www")) await writeIndexHtml(coreDir, generateIndexHtml({
|
|
4304
|
+
projectName,
|
|
4305
|
+
namespace,
|
|
4306
|
+
globalStyle: features.globalStyle
|
|
4307
|
+
}));
|
|
4308
|
+
s1.stop("Project files created");
|
|
4309
|
+
const s2 = p.spinner();
|
|
4310
|
+
s2.start("Installing dependencies");
|
|
4311
|
+
await nypm.installDependencies({
|
|
4312
|
+
cwd,
|
|
4313
|
+
silent: true
|
|
4314
|
+
});
|
|
4315
|
+
s2.stop("Dependencies installed");
|
|
4316
|
+
await verifyInstalled(coreDir, ["@stencil/core"]);
|
|
4317
|
+
if (selectedIntegrations.length > 0) {
|
|
4318
|
+
const s3 = p.spinner();
|
|
4319
|
+
const pkgs = selectedIntegrations.map((i) => i.package);
|
|
4320
|
+
s3.start(`Installing ${pkgs.join(", ")}`);
|
|
4321
|
+
await nypm.addDevDependency(withVersionRanges(pkgs), {
|
|
4322
|
+
cwd: coreDir,
|
|
4323
|
+
silent: true
|
|
4324
|
+
});
|
|
4325
|
+
s3.stop("Integrations installed");
|
|
4326
|
+
await verifyInstalled(coreDir, pkgs);
|
|
4327
|
+
}
|
|
4328
|
+
if (selectedIntegrations.length > 0) {
|
|
4329
|
+
const discovered = await discoverPlugins(coreDir);
|
|
4330
|
+
const selectedPkgs = new Set(selectedIntegrations.map((i) => i.package));
|
|
4331
|
+
const resolvedValidated = loadProjectConfig && configSource ? await loadProjectConfig(join(coreDir, "stencil.config.ts")) : coreCompiler ? coreCompiler.validateConfig({
|
|
4332
|
+
rootDir: coreDir,
|
|
4333
|
+
outputTargets: outputKeysToTargets(outputs),
|
|
4334
|
+
...configSource ? { namespace } : {}
|
|
4335
|
+
}, {}).config : null;
|
|
4336
|
+
const projectConfig = resolvedValidated ? {
|
|
4337
|
+
...toProjectConfig(resolvedValidated),
|
|
4338
|
+
rootDir: coreDir
|
|
4339
|
+
} : defaultProjectConfig(coreDir, { namespace });
|
|
4340
|
+
for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run({
|
|
4341
|
+
isNewProject: true,
|
|
4342
|
+
prompts: p,
|
|
4343
|
+
nypm,
|
|
4344
|
+
config: projectConfig,
|
|
4345
|
+
workspaceRoot: monorepo ? cwd : void 0,
|
|
4346
|
+
ts,
|
|
4347
|
+
openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
|
|
4348
|
+
});
|
|
4349
|
+
}
|
|
4350
|
+
const pm = (await nypm.detectPackageManager(cwd))?.name ?? "npm";
|
|
4351
|
+
const devDir = monorepo ? `packages/${coreName}` : null;
|
|
4352
|
+
const devCmd = `${pm} run dev`;
|
|
4353
|
+
p.outro(devDir ? `Your project is ready!\n cd ${devDir}\n ${devCmd}` : `Your project is ready! Run: ${devCmd}`);
|
|
4354
|
+
}
|
|
4355
|
+
async function addCapabilities(cwd, strictConfig) {
|
|
4356
|
+
const workspaceRoot = await detectWorkspaceRoot(cwd);
|
|
4357
|
+
const raw = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
|
|
4358
|
+
const installed = /* @__PURE__ */ new Set([...Object.keys(raw.dependencies ?? {}), ...Object.keys(raw.devDependencies ?? {})]);
|
|
4359
|
+
const discovered = await discoverPlugins(cwd);
|
|
4360
|
+
const configurable = discovered.filter((d) => d.plugin.init);
|
|
4361
|
+
const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
|
|
4362
|
+
if (installable.length === 0 && configurable.length === 0) {
|
|
4363
|
+
p.log.info("All known integrations are already installed and configured.");
|
|
4364
|
+
p.outro("Nothing to do.");
|
|
4365
|
+
return;
|
|
4366
|
+
}
|
|
4367
|
+
const { toInstall, toConfigure } = await promptAddCapabilities(installable, configurable);
|
|
4368
|
+
if (toInstall.length === 0 && toConfigure.length === 0) {
|
|
4369
|
+
p.outro("No changes made.");
|
|
4370
|
+
return;
|
|
4371
|
+
}
|
|
4372
|
+
const summaryLines = [];
|
|
4373
|
+
for (const i of toInstall) summaryLines.push(`Install: ${i.displayName}`);
|
|
4374
|
+
for (const d of toConfigure) summaryLines.push(`Configure: ${d.plugin.init.displayName}`);
|
|
4375
|
+
p.note(summaryLines.join("\n"), "Summary");
|
|
4376
|
+
const confirmed = await p.confirm({ message: "Apply changes?" });
|
|
4377
|
+
cancelIfAborted(confirmed);
|
|
4378
|
+
if (!confirmed) {
|
|
4379
|
+
p.cancel("Cancelled.");
|
|
4380
|
+
process.exit(0);
|
|
4381
|
+
}
|
|
4382
|
+
if (toInstall.length > 0) {
|
|
4383
|
+
const s = p.spinner();
|
|
4384
|
+
const pkgs = toInstall.map((i) => i.package);
|
|
4385
|
+
s.start(`Installing ${pkgs.join(", ")}`);
|
|
4386
|
+
await nypm.addDevDependency(withVersionRanges(pkgs), {
|
|
4387
|
+
cwd,
|
|
4388
|
+
silent: true
|
|
4389
|
+
});
|
|
4390
|
+
s.stop("Dependencies installed");
|
|
4391
|
+
await verifyInstalled(cwd, pkgs);
|
|
4392
|
+
}
|
|
4393
|
+
const allDiscovered = toInstall.length > 0 ? await discoverPlugins(cwd) : discovered;
|
|
4394
|
+
const newlyInstalledPkgs = new Set(toInstall.map((i) => i.package));
|
|
4395
|
+
const toRun = [...allDiscovered.filter((d) => newlyInstalledPkgs.has(d.packageName)), ...toConfigure].filter((d) => d.plugin.init?.run);
|
|
4396
|
+
const projectConfig = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
|
|
4397
|
+
for (const d of toRun) await d.plugin.init.run({
|
|
4398
|
+
isNewProject: false,
|
|
4399
|
+
prompts: p,
|
|
4400
|
+
nypm,
|
|
4401
|
+
config: projectConfig,
|
|
4402
|
+
workspaceRoot,
|
|
4403
|
+
ts,
|
|
4404
|
+
openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
|
|
4405
|
+
});
|
|
4406
|
+
p.outro("Done! Run pnpm run dev to continue.");
|
|
4407
|
+
}
|
|
4408
|
+
function toNamespace(name) {
|
|
4409
|
+
const base = name.replace(/^@[^/]+\//, "");
|
|
4410
|
+
return toPascalCase(base.replace(/[/_]/g, "-"));
|
|
4411
|
+
}
|
|
4412
|
+
//#endregion
|
|
2077
4413
|
//#region src/task-serve.ts
|
|
2078
4414
|
const taskServe = async (config, flags) => {
|
|
2079
4415
|
config.suppressLogs = true;
|
|
@@ -2129,6 +4465,41 @@ const run = async (init) => {
|
|
|
2129
4465
|
}), logger, sys);
|
|
2130
4466
|
return;
|
|
2131
4467
|
}
|
|
4468
|
+
if (task === "add" || task === "init") {
|
|
4469
|
+
const coreCompiler = await loadCoreCompiler(sys);
|
|
4470
|
+
const rootDir = sys.getCurrentDirectory();
|
|
4471
|
+
const findConfigResults = await findConfig({
|
|
4472
|
+
sys,
|
|
4473
|
+
configPath: flags.config
|
|
4474
|
+
});
|
|
4475
|
+
let strictConfig;
|
|
4476
|
+
const foundConfigPath = !findConfigResults.isErr ? result.unwrap(findConfigResults).configPath : null;
|
|
4477
|
+
if (foundConfigPath) {
|
|
4478
|
+
const loaded = await coreCompiler.loadConfig({
|
|
4479
|
+
config: { rootDir: dirname(foundConfigPath) },
|
|
4480
|
+
configPath: foundConfigPath,
|
|
4481
|
+
logger,
|
|
4482
|
+
sys
|
|
4483
|
+
});
|
|
4484
|
+
strictConfig = coreCompiler.validateConfig(loaded.config, {}).config;
|
|
4485
|
+
} else strictConfig = coreCompiler.validateConfig({ rootDir }, {}).config;
|
|
4486
|
+
if (task === "add") await taskAdd(flags.unknownArgs, strictConfig);
|
|
4487
|
+
else {
|
|
4488
|
+
const loadProjectConfig = async (configPath) => {
|
|
4489
|
+
const derivedRootDir = configPath ? dirname(configPath) : rootDir;
|
|
4490
|
+
const loaded = await coreCompiler.loadConfig({
|
|
4491
|
+
config: { rootDir: derivedRootDir },
|
|
4492
|
+
configPath,
|
|
4493
|
+
logger,
|
|
4494
|
+
sys
|
|
4495
|
+
});
|
|
4496
|
+
if (loaded.diagnostics.length > 0) logger.printDiagnostics(loaded.diagnostics);
|
|
4497
|
+
return coreCompiler.validateConfig(loaded.config ?? { rootDir: derivedRootDir }, {}).config;
|
|
4498
|
+
};
|
|
4499
|
+
await taskInit(coreCompiler, strictConfig, loadProjectConfig);
|
|
4500
|
+
}
|
|
4501
|
+
return;
|
|
4502
|
+
}
|
|
2132
4503
|
startupLog(logger, task);
|
|
2133
4504
|
const findConfigResults = await findConfig({
|
|
2134
4505
|
sys,
|
|
@@ -2149,7 +4520,7 @@ const run = async (init) => {
|
|
|
2149
4520
|
const configWithFlags = mergeFlags({}, flags);
|
|
2150
4521
|
const validated = await coreCompiler.loadConfig({
|
|
2151
4522
|
config: configWithFlags,
|
|
2152
|
-
configPath: foundConfig.configPath,
|
|
4523
|
+
configPath: foundConfig.configPath ?? void 0,
|
|
2153
4524
|
logger,
|
|
2154
4525
|
sys
|
|
2155
4526
|
});
|
|
@@ -2186,6 +4557,9 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
|
|
|
2186
4557
|
if (!configWithFlags.sys) configWithFlags.sys = sys;
|
|
2187
4558
|
const strictConfig = coreCompiler.validateConfig(configWithFlags, {}).config;
|
|
2188
4559
|
switch (task) {
|
|
4560
|
+
case "add":
|
|
4561
|
+
await taskAdd(resolvedFlags.unknownArgs ?? [], strictConfig);
|
|
4562
|
+
break;
|
|
2189
4563
|
case "build":
|
|
2190
4564
|
await taskBuild(coreCompiler, strictConfig, resolvedFlags);
|
|
2191
4565
|
break;
|
|
@@ -2199,6 +4573,9 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
|
|
|
2199
4573
|
case "help":
|
|
2200
4574
|
await taskHelp(resolvedFlags, strictConfig.logger, sys);
|
|
2201
4575
|
break;
|
|
4576
|
+
case "init":
|
|
4577
|
+
await taskInit(coreCompiler, strictConfig);
|
|
4578
|
+
break;
|
|
2202
4579
|
case "migrate":
|
|
2203
4580
|
await taskMigrate(coreCompiler, strictConfig, resolvedFlags);
|
|
2204
4581
|
break;
|