@stencil/cli 5.0.0-alpha.6 → 5.0.0-alpha.8

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/dist/index.mjs CHANGED
@@ -1,7 +1,17 @@
1
1
  import { LOG_LEVELS } from "@stencil/core/compiler";
2
2
  import { buildError, catchError, hasError, isFunction, isOutputTargetDocs, isOutputTargetSsr, isOutputTargetWww, isString, normalizePath, readOnlyArrayHasStringMember, result, shouldIgnoreError, toCamelCase, validateComponentTag } from "@stencil/core/compiler/utils";
3
- import { dirname, isAbsolute, join, parse, relative } from "path";
3
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
4
+ import { basename, dirname, join, parse, relative, resolve } from "node:path";
5
+ import * as p from "@clack/prompts";
6
+ import { cancel, isCancel, select } from "@clack/prompts";
7
+ import * as nypm from "nypm";
8
+ import { addDevDependency, installDependencies } from "nypm";
9
+ import { isCI } from "std-env";
10
+ import { pathToFileURL } from "node:url";
11
+ import { existsSync } from "node:fs";
12
+ import { dirname as dirname$1, isAbsolute, join as join$1, relative as relative$1 } from "path";
4
13
  import ts from "typescript";
14
+ import { generatePackageJsonFields, generateStencilConfig, getComponentBoilerplate, getStyleBoilerplate, getTemplatePath, toPascalCase } from "@stencil/templates";
5
15
  import { start } from "@stencil/dev-server";
6
16
  //#region src/config-flags.ts
7
17
  /**
@@ -440,7 +450,7 @@ const findConfig = async (opts) => {
440
450
  else configPath = normalizePath(configPath);
441
451
  else configPath = rootDir;
442
452
  const results = {
443
- configPath,
453
+ configPath: null,
444
454
  rootDir: normalizePath(cwd)
445
455
  };
446
456
  const stat = await sys.stat(configPath);
@@ -455,12 +465,15 @@ const findConfig = async (opts) => {
455
465
  if (stat.isFile) {
456
466
  results.configPath = configPath;
457
467
  results.rootDir = sys.platformPath.dirname(configPath);
458
- } else if (stat.isDirectory) for (const configName of ["stencil.config.ts", "stencil.config.js"]) {
459
- const testConfigFilePath = sys.platformPath.join(configPath, configName);
460
- if ((await sys.stat(testConfigFilePath)).isFile) {
461
- results.configPath = testConfigFilePath;
462
- results.rootDir = sys.platformPath.dirname(testConfigFilePath);
463
- break;
468
+ } else if (stat.isDirectory) {
469
+ results.rootDir = configPath;
470
+ for (const configName of ["stencil.config.ts", "stencil.config.js"]) {
471
+ const testConfigFilePath = sys.platformPath.join(configPath, configName);
472
+ if ((await sys.stat(testConfigFilePath)).isFile) {
473
+ results.configPath = testConfigFilePath;
474
+ results.rootDir = sys.platformPath.dirname(testConfigFilePath);
475
+ break;
476
+ }
464
477
  }
465
478
  }
466
479
  return result.ok(results);
@@ -588,6 +601,503 @@ const mergeFlags = (config, flags) => {
588
601
  return merged;
589
602
  };
590
603
  //#endregion
604
+ //#region src/wizard/discover.ts
605
+ function toStringRecord(val) {
606
+ return val !== null && typeof val === "object" ? val : {};
607
+ }
608
+ async function readJson$1(filePath) {
609
+ try {
610
+ return JSON.parse(await readFile(filePath, "utf8"));
611
+ } catch {
612
+ return null;
613
+ }
614
+ }
615
+ async function loadOne(rootDir, packageName, loader) {
616
+ const wizardEntry = ((await readJson$1(join(rootDir, "node_modules", packageName, "package.json")))?.stencil)?.wizard;
617
+ if (!wizardEntry) return null;
618
+ const wizardPath = join(rootDir, "node_modules", packageName, wizardEntry);
619
+ let mod;
620
+ try {
621
+ mod = await loader(pathToFileURL(wizardPath).href);
622
+ } catch {
623
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but the module failed to load: ${wizardPath}`);
624
+ return null;
625
+ }
626
+ const plugin = mod.wizard;
627
+ if (!plugin || typeof plugin !== "object") {
628
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but does not export a 'wizard' object`);
629
+ return null;
630
+ }
631
+ return {
632
+ packageName,
633
+ plugin
634
+ };
635
+ }
636
+ /**
637
+ * Scans the project's declared dependencies for packages that expose a
638
+ * `stencil.wizard` entry in their `package.json` and dynamically imports
639
+ * each matching module.
640
+ *
641
+ * @param rootDir - Absolute path to the project root (where `package.json` lives).
642
+ * @param loader - Module loader; injectable for testing. Defaults to `import()`.
643
+ * @returns Array of successfully loaded plugins, in dependency declaration order.
644
+ */
645
+ async function discoverPlugins(rootDir, loader = (url) => import(url)) {
646
+ const pkg = await readJson$1(join(rootDir, "package.json"));
647
+ if (!pkg) return [];
648
+ const depNames = [...new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
649
+ const plugins = (await Promise.allSettled(depNames.map((name) => loadOne(rootDir, name, loader)))).filter((r) => r.status === "fulfilled" && r.value !== null).map((r) => r.value);
650
+ const devPath = process.env.STENCIL_WIZARD_DEV;
651
+ if (devPath) {
652
+ const devPlugin = await loadDevPlugin(resolve(rootDir, devPath), loader);
653
+ if (devPlugin) {
654
+ const deduped = plugins.filter((p) => p.packageName !== devPlugin.packageName);
655
+ plugins.length = 0;
656
+ plugins.push(devPlugin, ...deduped);
657
+ }
658
+ }
659
+ return plugins;
660
+ }
661
+ async function findDevPackageName(wizardPath) {
662
+ const dir = dirname(wizardPath);
663
+ for (const candidate of [dir, resolve(dir, "..")]) {
664
+ const pkg = await readJson$1(join(candidate, "package.json"));
665
+ if (typeof pkg?.name === "string") return pkg.name;
666
+ }
667
+ return basename(dir);
668
+ }
669
+ async function loadDevPlugin(wizardPath, loader) {
670
+ const packageName = await findDevPackageName(wizardPath);
671
+ let mod;
672
+ try {
673
+ mod = await loader(pathToFileURL(wizardPath).href);
674
+ } catch {
675
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: failed to load ${wizardPath}`);
676
+ return null;
677
+ }
678
+ const plugin = mod.wizard;
679
+ if (!plugin || typeof plugin !== "object") {
680
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: ${wizardPath} does not export a 'wizard' object`);
681
+ return null;
682
+ }
683
+ return {
684
+ packageName,
685
+ plugin
686
+ };
687
+ }
688
+ //#endregion
689
+ //#region src/wizard/clack.ts
690
+ /**
691
+ * Exits cleanly if the user cancelled a prompt (Ctrl+C).
692
+ * Narrows the type from `T | symbol` to `T` for callers.
693
+ *
694
+ * @param value - Return value from a `@clack/prompts` prompt call.
695
+ */
696
+ function cancelIfAborted(value) {
697
+ if (isCancel(value)) {
698
+ cancel("Cancelled.");
699
+ process.exit(0);
700
+ }
701
+ }
702
+ //#endregion
703
+ //#region src/wizard/init/steps.ts
704
+ /** Well-known integrations the CLI can offer before any packages are installed. */
705
+ const KNOWN_INTEGRATIONS = [
706
+ {
707
+ package: "@stencil/vitest",
708
+ displayName: "Vitest",
709
+ description: "Unit / Spec / Integration / Browser testing",
710
+ group: "Testing"
711
+ },
712
+ {
713
+ package: "@stencil/playwright",
714
+ displayName: "Playwright",
715
+ description: "E2E testing",
716
+ group: "Testing"
717
+ },
718
+ {
719
+ package: "@stencil/sass",
720
+ displayName: "Sass",
721
+ description: "Sass/SCSS styles",
722
+ group: "Styling"
723
+ },
724
+ {
725
+ package: "@stencil/eslint-plugin",
726
+ displayName: "ESLint Plugin",
727
+ description: "Stencil-aware lint rules (ESLint, oxlint, Biome)",
728
+ group: "Linting"
729
+ },
730
+ {
731
+ package: "@stencil/storybook-plugin",
732
+ displayName: "Storybook",
733
+ description: "Component development & documentation",
734
+ group: "Tooling"
735
+ },
736
+ {
737
+ package: "@stencil/types-output-target",
738
+ displayName: "Types",
739
+ description: "TypeScript types for React, Vue, Solid, Svelte, Preact",
740
+ group: "Framework integrations"
741
+ },
742
+ {
743
+ package: "@stencil/react-output-target",
744
+ displayName: "React",
745
+ description: "React component wrappers",
746
+ group: "Framework integrations"
747
+ },
748
+ {
749
+ package: "@stencil/angular-output-target",
750
+ displayName: "Angular",
751
+ description: "Angular component wrappers",
752
+ group: "Framework integrations"
753
+ },
754
+ {
755
+ package: "@stencil/vue-output-target",
756
+ displayName: "Vue",
757
+ description: "Vue component wrappers",
758
+ group: "Framework integrations"
759
+ }
760
+ ];
761
+ async function promptOutputs() {
762
+ const picks = await p.multiselect({
763
+ message: "Outputs:",
764
+ options: [
765
+ {
766
+ value: "loader",
767
+ label: "Loader",
768
+ hint: "performant lazy-loader; browser & bundler ready"
769
+ },
770
+ {
771
+ value: "standalone",
772
+ label: "Standalone",
773
+ hint: "per-component modules, import only what you need"
774
+ },
775
+ {
776
+ value: "ssr",
777
+ label: "SSR",
778
+ hint: "pre-render components in any JS server environment"
779
+ },
780
+ {
781
+ value: "ssr-wasm",
782
+ label: "SSR WASM",
783
+ hint: "experimental: compile SSR to a portable WASM binary"
784
+ },
785
+ {
786
+ value: "www",
787
+ label: "WWW",
788
+ hint: "app mode with dev server and optional PWA support"
789
+ }
790
+ ],
791
+ required: false
792
+ });
793
+ cancelIfAborted(picks);
794
+ return picks;
795
+ }
796
+ async function promptFeatures() {
797
+ const picks = await p.multiselect({
798
+ message: "Features:",
799
+ options: [
800
+ {
801
+ value: "signals",
802
+ label: "Signals",
803
+ hint: "signal-backed @Prop/@State for cross-framework reactive interop"
804
+ },
805
+ {
806
+ value: "globalStyle",
807
+ label: "Global style",
808
+ hint: "Global stylesheet for font definitions, CSS variables, pre-load styles etc"
809
+ },
810
+ {
811
+ value: "globalScript",
812
+ label: "Global script",
813
+ hint: "Global script for initializing application-wide logic before components load"
814
+ }
815
+ ],
816
+ required: false
817
+ });
818
+ cancelIfAborted(picks);
819
+ const set = new Set(picks);
820
+ return {
821
+ signals: set.has("signals"),
822
+ globalStyle: set.has("globalStyle"),
823
+ globalScript: set.has("globalScript")
824
+ };
825
+ }
826
+ async function promptDocs() {
827
+ const picks = await p.multiselect({
828
+ message: "Docs:",
829
+ options: [
830
+ {
831
+ value: "cem",
832
+ label: "CEM",
833
+ hint: "custom-elements.json - preferred format for interop with tools like Storybook, Styleguidist, etc"
834
+ },
835
+ {
836
+ value: "json",
837
+ label: "JSON",
838
+ hint: "docs.json - Stencil / Ionic centric schema"
839
+ },
840
+ {
841
+ value: "vscode",
842
+ label: "VS Code",
843
+ hint: "vscode-data.json - editor autocomplete for your components"
844
+ }
845
+ ],
846
+ initialValues: ["cem"],
847
+ required: false
848
+ });
849
+ cancelIfAborted(picks);
850
+ return picks;
851
+ }
852
+ async function promptProjectName() {
853
+ const name = await p.text({
854
+ message: "Project name:",
855
+ defaultValue: "my-stencil-library",
856
+ validate: (v) => {
857
+ if (!v?.trim()) return "Project name is required";
858
+ }
859
+ });
860
+ cancelIfAborted(name);
861
+ return name;
862
+ }
863
+ function buildGroupedOptions(integrations) {
864
+ const groups = {};
865
+ for (const i of integrations) (groups[i.group] ??= []).push({
866
+ value: i.package,
867
+ label: i.displayName,
868
+ hint: i.description
869
+ });
870
+ return groups;
871
+ }
872
+ async function promptCustomPackages() {
873
+ const input = await p.text({
874
+ message: "Additional packages to install:",
875
+ placeholder: "e.g. my-plugin another-package (leave blank to skip)"
876
+ });
877
+ cancelIfAborted(input);
878
+ if (typeof input !== "string" || !input.trim()) return [];
879
+ return input.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
880
+ }
881
+ async function promptIntegrations() {
882
+ const picks = await p.groupMultiselect({
883
+ message: "Add integrations (optional):",
884
+ options: buildGroupedOptions(KNOWN_INTEGRATIONS),
885
+ required: false
886
+ });
887
+ cancelIfAborted(picks);
888
+ return KNOWN_INTEGRATIONS.filter((i) => picks.includes(i.package));
889
+ }
890
+ /**
891
+ * Prompt for actions on an existing project: install new integrations and/or
892
+ * run init wizards for already-installed packages with wizard contributions.
893
+ *
894
+ * @param installable - KNOWN_INTEGRATIONS not yet present in the project.
895
+ * @param configurable - Already-installed plugins that declare an `init` contribution.
896
+ * @returns Selected integrations to install and plugins to configure.
897
+ */
898
+ async function promptAddCapabilities(installable, configurable) {
899
+ const options = {};
900
+ if (installable.length > 0) options["Install new integrations"] = installable.map((i) => ({
901
+ value: `install:${i.package}`,
902
+ label: i.displayName,
903
+ hint: i.description
904
+ }));
905
+ if (configurable.length > 0) options["Configure existing integrations"] = configurable.map((d) => ({
906
+ value: `configure:${d.packageName}`,
907
+ label: d.plugin.init.displayName,
908
+ hint: d.plugin.init.description
909
+ }));
910
+ const picks = await p.groupMultiselect({
911
+ message: "What would you like to do?",
912
+ options,
913
+ required: false
914
+ });
915
+ cancelIfAborted(picks);
916
+ const pickedSet = new Set(picks);
917
+ return {
918
+ toInstall: installable.filter((i) => pickedSet.has(`install:${i.package}`)),
919
+ toConfigure: configurable.filter((d) => pickedSet.has(`configure:${d.packageName}`))
920
+ };
921
+ }
922
+ //#endregion
923
+ //#region src/wizard/project.ts
924
+ /**
925
+ * Extracts the stable, plugin-relevant fields from a fully-resolved compiler config.
926
+ * @param validated The fully-resolved compiler config.
927
+ * @returns A ProjectConfig with only the fields relevant to plugins and the wizard.
928
+ * This is a stable subset of the compiler config that won't change between versions.
929
+ */
930
+ function toProjectConfig(validated) {
931
+ return {
932
+ rootDir: validated.rootDir,
933
+ srcDir: validated.srcDir,
934
+ namespace: validated.namespace,
935
+ fsNamespace: validated.fsNamespace,
936
+ outputTargets: validated.outputTargets ?? [],
937
+ globalScript: validated.globalScript,
938
+ globalStyle: validated.globalStyle,
939
+ compat: validated.compat,
940
+ signalBacking: validated.signalBacking
941
+ };
942
+ }
943
+ /**
944
+ * Builds a minimal ProjectConfig when no validated config is available (e.g. new project, no compiler).
945
+ * @param rootDir The root directory of the project.
946
+ * @param overrides Optional fields to override the defaults.
947
+ * @returns A ProjectConfig with reasonable defaults for a new project.
948
+ * */
949
+ function defaultProjectConfig(rootDir, overrides) {
950
+ const namespace = overrides?.namespace ?? "";
951
+ return {
952
+ rootDir,
953
+ srcDir: join(rootDir, "src"),
954
+ namespace,
955
+ fsNamespace: overrides?.fsNamespace ?? namespace.toLowerCase(),
956
+ outputTargets: [],
957
+ ...overrides
958
+ };
959
+ }
960
+ /**
961
+ * Returns true if the directory looks like an existing Stencil project:
962
+ * - has an explicit `stencil.config.ts`, OR
963
+ * - has `.tsx` files under `src/` (zero-config project).
964
+ * @param dir The directory to check for an existing Stencil project.
965
+ * @returns A promise that resolves to true if the directory looks like an existing Stencil project, false otherwise.
966
+ */
967
+ async function isExistingStencilProject(dir) {
968
+ if (existsSync(join(dir, "stencil.config.ts"))) return true;
969
+ try {
970
+ return (await readdir(join(dir, "src"), {
971
+ recursive: true,
972
+ withFileTypes: true
973
+ })).some((e) => e.isFile() && e.name.endsWith(".tsx"));
974
+ } catch {
975
+ return false;
976
+ }
977
+ }
978
+ //#endregion
979
+ //#region src/wizard/splash.ts
980
+ const CLI_VERSION = "5.0.0-alpha.8";
981
+ const isTTY = process.stdout.isTTY;
982
+ const noColor = !isTTY || "NO_COLOR" in process.env;
983
+ const RESET = noColor ? "" : "\x1B[0m";
984
+ const BOLD = noColor ? "" : "\x1B[1m";
985
+ const DIM = noColor ? "" : "\x1B[2m";
986
+ const BLUE = noColor ? "" : "\x1B[38;2;60;44;255m";
987
+ const RAW = `\
988
+ .............
989
+ ...................
990
+ .........................
991
+ ..............................
992
+ .................................
993
+ ..............████████████.........
994
+ .............████████████............
995
+ ............████████████...............
996
+ ...........*************.................
997
+ .........████████████████████████████....
998
+ .......████████████████████████████......
999
+ .....████████████████████████████........
1000
+ ...████████████████████████████..........
1001
+ ................*************............
1002
+ ..............████████████.............
1003
+ ............████████████..............
1004
+ .........████████████...............
1005
+ .................................
1006
+ ..............................
1007
+ ..........................
1008
+ ......................
1009
+ ................`;
1010
+ function colorize(raw) {
1011
+ if (noColor) return raw;
1012
+ let out = "";
1013
+ let style = "";
1014
+ for (const ch of raw) {
1015
+ const next = ".*".includes(ch) ? BLUE : "";
1016
+ if (next !== style) {
1017
+ if (style) out += RESET;
1018
+ if (next) out += next;
1019
+ style = next;
1020
+ }
1021
+ out += ch;
1022
+ }
1023
+ return style ? out + RESET : out;
1024
+ }
1025
+ const SPLASH = colorize(RAW);
1026
+ function printSplash() {
1027
+ if (!isTTY) return;
1028
+ const header = ` ${BOLD}Stencil${RESET} ${BLUE}v${CLI_VERSION}${RESET}`;
1029
+ const tagline = ` ${DIM}The Custom Element Compiler${RESET}`;
1030
+ process.stdout.write(`\n${SPLASH}\n\n${header}\n${tagline}\n\n`);
1031
+ }
1032
+ //#endregion
1033
+ //#region src/task-add.ts
1034
+ async function getInstalledPackageNames(rootDir) {
1035
+ try {
1036
+ const pkg = JSON.parse(await readFile(join(rootDir, "package.json"), "utf8"));
1037
+ const keys = (v) => Object.keys(v !== null && typeof v === "object" ? v : {});
1038
+ return new Set([...keys(pkg.dependencies), ...keys(pkg.devDependencies)]);
1039
+ } catch {
1040
+ return /* @__PURE__ */ new Set();
1041
+ }
1042
+ }
1043
+ async function selectInteractive(cwd) {
1044
+ const discovered = await discoverPlugins(cwd);
1045
+ const installed = await getInstalledPackageNames(cwd);
1046
+ const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
1047
+ const configurable = discovered.filter((d) => d.plugin.init != null);
1048
+ let toInstall = [];
1049
+ let toConfigure = [];
1050
+ if (installable.length > 0 || configurable.length > 0) {
1051
+ const result = await promptAddCapabilities(installable, configurable);
1052
+ toInstall = result.toInstall;
1053
+ toConfigure = result.toConfigure;
1054
+ } else p.log.info("All known integrations are already installed.");
1055
+ const customPackages = await promptCustomPackages();
1056
+ return {
1057
+ packagesToInstall: [...toInstall.map((i) => i.package), ...customPackages],
1058
+ pluginsToReconfigure: toConfigure
1059
+ };
1060
+ }
1061
+ async function taskAdd(packages, strictConfig) {
1062
+ const cwd = process.cwd();
1063
+ printSplash();
1064
+ p.intro("stencil add");
1065
+ if (isCI) {
1066
+ p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil add`.");
1067
+ process.exit(1);
1068
+ }
1069
+ let packagesToInstall = packages;
1070
+ let pluginsToReconfigure = [];
1071
+ if (packages.length === 0) ({packagesToInstall, pluginsToReconfigure} = await selectInteractive(cwd));
1072
+ if (packagesToInstall.length === 0 && pluginsToReconfigure.length === 0) {
1073
+ p.outro("Nothing to do.");
1074
+ return;
1075
+ }
1076
+ if (packagesToInstall.length > 0) if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: skipping install, loading wizard from ${process.env.STENCIL_WIZARD_DEV}`);
1077
+ else {
1078
+ const s = p.spinner();
1079
+ s.start(`Installing ${packagesToInstall.join(", ")}`);
1080
+ await addDevDependency(packagesToInstall, {
1081
+ cwd,
1082
+ silent: true
1083
+ });
1084
+ s.stop("Installed");
1085
+ }
1086
+ const context = {
1087
+ isNewProject: false,
1088
+ prompts: p,
1089
+ nypm,
1090
+ config: strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd)
1091
+ };
1092
+ if (packagesToInstall.length > 0) {
1093
+ const discovered = await discoverPlugins(cwd);
1094
+ const installedSet = new Set(packagesToInstall);
1095
+ for (const d of discovered) if (installedSet.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run(context);
1096
+ }
1097
+ for (const d of pluginsToReconfigure) if (d.plugin.init?.run) await d.plugin.init.run(context);
1098
+ p.outro("Done!");
1099
+ }
1100
+ //#endregion
591
1101
  //#region src/check-version.ts
592
1102
  /**
593
1103
  * Retrieve a reference to the active `CompilerSystem`'s `checkVersion` function
@@ -904,6 +1414,53 @@ const externalRuntimeRule = {
904
1414
  }
905
1415
  };
906
1416
  //#endregion
1417
+ //#region src/migrations/rules/extras-to-compat.ts
1418
+ /**
1419
+ * Migration rule: rename the top-level `extras` config key to `compat`.
1420
+ *
1421
+ * In v5, `extras` is replaced by `compat` (framework/bundler compatibility flags).
1422
+ */
1423
+ const extrasToCompatRule = {
1424
+ id: "extras-to-compat",
1425
+ name: "Extras → Compat Rename",
1426
+ description: "Rename top-level 'extras' config key to 'compat'",
1427
+ fromVersion: "4.x",
1428
+ toVersion: "5.x",
1429
+ detect(sourceFile) {
1430
+ const matches = [];
1431
+ const visit = (node) => {
1432
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1433
+ if (node.name.text === "extras") {
1434
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1435
+ matches.push({
1436
+ node,
1437
+ message: "'extras' has been renamed to 'compat'",
1438
+ line: line + 1,
1439
+ column: character + 1
1440
+ });
1441
+ }
1442
+ }
1443
+ ts.forEachChild(node, visit);
1444
+ };
1445
+ visit(sourceFile);
1446
+ return matches;
1447
+ },
1448
+ transform(sourceFile, matches) {
1449
+ if (matches.length === 0) return sourceFile.getFullText();
1450
+ let text = sourceFile.getFullText();
1451
+ const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
1452
+ for (const match of sorted) {
1453
+ const node = match.node;
1454
+ if (node.name.text === "extras") {
1455
+ const keyStart = node.name.getStart();
1456
+ const keyEnd = node.name.getEnd();
1457
+ text = text.slice(0, keyStart) + "compat" + text.slice(keyEnd);
1458
+ }
1459
+ }
1460
+ return text;
1461
+ }
1462
+ };
1463
+ //#endregion
907
1464
  //#region src/migrations/rules/form-associated.ts
908
1465
  /**
909
1466
  * Migration rule for formAssociated → @AttachInternals.
@@ -1769,6 +2326,64 @@ const rolldownConfigRule = {
1769
2326
  }
1770
2327
  };
1771
2328
  //#endregion
2329
+ //#region src/migrations/rules/service-worker-default.ts
2330
+ /**
2331
+ * Migration rule for `serviceWorker: null` / `serviceWorker: false` on `www` output targets.
2332
+ *
2333
+ * In Stencil v5, `serviceWorker` defaults to `null` (disabled). Explicit `null` or `false`
2334
+ * values on `www` output targets are now redundant and can be removed.
2335
+ */
2336
+ const serviceWorkerDefaultRule = {
2337
+ id: "service-worker-default",
2338
+ name: "Service Worker Default Cleanup",
2339
+ description: "Remove redundant 'serviceWorker: null' / 'serviceWorker: false' from www output targets - null is now the default",
2340
+ fromVersion: "4.x",
2341
+ toVersion: "5.x",
2342
+ detect(sourceFile) {
2343
+ const matches = [];
2344
+ const visit = (node) => {
2345
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "serviceWorker") {
2346
+ const init = node.initializer;
2347
+ if (init.kind === ts.SyntaxKind.NullKeyword || init.kind === ts.SyntaxKind.FalseKeyword) {
2348
+ const parent = node.parent;
2349
+ if (ts.isObjectLiteralExpression(parent)) {
2350
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && p.initializer.text === "www")) {
2351
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2352
+ matches.push({
2353
+ node,
2354
+ message: `'serviceWorker: ${init.kind === ts.SyntaxKind.NullKeyword ? "null" : "false"}' is now the default on www output targets and can be removed`,
2355
+ line: line + 1,
2356
+ column: character + 1
2357
+ });
2358
+ }
2359
+ }
2360
+ }
2361
+ }
2362
+ ts.forEachChild(node, visit);
2363
+ };
2364
+ visit(sourceFile);
2365
+ return matches;
2366
+ },
2367
+ transform(sourceFile, matches) {
2368
+ if (matches.length === 0) return sourceFile.getFullText();
2369
+ let text = sourceFile.getFullText();
2370
+ for (const match of [...matches].reverse()) {
2371
+ const node = match.node;
2372
+ let start = node.getFullStart();
2373
+ const end = node.getEnd();
2374
+ let removeEnd = end;
2375
+ const trailingComma = text.slice(end).match(/^\s*,/);
2376
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
2377
+ else {
2378
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
2379
+ if (leadingComma) start -= leadingComma[0].length;
2380
+ }
2381
+ text = text.slice(0, start) + text.slice(removeEnd);
2382
+ }
2383
+ return text;
2384
+ }
2385
+ };
2386
+ //#endregion
1772
2387
  //#region src/migrations/index.ts
1773
2388
  /**
1774
2389
  * Build a map of local import names to their original names from @stencil/core.
@@ -1814,9 +2429,11 @@ const migrationRules = [
1814
2429
  devModeRule,
1815
2430
  globalStyleInjectRule,
1816
2431
  lightDomPatchesRule,
2432
+ extrasToCompatRule,
1817
2433
  externalRuntimeRule,
1818
2434
  hashFileNamesRule,
1819
- rolldownConfigRule
2435
+ rolldownConfigRule,
2436
+ serviceWorkerDefaultRule
1820
2437
  ];
1821
2438
  /**
1822
2439
  * Get all migration rules for a specific version upgrade.
@@ -1865,7 +2482,7 @@ const taskMigrate = async (coreCompiler, config, flags) => {
1865
2482
  const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
1866
2483
  const matches = rule.detect(sourceFile);
1867
2484
  if (matches.length > 0) {
1868
- const relPath = relative(config.rootDir, filePath);
2485
+ const relPath = relative$1(config.rootDir, filePath);
1869
2486
  logger.info(`\n${logger.cyan(relPath)}`);
1870
2487
  logger.info(` ${logger.yellow(`[${rule.id}]`)} ${rule.name}`);
1871
2488
  for (const match of matches) logger.info(` Line ${match.line}: ${match.message}`);
@@ -1977,8 +2594,8 @@ const detectMigrations = async (coreCompiler, config) => {
1977
2594
  */
1978
2595
  async function getTypeScriptFiles(config, sys, logger) {
1979
2596
  let tsconfigPath;
1980
- if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join(config.rootDir, config.tsconfig);
1981
- else tsconfigPath = join(config.rootDir, "tsconfig.json");
2597
+ if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join$1(config.rootDir, config.tsconfig);
2598
+ else tsconfigPath = join$1(config.rootDir, "tsconfig.json");
1982
2599
  logger.debug(`Using tsconfig: ${tsconfigPath}`);
1983
2600
  const tsconfigContent = await sys.readFile(tsconfigPath);
1984
2601
  if (!tsconfigContent) {
@@ -2008,11 +2625,11 @@ async function getTypeScriptFiles(config, sys, logger) {
2008
2625
  const configContent = await sys.readFile(configFile);
2009
2626
  if (configContent) {
2010
2627
  const configSourceFile = ts.createSourceFile(configFile, configContent, ts.ScriptTarget.Latest, true);
2011
- const configDir = dirname(configFile);
2628
+ const configDir = dirname$1(configFile);
2012
2629
  for (const statement of configSourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
2013
2630
  const specifier = statement.moduleSpecifier.text;
2014
2631
  if (!specifier.startsWith("./") && !specifier.startsWith("../")) continue;
2015
- const basePath = join(configDir, specifier);
2632
+ const basePath = join$1(configDir, specifier);
2016
2633
  const candidates = basePath.endsWith(".ts") || basePath.endsWith(".tsx") ? [basePath] : [`${basePath}.ts`, `${basePath}.tsx`];
2017
2634
  for (const candidate of candidates) if (!candidate.endsWith(".d.ts") && !files.includes(candidate) && candidate.startsWith(config.rootDir)) {
2018
2635
  if (await sys.readFile(candidate)) {
@@ -2148,8 +2765,8 @@ function hasVerbose(flags) {
2148
2765
  }
2149
2766
  //#endregion
2150
2767
  //#region src/ionic-config.ts
2151
- const isTest$1 = () => process.env.JEST_WORKER_ID !== void 0;
2152
- const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest$1() ? "tmp-config.json" : "config.json"}`);
2768
+ const isTest = () => process.env.JEST_WORKER_ID !== void 0;
2769
+ const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest() ? "tmp-config.json" : "config.json"}`);
2153
2770
  const defaultConfigDirectory = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic`);
2154
2771
  /**
2155
2772
  * Reads an Ionic configuration file from disk, parses it, and performs any necessary corrections to it if certain
@@ -2647,37 +3264,34 @@ async function promptForMigration(config, migrationResult, context) {
2647
3264
  logger.info("─".repeat(40));
2648
3265
  logger.info(`Found ${migrationResult.totalMatches} item(s) in ${migrationResult.filesAffected} file(s) that need to be migrated for Stencil v5.`);
2649
3266
  for (const migration of migrationResult.migrations) {
2650
- const relPath = relative(config.rootDir, migration.filePath);
3267
+ const relPath = relative$1(config.rootDir, migration.filePath);
2651
3268
  logger.info(` ${logger.cyan(relPath)}: ${migration.matches.length} item(s)`);
2652
3269
  }
2653
3270
  logger.info("");
2654
3271
  if (context === "pre-build") logger.info("Your config contains deprecated options that must be migrated before building.");
2655
3272
  else logger.info("These migrations may help resolve the build errors above.");
2656
- const prompt = (await import("prompts")).default;
2657
- const response = await prompt({
2658
- name: "action",
2659
- type: "select",
3273
+ const action = await select({
2660
3274
  message: "What would you like to do?",
2661
- choices: [
3275
+ options: [
2662
3276
  {
2663
- title: "Run migration",
2664
3277
  value: "run",
2665
- description: "Apply migrations and re-run build"
3278
+ label: "Run migration",
3279
+ hint: "Apply migrations and re-run build"
2666
3280
  },
2667
3281
  {
2668
- title: "Dry run",
2669
3282
  value: "dry-run",
2670
- description: "Preview changes without modifying files"
3283
+ label: "Dry run",
3284
+ hint: "Preview changes without modifying files"
2671
3285
  },
2672
3286
  {
2673
- title: "Exit",
2674
3287
  value: "exit",
2675
- description: "Exit without making changes"
3288
+ label: "Exit",
3289
+ hint: "Exit without making changes"
2676
3290
  }
2677
3291
  ]
2678
3292
  });
2679
- if (response.action === void 0) return "exit";
2680
- return response.action;
3293
+ if (isCancel(action)) return "exit";
3294
+ return action;
2681
3295
  }
2682
3296
  //#endregion
2683
3297
  //#region src/task-docs.ts
@@ -2692,276 +3306,109 @@ const taskDocs = async (coreCompiler, config) => {
2692
3306
  };
2693
3307
  //#endregion
2694
3308
  //#region src/task-generate.ts
2695
- /**
2696
- * Task to generate component boilerplate and write it to disk. This task can
2697
- * cause the program to exit with an error under various circumstances, such as
2698
- * being called in an inappropriate place, being asked to overwrite files that
2699
- * already exist, etc.
2700
- *
2701
- * @param config the user-supplied config, which we need here to access `.sys`.
2702
- * @param flags the CLI flags (owned by CLI, not part of core config)
2703
- * @returns a void promise
2704
- */
3309
+ async function resolveFileTemplates(contrib, ctx) {
3310
+ const { fileTemplates } = contrib;
3311
+ if (!fileTemplates) return [];
3312
+ return typeof fileTemplates === "function" ? fileTemplates(ctx) : fileTemplates;
3313
+ }
2705
3314
  const taskGenerate = async (config, flags) => {
2706
- if (!config.configPath) {
2707
- config.logger.error("Please run this command in your root directory (i. e. the one containing stencil.config.ts).");
3315
+ const srcDir = config.srcDir;
3316
+ if (!srcDir || !existsSync(srcDir)) {
3317
+ config.logger.error("Please run this command in your project root directory.");
2708
3318
  return config.sys.exit(1);
2709
3319
  }
2710
- const absoluteSrcDir = config.srcDir;
2711
- if (!absoluteSrcDir) {
2712
- config.logger.error(`Stencil's srcDir was not specified.`);
2713
- return config.sys.exit(1);
3320
+ const generateContribs = (await discoverPlugins(config.rootDir)).flatMap((d) => d.plugin.generate ? [d.plugin.generate] : []);
3321
+ p.intro("stencil generate");
3322
+ const rawInput = flags.unknownArgs.find((arg) => !arg.startsWith("-"));
3323
+ let input;
3324
+ if (rawInput) input = rawInput;
3325
+ else {
3326
+ const tagName = await p.text({
3327
+ message: "Component tag name (dash-case):",
3328
+ validate: (value) => validateComponentTag(value ?? "")
3329
+ });
3330
+ cancelIfAborted(tagName);
3331
+ input = tagName;
2714
3332
  }
2715
- const { prompt } = await import("prompts");
2716
- const input = flags.unknownArgs.find((arg) => !arg.startsWith("-")) || (await prompt({
2717
- name: "tagName",
2718
- type: "text",
2719
- message: "Component tag name (dash-case):"
2720
- })).tagName;
2721
- if (void 0 === input) return;
2722
3333
  const { dir, base: componentName } = parse(input);
2723
3334
  const tagError = validateComponentTag(componentName);
2724
3335
  if (tagError) {
2725
3336
  config.logger.error(tagError);
2726
3337
  return config.sys.exit(1);
2727
3338
  }
2728
- let cssExtension = "css";
2729
- if (config.plugins?.find((plugin) => plugin.name === "sass")) cssExtension = await chooseSassExtension();
2730
- else if (config.plugins?.find((plugin) => plugin.name === "less")) cssExtension = "less";
2731
- const filesToGenerateExt = await chooseFilesToGenerate(cssExtension);
2732
- if (!filesToGenerateExt) return;
2733
- const extensionsToGenerate = ["tsx", ...filesToGenerateExt];
2734
- const testFolder = extensionsToGenerate.some(isTest) ? "test" : "";
2735
- const outDir = join(absoluteSrcDir, "components", dir, componentName);
2736
- await config.sys.createDir(normalizePath(join(outDir, testFolder)), { recursive: true });
2737
- const filesToGenerate = extensionsToGenerate.map((extension) => ({
2738
- extension,
2739
- path: getFilepathForFile(outDir, componentName, extension)
2740
- }));
2741
- await checkForOverwrite(filesToGenerate, config);
2742
- const writtenFiles = await Promise.all(filesToGenerate.map((file) => getBoilerplateAndWriteFile(config, componentName, extensionsToGenerate.includes("css") || extensionsToGenerate.includes("sass") || extensionsToGenerate.includes("scss") || extensionsToGenerate.includes("less"), file, cssExtension))).catch((error) => config.logger.error(error));
2743
- if (!writtenFiles) return config.sys.exit(1);
2744
- console.log();
2745
- console.log(`${config.logger.gray("$")} stencil generate ${input}`);
2746
- console.log();
2747
- console.log(config.logger.bold("The following files have been generated:"));
2748
- const absoluteRootDir = config.rootDir;
2749
- writtenFiles.map((file) => console.log(` - ${relative(absoluteRootDir, file)}`));
2750
- };
2751
- /**
2752
- * Show a checkbox prompt to select the files to be generated.
2753
- *
2754
- * @param cssExtension the extension of the CSS file to be generated
2755
- * @returns a read-only array of `GeneratableExtension`, the extensions that the user has decided
2756
- * to generate
2757
- */
2758
- const chooseFilesToGenerate = async (cssExtension) => {
2759
- const { prompt } = await import("prompts");
2760
- return (await prompt({
2761
- name: "filesToGenerate",
2762
- type: "multiselect",
2763
- message: "Which additional files do you want to generate?",
2764
- choices: [
2765
- {
2766
- value: cssExtension,
2767
- title: `Stylesheet (.${cssExtension})`,
2768
- selected: true
2769
- },
2770
- {
2771
- value: "spec.tsx",
2772
- title: "Spec Test (.spec.tsx)",
2773
- selected: true
2774
- },
2775
- {
2776
- value: "e2e.ts",
2777
- title: "E2E Test (.e2e.ts)",
2778
- selected: true
2779
- }
2780
- ]
2781
- })).filesToGenerate;
2782
- };
2783
- const chooseSassExtension = async () => {
2784
- const { prompt } = await import("prompts");
2785
- return (await prompt({
2786
- name: "sassFormat",
2787
- type: "select",
2788
- message: "Which Sass format would you like to use? (More info: https://sass-lang.com/documentation/syntax/#the-indented-syntax)",
2789
- choices: [{
2790
- value: "sass",
2791
- title: `*.sass Format`,
2792
- selected: true
2793
- }, {
2794
- value: "scss",
2795
- title: "*.scss Format"
2796
- }]
2797
- })).sassFormat;
2798
- };
2799
- /**
2800
- * Get a filepath for a file we want to generate!
2801
- *
2802
- * The filepath for a given file depends on the path, the user-supplied
2803
- * component name, the extension, and whether we're inside of a test directory.
2804
- *
2805
- * @param filePath path to where we're going to generate the component
2806
- * @param componentName the user-supplied name for the generated component
2807
- * @param extension the file extension
2808
- * @returns the full filepath to the component (with a possible `test` directory
2809
- * added)
2810
- */
2811
- const getFilepathForFile = (filePath, componentName, extension) => isTest(extension) ? normalizePath(join(filePath, "test", `${componentName}.${extension}`)) : normalizePath(join(filePath, `${componentName}.${extension}`));
2812
- /**
2813
- * Get the boilerplate for a file and write it to disk
2814
- *
2815
- * @param config the current config, needed for file operations
2816
- * @param componentName the component name (user-supplied)
2817
- * @param withCss are we generating CSS?
2818
- * @param file the file we want to write
2819
- * @param styleExtension extension used for styles
2820
- * @returns a `Promise<string>` which holds the full filepath we've written to,
2821
- * used to print out a little summary of our activity to the user.
2822
- */
2823
- const getBoilerplateAndWriteFile = async (config, componentName, withCss, file, styleExtension) => {
2824
- const boilerplate = getBoilerplateByExtension(componentName, file.extension, withCss, styleExtension);
2825
- await config.sys.writeFile(normalizePath(file.path), boilerplate);
2826
- return file.path;
2827
- };
2828
- /**
2829
- * Check to see if any of the files we plan to write already exist and would
2830
- * therefore be overwritten if we proceed, because we'd like to not overwrite
2831
- * people's code!
2832
- *
2833
- * This function will check all the filepaths and if it finds any files log an
2834
- * error and exit with an error code. If it doesn't find anything it will just
2835
- * peacefully return `Promise<void>`.
2836
- *
2837
- * @param files the files we want to check
2838
- * @param config the Config object, used here to get access to `sys.readFile`
2839
- */
2840
- const checkForOverwrite = async (files, config) => {
2841
- const alreadyPresent = [];
2842
- await Promise.all(files.map(async ({ path }) => {
2843
- if (await config.sys.readFile(path) !== void 0) alreadyPresent.push(path);
2844
- }));
2845
- if (alreadyPresent.length > 0) {
2846
- config.logger.error("Generating code would overwrite the following files:", ...alreadyPresent.map((path) => " " + normalizePath(path)));
2847
- await config.sys.exit(1);
3339
+ const styleOptions = [
3340
+ {
3341
+ value: "css",
3342
+ label: "CSS (.css)"
3343
+ },
3344
+ ...[...new Set(generateContribs.flatMap((c) => c.styleExtensions ?? []))].map((ext) => ({
3345
+ value: ext,
3346
+ label: `${ext.toUpperCase()} (.${ext})`
3347
+ })),
3348
+ {
3349
+ value: "",
3350
+ label: "None"
3351
+ }
3352
+ ];
3353
+ const stylePick = await p.select({
3354
+ message: "Stylesheet format:",
3355
+ options: styleOptions
3356
+ });
3357
+ cancelIfAborted(stylePick);
3358
+ const styleExtension = stylePick || void 0;
3359
+ const generateCtx = {
3360
+ tagName: componentName,
3361
+ config: toProjectConfig(config),
3362
+ prompts: p,
3363
+ nypm
3364
+ };
3365
+ const allFileTemplates = [];
3366
+ for (const contrib of generateContribs) allFileTemplates.push(...await resolveFileTemplates(contrib, generateCtx));
3367
+ let pickedExtensions = [];
3368
+ if (allFileTemplates.length > 0) {
3369
+ const filePick = await p.multiselect({
3370
+ message: "Additional files:",
3371
+ options: allFileTemplates.map((ft) => ({
3372
+ value: ft.extension,
3373
+ label: ft.label
3374
+ })),
3375
+ initialValues: allFileTemplates.filter((ft) => ft.selectedByDefault !== false).map((ft) => ft.extension),
3376
+ required: false
3377
+ });
3378
+ cancelIfAborted(filePick);
3379
+ pickedExtensions = filePick;
2848
3380
  }
2849
- };
2850
- /**
2851
- * Check if an extension is for a test
2852
- *
2853
- * @param extension the extension we want to check
2854
- * @returns a boolean indicating whether or not its a test
2855
- */
2856
- const isTest = (extension) => {
2857
- return extension === "e2e.ts" || extension === "spec.tsx";
2858
- };
2859
- /**
2860
- * Get the boilerplate for a file by its extension.
2861
- *
2862
- * @param tagName the name of the component we're generating
2863
- * @param extension the file extension we want boilerplate for (.css, tsx, etc)
2864
- * @param withCss a boolean indicating whether we're generating a CSS file
2865
- * @param styleExtension extension used for styles
2866
- * @returns a string container the file boilerplate for the supplied extension
2867
- */
2868
- const getBoilerplateByExtension = (tagName, extension, withCss, styleExtension) => {
2869
- switch (extension) {
2870
- case "tsx": return getComponentBoilerplate(tagName, withCss, styleExtension);
2871
- case "css":
2872
- case "less":
2873
- case "sass":
2874
- case "scss": return getStyleUrlBoilerplate(styleExtension);
2875
- case "spec.tsx": return getSpecTestBoilerplate(tagName);
2876
- case "e2e.ts": return getE2eTestBoilerplate(tagName);
2877
- default: throw new Error(`Unkown extension "${extension}".`);
3381
+ const outDir = join(srcDir, "components", dir, componentName);
3382
+ const className = toPascalCase(componentName);
3383
+ const filesToWrite = [];
3384
+ filesToWrite.push({
3385
+ absPath: normalizePath(join(outDir, `${componentName}.tsx`)),
3386
+ content: getComponentBoilerplate(componentName, styleExtension)
3387
+ });
3388
+ if (styleExtension) filesToWrite.push({
3389
+ absPath: normalizePath(join(outDir, `${componentName}.${styleExtension}`)),
3390
+ content: getStyleBoilerplate(styleExtension)
3391
+ });
3392
+ for (const ext of pickedExtensions) {
3393
+ const tmpl = allFileTemplates.find((ft) => ft.extension === ext);
3394
+ const absPath = normalizePath(join(outDir, tmpl.subdirectory ?? "", `${componentName}.${ext}`));
3395
+ filesToWrite.push({
3396
+ absPath,
3397
+ content: tmpl.template(componentName, className)
3398
+ });
2878
3399
  }
3400
+ const wouldOverwrite = (await Promise.all(filesToWrite.map(async ({ absPath }) => await config.sys.readFile(absPath) !== void 0 ? absPath : null))).filter((f) => f !== null);
3401
+ if (wouldOverwrite.length > 0) {
3402
+ config.logger.error("Generating code would overwrite the following files:", ...wouldOverwrite.map((path) => " " + normalizePath(path)));
3403
+ await config.sys.exit(1);
3404
+ return;
3405
+ }
3406
+ const dirs = [...new Set(filesToWrite.map(({ absPath }) => normalizePath(join(absPath, ".."))))];
3407
+ await Promise.all(dirs.map((d) => config.sys.createDir(d, { recursive: true })));
3408
+ await Promise.all(filesToWrite.map(({ absPath, content }) => config.sys.writeFile(absPath, content)));
3409
+ p.note(filesToWrite.map(({ absPath }) => relative(config.rootDir, absPath)).join("\n"), "Generated");
3410
+ p.outro(`stencil generate ${input}`);
2879
3411
  };
2880
- /**
2881
- * Get the boilerplate for a file containing the definition of a component
2882
- * @param tagName the name of the tag to give the component
2883
- * @param hasStyle designates if the component has an external stylesheet or not
2884
- * @param styleExtension extension used for styles
2885
- * @returns the contents of a file that defines a component
2886
- */
2887
- const getComponentBoilerplate = (tagName, hasStyle, styleExtension) => {
2888
- const decorator = [`{`];
2889
- decorator.push(` tag: '${tagName}',`);
2890
- if (hasStyle) decorator.push(` styleUrl: '${tagName}.${styleExtension}',`);
2891
- decorator.push(` shadow: true,`);
2892
- decorator.push(`}`);
2893
- return `import { Component, Host, h } from '@stencil/core';
2894
-
2895
- @Component(${decorator.join("\n")})
2896
- export class ${toPascalCase(tagName)} {
2897
- render() {
2898
- return (
2899
- <Host>
2900
- <slot></slot>
2901
- </Host>
2902
- );
2903
- }
2904
- }
2905
- `;
2906
- };
2907
- /**
2908
- * Get the boilerplate for style for a generated component
2909
- * @param ext extension used for styles
2910
- * @returns a boilerplate CSS block
2911
- */
2912
- const getStyleUrlBoilerplate = (ext) => ext === "sass" ? `:host
2913
- display: block
2914
- ` : `:host {
2915
- display: block;
2916
- }
2917
- `;
2918
- /**
2919
- * Get the boilerplate for a file containing a spec (unit) test for a component
2920
- * @param tagName the name of the tag associated with the component under test
2921
- * @returns the contents of a file that unit tests a component
2922
- */
2923
- const getSpecTestBoilerplate = (tagName) => `import { newSpecPage } from '@stencil/core/testing';
2924
- import { ${toPascalCase(tagName)} } from '../${tagName}';
2925
-
2926
- describe('${tagName}', () => {
2927
- it('renders', async () => {
2928
- const page = await newSpecPage({
2929
- components: [${toPascalCase(tagName)}],
2930
- html: \`<${tagName}></${tagName}>\`,
2931
- });
2932
- expect(page.root).toEqualHtml(\`
2933
- <${tagName}>
2934
- <mock:shadow-root>
2935
- <slot></slot>
2936
- </mock:shadow-root>
2937
- </${tagName}>
2938
- \`);
2939
- });
2940
- });
2941
- `;
2942
- /**
2943
- * Get the boilerplate for a file containing an end-to-end (E2E) test for a component
2944
- * @param tagName the name of the tag associated with the component under test
2945
- * @returns the contents of a file that E2E tests a component
2946
- */
2947
- const getE2eTestBoilerplate = (tagName) => `import { newE2EPage } from '@stencil/core/testing';
2948
-
2949
- describe('${tagName}', () => {
2950
- it('renders', async () => {
2951
- const page = await newE2EPage();
2952
- await page.setContent('<${tagName}></${tagName}>');
2953
-
2954
- const element = await page.find('${tagName}');
2955
- expect(element).toHaveClass('hydrated');
2956
- });
2957
- });
2958
- `;
2959
- /**
2960
- * Convert a dash case string to pascal case.
2961
- * @param str the string to convert
2962
- * @returns the converted input as pascal case
2963
- */
2964
- const toPascalCase = (str) => str.split("-").reduce((res, part) => res + part[0].toUpperCase() + part.slice(1), "");
2965
3412
  //#endregion
2966
3413
  //#region src/task-telemetry.ts
2967
3414
  /**
@@ -3075,6 +3522,276 @@ const taskInfo = (coreCompiler, sys, logger) => {
3075
3522
  console.log(``);
3076
3523
  };
3077
3524
  //#endregion
3525
+ //#region src/wizard/init/apply.ts
3526
+ /**
3527
+ * Copy component-starter template into rootDir, interpolating project name and namespace.
3528
+ *
3529
+ * @param rootDir - Destination directory (typically `process.cwd()`).
3530
+ * @param projectName - Value to substitute for `{{PROJECT_NAME}}` placeholders.
3531
+ * @param namespace - Value to substitute for `{{NAMESPACE}}` placeholders.
3532
+ */
3533
+ async function copyTemplate(rootDir, projectName, namespace) {
3534
+ const templateDir = getTemplatePath("component-starter");
3535
+ const entries = await readdir(templateDir, {
3536
+ recursive: true,
3537
+ withFileTypes: true
3538
+ });
3539
+ for (const entry of entries) {
3540
+ if (!entry.isFile()) continue;
3541
+ const srcPath = join(entry.parentPath, entry.name);
3542
+ const relPath = relative(templateDir, srcPath);
3543
+ const destPath = join(rootDir, relPath);
3544
+ await mkdir(dirname(destPath), { recursive: true });
3545
+ const content = (await readFile(srcPath, "utf8")).replace(/\{\{PROJECT_NAME\}\}/g, projectName).replace(/\{\{NAMESPACE\}\}/g, namespace);
3546
+ if (relPath === "package.json") await mergePackageJson(destPath, content);
3547
+ else if (relPath === "tsconfig.json") await mergeTsConfig(destPath, content);
3548
+ else if (relPath === ".gitignore") await mergeGitignore(destPath, content);
3549
+ else await writeIfAbsent(destPath, content);
3550
+ }
3551
+ }
3552
+ async function writeIfAbsent(destPath, content) {
3553
+ try {
3554
+ await writeFile(destPath, content, {
3555
+ encoding: "utf8",
3556
+ flag: "wx"
3557
+ });
3558
+ } catch (e) {
3559
+ if (e.code !== "EEXIST") throw e;
3560
+ }
3561
+ }
3562
+ async function mergePackageJson(destPath, templateContent) {
3563
+ const template = JSON.parse(templateContent);
3564
+ let existing;
3565
+ try {
3566
+ existing = JSON.parse(await readFile(destPath, "utf8"));
3567
+ } catch {
3568
+ await writeFile(destPath, templateContent, "utf8");
3569
+ return;
3570
+ }
3571
+ const dependencies = mergeStringRecord(template.dependencies, existing.dependencies);
3572
+ const devDependencies = mergeStringRecord(template.devDependencies, existing.devDependencies);
3573
+ for (const pkg of Object.keys(devDependencies)) if (pkg in dependencies) delete devDependencies[pkg];
3574
+ const merged = {
3575
+ ...template,
3576
+ ...existing,
3577
+ scripts: mergeStringRecord(template.scripts, existing.scripts),
3578
+ dependencies,
3579
+ devDependencies
3580
+ };
3581
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
3582
+ }
3583
+ async function mergeTsConfig(destPath, templateContent) {
3584
+ const template = JSON.parse(templateContent);
3585
+ let existing;
3586
+ try {
3587
+ existing = JSON.parse(await readFile(destPath, "utf8"));
3588
+ } catch {
3589
+ await writeFile(destPath, templateContent, "utf8");
3590
+ return;
3591
+ }
3592
+ const merged = {
3593
+ ...template,
3594
+ ...existing,
3595
+ compilerOptions: mergeStringRecord(template.compilerOptions, existing.compilerOptions)
3596
+ };
3597
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
3598
+ }
3599
+ async function mergeGitignore(destPath, templateContent) {
3600
+ let existing;
3601
+ try {
3602
+ existing = await readFile(destPath, "utf8");
3603
+ } catch {
3604
+ await writeFile(destPath, templateContent, "utf8");
3605
+ return;
3606
+ }
3607
+ const existingEntries = new Set(existing.split("\n").map((l) => l.trim()).filter(Boolean));
3608
+ const missing = templateContent.split("\n").filter((line) => line.trim() && !existingEntries.has(line.trim()));
3609
+ if (missing.length === 0) return;
3610
+ const separator = existing.endsWith("\n") ? "" : "\n";
3611
+ await writeFile(destPath, existing + separator + missing.join("\n") + "\n", "utf8");
3612
+ }
3613
+ function mergeStringRecord(base, override) {
3614
+ const toObj = (v) => v !== null && typeof v === "object" ? v : {};
3615
+ return {
3616
+ ...toObj(base),
3617
+ ...toObj(override)
3618
+ };
3619
+ }
3620
+ async function writeStencilConfig(rootDir, content) {
3621
+ await writeFile(join(rootDir, "stencil.config.ts"), content, "utf8");
3622
+ }
3623
+ async function writeGlobalStyle(rootDir) {
3624
+ const path = join(rootDir, "src", "global.css");
3625
+ await mkdir(dirname(path), { recursive: true });
3626
+ await writeIfAbsent(path, `@import "stencil-globals";\n@import "stencil-hydrate";\n`);
3627
+ }
3628
+ async function writeGlobalScript(rootDir) {
3629
+ const path = join(rootDir, "src", "global.ts");
3630
+ await mkdir(dirname(path), { recursive: true });
3631
+ await writeIfAbsent(path, `export default function (): void {}\n`);
3632
+ }
3633
+ /**
3634
+ * Write output-driven distributable fields (type, module, types) into package.json.
3635
+ * These fields depend on which outputs the user selected, so they cannot be static in the template.
3636
+ * Skips if fields is empty (e.g. www-only project).
3637
+ *
3638
+ * @param rootDir - Absolute path to the project root.
3639
+ * @param fields - Fields to write, from generatePackageJsonFields().
3640
+ */
3641
+ async function applyPackageJsonFields(rootDir, fields) {
3642
+ if (Object.keys(fields).length === 0) return;
3643
+ const pkgPath = join(rootDir, "package.json");
3644
+ const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
3645
+ Object.assign(pkg, fields);
3646
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
3647
+ }
3648
+ //#endregion
3649
+ //#region src/task-init.ts
3650
+ function outputKeysToTargets(keys) {
3651
+ const map = {
3652
+ loader: "loader-bundle",
3653
+ standalone: "standalone",
3654
+ ssr: "ssr",
3655
+ "ssr-wasm": "ssr-wasm",
3656
+ www: "www"
3657
+ };
3658
+ return keys.length > 0 ? keys.map((k) => ({ type: map[k] })) : [{ type: "loader-bundle" }];
3659
+ }
3660
+ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
3661
+ const cwd = process.cwd();
3662
+ const isExistingProject = await isExistingStencilProject(cwd);
3663
+ printSplash();
3664
+ p.intro(`stencil init`);
3665
+ if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: loading wizard from ${process.env.STENCIL_WIZARD_DEV}`);
3666
+ if (isCI) {
3667
+ p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil init`.");
3668
+ process.exit(1);
3669
+ }
3670
+ if (isExistingProject) {
3671
+ await addCapabilities(cwd, strictConfig);
3672
+ return;
3673
+ }
3674
+ const projectName = await promptProjectName();
3675
+ const namespace = toNamespace(projectName);
3676
+ const outputs = await promptOutputs();
3677
+ const features = await promptFeatures();
3678
+ const docs = await promptDocs();
3679
+ const selectedIntegrations = await promptIntegrations();
3680
+ const configSource = generateStencilConfig({
3681
+ namespace,
3682
+ outputs,
3683
+ signals: features.signals,
3684
+ docs
3685
+ });
3686
+ const summaryLines = [
3687
+ `Template: component-starter`,
3688
+ `Name: ${projectName}`,
3689
+ `Namespace: ${namespace}`,
3690
+ `Config: ${configSource ? "stencil.config.ts" : "zero-config (loader default)"}`
3691
+ ];
3692
+ if (selectedIntegrations.length > 0) summaryLines.push(`Add: ${selectedIntegrations.map((i) => i.displayName).join(", ")}`);
3693
+ p.note(summaryLines.join("\n"), "Summary");
3694
+ const confirmed = await p.confirm({ message: "Scaffold project in current directory?" });
3695
+ cancelIfAborted(confirmed);
3696
+ if (!confirmed) {
3697
+ p.cancel("Cancelled.");
3698
+ process.exit(0);
3699
+ }
3700
+ const s1 = p.spinner();
3701
+ s1.start("Scaffolding project files");
3702
+ await copyTemplate(cwd, projectName, namespace);
3703
+ await applyPackageJsonFields(cwd, generatePackageJsonFields(outputs));
3704
+ if (configSource) await writeStencilConfig(cwd, configSource);
3705
+ if (features.globalStyle) await writeGlobalStyle(cwd);
3706
+ if (features.globalScript) await writeGlobalScript(cwd);
3707
+ s1.stop("Project files created");
3708
+ const s2 = p.spinner();
3709
+ s2.start("Installing dependencies");
3710
+ await installDependencies({
3711
+ cwd,
3712
+ silent: true
3713
+ });
3714
+ s2.stop("Dependencies installed");
3715
+ if (selectedIntegrations.length > 0) {
3716
+ const s3 = p.spinner();
3717
+ const pkgs = selectedIntegrations.map((i) => i.package);
3718
+ s3.start(`Installing ${pkgs.join(", ")}`);
3719
+ await addDevDependency(pkgs, {
3720
+ cwd,
3721
+ silent: true
3722
+ });
3723
+ s3.stop("Integrations installed");
3724
+ }
3725
+ if (selectedIntegrations.length > 0) {
3726
+ const discovered = await discoverPlugins(cwd);
3727
+ const selectedPkgs = new Set(selectedIntegrations.map((i) => i.package));
3728
+ const resolvedValidated = loadProjectConfig ? await loadProjectConfig(configSource ? join(cwd, "stencil.config.ts") : void 0) : coreCompiler ? coreCompiler.validateConfig({
3729
+ rootDir: cwd,
3730
+ outputTargets: outputKeysToTargets(outputs),
3731
+ ...configSource ? { namespace } : {}
3732
+ }, {}).config : null;
3733
+ const context = {
3734
+ isNewProject: true,
3735
+ prompts: p,
3736
+ nypm,
3737
+ config: resolvedValidated ? toProjectConfig(resolvedValidated) : defaultProjectConfig(cwd, { namespace })
3738
+ };
3739
+ for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run(context);
3740
+ }
3741
+ p.outro("Your project is ready! Run: pnpm run dev");
3742
+ }
3743
+ async function addCapabilities(cwd, strictConfig) {
3744
+ const raw = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
3745
+ const installed = new Set([...Object.keys(raw.dependencies ?? {}), ...Object.keys(raw.devDependencies ?? {})]);
3746
+ const discovered = await discoverPlugins(cwd);
3747
+ const configurable = discovered.filter((d) => d.plugin.init);
3748
+ const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
3749
+ if (installable.length === 0 && configurable.length === 0) {
3750
+ p.log.info("All known integrations are already installed and configured.");
3751
+ p.outro("Nothing to do.");
3752
+ return;
3753
+ }
3754
+ const { toInstall, toConfigure } = await promptAddCapabilities(installable, configurable);
3755
+ if (toInstall.length === 0 && toConfigure.length === 0) {
3756
+ p.outro("No changes made.");
3757
+ return;
3758
+ }
3759
+ const summaryLines = [];
3760
+ for (const i of toInstall) summaryLines.push(`Install: ${i.displayName}`);
3761
+ for (const d of toConfigure) summaryLines.push(`Configure: ${d.plugin.init.displayName}`);
3762
+ p.note(summaryLines.join("\n"), "Summary");
3763
+ const confirmed = await p.confirm({ message: "Apply changes?" });
3764
+ cancelIfAborted(confirmed);
3765
+ if (!confirmed) {
3766
+ p.cancel("Cancelled.");
3767
+ process.exit(0);
3768
+ }
3769
+ if (toInstall.length > 0) {
3770
+ const s = p.spinner();
3771
+ const pkgs = toInstall.map((i) => i.package);
3772
+ s.start(`Installing ${pkgs.join(", ")}`);
3773
+ await addDevDependency(pkgs, {
3774
+ cwd,
3775
+ silent: true
3776
+ });
3777
+ s.stop("Dependencies installed");
3778
+ }
3779
+ const allDiscovered = toInstall.length > 0 ? await discoverPlugins(cwd) : discovered;
3780
+ const newlyInstalledPkgs = new Set(toInstall.map((i) => i.package));
3781
+ const toRun = [...allDiscovered.filter((d) => newlyInstalledPkgs.has(d.packageName)), ...toConfigure].filter((d) => d.plugin.init?.run);
3782
+ const context = {
3783
+ isNewProject: false,
3784
+ prompts: p,
3785
+ nypm,
3786
+ config: strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd)
3787
+ };
3788
+ for (const d of toRun) await d.plugin.init.run(context);
3789
+ p.outro("Done! Run pnpm run dev to continue.");
3790
+ }
3791
+ function toNamespace(name) {
3792
+ return toPascalCase(name.replace(/^@[^/]+\//, "").replace(/[/_]/g, "-"));
3793
+ }
3794
+ //#endregion
3078
3795
  //#region src/task-serve.ts
3079
3796
  const taskServe = async (config, flags) => {
3080
3797
  config.suppressLogs = true;
@@ -3130,6 +3847,39 @@ const run = async (init) => {
3130
3847
  }), logger, sys);
3131
3848
  return;
3132
3849
  }
3850
+ if (task === "add" || task === "init") {
3851
+ const coreCompiler = await loadCoreCompiler(sys);
3852
+ const rootDir = sys.getCurrentDirectory();
3853
+ const findConfigResults = await findConfig({
3854
+ sys,
3855
+ configPath: flags.config
3856
+ });
3857
+ let strictConfig;
3858
+ if (!findConfigResults.isErr) {
3859
+ const foundConfig = result.unwrap(findConfigResults);
3860
+ const loaded = await coreCompiler.loadConfig({
3861
+ config: { rootDir },
3862
+ configPath: foundConfig.configPath ?? void 0,
3863
+ logger,
3864
+ sys
3865
+ });
3866
+ strictConfig = coreCompiler.validateConfig(loaded.config, {}).config;
3867
+ } else strictConfig = coreCompiler.validateConfig({ rootDir }, {}).config;
3868
+ if (task === "add") await taskAdd(flags.unknownArgs, strictConfig);
3869
+ else {
3870
+ const loadProjectConfig = async (configPath) => {
3871
+ const loaded = await coreCompiler.loadConfig({
3872
+ config: { rootDir },
3873
+ configPath,
3874
+ logger,
3875
+ sys
3876
+ });
3877
+ return coreCompiler.validateConfig(loaded.config, {}).config;
3878
+ };
3879
+ await taskInit(coreCompiler, strictConfig, loadProjectConfig);
3880
+ }
3881
+ return;
3882
+ }
3133
3883
  startupLog(logger, task);
3134
3884
  const findConfigResults = await findConfig({
3135
3885
  sys,
@@ -3150,7 +3900,7 @@ const run = async (init) => {
3150
3900
  const configWithFlags = mergeFlags({}, flags);
3151
3901
  const validated = await coreCompiler.loadConfig({
3152
3902
  config: configWithFlags,
3153
- configPath: foundConfig.configPath,
3903
+ configPath: foundConfig.configPath ?? void 0,
3154
3904
  logger,
3155
3905
  sys
3156
3906
  });
@@ -3187,6 +3937,9 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
3187
3937
  if (!configWithFlags.sys) configWithFlags.sys = sys;
3188
3938
  const strictConfig = coreCompiler.validateConfig(configWithFlags, {}).config;
3189
3939
  switch (task) {
3940
+ case "add":
3941
+ await taskAdd(resolvedFlags.unknownArgs ?? [], strictConfig);
3942
+ break;
3190
3943
  case "build":
3191
3944
  await taskBuild(coreCompiler, strictConfig, resolvedFlags);
3192
3945
  break;
@@ -3200,6 +3953,9 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
3200
3953
  case "help":
3201
3954
  await taskHelp(resolvedFlags, strictConfig.logger, sys);
3202
3955
  break;
3956
+ case "init":
3957
+ await taskInit(coreCompiler, strictConfig);
3958
+ break;
3203
3959
  case "migrate":
3204
3960
  await taskMigrate(coreCompiler, strictConfig, resolvedFlags);
3205
3961
  break;