@stencil/cli 5.0.0-alpha.7 → 5.0.0-alpha.9

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,16 +1,18 @@
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, relative } from "path";
3
+ import { basename, dirname, join, parse, relative, resolve } from "node:path";
4
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
4
5
  import * as p from "@clack/prompts";
5
6
  import { cancel, isCancel, select } from "@clack/prompts";
6
- import ts from "typescript";
7
- import { basename, dirname as dirname$1, join as join$1, parse, relative as relative$1, resolve } from "node:path";
8
- import { getComponentBoilerplate, getStyleBoilerplate, getTemplatePath, toPascalCase } from "@stencil/templates";
9
- import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
7
+ import * as nypm from "nypm";
8
+ import { addDevDependency, detectPackageManager, installDependencies } from "nypm";
9
+ import { isCI } from "std-env";
10
10
  import { pathToFileURL } from "node:url";
11
11
  import { existsSync } from "node:fs";
12
- import { installDependencies } from "nypm";
13
- import { isCI } from "std-env";
12
+ import { homedir } from "node:os";
13
+ import { dirname as dirname$1, isAbsolute, join as join$1, relative as relative$1 } from "path";
14
+ import ts from "typescript";
15
+ import { generatePackageJsonFields, generateStencilConfig, getComponentBoilerplate, getStyleBoilerplate, getTemplatePath, toPascalCase } from "@stencil/templates";
14
16
  import { start } from "@stencil/dev-server";
15
17
  //#region src/config-flags.ts
16
18
  /**
@@ -600,195 +602,744 @@ const mergeFlags = (config, flags) => {
600
602
  return merged;
601
603
  };
602
604
  //#endregion
603
- //#region src/check-version.ts
604
- /**
605
- * Retrieve a reference to the active `CompilerSystem`'s `checkVersion` function
606
- * @param config the Stencil configuration associated with the currently compiled project
607
- * @param currentVersion the Stencil compiler's version string
608
- * @param flags the CLI flags (owned by CLI, not part of core config)
609
- * @returns a reference to `checkVersion`, or `null` if one does not exist on the current `CompilerSystem`
610
- */
611
- const startCheckVersion = async (config, currentVersion, flags) => {
612
- if (config.devMode && !flags.ci && !currentVersion.includes("-dev.") && isFunction(config.sys.checkVersion)) return config.sys.checkVersion(config.logger, currentVersion);
613
- return null;
614
- };
615
- /**
616
- * Print the results of running the provided `versionChecker`.
617
- *
618
- * Does not print if no `versionChecker` is provided.
619
- *
620
- * @param versionChecker the function to invoke.
621
- */
622
- const printCheckVersionResults = async (versionChecker) => {
623
- if (versionChecker) {
624
- const checkVersionResults = await versionChecker;
625
- if (isFunction(checkVersionResults)) checkVersionResults();
605
+ //#region src/wizard/discover.ts
606
+ function toStringRecord(val) {
607
+ return val !== null && typeof val === "object" ? val : {};
608
+ }
609
+ async function readJson$1(filePath) {
610
+ try {
611
+ return JSON.parse(await readFile(filePath, "utf8"));
612
+ } catch {
613
+ return null;
626
614
  }
627
- };
628
- //#endregion
629
- //#region src/migrations/rules/build-dist-docs.ts
615
+ }
616
+ async function loadOne(rootDir, packageName, loader) {
617
+ const wizardEntry = ((await readJson$1(join(rootDir, "node_modules", packageName, "package.json")))?.stencil)?.wizard;
618
+ if (!wizardEntry) return null;
619
+ const wizardPath = join(rootDir, "node_modules", packageName, wizardEntry);
620
+ let mod;
621
+ try {
622
+ mod = await loader(pathToFileURL(wizardPath).href);
623
+ } catch {
624
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but the module failed to load: ${wizardPath}`);
625
+ return null;
626
+ }
627
+ const plugin = mod.wizard;
628
+ if (!plugin || typeof plugin !== "object") {
629
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but does not export a 'wizard' object`);
630
+ return null;
631
+ }
632
+ return {
633
+ packageName,
634
+ plugin
635
+ };
636
+ }
630
637
  /**
631
- * Migration rule for buildDist and buildDocs removal.
638
+ * Scans the project's declared dependencies for packages that expose a
639
+ * `stencil.wizard` entry in their `package.json` and dynamically imports
640
+ * each matching module.
632
641
  *
633
- * In Stencil v5, these global config options are replaced with per-output-target
634
- * `skipInDev` property. This migration:
635
- * - Detects `buildDist` or `buildDocs` in stencil.config.ts
636
- * - Removes the property
637
- * - For `buildDist: true` or `buildDocs: true`, adds `skipInDev: false` to relevant output targets
642
+ * @param rootDir - Absolute path to the project root (where `package.json` lives).
643
+ * @param loader - Module loader; injectable for testing. Defaults to `import()`.
644
+ * @returns Array of successfully loaded plugins, in dependency declaration order.
638
645
  */
639
- const buildDistDocsRule = {
640
- id: "build-dist-docs",
641
- name: "buildDist/buildDocs Removal",
642
- description: "Remove deprecated buildDist and buildDocs config options",
643
- fromVersion: "4.x",
644
- toVersion: "5.x",
645
- detect(sourceFile) {
646
- const matches = [];
647
- const visit = (node) => {
648
- if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
649
- const propName = node.name.text;
650
- if (propName === "buildDist" || propName === "buildDocs") {
651
- const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
652
- const isTrue = node.initializer.kind === ts.SyntaxKind.TrueKeyword;
653
- matches.push({
654
- node,
655
- message: `Deprecated '${propName}' found${isTrue ? " (set to true)" : ""} - will be removed and skipInDev added to output targets`,
656
- line: line + 1,
657
- column: character + 1
658
- });
659
- }
660
- }
661
- ts.forEachChild(node, visit);
662
- };
663
- visit(sourceFile);
664
- return matches;
665
- },
666
- transform(sourceFile, matches) {
667
- if (matches.length === 0) return sourceFile.getFullText();
668
- let text = sourceFile.getFullText();
669
- const targetTypesNeedingSkipInDev = [];
670
- for (const match of matches) {
671
- const prop = match.node;
672
- const propName = prop.name.text;
673
- if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
674
- if (propName === "buildDist") targetTypesNeedingSkipInDev.push("dist", "dist-custom-elements", "dist-hydrate-script", "loader-bundle", "standalone", "ssr");
675
- else if (propName === "buildDocs") targetTypesNeedingSkipInDev.push("docs-readme", "docs-json", "docs-custom", "docs-vscode", "docs-custom-elements-manifest");
676
- }
677
- }
678
- const outputTargetsToModify = [];
679
- const findOutputTargets = (node) => {
680
- if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
681
- for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
682
- const typeProp = element.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type");
683
- if (typeProp && ts.isStringLiteral(typeProp.initializer)) {
684
- const targetType = typeProp.initializer.text;
685
- if (targetTypesNeedingSkipInDev.includes(targetType)) {
686
- if (!element.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "skipInDev")) outputTargetsToModify.push(element);
687
- }
688
- }
689
- }
690
- }
691
- ts.forEachChild(node, findOutputTargets);
692
- };
693
- findOutputTargets(sourceFile);
694
- const allModifications = [];
695
- for (const match of matches) {
696
- const prop = match.node;
697
- const start = prop.getStart();
698
- let end = prop.getEnd();
699
- const afterProp = text.slice(end).match(/^\s*,/);
700
- if (afterProp) end = end + afterProp[0].length;
701
- allModifications.push({
702
- type: "remove",
703
- start,
704
- end,
705
- node: prop
706
- });
707
- }
708
- for (const target of outputTargetsToModify) {
709
- const lastProp = target.properties[target.properties.length - 1];
710
- if (lastProp) allModifications.push({
711
- type: "addSkipInDev",
712
- start: lastProp.getEnd(),
713
- end: lastProp.getEnd(),
714
- node: target
715
- });
716
- }
717
- allModifications.sort((a, b) => b.start - a.start);
718
- for (const mod of allModifications) if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
719
- else if (mod.type === "addSkipInDev") {
720
- const firstProp = mod.node.properties[0];
721
- let indent = " ";
722
- if (firstProp) {
723
- const propStart = firstProp.getStart();
724
- const lineStart = text.lastIndexOf("\n", propStart) + 1;
725
- const leadingWhitespace = text.slice(lineStart, propStart);
726
- if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
646
+ async function discoverPlugins(rootDir, loader = (url) => import(url)) {
647
+ const pkg = await readJson$1(join(rootDir, "package.json"));
648
+ if (!pkg) return [];
649
+ const depNames = [...new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
650
+ const plugins = (await Promise.allSettled(depNames.map((name) => loadOne(rootDir, name, loader)))).filter((r) => r.status === "fulfilled" && r.value !== null).map((r) => r.value);
651
+ const devEnv = process.env.STENCIL_WIZARD_DEV;
652
+ if (devEnv) {
653
+ const devPaths = devEnv.split(",").map((s) => s.trim()).filter(Boolean);
654
+ for (const devPath of devPaths) {
655
+ const devPlugin = await loadDevPlugin(resolve(rootDir, devPath), loader);
656
+ if (devPlugin) {
657
+ const idx = plugins.findIndex((p) => p.packageName === devPlugin.packageName);
658
+ if (idx >= 0) plugins.splice(idx, 1, devPlugin);
659
+ else plugins.unshift(devPlugin);
727
660
  }
728
- const afterLastProp = text.slice(mod.start).match(/^(\s*,)?/);
729
- const skipLength = afterLastProp && afterLastProp[1] ? afterLastProp[0].length : 0;
730
- text = text.slice(0, mod.start) + `,\n${indent}skipInDev: false,` + text.slice(mod.start + skipLength);
731
661
  }
732
- text = text.replace(/,\s*\n\s*\n/g, ",\n");
733
- text = text.replace(/{\s*\n\s*\n/g, "{\n");
734
- return text;
735
662
  }
736
- };
663
+ return plugins;
664
+ }
665
+ async function findDevPackageName(wizardPath) {
666
+ const dir = dirname(wizardPath);
667
+ for (const candidate of [dir, resolve(dir, "..")]) {
668
+ const pkg = await readJson$1(join(candidate, "package.json"));
669
+ if (typeof pkg?.name === "string") return pkg.name;
670
+ }
671
+ return basename(dir);
672
+ }
673
+ async function loadDevPlugin(wizardPath, loader) {
674
+ const packageName = await findDevPackageName(wizardPath);
675
+ let mod;
676
+ try {
677
+ mod = await loader(pathToFileURL(wizardPath).href);
678
+ } catch {
679
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: failed to load ${wizardPath}`);
680
+ return null;
681
+ }
682
+ const plugin = mod.wizard;
683
+ if (!plugin || typeof plugin !== "object") {
684
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: ${wizardPath} does not export a 'wizard' object`);
685
+ return null;
686
+ }
687
+ return {
688
+ packageName,
689
+ plugin
690
+ };
691
+ }
737
692
  //#endregion
738
- //#region src/migrations/rules/dev-mode.ts
693
+ //#region src/wizard/clack.ts
739
694
  /**
740
- * Migration rule for `devMode` config option removal.
695
+ * Exits cleanly if the user cancelled a prompt (Ctrl+C).
696
+ * Narrows the type from `T | symbol` to `T` for callers.
741
697
  *
742
- * In Stencil v5, `devMode` is no longer a user-settable config option in `stencil.config.ts`.
743
- * Build mode is controlled exclusively by the `--dev` CLI flag (default is production).
744
- * This migration removes `devMode` from the config object.
698
+ * @param value - Return value from a `@clack/prompts` prompt call.
745
699
  */
746
- const devModeRule = {
747
- id: "dev-mode",
748
- name: "devMode Config Removal",
749
- description: "Remove deprecated devMode config option - use --dev CLI flag instead",
750
- fromVersion: "4.x",
751
- toVersion: "5.x",
752
- detect(sourceFile) {
753
- const matches = [];
754
- const visit = (node) => {
755
- if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
756
- if (node.name.text === "devMode") {
757
- const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
758
- matches.push({
759
- node,
760
- message: `Deprecated 'devMode' config option found - build mode is now set via the --dev CLI flag (production is the default)`,
761
- line: line + 1,
762
- column: character + 1
763
- });
764
- }
765
- }
766
- ts.forEachChild(node, visit);
767
- };
768
- visit(sourceFile);
769
- return matches;
770
- },
771
- transform(sourceFile, matches) {
772
- if (matches.length === 0) return sourceFile.getFullText();
773
- let text = sourceFile.getFullText();
774
- for (const match of [...matches].reverse()) {
775
- const node = match.node;
776
- const start = node.getFullStart();
777
- const end = node.getEnd();
778
- let removeEnd = end;
779
- const trailingComma = text.slice(end).match(/^\s*,/);
780
- if (trailingComma) removeEnd = end + trailingComma[0].length;
781
- text = text.slice(0, start) + text.slice(removeEnd);
782
- }
783
- return text;
700
+ function cancelIfAborted(value) {
701
+ if (isCancel(value)) {
702
+ cancel("Cancelled.");
703
+ process.exit(0);
784
704
  }
785
- };
705
+ }
786
706
  //#endregion
787
- //#region src/migrations/rules/encapsulation-api.ts
788
- /**
789
- * Migration rule for the @Component encapsulation API change.
790
- *
791
- * Migrates:
707
+ //#region src/wizard/init/steps.ts
708
+ /** Well-known integrations the CLI can offer before any packages are installed. */
709
+ const KNOWN_INTEGRATIONS = [
710
+ {
711
+ package: "@stencil/vitest",
712
+ displayName: "Vitest",
713
+ description: "Unit / Spec / Integration / Browser testing",
714
+ group: "Testing"
715
+ },
716
+ {
717
+ package: "@stencil/playwright",
718
+ displayName: "Playwright",
719
+ description: "E2E testing",
720
+ group: "Testing"
721
+ },
722
+ {
723
+ package: "@stencil/sass",
724
+ displayName: "Sass",
725
+ description: "Sass/SCSS styles",
726
+ group: "Styling",
727
+ requiresStencilConfig: true
728
+ },
729
+ {
730
+ package: "@stencil/eslint-plugin",
731
+ displayName: "ESLint Plugin",
732
+ description: "Stencil-aware lint rules (ESLint, oxlint, Biome)",
733
+ group: "Linting"
734
+ },
735
+ {
736
+ package: "@stencil/storybook-plugin",
737
+ displayName: "Storybook",
738
+ description: "Component development & documentation",
739
+ group: "Tooling"
740
+ },
741
+ {
742
+ package: "@stencil/types-output-target",
743
+ displayName: "Types",
744
+ description: "TypeScript types for React, Vue, Solid, Svelte, Preact",
745
+ group: "Framework integrations",
746
+ requiresStencilConfig: true
747
+ },
748
+ {
749
+ package: "@stencil/react-output-target",
750
+ displayName: "React",
751
+ description: "React component wrappers",
752
+ group: "Framework integrations",
753
+ requiresStencilConfig: true
754
+ },
755
+ {
756
+ package: "@stencil/angular-output-target",
757
+ displayName: "Angular",
758
+ description: "Angular component wrappers",
759
+ group: "Framework integrations",
760
+ requiresStencilConfig: true
761
+ },
762
+ {
763
+ package: "@stencil/vue-output-target",
764
+ displayName: "Vue",
765
+ description: "Vue component wrappers",
766
+ group: "Framework integrations",
767
+ requiresStencilConfig: true
768
+ }
769
+ ];
770
+ async function promptOutputs() {
771
+ const picks = await p.multiselect({
772
+ message: "Outputs:",
773
+ options: [
774
+ {
775
+ value: "loader",
776
+ label: "Loader",
777
+ hint: "performant lazy-loader; browser & bundler ready"
778
+ },
779
+ {
780
+ value: "standalone",
781
+ label: "Standalone",
782
+ hint: "per-component modules, import only what you need"
783
+ },
784
+ {
785
+ value: "ssr",
786
+ label: "SSR",
787
+ hint: "pre-render components in any JS server environment"
788
+ },
789
+ {
790
+ value: "ssr-wasm",
791
+ label: "SSR WASM",
792
+ hint: "experimental: compile SSR to a portable WASM binary"
793
+ },
794
+ {
795
+ value: "www",
796
+ label: "WWW",
797
+ hint: "app mode with dev server and optional PWA support"
798
+ }
799
+ ],
800
+ required: false
801
+ });
802
+ cancelIfAborted(picks);
803
+ return picks;
804
+ }
805
+ async function promptFeatures() {
806
+ const picks = await p.multiselect({
807
+ message: "Features:",
808
+ options: [
809
+ {
810
+ value: "signals",
811
+ label: "Signals",
812
+ hint: "signal-backed @Prop/@State for cross-framework reactive interop"
813
+ },
814
+ {
815
+ value: "globalStyle",
816
+ label: "Global style",
817
+ hint: "Global stylesheet for font definitions, CSS variables, pre-load styles etc"
818
+ },
819
+ {
820
+ value: "globalScript",
821
+ label: "Global script",
822
+ hint: "Global script for initializing application-wide logic before components load"
823
+ }
824
+ ],
825
+ required: false
826
+ });
827
+ cancelIfAborted(picks);
828
+ const set = new Set(picks);
829
+ return {
830
+ signals: set.has("signals"),
831
+ globalStyle: set.has("globalStyle"),
832
+ globalScript: set.has("globalScript")
833
+ };
834
+ }
835
+ async function promptDocs() {
836
+ const picks = await p.multiselect({
837
+ message: "Docs:",
838
+ options: [
839
+ {
840
+ value: "cem",
841
+ label: "CEM",
842
+ hint: "custom-elements.json - preferred format for interop with tools like Storybook, Styleguidist, etc"
843
+ },
844
+ {
845
+ value: "json",
846
+ label: "JSON",
847
+ hint: "docs.json - Stencil / Ionic centric schema"
848
+ },
849
+ {
850
+ value: "vscode",
851
+ label: "VS Code",
852
+ hint: "vscode-data.json - editor autocomplete for your components"
853
+ }
854
+ ],
855
+ required: false
856
+ });
857
+ cancelIfAborted(picks);
858
+ return picks;
859
+ }
860
+ async function promptProjectName() {
861
+ const name = await p.text({
862
+ message: "Project name:",
863
+ defaultValue: "my-stencil-library",
864
+ validate: (v) => {
865
+ if (!v?.trim()) return "Project name is required";
866
+ }
867
+ });
868
+ cancelIfAborted(name);
869
+ return name;
870
+ }
871
+ function buildGroupedOptions(integrations) {
872
+ const groups = {};
873
+ for (const i of integrations) (groups[i.group] ??= []).push({
874
+ value: i.package,
875
+ label: i.displayName,
876
+ hint: i.description
877
+ });
878
+ return groups;
879
+ }
880
+ async function promptCustomPackages() {
881
+ const input = await p.text({
882
+ message: "Additional packages to install:",
883
+ placeholder: "e.g. my-plugin another-package (leave blank to skip)"
884
+ });
885
+ cancelIfAborted(input);
886
+ if (typeof input !== "string" || !input.trim()) return [];
887
+ return input.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
888
+ }
889
+ async function promptIntegrations() {
890
+ const picks = await p.groupMultiselect({
891
+ message: "Add integrations (optional):",
892
+ options: buildGroupedOptions(KNOWN_INTEGRATIONS),
893
+ required: false
894
+ });
895
+ cancelIfAborted(picks);
896
+ return KNOWN_INTEGRATIONS.filter((i) => picks.includes(i.package));
897
+ }
898
+ function hasFrameworkTargets(integrations) {
899
+ return integrations.some((i) => i.group === "Framework integrations");
900
+ }
901
+ function needsStencilConfig(integrations) {
902
+ return integrations.some((i) => i.requiresStencilConfig);
903
+ }
904
+ async function promptMonorepo() {
905
+ const answer = await p.confirm({
906
+ message: "Set up as a monorepo workspace? (recommended for publishing framework wrappers)",
907
+ initialValue: true
908
+ });
909
+ cancelIfAborted(answer);
910
+ return answer;
911
+ }
912
+ async function promptWorkspaceCoreName() {
913
+ const name = await p.text({
914
+ message: "Core package directory name:",
915
+ defaultValue: "core",
916
+ placeholder: "core"
917
+ });
918
+ cancelIfAborted(name);
919
+ return name || "core";
920
+ }
921
+ /**
922
+ * Prompt for actions on an existing project: install new integrations and/or
923
+ * run init wizards for already-installed packages with wizard contributions.
924
+ *
925
+ * @param installable - KNOWN_INTEGRATIONS not yet present in the project.
926
+ * @param configurable - Already-installed plugins that declare an `init` contribution.
927
+ * @returns Selected integrations to install and plugins to configure.
928
+ */
929
+ async function promptAddCapabilities(installable, configurable) {
930
+ const options = {};
931
+ if (installable.length > 0) options["Install new integrations"] = installable.map((i) => ({
932
+ value: `install:${i.package}`,
933
+ label: i.displayName,
934
+ hint: i.description
935
+ }));
936
+ if (configurable.length > 0) options["Configure existing integrations"] = configurable.map((d) => ({
937
+ value: `configure:${d.packageName}`,
938
+ label: d.plugin.init.displayName,
939
+ hint: d.plugin.init.description
940
+ }));
941
+ const picks = await p.groupMultiselect({
942
+ message: "What would you like to do?",
943
+ options,
944
+ required: false
945
+ });
946
+ cancelIfAborted(picks);
947
+ const pickedSet = new Set(picks);
948
+ return {
949
+ toInstall: installable.filter((i) => pickedSet.has(`install:${i.package}`)),
950
+ toConfigure: configurable.filter((d) => pickedSet.has(`configure:${d.packageName}`))
951
+ };
952
+ }
953
+ //#endregion
954
+ //#region src/wizard/project.ts
955
+ /**
956
+ * Extracts the stable, plugin-relevant fields from a fully-resolved compiler config.
957
+ * @param validated The fully-resolved compiler config.
958
+ * @returns A ProjectConfig with only the fields relevant to plugins and the wizard.
959
+ * This is a stable subset of the compiler config that won't change between versions.
960
+ */
961
+ function toProjectConfig(validated) {
962
+ return {
963
+ rootDir: validated.rootDir,
964
+ srcDir: validated.srcDir,
965
+ namespace: validated.namespace,
966
+ fsNamespace: validated.fsNamespace,
967
+ outputTargets: validated.outputTargets ?? [],
968
+ globalScript: validated.globalScript,
969
+ globalStyle: validated.globalStyle,
970
+ compat: validated.compat,
971
+ signalBacking: validated.signalBacking
972
+ };
973
+ }
974
+ /**
975
+ * Builds a minimal ProjectConfig when no validated config is available (e.g. new project, no compiler).
976
+ * @param rootDir The root directory of the project.
977
+ * @param overrides Optional fields to override the defaults.
978
+ * @returns A ProjectConfig with reasonable defaults for a new project.
979
+ * */
980
+ function defaultProjectConfig(rootDir, overrides) {
981
+ const namespace = overrides?.namespace ?? "";
982
+ return {
983
+ rootDir,
984
+ srcDir: join(rootDir, "src"),
985
+ namespace,
986
+ fsNamespace: overrides?.fsNamespace ?? namespace.toLowerCase(),
987
+ outputTargets: [],
988
+ ...overrides
989
+ };
990
+ }
991
+ /**
992
+ * Walk up from `startDir` looking for a monorepo workspace root — a directory
993
+ * containing `pnpm-workspace.yaml` or a `package.json` with a `workspaces` field.
994
+ * Stops at the home directory or filesystem root. Returns `undefined` if none found.
995
+ * @param startDir The directory to start searching from.
996
+ * @returns A promise that resolves to the workspace root directory, or undefined if none found.
997
+ */
998
+ async function detectWorkspaceRoot(startDir) {
999
+ const home = homedir();
1000
+ let dir = startDir;
1001
+ while (true) {
1002
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
1003
+ try {
1004
+ const pkg = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
1005
+ if (Array.isArray(pkg.workspaces)) return dir;
1006
+ } catch {}
1007
+ const parent = dirname(dir);
1008
+ if (parent === dir || dir === home) return void 0;
1009
+ dir = parent;
1010
+ }
1011
+ }
1012
+ /**
1013
+ * Returns true if the directory looks like an existing Stencil project:
1014
+ * - has an explicit `stencil.config.ts`, OR
1015
+ * - has `.tsx` files under `src/` (zero-config project).
1016
+ * @param dir The directory to check for an existing Stencil project.
1017
+ * @returns A promise that resolves to true if the directory looks like an existing Stencil project, false otherwise.
1018
+ */
1019
+ async function isExistingStencilProject(dir) {
1020
+ if (existsSync(join(dir, "stencil.config.ts"))) return true;
1021
+ try {
1022
+ return (await readdir(join(dir, "src"), {
1023
+ recursive: true,
1024
+ withFileTypes: true
1025
+ })).some((e) => e.isFile() && e.name.endsWith(".tsx"));
1026
+ } catch {
1027
+ return false;
1028
+ }
1029
+ }
1030
+ //#endregion
1031
+ //#region src/wizard/splash.ts
1032
+ const CLI_VERSION = "5.0.0-alpha.9";
1033
+ const isTTY = process.stdout.isTTY;
1034
+ const noColor = !isTTY || "NO_COLOR" in process.env;
1035
+ const RESET = noColor ? "" : "\x1B[0m";
1036
+ const BOLD = noColor ? "" : "\x1B[1m";
1037
+ const DIM = noColor ? "" : "\x1B[2m";
1038
+ const BLUE = noColor ? "" : "\x1B[38;2;60;44;255m";
1039
+ const RAW = `\
1040
+ .............
1041
+ ...................
1042
+ .........................
1043
+ ..............................
1044
+ .................................
1045
+ ..............████████████.........
1046
+ .............████████████............
1047
+ ............████████████...............
1048
+ ...........*************.................
1049
+ .........████████████████████████████....
1050
+ .......████████████████████████████......
1051
+ .....████████████████████████████........
1052
+ ...████████████████████████████..........
1053
+ ................*************............
1054
+ ..............████████████.............
1055
+ ............████████████..............
1056
+ .........████████████...............
1057
+ .................................
1058
+ ..............................
1059
+ ..........................
1060
+ ......................
1061
+ ................`;
1062
+ function colorize(raw) {
1063
+ if (noColor) return raw;
1064
+ let out = "";
1065
+ let style = "";
1066
+ for (const ch of raw) {
1067
+ const next = ".*".includes(ch) ? BLUE : "";
1068
+ if (next !== style) {
1069
+ if (style) out += RESET;
1070
+ if (next) out += next;
1071
+ style = next;
1072
+ }
1073
+ out += ch;
1074
+ }
1075
+ return style ? out + RESET : out;
1076
+ }
1077
+ const SPLASH = colorize(RAW);
1078
+ function printSplash() {
1079
+ if (!isTTY) return;
1080
+ const header = ` ${BOLD}Stencil${RESET} ${BLUE}v${CLI_VERSION}${RESET}`;
1081
+ const tagline = ` ${DIM}The Custom Element Compiler${RESET}`;
1082
+ process.stdout.write(`\n${SPLASH}\n\n${header}\n${tagline}\n\n`);
1083
+ }
1084
+ //#endregion
1085
+ //#region src/task-add.ts
1086
+ async function getInstalledPackageNames(rootDir) {
1087
+ try {
1088
+ const pkg = JSON.parse(await readFile(join(rootDir, "package.json"), "utf8"));
1089
+ const keys = (v) => Object.keys(v !== null && typeof v === "object" ? v : {});
1090
+ return new Set([...keys(pkg.dependencies), ...keys(pkg.devDependencies)]);
1091
+ } catch {
1092
+ return /* @__PURE__ */ new Set();
1093
+ }
1094
+ }
1095
+ async function selectInteractive(cwd) {
1096
+ const discovered = await discoverPlugins(cwd);
1097
+ const installed = await getInstalledPackageNames(cwd);
1098
+ const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
1099
+ const configurable = discovered.filter((d) => d.plugin.init != null);
1100
+ let toInstall = [];
1101
+ let toConfigure = [];
1102
+ if (installable.length > 0 || configurable.length > 0) {
1103
+ const result = await promptAddCapabilities(installable, configurable);
1104
+ toInstall = result.toInstall;
1105
+ toConfigure = result.toConfigure;
1106
+ } else p.log.info("All known integrations are already installed.");
1107
+ const customPackages = await promptCustomPackages();
1108
+ return {
1109
+ packagesToInstall: [...toInstall.map((i) => i.package), ...customPackages],
1110
+ pluginsToReconfigure: toConfigure
1111
+ };
1112
+ }
1113
+ async function taskAdd(packages, strictConfig) {
1114
+ const cwd = process.cwd();
1115
+ printSplash();
1116
+ p.intro("stencil add");
1117
+ if (isCI) {
1118
+ p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil add`.");
1119
+ process.exit(1);
1120
+ }
1121
+ let packagesToInstall = packages;
1122
+ let pluginsToReconfigure = [];
1123
+ if (packages.length === 0) ({packagesToInstall, pluginsToReconfigure} = await selectInteractive(cwd));
1124
+ if (packagesToInstall.length === 0 && pluginsToReconfigure.length === 0) {
1125
+ p.outro("Nothing to do.");
1126
+ return;
1127
+ }
1128
+ 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}`);
1129
+ else {
1130
+ const s = p.spinner();
1131
+ s.start(`Installing ${packagesToInstall.join(", ")}`);
1132
+ await addDevDependency(packagesToInstall, {
1133
+ cwd,
1134
+ silent: true
1135
+ });
1136
+ s.stop("Installed");
1137
+ }
1138
+ const context = {
1139
+ isNewProject: false,
1140
+ prompts: p,
1141
+ nypm,
1142
+ config: strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd),
1143
+ workspaceRoot: await detectWorkspaceRoot(cwd)
1144
+ };
1145
+ if (packagesToInstall.length > 0) {
1146
+ const discovered = await discoverPlugins(cwd);
1147
+ const installedSet = new Set(packagesToInstall);
1148
+ for (const d of discovered) if (installedSet.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run(context);
1149
+ }
1150
+ for (const d of pluginsToReconfigure) if (d.plugin.init?.run) await d.plugin.init.run(context);
1151
+ p.outro("Done!");
1152
+ }
1153
+ //#endregion
1154
+ //#region src/check-version.ts
1155
+ /**
1156
+ * Retrieve a reference to the active `CompilerSystem`'s `checkVersion` function
1157
+ * @param config the Stencil configuration associated with the currently compiled project
1158
+ * @param currentVersion the Stencil compiler's version string
1159
+ * @param flags the CLI flags (owned by CLI, not part of core config)
1160
+ * @returns a reference to `checkVersion`, or `null` if one does not exist on the current `CompilerSystem`
1161
+ */
1162
+ const startCheckVersion = async (config, currentVersion, flags) => {
1163
+ if (config.devMode && !flags.ci && !currentVersion.includes("-dev.") && isFunction(config.sys.checkVersion)) return config.sys.checkVersion(config.logger, currentVersion);
1164
+ return null;
1165
+ };
1166
+ /**
1167
+ * Print the results of running the provided `versionChecker`.
1168
+ *
1169
+ * Does not print if no `versionChecker` is provided.
1170
+ *
1171
+ * @param versionChecker the function to invoke.
1172
+ */
1173
+ const printCheckVersionResults = async (versionChecker) => {
1174
+ if (versionChecker) {
1175
+ const checkVersionResults = await versionChecker;
1176
+ if (isFunction(checkVersionResults)) checkVersionResults();
1177
+ }
1178
+ };
1179
+ //#endregion
1180
+ //#region src/migrations/rules/build-dist-docs.ts
1181
+ /**
1182
+ * Migration rule for buildDist and buildDocs removal.
1183
+ *
1184
+ * In Stencil v5, these global config options are replaced with per-output-target
1185
+ * `skipInDev` property. This migration:
1186
+ * - Detects `buildDist` or `buildDocs` in stencil.config.ts
1187
+ * - Removes the property
1188
+ * - For `buildDist: true` or `buildDocs: true`, adds `skipInDev: false` to relevant output targets
1189
+ */
1190
+ const buildDistDocsRule = {
1191
+ id: "build-dist-docs",
1192
+ name: "buildDist/buildDocs Removal",
1193
+ description: "Remove deprecated buildDist and buildDocs config options",
1194
+ fromVersion: "4.x",
1195
+ toVersion: "5.x",
1196
+ detect(sourceFile) {
1197
+ const matches = [];
1198
+ const visit = (node) => {
1199
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1200
+ const propName = node.name.text;
1201
+ if (propName === "buildDist" || propName === "buildDocs") {
1202
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1203
+ const isTrue = node.initializer.kind === ts.SyntaxKind.TrueKeyword;
1204
+ matches.push({
1205
+ node,
1206
+ message: `Deprecated '${propName}' found${isTrue ? " (set to true)" : ""} - will be removed and skipInDev added to output targets`,
1207
+ line: line + 1,
1208
+ column: character + 1
1209
+ });
1210
+ }
1211
+ }
1212
+ ts.forEachChild(node, visit);
1213
+ };
1214
+ visit(sourceFile);
1215
+ return matches;
1216
+ },
1217
+ transform(sourceFile, matches) {
1218
+ if (matches.length === 0) return sourceFile.getFullText();
1219
+ let text = sourceFile.getFullText();
1220
+ const targetTypesNeedingSkipInDev = [];
1221
+ for (const match of matches) {
1222
+ const prop = match.node;
1223
+ const propName = prop.name.text;
1224
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
1225
+ if (propName === "buildDist") targetTypesNeedingSkipInDev.push("dist", "dist-custom-elements", "dist-hydrate-script", "loader-bundle", "standalone", "ssr");
1226
+ else if (propName === "buildDocs") targetTypesNeedingSkipInDev.push("docs-readme", "docs-json", "docs-custom", "docs-vscode", "docs-custom-elements-manifest");
1227
+ }
1228
+ }
1229
+ const outputTargetsToModify = [];
1230
+ const findOutputTargets = (node) => {
1231
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
1232
+ for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
1233
+ const typeProp = element.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type");
1234
+ if (typeProp && ts.isStringLiteral(typeProp.initializer)) {
1235
+ const targetType = typeProp.initializer.text;
1236
+ if (targetTypesNeedingSkipInDev.includes(targetType)) {
1237
+ if (!element.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "skipInDev")) outputTargetsToModify.push(element);
1238
+ }
1239
+ }
1240
+ }
1241
+ }
1242
+ ts.forEachChild(node, findOutputTargets);
1243
+ };
1244
+ findOutputTargets(sourceFile);
1245
+ const allModifications = [];
1246
+ for (const match of matches) {
1247
+ const prop = match.node;
1248
+ const start = prop.getStart();
1249
+ let end = prop.getEnd();
1250
+ const afterProp = text.slice(end).match(/^\s*,/);
1251
+ if (afterProp) end = end + afterProp[0].length;
1252
+ allModifications.push({
1253
+ type: "remove",
1254
+ start,
1255
+ end,
1256
+ node: prop
1257
+ });
1258
+ }
1259
+ for (const target of outputTargetsToModify) {
1260
+ const lastProp = target.properties[target.properties.length - 1];
1261
+ if (lastProp) allModifications.push({
1262
+ type: "addSkipInDev",
1263
+ start: lastProp.getEnd(),
1264
+ end: lastProp.getEnd(),
1265
+ node: target
1266
+ });
1267
+ }
1268
+ allModifications.sort((a, b) => b.start - a.start);
1269
+ for (const mod of allModifications) if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
1270
+ else if (mod.type === "addSkipInDev") {
1271
+ const firstProp = mod.node.properties[0];
1272
+ let indent = " ";
1273
+ if (firstProp) {
1274
+ const propStart = firstProp.getStart();
1275
+ const lineStart = text.lastIndexOf("\n", propStart) + 1;
1276
+ const leadingWhitespace = text.slice(lineStart, propStart);
1277
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
1278
+ }
1279
+ const afterLastProp = text.slice(mod.start).match(/^(\s*,)?/);
1280
+ const skipLength = afterLastProp && afterLastProp[1] ? afterLastProp[0].length : 0;
1281
+ text = text.slice(0, mod.start) + `,\n${indent}skipInDev: false,` + text.slice(mod.start + skipLength);
1282
+ }
1283
+ text = text.replace(/,\s*\n\s*\n/g, ",\n");
1284
+ text = text.replace(/{\s*\n\s*\n/g, "{\n");
1285
+ return text;
1286
+ }
1287
+ };
1288
+ //#endregion
1289
+ //#region src/migrations/rules/dev-mode.ts
1290
+ /**
1291
+ * Migration rule for `devMode` config option removal.
1292
+ *
1293
+ * In Stencil v5, `devMode` is no longer a user-settable config option in `stencil.config.ts`.
1294
+ * Build mode is controlled exclusively by the `--dev` CLI flag (default is production).
1295
+ * This migration removes `devMode` from the config object.
1296
+ */
1297
+ const devModeRule = {
1298
+ id: "dev-mode",
1299
+ name: "devMode Config Removal",
1300
+ description: "Remove deprecated devMode config option - use --dev CLI flag instead",
1301
+ fromVersion: "4.x",
1302
+ toVersion: "5.x",
1303
+ detect(sourceFile) {
1304
+ const matches = [];
1305
+ const visit = (node) => {
1306
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1307
+ if (node.name.text === "devMode") {
1308
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1309
+ matches.push({
1310
+ node,
1311
+ message: `Deprecated 'devMode' config option found - build mode is now set via the --dev CLI flag (production is the default)`,
1312
+ line: line + 1,
1313
+ column: character + 1
1314
+ });
1315
+ }
1316
+ }
1317
+ ts.forEachChild(node, visit);
1318
+ };
1319
+ visit(sourceFile);
1320
+ return matches;
1321
+ },
1322
+ transform(sourceFile, matches) {
1323
+ if (matches.length === 0) return sourceFile.getFullText();
1324
+ let text = sourceFile.getFullText();
1325
+ for (const match of [...matches].reverse()) {
1326
+ const node = match.node;
1327
+ const start = node.getFullStart();
1328
+ const end = node.getEnd();
1329
+ let removeEnd = end;
1330
+ const trailingComma = text.slice(end).match(/^\s*,/);
1331
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
1332
+ text = text.slice(0, start) + text.slice(removeEnd);
1333
+ }
1334
+ return text;
1335
+ }
1336
+ };
1337
+ //#endregion
1338
+ //#region src/migrations/rules/encapsulation-api.ts
1339
+ /**
1340
+ * Migration rule for the @Component encapsulation API change.
1341
+ *
1342
+ * Migrates:
792
1343
  * - `shadow: true` → `encapsulation: { type: 'shadow' }`
793
1344
  * - `shadow: { delegatesFocus: true }` → `encapsulation: { type: 'shadow', delegatesFocus: true }`
794
1345
  * - `scoped: true` → `encapsulation: { type: 'scoped' }`
@@ -1984,7 +2535,7 @@ const taskMigrate = async (coreCompiler, config, flags) => {
1984
2535
  const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
1985
2536
  const matches = rule.detect(sourceFile);
1986
2537
  if (matches.length > 0) {
1987
- const relPath = relative(config.rootDir, filePath);
2538
+ const relPath = relative$1(config.rootDir, filePath);
1988
2539
  logger.info(`\n${logger.cyan(relPath)}`);
1989
2540
  logger.info(` ${logger.yellow(`[${rule.id}]`)} ${rule.name}`);
1990
2541
  for (const match of matches) logger.info(` Line ${match.line}: ${match.message}`);
@@ -2096,8 +2647,8 @@ const detectMigrations = async (coreCompiler, config) => {
2096
2647
  */
2097
2648
  async function getTypeScriptFiles(config, sys, logger) {
2098
2649
  let tsconfigPath;
2099
- if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join(config.rootDir, config.tsconfig);
2100
- else tsconfigPath = join(config.rootDir, "tsconfig.json");
2650
+ if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join$1(config.rootDir, config.tsconfig);
2651
+ else tsconfigPath = join$1(config.rootDir, "tsconfig.json");
2101
2652
  logger.debug(`Using tsconfig: ${tsconfigPath}`);
2102
2653
  const tsconfigContent = await sys.readFile(tsconfigPath);
2103
2654
  if (!tsconfigContent) {
@@ -2127,11 +2678,11 @@ async function getTypeScriptFiles(config, sys, logger) {
2127
2678
  const configContent = await sys.readFile(configFile);
2128
2679
  if (configContent) {
2129
2680
  const configSourceFile = ts.createSourceFile(configFile, configContent, ts.ScriptTarget.Latest, true);
2130
- const configDir = dirname(configFile);
2681
+ const configDir = dirname$1(configFile);
2131
2682
  for (const statement of configSourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
2132
2683
  const specifier = statement.moduleSpecifier.text;
2133
2684
  if (!specifier.startsWith("./") && !specifier.startsWith("../")) continue;
2134
- const basePath = join(configDir, specifier);
2685
+ const basePath = join$1(configDir, specifier);
2135
2686
  const candidates = basePath.endsWith(".ts") || basePath.endsWith(".tsx") ? [basePath] : [`${basePath}.ts`, `${basePath}.tsx`];
2136
2687
  for (const candidate of candidates) if (!candidate.endsWith(".d.ts") && !files.includes(candidate) && candidate.startsWith(config.rootDir)) {
2137
2688
  if (await sys.readFile(candidate)) {
@@ -2245,7 +2796,7 @@ function uuidv4() {
2245
2796
  * @param path the path on the file system to read and parse
2246
2797
  * @returns the parsed JSON
2247
2798
  */
2248
- async function readJson$1(sys, path) {
2799
+ async function readJson(sys, path) {
2249
2800
  const file = await sys.readFile(path);
2250
2801
  return file ? JSON.parse(file) : null;
2251
2802
  }
@@ -2277,7 +2828,7 @@ const defaultConfigDirectory = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic
2277
2828
  * @returns the config read from disk that has been potentially been updated
2278
2829
  */
2279
2830
  async function readConfig(sys) {
2280
- let config = await readJson$1(sys, defaultConfig(sys));
2831
+ let config = await readJson(sys, defaultConfig(sys));
2281
2832
  if (!config) {
2282
2833
  config = {
2283
2834
  "tokens.telemetry": uuidv4(),
@@ -2515,7 +3066,7 @@ async function getInstalledPackages(sys, flags) {
2515
3066
  const yarn = isUsingYarn(sys);
2516
3067
  try {
2517
3068
  const appRootDir = sys.getCurrentDirectory();
2518
- const packageJson = await tryFn(readJson$1, sys, sys.resolvePath(appRootDir + "/package.json"));
3069
+ const packageJson = await tryFn(readJson, sys, sys.resolvePath(appRootDir + "/package.json"));
2519
3070
  if (!packageJson) return {
2520
3071
  packages,
2521
3072
  packagesNoVersions
@@ -2550,7 +3101,7 @@ async function getInstalledPackages(sys, flags) {
2550
3101
  */
2551
3102
  async function npmPackages(sys, ionicPackages) {
2552
3103
  const appRootDir = sys.getCurrentDirectory();
2553
- const packageLockJson = await tryFn(readJson$1, sys, sys.resolvePath(appRootDir + "/package-lock.json"));
3104
+ const packageLockJson = await tryFn(readJson, sys, sys.resolvePath(appRootDir + "/package-lock.json"));
2554
3105
  return ionicPackages.map(([k, v]) => {
2555
3106
  let version = packageLockJson?.dependencies[k]?.version ?? packageLockJson?.devDependencies[k]?.version ?? v;
2556
3107
  version = version.includes("file:") ? sanitizeDeclaredVersion(v) : version;
@@ -2755,162 +3306,68 @@ const taskBuild = async (coreCompiler, config, flags) => {
2755
3306
  * Prompt the user about available migrations.
2756
3307
  * Shows what migrations are available and lets them choose to run them.
2757
3308
  * @param config the Stencil config
2758
- * @param migrationResult the result of migration detection with available migrations
2759
- * @param context whether this is a pre-build check or post-error check
2760
- * @returns the user's chosen action for handling migrations
2761
- */
2762
- async function promptForMigration(config, migrationResult, context) {
2763
- const logger = config.logger;
2764
- logger.info("");
2765
- logger.info(logger.bold(logger.yellow("Migrations Required")));
2766
- logger.info("─".repeat(40));
2767
- logger.info(`Found ${migrationResult.totalMatches} item(s) in ${migrationResult.filesAffected} file(s) that need to be migrated for Stencil v5.`);
2768
- for (const migration of migrationResult.migrations) {
2769
- const relPath = relative(config.rootDir, migration.filePath);
2770
- logger.info(` ${logger.cyan(relPath)}: ${migration.matches.length} item(s)`);
2771
- }
2772
- logger.info("");
2773
- if (context === "pre-build") logger.info("Your config contains deprecated options that must be migrated before building.");
2774
- else logger.info("These migrations may help resolve the build errors above.");
2775
- const action = await select({
2776
- message: "What would you like to do?",
2777
- options: [
2778
- {
2779
- value: "run",
2780
- label: "Run migration",
2781
- hint: "Apply migrations and re-run build"
2782
- },
2783
- {
2784
- value: "dry-run",
2785
- label: "Dry run",
2786
- hint: "Preview changes without modifying files"
2787
- },
2788
- {
2789
- value: "exit",
2790
- label: "Exit",
2791
- hint: "Exit without making changes"
2792
- }
2793
- ]
2794
- });
2795
- if (isCancel(action)) return "exit";
2796
- return action;
2797
- }
2798
- //#endregion
2799
- //#region src/task-docs.ts
2800
- const taskDocs = async (coreCompiler, config) => {
2801
- config.devServer = {};
2802
- config.outputTargets = config.outputTargets.filter(isOutputTargetDocs);
2803
- config.devMode = true;
2804
- startupCompilerLog(coreCompiler, config);
2805
- const compiler = await coreCompiler.createCompiler(config);
2806
- await compiler.build();
2807
- await compiler.destroy();
2808
- };
2809
- //#endregion
2810
- //#region src/wizard/clack.ts
2811
- /**
2812
- * Exits cleanly if the user cancelled a prompt (Ctrl+C).
2813
- * Narrows the type from `T | symbol` to `T` for callers.
2814
- *
2815
- * @param value - Return value from a `@clack/prompts` prompt call.
2816
- */
2817
- function cancelIfAborted(value) {
2818
- if (isCancel(value)) {
2819
- cancel("Cancelled.");
2820
- process.exit(0);
2821
- }
2822
- }
2823
- //#endregion
2824
- //#region src/wizard/discover.ts
2825
- function toStringRecord(val) {
2826
- return val !== null && typeof val === "object" ? val : {};
2827
- }
2828
- async function readJson(filePath) {
2829
- try {
2830
- return JSON.parse(await readFile(filePath, "utf8"));
2831
- } catch {
2832
- return null;
2833
- }
2834
- }
2835
- async function loadOne(rootDir, packageName, loader) {
2836
- const wizardEntry = ((await readJson(join$1(rootDir, "node_modules", packageName, "package.json")))?.stencil)?.wizard;
2837
- if (!wizardEntry) return null;
2838
- const wizardPath = join$1(rootDir, "node_modules", packageName, wizardEntry);
2839
- let mod;
2840
- try {
2841
- mod = await loader(pathToFileURL(wizardPath).href);
2842
- } catch {
2843
- console.warn(`[stencil] ${packageName} declares stencil.wizard but the module failed to load: ${wizardPath}`);
2844
- return null;
2845
- }
2846
- const plugin = mod.wizard;
2847
- if (!plugin || typeof plugin !== "object") {
2848
- console.warn(`[stencil] ${packageName} declares stencil.wizard but does not export a 'wizard' object`);
2849
- return null;
2850
- }
2851
- return {
2852
- packageName,
2853
- plugin
2854
- };
2855
- }
2856
- /**
2857
- * Scans the project's declared dependencies for packages that expose a
2858
- * `stencil.wizard` entry in their `package.json` and dynamically imports
2859
- * each matching module.
2860
- *
2861
- * @param rootDir - Absolute path to the project root (where `package.json` lives).
2862
- * @param loader - Module loader; injectable for testing. Defaults to `import()`.
2863
- * @returns Array of successfully loaded plugins, in dependency declaration order.
2864
- */
2865
- async function discoverPlugins(rootDir, loader = (url) => import(url)) {
2866
- const pkg = await readJson(join$1(rootDir, "package.json"));
2867
- if (!pkg) return [];
2868
- const depNames = [...new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
2869
- const plugins = (await Promise.allSettled(depNames.map((name) => loadOne(rootDir, name, loader)))).filter((r) => r.status === "fulfilled" && r.value !== null).map((r) => r.value);
2870
- const devPath = process.env.STENCIL_WIZARD_DEV;
2871
- if (devPath) {
2872
- const devPlugin = await loadDevPlugin(resolve(rootDir, devPath), loader);
2873
- if (devPlugin) plugins.unshift(devPlugin);
2874
- }
2875
- return plugins;
2876
- }
2877
- async function findDevPackageName(wizardPath) {
2878
- const dir = dirname$1(wizardPath);
2879
- for (const candidate of [dir, resolve(dir, "..")]) {
2880
- const pkg = await readJson(join$1(candidate, "package.json"));
2881
- if (typeof pkg?.name === "string") return pkg.name;
2882
- }
2883
- return basename(dir);
2884
- }
2885
- async function loadDevPlugin(wizardPath, loader) {
2886
- const packageName = await findDevPackageName(wizardPath);
2887
- let mod;
2888
- try {
2889
- mod = await loader(pathToFileURL(wizardPath).href);
2890
- } catch {
2891
- console.warn(`[stencil] STENCIL_WIZARD_DEV: failed to load ${wizardPath}`);
2892
- return null;
2893
- }
2894
- const plugin = mod.wizard;
2895
- if (!plugin || typeof plugin !== "object") {
2896
- console.warn(`[stencil] STENCIL_WIZARD_DEV: ${wizardPath} does not export a 'wizard' object`);
2897
- return null;
3309
+ * @param migrationResult the result of migration detection with available migrations
3310
+ * @param context whether this is a pre-build check or post-error check
3311
+ * @returns the user's chosen action for handling migrations
3312
+ */
3313
+ async function promptForMigration(config, migrationResult, context) {
3314
+ const logger = config.logger;
3315
+ logger.info("");
3316
+ logger.info(logger.bold(logger.yellow("Migrations Required")));
3317
+ logger.info("─".repeat(40));
3318
+ logger.info(`Found ${migrationResult.totalMatches} item(s) in ${migrationResult.filesAffected} file(s) that need to be migrated for Stencil v5.`);
3319
+ for (const migration of migrationResult.migrations) {
3320
+ const relPath = relative$1(config.rootDir, migration.filePath);
3321
+ logger.info(` ${logger.cyan(relPath)}: ${migration.matches.length} item(s)`);
2898
3322
  }
2899
- return {
2900
- packageName,
2901
- plugin
2902
- };
3323
+ logger.info("");
3324
+ if (context === "pre-build") logger.info("Your config contains deprecated options that must be migrated before building.");
3325
+ else logger.info("These migrations may help resolve the build errors above.");
3326
+ const action = await select({
3327
+ message: "What would you like to do?",
3328
+ options: [
3329
+ {
3330
+ value: "run",
3331
+ label: "Run migration",
3332
+ hint: "Apply migrations and re-run build"
3333
+ },
3334
+ {
3335
+ value: "dry-run",
3336
+ label: "Dry run",
3337
+ hint: "Preview changes without modifying files"
3338
+ },
3339
+ {
3340
+ value: "exit",
3341
+ label: "Exit",
3342
+ hint: "Exit without making changes"
3343
+ }
3344
+ ]
3345
+ });
3346
+ if (isCancel(action)) return "exit";
3347
+ return action;
2903
3348
  }
2904
3349
  //#endregion
3350
+ //#region src/task-docs.ts
3351
+ const taskDocs = async (coreCompiler, config) => {
3352
+ config.devServer = {};
3353
+ config.outputTargets = config.outputTargets.filter(isOutputTargetDocs);
3354
+ config.devMode = true;
3355
+ startupCompilerLog(coreCompiler, config);
3356
+ const compiler = await coreCompiler.createCompiler(config);
3357
+ await compiler.build();
3358
+ await compiler.destroy();
3359
+ };
3360
+ //#endregion
2905
3361
  //#region src/task-generate.ts
3362
+ async function resolveFileTemplates(contrib, ctx) {
3363
+ const { fileTemplates } = contrib;
3364
+ if (!fileTemplates) return [];
3365
+ return typeof fileTemplates === "function" ? fileTemplates(ctx) : fileTemplates;
3366
+ }
2906
3367
  const taskGenerate = async (config, flags) => {
2907
- if (!config.configPath) {
2908
- config.logger.error("Please run this command in your root directory (i. e. the one containing stencil.config.ts).");
2909
- return config.sys.exit(1);
2910
- }
2911
3368
  const srcDir = config.srcDir;
2912
- if (!srcDir) {
2913
- config.logger.error(`Stencil's srcDir was not specified.`);
3369
+ if (!srcDir || !existsSync(srcDir)) {
3370
+ config.logger.error("Please run this command in your project root directory.");
2914
3371
  return config.sys.exit(1);
2915
3372
  }
2916
3373
  const generateContribs = (await discoverPlugins(config.rootDir)).flatMap((d) => d.plugin.generate ? [d.plugin.generate] : []);
@@ -2952,7 +3409,14 @@ const taskGenerate = async (config, flags) => {
2952
3409
  });
2953
3410
  cancelIfAborted(stylePick);
2954
3411
  const styleExtension = stylePick || void 0;
2955
- const allFileTemplates = generateContribs.flatMap((c) => c.fileTemplates ?? []);
3412
+ const generateCtx = {
3413
+ tagName: componentName,
3414
+ config: toProjectConfig(config),
3415
+ prompts: p,
3416
+ nypm
3417
+ };
3418
+ const allFileTemplates = [];
3419
+ for (const contrib of generateContribs) allFileTemplates.push(...await resolveFileTemplates(contrib, generateCtx));
2956
3420
  let pickedExtensions = [];
2957
3421
  if (allFileTemplates.length > 0) {
2958
3422
  const filePick = await p.multiselect({
@@ -2967,20 +3431,20 @@ const taskGenerate = async (config, flags) => {
2967
3431
  cancelIfAborted(filePick);
2968
3432
  pickedExtensions = filePick;
2969
3433
  }
2970
- const outDir = join$1(srcDir, "components", dir, componentName);
3434
+ const outDir = join(srcDir, "components", dir, componentName);
2971
3435
  const className = toPascalCase(componentName);
2972
3436
  const filesToWrite = [];
2973
3437
  filesToWrite.push({
2974
- absPath: normalizePath(join$1(outDir, `${componentName}.tsx`)),
3438
+ absPath: normalizePath(join(outDir, `${componentName}.tsx`)),
2975
3439
  content: getComponentBoilerplate(componentName, styleExtension)
2976
3440
  });
2977
3441
  if (styleExtension) filesToWrite.push({
2978
- absPath: normalizePath(join$1(outDir, `${componentName}.${styleExtension}`)),
3442
+ absPath: normalizePath(join(outDir, `${componentName}.${styleExtension}`)),
2979
3443
  content: getStyleBoilerplate(styleExtension)
2980
3444
  });
2981
3445
  for (const ext of pickedExtensions) {
2982
3446
  const tmpl = allFileTemplates.find((ft) => ft.extension === ext);
2983
- const absPath = normalizePath(join$1(outDir, tmpl.subdirectory ?? "", `${componentName}.${ext}`));
3447
+ const absPath = normalizePath(join(outDir, tmpl.subdirectory ?? "", `${componentName}.${ext}`));
2984
3448
  filesToWrite.push({
2985
3449
  absPath,
2986
3450
  content: tmpl.template(componentName, className)
@@ -2992,10 +3456,10 @@ const taskGenerate = async (config, flags) => {
2992
3456
  await config.sys.exit(1);
2993
3457
  return;
2994
3458
  }
2995
- const dirs = [...new Set(filesToWrite.map(({ absPath }) => normalizePath(join$1(absPath, ".."))))];
3459
+ const dirs = [...new Set(filesToWrite.map(({ absPath }) => normalizePath(join(absPath, ".."))))];
2996
3460
  await Promise.all(dirs.map((d) => config.sys.createDir(d, { recursive: true })));
2997
3461
  await Promise.all(filesToWrite.map(({ absPath, content }) => config.sys.writeFile(absPath, content)));
2998
- p.note(filesToWrite.map(({ absPath }) => relative$1(config.rootDir, absPath)).join("\n"), "Generated");
3462
+ p.note(filesToWrite.map(({ absPath }) => relative(config.rootDir, absPath)).join("\n"), "Generated");
2999
3463
  p.outro(`stencil generate ${input}`);
3000
3464
  };
3001
3465
  //#endregion
@@ -3118,242 +3582,237 @@ const taskInfo = (coreCompiler, sys, logger) => {
3118
3582
  * @param rootDir - Destination directory (typically `process.cwd()`).
3119
3583
  * @param projectName - Value to substitute for `{{PROJECT_NAME}}` placeholders.
3120
3584
  * @param namespace - Value to substitute for `{{NAMESPACE}}` placeholders.
3585
+ * @param stencilVersion - Optional version to substitute for `{{STENCIL_VERSION}}` placeholders.
3121
3586
  */
3122
- async function copyTemplate(rootDir, projectName, namespace) {
3587
+ async function copyTemplate(rootDir, projectName, namespace, stencilVersion) {
3123
3588
  const templateDir = getTemplatePath("component-starter");
3124
3589
  const entries = await readdir(templateDir, {
3125
3590
  recursive: true,
3126
3591
  withFileTypes: true
3127
3592
  });
3593
+ const resolvedStencilVersion = stencilVersion ? `^${stencilVersion}` : "^5.0.0";
3128
3594
  for (const entry of entries) {
3129
3595
  if (!entry.isFile()) continue;
3130
- const srcPath = join$1(entry.parentPath, entry.name);
3131
- const destPath = join$1(rootDir, relative$1(templateDir, srcPath));
3132
- await mkdir(dirname$1(destPath), { recursive: true });
3133
- await writeFile(destPath, (await readFile(srcPath, "utf8")).replace(/\{\{PROJECT_NAME\}\}/g, projectName).replace(/\{\{NAMESPACE\}\}/g, namespace), "utf8");
3596
+ const srcPath = join(entry.parentPath, entry.name);
3597
+ const relPath = relative(templateDir, srcPath);
3598
+ const destPath = join(rootDir, relPath);
3599
+ await mkdir(dirname(destPath), { recursive: true });
3600
+ const content = (await readFile(srcPath, "utf8")).replace(/\{\{PROJECT_NAME\}\}/g, projectName).replace(/\{\{NAMESPACE\}\}/g, namespace).replace(/\{\{STENCIL_VERSION\}\}/g, resolvedStencilVersion);
3601
+ if (relPath === "package.json") await mergePackageJson(destPath, content);
3602
+ else if (relPath === "tsconfig.json") await mergeTsConfig(destPath, content);
3603
+ else if (relPath === ".gitignore") await mergeGitignore(destPath, content);
3604
+ else await writeIfAbsent(destPath, content);
3134
3605
  }
3135
3606
  }
3136
- /**
3137
- * Inject integration package names into the project's package.json devDependencies.
3138
- * Versions are set to 'latest' so the subsequent install resolves them from the registry.
3139
- *
3140
- * @param rootDir - Absolute path to the project root.
3141
- * @param integrations - npm package names to add as devDependencies.
3142
- */
3143
- async function patchPackageJson(rootDir, integrations) {
3144
- if (integrations.length === 0) return;
3145
- const pkgPath = join$1(rootDir, "package.json");
3146
- const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
3147
- const devDeps = pkg.devDependencies ?? {};
3148
- for (const name of integrations) devDeps[name] = "latest";
3149
- pkg.devDependencies = devDeps;
3150
- await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
3607
+ async function writeIfAbsent(destPath, content) {
3608
+ try {
3609
+ await writeFile(destPath, content, {
3610
+ encoding: "utf8",
3611
+ flag: "wx"
3612
+ });
3613
+ } catch (e) {
3614
+ if (e.code !== "EEXIST") throw e;
3615
+ }
3151
3616
  }
3152
- //#endregion
3153
- //#region src/wizard/init/steps.ts
3154
- /** Well-known integrations the CLI can offer before any packages are installed. */
3155
- const KNOWN_INTEGRATIONS = [
3156
- {
3157
- package: "@stencil/vitest",
3158
- displayName: "Vitest",
3159
- description: "Unit / Spec / Integration / Browser testing",
3160
- group: "Testing"
3161
- },
3162
- {
3163
- package: "@stencil/playwright",
3164
- displayName: "Playwright",
3165
- description: "E2E testing",
3166
- group: "Testing"
3167
- },
3168
- {
3169
- package: "@stencil/sass",
3170
- displayName: "Sass",
3171
- description: "Sass/SCSS styles",
3172
- group: "Styling"
3173
- },
3174
- {
3175
- package: "@stencil/eslint-plugin",
3176
- displayName: "ESLint Plugin",
3177
- description: "Stencil-aware lint rules (ESLint, oxlint, Biome)",
3178
- group: "Linting"
3179
- },
3180
- {
3181
- package: "@stencil/storybook-plugin",
3182
- displayName: "Storybook",
3183
- description: "Component development & documentation",
3184
- group: "Tooling"
3185
- },
3186
- {
3187
- package: "@stencil/types-output-target",
3188
- displayName: "Types",
3189
- description: "TypeScript types for React, Vue, Solid, Svelte, Preact",
3190
- group: "Framework integrations"
3191
- },
3192
- {
3193
- package: "@stencil/react-output-target",
3194
- displayName: "React",
3195
- description: "React component wrappers",
3196
- group: "Framework integrations"
3197
- },
3198
- {
3199
- package: "@stencil/angular-output-target",
3200
- displayName: "Angular",
3201
- description: "Angular component wrappers",
3202
- group: "Framework integrations"
3203
- },
3204
- {
3205
- package: "@stencil/vue-output-target",
3206
- displayName: "Vue",
3207
- description: "Vue component wrappers",
3208
- group: "Framework integrations"
3617
+ async function mergePackageJson(destPath, templateContent) {
3618
+ const template = JSON.parse(templateContent);
3619
+ let existing;
3620
+ try {
3621
+ existing = JSON.parse(await readFile(destPath, "utf8"));
3622
+ } catch {
3623
+ await writeFile(destPath, templateContent, "utf8");
3624
+ return;
3209
3625
  }
3210
- ];
3211
- async function promptProjectName() {
3212
- const name = await p.text({
3213
- message: "Project name:",
3214
- defaultValue: "my-stencil-library",
3215
- validate: (v) => {
3216
- if (!v?.trim()) return "Project name is required";
3217
- }
3218
- });
3219
- cancelIfAborted(name);
3220
- return name;
3626
+ const dependencies = mergeStringRecord(template.dependencies, existing.dependencies);
3627
+ const devDependencies = mergeStringRecord(template.devDependencies, existing.devDependencies);
3628
+ for (const pkg of Object.keys(devDependencies)) if (pkg in dependencies) delete devDependencies[pkg];
3629
+ const merged = {
3630
+ ...template,
3631
+ ...existing,
3632
+ scripts: mergeStringRecord(template.scripts, existing.scripts),
3633
+ dependencies,
3634
+ devDependencies
3635
+ };
3636
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
3221
3637
  }
3222
- function buildGroupedOptions(integrations) {
3223
- const groups = {};
3224
- for (const i of integrations) (groups[i.group] ??= []).push({
3225
- value: i.package,
3226
- label: i.displayName,
3227
- hint: i.description
3228
- });
3229
- return groups;
3638
+ async function mergeTsConfig(destPath, templateContent) {
3639
+ const template = JSON.parse(templateContent);
3640
+ let existing;
3641
+ try {
3642
+ existing = JSON.parse(await readFile(destPath, "utf8"));
3643
+ } catch {
3644
+ await writeFile(destPath, templateContent, "utf8");
3645
+ return;
3646
+ }
3647
+ const merged = {
3648
+ ...template,
3649
+ ...existing,
3650
+ compilerOptions: mergeStringRecord(template.compilerOptions, existing.compilerOptions)
3651
+ };
3652
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
3230
3653
  }
3231
- async function promptIntegrations() {
3232
- const picks = await p.groupMultiselect({
3233
- message: "Add integrations (optional):",
3234
- options: buildGroupedOptions(KNOWN_INTEGRATIONS),
3235
- required: false
3236
- });
3237
- cancelIfAborted(picks);
3238
- return KNOWN_INTEGRATIONS.filter((i) => picks.includes(i.package));
3654
+ async function mergeGitignore(destPath, templateContent) {
3655
+ let existing;
3656
+ try {
3657
+ existing = await readFile(destPath, "utf8");
3658
+ } catch {
3659
+ await writeFile(destPath, templateContent, "utf8");
3660
+ return;
3661
+ }
3662
+ const existingEntries = new Set(existing.split("\n").map((l) => l.trim()).filter(Boolean));
3663
+ const missing = templateContent.split("\n").filter((line) => line.trim() && !existingEntries.has(line.trim()));
3664
+ if (missing.length === 0) return;
3665
+ const separator = existing.endsWith("\n") ? "" : "\n";
3666
+ await writeFile(destPath, existing + separator + missing.join("\n") + "\n", "utf8");
3239
3667
  }
3240
- /**
3241
- * Prompt for actions on an existing project: install new integrations and/or
3242
- * run init wizards for already-installed packages with wizard contributions.
3243
- *
3244
- * @param installable - KNOWN_INTEGRATIONS not yet present in the project.
3245
- * @param configurable - Already-installed plugins that declare an `init` contribution.
3246
- * @returns Selected integrations to install and plugins to configure.
3247
- */
3248
- async function promptAddCapabilities(installable, configurable) {
3249
- const options = {};
3250
- if (installable.length > 0) options["Install new integrations"] = installable.map((i) => ({
3251
- value: `install:${i.package}`,
3252
- label: i.displayName,
3253
- hint: i.description
3254
- }));
3255
- if (configurable.length > 0) options["Configure existing integrations"] = configurable.map((d) => ({
3256
- value: `configure:${d.packageName}`,
3257
- label: d.plugin.init.displayName,
3258
- hint: d.plugin.init.description
3259
- }));
3260
- const picks = await p.groupMultiselect({
3261
- message: "What would you like to do?",
3262
- options,
3263
- required: false
3264
- });
3265
- cancelIfAborted(picks);
3266
- const pickedSet = new Set(picks);
3668
+ function mergeStringRecord(base, override) {
3669
+ const toObj = (v) => v !== null && typeof v === "object" ? v : {};
3267
3670
  return {
3268
- toInstall: installable.filter((i) => pickedSet.has(`install:${i.package}`)),
3269
- toConfigure: configurable.filter((d) => pickedSet.has(`configure:${d.packageName}`))
3671
+ ...toObj(base),
3672
+ ...toObj(override)
3270
3673
  };
3271
3674
  }
3272
- //#endregion
3273
- //#region src/wizard/splash.ts
3274
- const noColor = !process.stdout.isTTY || "NO_COLOR" in process.env;
3275
- const RESET = noColor ? "" : "\x1B[0m";
3276
- const BG = noColor ? "" : "\x1B[38;2;60;44;255m";
3277
- const RAW = `\
3278
- .............
3279
- ...................
3280
- .........................
3281
- ..............................
3282
- .................................
3283
- ..............████████████.........
3284
- .............████████████............
3285
- ............████████████...............
3286
- ...........***************...............
3287
- .........████████████████████████████....
3288
- .......████████████████████████████......
3289
- .....████████████████████████████........
3290
- ...████████████████████████████..........
3291
- ...............**************............
3292
- ..............████████████.............
3293
- ............████████████..............
3294
- .........████████████...............
3295
- .................................
3296
- ..............................
3297
- ..........................
3298
- ......................
3299
- ................`;
3300
- function colorize(raw) {
3301
- if (noColor) return raw;
3302
- let out = "";
3303
- let style = "";
3304
- for (const ch of raw) {
3305
- const next = ".*".includes(ch) ? BG : "";
3306
- if (next !== style) {
3307
- if (style) out += RESET;
3308
- if (next) out += next;
3309
- style = next;
3675
+ async function writeStencilConfig(rootDir, content) {
3676
+ await writeFile(join(rootDir, "stencil.config.ts"), content, "utf8");
3677
+ }
3678
+ async function writeGlobalStyle(rootDir) {
3679
+ const path = join(rootDir, "src", "global.css");
3680
+ await mkdir(dirname(path), { recursive: true });
3681
+ await writeIfAbsent(path, `@import "stencil-globals";\n@import "stencil-hydrate";\n`);
3682
+ }
3683
+ async function writeGlobalScript(rootDir) {
3684
+ const path = join(rootDir, "src", "global.ts");
3685
+ await mkdir(dirname(path), { recursive: true });
3686
+ await writeIfAbsent(path, `export default function (): void {}\n`);
3687
+ }
3688
+ function workspaceBuildScript(pm) {
3689
+ switch (pm) {
3690
+ case "pnpm": return "pnpm -r build";
3691
+ case "yarn": return "yarn workspaces run build";
3692
+ case "bun": return "bun run --filter \"*\" build";
3693
+ default: return "npm run build --workspaces --if-present";
3694
+ }
3695
+ }
3696
+ /**
3697
+ * Scaffold a workspace root in `cwd`: creates `packages/`, writes the appropriate
3698
+ * workspace manifest (`pnpm-workspace.yaml` for pnpm, `workspaces` field in
3699
+ * `package.json` for npm / yarn / bun), and ensures a root `package.json` exists.
3700
+ * @param cwd - Absolute path to the workspace root (where `package.json` will be created).
3701
+ * @param projectName - Name to use for the root package.json (typically the project name).
3702
+ * @returns A promise that resolves when the workspace root has been scaffolded.
3703
+ */
3704
+ async function scaffoldWorkspaceRoot(cwd, projectName) {
3705
+ await mkdir(join(cwd, "packages"), { recursive: true });
3706
+ const pm = await detectPackageManager(cwd);
3707
+ const usePnpmYaml = pm?.name === "pnpm";
3708
+ const pkgPath = join(cwd, "package.json");
3709
+ let pkg;
3710
+ try {
3711
+ pkg = JSON.parse(await readFile(pkgPath, "utf8"));
3712
+ } catch {
3713
+ pkg = {};
3714
+ }
3715
+ pkg.name ??= `${projectName}-workspace`;
3716
+ pkg.version ??= "0.0.1";
3717
+ pkg.private = true;
3718
+ pkg.scripts ??= { build: workspaceBuildScript(pm?.name) };
3719
+ if (!usePnpmYaml) pkg.workspaces = ["packages/*"];
3720
+ delete pkg.dependencies;
3721
+ delete pkg.devDependencies;
3722
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
3723
+ if (usePnpmYaml) {
3724
+ const yamlPath = join(cwd, "pnpm-workspace.yaml");
3725
+ try {
3726
+ await writeFile(yamlPath, `packages:\n - 'packages/*'\n`, {
3727
+ encoding: "utf8",
3728
+ flag: "wx"
3729
+ });
3730
+ } catch (e) {
3731
+ if (e.code !== "EEXIST") throw e;
3310
3732
  }
3311
- out += ch;
3312
3733
  }
3313
- return style ? out + RESET : out;
3314
3734
  }
3315
- const SPLASH = colorize(RAW);
3316
- function printSplash() {
3317
- if (!process.stdout.isTTY) return;
3318
- process.stdout.write("\n" + SPLASH + "\n\n");
3735
+ /**
3736
+ * Write output-driven distributable fields (type, module, types) into package.json.
3737
+ * These fields depend on which outputs the user selected, so they cannot be static in the template.
3738
+ * Skips if fields is empty (e.g. www-only project).
3739
+ *
3740
+ * @param rootDir - Absolute path to the project root.
3741
+ * @param fields - Fields to write, from generatePackageJsonFields().
3742
+ */
3743
+ async function applyPackageJsonFields(rootDir, fields) {
3744
+ if (Object.keys(fields).length === 0) return;
3745
+ const pkgPath = join(rootDir, "package.json");
3746
+ const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
3747
+ Object.assign(pkg, fields);
3748
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
3319
3749
  }
3320
3750
  //#endregion
3321
3751
  //#region src/task-init.ts
3322
- async function taskInit() {
3752
+ function outputKeysToTargets(keys) {
3753
+ const map = {
3754
+ loader: "loader-bundle",
3755
+ standalone: "standalone",
3756
+ ssr: "ssr",
3757
+ "ssr-wasm": "ssr-wasm",
3758
+ www: "www"
3759
+ };
3760
+ return keys.length > 0 ? keys.map((k) => ({ type: map[k] })) : [{ type: "loader-bundle" }];
3761
+ }
3762
+ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
3323
3763
  const cwd = process.cwd();
3324
- const isExistingProject = existsSync(join$1(cwd, "stencil.config.ts"));
3764
+ const isExistingProject = await isExistingStencilProject(cwd);
3325
3765
  printSplash();
3326
- p.intro("stencil init");
3327
- if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: loading wizard from ${process.env.STENCIL_WIZARD_DEV}`);
3766
+ p.intro(`stencil init`);
3767
+ if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: loading wizards from ${process.env.STENCIL_WIZARD_DEV}`);
3328
3768
  if (isCI) {
3329
3769
  p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil init`.");
3330
3770
  process.exit(1);
3331
3771
  }
3332
3772
  if (isExistingProject) {
3333
- await addCapabilities(cwd);
3773
+ await addCapabilities(cwd, strictConfig);
3334
3774
  return;
3335
3775
  }
3336
3776
  const projectName = await promptProjectName();
3337
3777
  const namespace = toNamespace(projectName);
3778
+ const outputs = await promptOutputs();
3779
+ const features = await promptFeatures();
3780
+ const docs = await promptDocs();
3338
3781
  const selectedIntegrations = await promptIntegrations();
3782
+ let monorepo = false;
3783
+ let coreName = "";
3784
+ if (hasFrameworkTargets(selectedIntegrations)) {
3785
+ monorepo = await promptMonorepo();
3786
+ if (monorepo) coreName = await promptWorkspaceCoreName();
3787
+ }
3788
+ const configSource = generateStencilConfig({
3789
+ namespace,
3790
+ outputs,
3791
+ signals: features.signals,
3792
+ docs
3793
+ }) ?? (needsStencilConfig(selectedIntegrations) ? `import { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n outputTargets: [{ type: 'loader-bundle' }],\n};\n` : null);
3339
3794
  const summaryLines = [
3340
3795
  `Template: component-starter`,
3341
3796
  `Name: ${projectName}`,
3342
- `Namespace: ${namespace}`
3797
+ `Namespace: ${namespace}`,
3798
+ `Config: ${configSource ? "stencil.config.ts" : "zero-config (loader default)"}`
3343
3799
  ];
3800
+ if (monorepo) {
3801
+ summaryLines.push(`Structure: monorepo workspace`);
3802
+ summaryLines.push(`Core: packages/${coreName}/`);
3803
+ }
3344
3804
  if (selectedIntegrations.length > 0) summaryLines.push(`Add: ${selectedIntegrations.map((i) => i.displayName).join(", ")}`);
3345
3805
  p.note(summaryLines.join("\n"), "Summary");
3346
- const confirmed = await p.confirm({ message: "Scaffold project in current directory?" });
3347
- cancelIfAborted(confirmed);
3348
- if (!confirmed) {
3349
- p.cancel("Cancelled.");
3350
- process.exit(0);
3351
- }
3806
+ const coreDir = monorepo ? join(cwd, "packages", coreName) : cwd;
3352
3807
  const s1 = p.spinner();
3353
3808
  s1.start("Scaffolding project files");
3354
- await copyTemplate(cwd, projectName, namespace);
3809
+ if (monorepo) await scaffoldWorkspaceRoot(cwd, projectName);
3810
+ await copyTemplate(coreDir, projectName, namespace, coreCompiler?.version);
3811
+ await applyPackageJsonFields(coreDir, generatePackageJsonFields(outputs));
3812
+ if (configSource) await writeStencilConfig(coreDir, configSource);
3813
+ if (features.globalStyle) await writeGlobalStyle(coreDir);
3814
+ if (features.globalScript) await writeGlobalScript(coreDir);
3355
3815
  s1.stop("Project files created");
3356
- if (selectedIntegrations.length > 0) await patchPackageJson(cwd, selectedIntegrations.map((i) => i.package));
3357
3816
  const s2 = p.spinner();
3358
3817
  s2.start("Installing dependencies");
3359
3818
  await installDependencies({
@@ -3362,18 +3821,43 @@ async function taskInit() {
3362
3821
  });
3363
3822
  s2.stop("Dependencies installed");
3364
3823
  if (selectedIntegrations.length > 0) {
3365
- const discovered = await discoverPlugins(cwd);
3824
+ const s3 = p.spinner();
3825
+ const pkgs = selectedIntegrations.map((i) => i.package);
3826
+ s3.start(`Installing ${pkgs.join(", ")}`);
3827
+ await addDevDependency(pkgs, {
3828
+ cwd: coreDir,
3829
+ silent: true
3830
+ });
3831
+ s3.stop("Integrations installed");
3832
+ }
3833
+ if (selectedIntegrations.length > 0) {
3834
+ const discovered = await discoverPlugins(coreDir);
3366
3835
  const selectedPkgs = new Set(selectedIntegrations.map((i) => i.package));
3367
- const context = {
3368
- rootDir: cwd,
3369
- isNewProject: true
3370
- };
3371
- for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run(context);
3836
+ const resolvedValidated = loadProjectConfig && configSource ? await loadProjectConfig(join(coreDir, "stencil.config.ts")) : coreCompiler ? coreCompiler.validateConfig({
3837
+ rootDir: coreDir,
3838
+ outputTargets: outputKeysToTargets(outputs),
3839
+ ...configSource ? { namespace } : {}
3840
+ }, {}).config : null;
3841
+ const projectConfig = resolvedValidated ? {
3842
+ ...toProjectConfig(resolvedValidated),
3843
+ rootDir: coreDir
3844
+ } : defaultProjectConfig(coreDir, { namespace });
3845
+ for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run({
3846
+ isNewProject: true,
3847
+ prompts: p,
3848
+ nypm,
3849
+ config: projectConfig,
3850
+ workspaceRoot: monorepo ? cwd : void 0
3851
+ });
3372
3852
  }
3373
- p.outro("Your project is ready! Run: pnpm run dev");
3853
+ const pm = (await nypm.detectPackageManager(cwd))?.name ?? "npm";
3854
+ const devDir = monorepo ? `packages/${coreName}` : null;
3855
+ const devCmd = `${pm} run dev`;
3856
+ p.outro(devDir ? `Your project is ready!\n cd ${devDir}\n ${devCmd}` : `Your project is ready! Run: ${devCmd}`);
3374
3857
  }
3375
- async function addCapabilities(cwd) {
3376
- const raw = JSON.parse(await readFile(join$1(cwd, "package.json"), "utf8"));
3858
+ async function addCapabilities(cwd, strictConfig) {
3859
+ const workspaceRoot = await detectWorkspaceRoot(cwd);
3860
+ const raw = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
3377
3861
  const installed = new Set([...Object.keys(raw.dependencies ?? {}), ...Object.keys(raw.devDependencies ?? {})]);
3378
3862
  const discovered = await discoverPlugins(cwd);
3379
3863
  const configurable = discovered.filter((d) => d.plugin.init);
@@ -3399,10 +3883,10 @@ async function addCapabilities(cwd) {
3399
3883
  process.exit(0);
3400
3884
  }
3401
3885
  if (toInstall.length > 0) {
3402
- await patchPackageJson(cwd, toInstall.map((i) => i.package));
3403
3886
  const s = p.spinner();
3404
- s.start("Installing dependencies");
3405
- await installDependencies({
3887
+ const pkgs = toInstall.map((i) => i.package);
3888
+ s.start(`Installing ${pkgs.join(", ")}`);
3889
+ await addDevDependency(pkgs, {
3406
3890
  cwd,
3407
3891
  silent: true
3408
3892
  });
@@ -3411,11 +3895,14 @@ async function addCapabilities(cwd) {
3411
3895
  const allDiscovered = toInstall.length > 0 ? await discoverPlugins(cwd) : discovered;
3412
3896
  const newlyInstalledPkgs = new Set(toInstall.map((i) => i.package));
3413
3897
  const toRun = [...allDiscovered.filter((d) => newlyInstalledPkgs.has(d.packageName)), ...toConfigure].filter((d) => d.plugin.init?.run);
3414
- const context = {
3415
- rootDir: cwd,
3416
- isNewProject: false
3417
- };
3418
- for (const d of toRun) await d.plugin.init.run(context);
3898
+ const projectConfig = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
3899
+ for (const d of toRun) await d.plugin.init.run({
3900
+ isNewProject: false,
3901
+ prompts: p,
3902
+ nypm,
3903
+ config: projectConfig,
3904
+ workspaceRoot
3905
+ });
3419
3906
  p.outro("Done! Run pnpm run dev to continue.");
3420
3907
  }
3421
3908
  function toNamespace(name) {
@@ -3477,8 +3964,37 @@ const run = async (init) => {
3477
3964
  }), logger, sys);
3478
3965
  return;
3479
3966
  }
3480
- if (task === "init") {
3481
- await taskInit();
3967
+ if (task === "add" || task === "init") {
3968
+ const coreCompiler = await loadCoreCompiler(sys);
3969
+ const rootDir = sys.getCurrentDirectory();
3970
+ const findConfigResults = await findConfig({
3971
+ sys,
3972
+ configPath: flags.config
3973
+ });
3974
+ let strictConfig;
3975
+ const foundConfigPath = !findConfigResults.isErr ? result.unwrap(findConfigResults).configPath : null;
3976
+ if (foundConfigPath) {
3977
+ const loaded = await coreCompiler.loadConfig({
3978
+ config: { rootDir: dirname(foundConfigPath) },
3979
+ configPath: foundConfigPath,
3980
+ logger,
3981
+ sys
3982
+ });
3983
+ strictConfig = coreCompiler.validateConfig(loaded.config, {}).config;
3984
+ } else strictConfig = coreCompiler.validateConfig({ rootDir }, {}).config;
3985
+ if (task === "add") await taskAdd(flags.unknownArgs, strictConfig);
3986
+ else {
3987
+ const loadProjectConfig = async (configPath) => {
3988
+ const loaded = await coreCompiler.loadConfig({
3989
+ config: { rootDir: configPath ? dirname(configPath) : rootDir },
3990
+ configPath,
3991
+ logger,
3992
+ sys
3993
+ });
3994
+ return coreCompiler.validateConfig(loaded.config, {}).config;
3995
+ };
3996
+ await taskInit(coreCompiler, strictConfig, loadProjectConfig);
3997
+ }
3482
3998
  return;
3483
3999
  }
3484
4000
  startupLog(logger, task);
@@ -3538,6 +4054,9 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
3538
4054
  if (!configWithFlags.sys) configWithFlags.sys = sys;
3539
4055
  const strictConfig = coreCompiler.validateConfig(configWithFlags, {}).config;
3540
4056
  switch (task) {
4057
+ case "add":
4058
+ await taskAdd(resolvedFlags.unknownArgs ?? [], strictConfig);
4059
+ break;
3541
4060
  case "build":
3542
4061
  await taskBuild(coreCompiler, strictConfig, resolvedFlags);
3543
4062
  break;
@@ -3552,7 +4071,7 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
3552
4071
  await taskHelp(resolvedFlags, strictConfig.logger, sys);
3553
4072
  break;
3554
4073
  case "init":
3555
- await taskInit();
4074
+ await taskInit(coreCompiler, strictConfig);
3556
4075
  break;
3557
4076
  case "migrate":
3558
4077
  await taskMigrate(coreCompiler, strictConfig, resolvedFlags);