@stencil/cli 5.0.0-beta.2 → 5.0.0-beta.21

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,5 +1,5 @@
1
1
  import { LOG_LEVELS } from "@stencil/core/compiler";
2
- import { buildError, catchError, hasError, isFunction, isOutputTargetDistLazy, isOutputTargetDocs, isOutputTargetSsr, isOutputTargetStandalone, isOutputTargetWww, isString, normalizePath, readOnlyArrayHasStringMember, result, shouldIgnoreError, toCamelCase, validateComponentTag } from "@stencil/core/compiler/utils";
2
+ import { buildError, catchError, hasError, isFunction, isOutputTargetDistLazy, isOutputTargetDocs, isOutputTargetStandalone, isOutputTargetWww, isString, normalizePath, readOnlyArrayHasStringMember, result, shouldIgnoreError, toCamelCase, validateComponentTag } from "@stencil/core/compiler/utils";
3
3
  import { basename, dirname, join, parse, relative, resolve } from "node:path";
4
4
  import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
5
5
  import * as p from "@clack/prompts";
@@ -13,14 +13,13 @@ import { getPackageInfo } from "local-pkg";
13
13
  import { existsSync } from "node:fs";
14
14
  import { homedir } from "node:os";
15
15
  import { dirname as dirname$1, isAbsolute, join as join$1, relative as relative$1 } from "path";
16
- import { generateIndexHtml, generatePackageJsonFields, generateStencilConfig, getComponentBoilerplate, getPreviewHtmlBoilerplate, getStyleBoilerplate, getTemplatePath, getUsageExampleBoilerplate, toPascalCase } from "@stencil/templates";
16
+ import { generateIndexHtml, generatePackageJsonFields, generateStencilConfig, getComponentBoilerplate, getCssOnlyComponentBoilerplate, getPreviewHtmlBoilerplate, getStyleBoilerplate, getTemplatePath, getUsageExampleBoilerplate, toPascalCase } from "@stencil/templates";
17
17
  import { start } from "@stencil/dev-server";
18
18
  //#region src/config-flags.ts
19
19
  /**
20
20
  * All the Boolean options supported by the Stencil CLI
21
21
  */
22
22
  const BOOLEAN_CLI_FLAGS = [
23
- "build",
24
23
  "cache",
25
24
  "ci",
26
25
  "debug",
@@ -588,7 +587,7 @@ const mergeFlags = (config, flags) => {
588
587
  if (flags.debug === true || flags.verbose === true) merged.logLevel = "debug";
589
588
  else if (flags.logLevel) merged.logLevel = flags.logLevel;
590
589
  if (typeof flags.watch === "boolean") merged.watch = flags.watch;
591
- if (flags.docs === true) merged._docsFlag = true;
590
+ if (flags.docs === true || flags.task === "docs") merged._docsFlag = true;
592
591
  if (typeof flags.profile === "boolean") merged.profile = flags.profile;
593
592
  if (typeof flags.log === "boolean") merged.writeLog = flags.log;
594
593
  if (typeof flags.cache === "boolean") merged.enableCache = flags.cache;
@@ -609,155 +608,164 @@ const mergeFlags = (config, flags) => {
609
608
  async function openStencilConfig(configPath) {
610
609
  let text = await readFile(configPath, "utf8");
611
610
  const parse = () => ts.createSourceFile(configPath, text, ts.ScriptTarget.Latest, true);
612
- function findArray(sf, propName) {
611
+ const nodeText = (node) => text.slice(node.getStart(), node.getEnd());
612
+ const splice = (start, end, replacement) => {
613
+ text = text.slice(0, start) + replacement + text.slice(end);
614
+ };
615
+ const indentAt = (pos) => {
616
+ const lineStart = text.lastIndexOf("\n", pos - 1) + 1;
617
+ return text.slice(lineStart, pos).match(/^\s*/)?.[0] ?? "";
618
+ };
619
+ const reindent = (code, indent) => code.replace(/\n/g, `\n${indent}`);
620
+ const listItems = (list) => ts.isArrayLiteralExpression(list) ? list.elements : list.properties;
621
+ const isMultiLine = (list) => {
622
+ const [first] = listItems(list);
623
+ return !!first && text.slice(list.getStart(), first.getStart()).includes("\n");
624
+ };
625
+ const findProp = (obj, name) => obj.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === name);
626
+ function findConfigObject(sf) {
627
+ for (const stmt of sf.statements) if (ts.isVariableStatement(stmt)) {
628
+ for (const decl of stmt.declarationList.declarations) if (ts.isIdentifier(decl.name) && decl.name.text === "config" && decl.initializer && ts.isObjectLiteralExpression(decl.initializer)) return decl.initializer;
629
+ }
613
630
  let found;
614
631
  const visit = (node) => {
615
- if (!found && ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === propName && ts.isArrayLiteralExpression(node.initializer)) found = node.initializer;
616
- else ts.forEachChild(node, visit);
632
+ if (found) return;
633
+ if (ts.isObjectLiteralExpression(node) && findProp(node, "namespace")) {
634
+ found = node;
635
+ return;
636
+ }
637
+ ts.forEachChild(node, visit);
617
638
  };
618
639
  visit(sf);
619
640
  return found;
620
641
  }
621
- function findConfigObject(sf) {
622
- for (const stmt of sf.statements) if (ts.isVariableStatement(stmt)) {
623
- for (const decl of stmt.declarationList.declarations) if (ts.isIdentifier(decl.name) && decl.name.text === "config" && decl.initializer && ts.isObjectLiteralExpression(decl.initializer)) return decl.initializer;
642
+ function requireConfigObject() {
643
+ const configObj = findConfigObject(parse());
644
+ if (!configObj) throw new Error("Could not find Stencil config object in stencil.config.ts");
645
+ return configObj;
646
+ }
647
+ function findArray(propName) {
648
+ const sf = parse();
649
+ const configObj = findConfigObject(sf);
650
+ if (configObj) {
651
+ const init = findProp(configObj, propName)?.initializer;
652
+ return init && ts.isArrayLiteralExpression(init) ? init : void 0;
624
653
  }
625
654
  let found;
626
655
  const visit = (node) => {
627
656
  if (found) return;
628
- if (ts.isObjectLiteralExpression(node)) {
629
- if (node.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "namespace")) {
630
- found = node;
631
- return;
632
- }
657
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === propName && ts.isArrayLiteralExpression(node.initializer)) {
658
+ found = node.initializer;
659
+ return;
633
660
  }
634
661
  ts.forEachChild(node, visit);
635
662
  };
636
663
  visit(sf);
637
664
  return found;
638
665
  }
639
- function replaceInArray(arr, substring, expression) {
640
- for (const element of arr.elements) if (text.slice(element.getStart(), element.getEnd()).includes(substring)) {
641
- const lineStart = text.lastIndexOf("\n", element.getStart()) + 1;
642
- const indent = text.slice(lineStart, element.getStart()).match(/^\s+/)?.[0] ?? "";
643
- const indentedExpression = indent ? expression.replace(/\n/g, `\n${indent}`) : expression;
644
- text = text.slice(0, element.getStart()) + indentedExpression + text.slice(element.getEnd());
645
- return true;
646
- }
647
- return false;
648
- }
649
- function removeFromArray(arr, substring) {
650
- const idx = arr.elements.findIndex((element) => text.slice(element.getStart(), element.getEnd()).includes(substring));
651
- if (idx === -1) return false;
652
- const element = arr.elements[idx];
653
- if (arr.elements.length > 0 && text.slice(arr.getStart(), arr.elements[0].getStart()).includes("\n")) {
654
- const lineStart = text.lastIndexOf("\n", element.getStart());
655
- let end = element.getEnd();
656
- const trailingComma = text.slice(end).match(/^\s*,/);
657
- if (trailingComma) end += trailingComma[0].length;
658
- text = text.slice(0, lineStart) + text.slice(end);
659
- } else {
660
- let start = element.getStart();
661
- let end = element.getEnd();
662
- if (idx < arr.elements.length - 1) {
663
- const trailingMatch = text.slice(end).match(/^,\s*/);
664
- if (trailingMatch) end += trailingMatch[0].length;
665
- } else if (idx > 0) {
666
- const precedingMatch = text.slice(0, start).match(/,\s*$/);
667
- if (precedingMatch) start -= precedingMatch[0].length;
668
- }
669
- text = text.slice(0, start) + text.slice(end);
666
+ /**
667
+ * Insert `code` as a new item of an array / object literal, matching the list's own layout
668
+ * (one item per line, or all on one line).
669
+ * @param list - The array or object literal to insert into.
670
+ * @param code - Source of the new item, indented relative to its own start.
671
+ * @param anchor - Item to insert after. Defaults to the last one.
672
+ */
673
+ function insertItem(list, code, anchor) {
674
+ const items = listItems(list);
675
+ const [open, close] = ts.isArrayLiteralExpression(list) ? "[]" : "{}";
676
+ const multiLine = isMultiLine(list);
677
+ if (!multiLine && (code.includes("\n") || items.length === 0 && ts.isObjectLiteralExpression(list))) {
678
+ const baseIndent = indentAt(list.getStart());
679
+ const indent = baseIndent + " ";
680
+ const lines = items.map(nodeText);
681
+ const at = anchor ? items.indexOf(anchor) + 1 : lines.length;
682
+ lines.splice(at, 0, reindent(code, indent));
683
+ splice(list.getStart(), list.getEnd(), `${open}\n${indent}${lines.join(`,\n${indent}`)},\n${baseIndent}${close}`);
684
+ return;
670
685
  }
671
- return true;
672
- }
673
- function appendToArray(arr, code) {
674
- if (arr.elements.length === 0) {
675
- const insertPos = arr.getEnd() - 1;
676
- text = text.slice(0, insertPos) + code + text.slice(insertPos);
686
+ if (items.length === 0) {
687
+ splice(list.getEnd() - 1, list.getEnd() - 1, code);
677
688
  return;
678
689
  }
679
- let insertPos = arr.elements[arr.elements.length - 1].getEnd();
680
- const trailingComma = text.slice(insertPos).match(/^\s*,/);
681
- if (trailingComma) insertPos += trailingComma[0].length;
682
- const separator = trailingComma ? "" : ",";
683
- const firstElemStart = arr.elements[0].getStart();
684
- if (text.slice(arr.getStart(), firstElemStart).includes("\n")) {
685
- const lineStart = text.lastIndexOf("\n", firstElemStart) + 1;
686
- const indent = text.slice(lineStart, firstElemStart).match(/^\s+/)?.[0] ?? " ";
687
- const indentedCode = code.replace(/\n/g, `\n${indent}`);
688
- text = `${text.slice(0, insertPos)}${separator}\n${indent}${indentedCode}${text.slice(insertPos)}`;
689
- } else text = `${text.slice(0, insertPos)}${separator} ${code}${text.slice(insertPos)}`;
690
+ anchor ??= items[items.length - 1];
691
+ let pos = anchor.getEnd();
692
+ const trailingComma = text.slice(pos).match(/^\s*,/);
693
+ if (trailingComma) pos += trailingComma[0].length;
694
+ const before = trailingComma ? "" : ",";
695
+ const after = trailingComma ? "," : "";
696
+ if (multiLine) {
697
+ const indent = indentAt(items[0].getStart());
698
+ splice(pos, pos, `${before}\n${indent}${reindent(code, indent)}${after}`);
699
+ } else splice(pos, pos, `${before} ${code}${after}`);
690
700
  }
691
- function addArrayProp(sf, propName, code) {
692
- const configObj = findConfigObject(sf);
693
- if (!configObj) throw new Error("Could not find Stencil config object in stencil.config.ts");
694
- let propIndent = " ";
695
- if (configObj.properties.length > 0) {
696
- const firstPropStart = configObj.properties[0].getStart();
697
- const lineStart = text.lastIndexOf("\n", firstPropStart) + 1;
698
- propIndent = text.slice(lineStart, firstPropStart).match(/^\s+/)?.[0] ?? " ";
699
- }
700
- const elemIndent = propIndent + " ";
701
- const newProp = `${propName}: [\n${elemIndent}${code.replace(/\n/g, `\n${elemIndent}`)},\n${propIndent}]`;
702
- const lastProp = configObj.properties[configObj.properties.length - 1];
703
- if (lastProp) {
704
- let insertPos = lastProp.getEnd();
705
- const trailingComma = text.slice(insertPos).match(/^\s*,/);
706
- const separator = trailingComma ? "" : ",";
707
- if (trailingComma) insertPos += trailingComma[0].length;
708
- text = `${text.slice(0, insertPos)}${separator}\n${propIndent}${newProp}${text.slice(insertPos)}`;
709
- } else {
710
- const insertPos = configObj.getEnd() - 1;
711
- text = `${text.slice(0, insertPos)}\n${propIndent}${newProp},\n${text.slice(insertPos)}`;
712
- }
701
+ function removeItem(arr, element) {
702
+ const idx = arr.elements.indexOf(element);
703
+ let start = element.getStart();
704
+ let end = element.getEnd();
705
+ if (isMultiLine(arr)) {
706
+ start = text.lastIndexOf("\n", start);
707
+ end += text.slice(end).match(/^\s*,/)?.[0].length ?? 0;
708
+ } else if (idx < arr.elements.length - 1) end += text.slice(end).match(/^,\s*/)?.[0].length ?? 0;
709
+ else if (idx > 0) start -= text.slice(0, start).match(/,\s*$/)?.[0].length ?? 0;
710
+ splice(start, end, "");
711
+ }
712
+ function hasImport(moduleSpecifier) {
713
+ return parse().statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier);
714
+ }
715
+ function arrayProp(propName) {
716
+ const findElement = (arr, substring) => arr?.elements.find((element) => nodeText(element).includes(substring));
717
+ return {
718
+ contains(substring) {
719
+ const arr = findArray(propName);
720
+ return arr ? nodeText(arr).includes(substring) : false;
721
+ },
722
+ add(expression) {
723
+ const arr = findArray(propName);
724
+ if (arr) insertItem(arr, expression);
725
+ else insertItem(requireConfigObject(), `${propName}: [\n ${reindent(expression, " ")},\n]`);
726
+ },
727
+ replace(substring, expression) {
728
+ const element = findElement(findArray(propName), substring);
729
+ if (!element) return false;
730
+ splice(element.getStart(), element.getEnd(), reindent(expression, indentAt(element.getStart())));
731
+ return true;
732
+ },
733
+ remove(substring) {
734
+ const arr = findArray(propName);
735
+ const element = findElement(arr, substring);
736
+ if (!arr || !element) return false;
737
+ removeItem(arr, element);
738
+ return true;
739
+ }
740
+ };
713
741
  }
742
+ const outputTargets = arrayProp("outputTargets");
743
+ const plugins = arrayProp("plugins");
714
744
  return {
715
- hasImport(moduleSpecifier) {
716
- return parse().statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier);
717
- },
745
+ hasImport,
718
746
  addImport(moduleSpecifier, namedImports) {
719
- const sf = parse();
720
- if (sf.statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier)) return;
721
- let insertPos = 0;
722
- for (const s of sf.statements) if (ts.isImportDeclaration(s)) insertPos = s.getEnd();
723
- const decl = `\nimport { ${namedImports.join(", ")} } from '${moduleSpecifier}';`;
724
- text = insertPos > 0 ? text.slice(0, insertPos) + decl + text.slice(insertPos) : decl + "\n" + text;
725
- },
726
- outputTargetsContains(substring) {
727
- const arr = findArray(parse(), "outputTargets");
728
- return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
729
- },
730
- addOutputTarget(expression) {
731
- const sf = parse();
732
- const arr = findArray(sf, "outputTargets");
733
- if (arr) appendToArray(arr, expression);
734
- else addArrayProp(sf, "outputTargets", expression);
735
- },
736
- replaceOutputTarget(substring, expression) {
737
- const arr = findArray(parse(), "outputTargets");
738
- return arr ? replaceInArray(arr, substring, expression) : false;
739
- },
740
- removeOutputTarget(substring) {
741
- const arr = findArray(parse(), "outputTargets");
742
- return arr ? removeFromArray(arr, substring) : false;
743
- },
744
- pluginsContains(substring) {
745
- const arr = findArray(parse(), "plugins");
746
- return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
747
- },
748
- addPlugin(expression) {
749
- const sf = parse();
750
- const arr = findArray(sf, "plugins");
751
- if (arr) appendToArray(arr, expression);
752
- else addArrayProp(sf, "plugins", expression);
753
- },
754
- replacePlugin(substring, expression) {
755
- const arr = findArray(parse(), "plugins");
756
- return arr ? replaceInArray(arr, substring, expression) : false;
747
+ if (hasImport(moduleSpecifier)) return;
748
+ const lastImport = parse().statements.filter(ts.isImportDeclaration).pop();
749
+ const decl = `import { ${namedImports.join(", ")} } from '${moduleSpecifier}';`;
750
+ if (lastImport) splice(lastImport.getEnd(), lastImport.getEnd(), `\n${decl}`);
751
+ else text = `\n${decl}\n${text}`;
757
752
  },
758
- removePlugin(substring) {
759
- const arr = findArray(parse(), "plugins");
760
- return arr ? removeFromArray(arr, substring) : false;
753
+ outputTargetsContains: outputTargets.contains,
754
+ addOutputTarget: outputTargets.add,
755
+ replaceOutputTarget: outputTargets.replace,
756
+ removeOutputTarget: outputTargets.remove,
757
+ pluginsContains: plugins.contains,
758
+ addPlugin: plugins.add,
759
+ replacePlugin: plugins.replace,
760
+ removePlugin: plugins.remove,
761
+ setProperty(name, expression) {
762
+ const configObj = requireConfigObject();
763
+ const existing = findProp(configObj, name);
764
+ if (existing) {
765
+ splice(existing.initializer.getStart(), existing.initializer.getEnd(), expression);
766
+ return;
767
+ }
768
+ insertItem(configObj, `${name}: ${expression}`, findProp(configObj, "namespace"));
761
769
  },
762
770
  async save() {
763
771
  await writeFile(configPath, text, "utf8");
@@ -769,7 +777,7 @@ async function openStencilConfig(configPath) {
769
777
  function toStringRecord(val) {
770
778
  return val !== null && typeof val === "object" ? val : {};
771
779
  }
772
- async function readJson$1(filePath) {
780
+ async function readJson(filePath) {
773
781
  try {
774
782
  return JSON.parse(await readFile(filePath, "utf8"));
775
783
  } catch {
@@ -809,7 +817,7 @@ async function loadOne(rootDir, packageName, loader) {
809
817
  * @returns Array of successfully loaded plugins, in dependency declaration order.
810
818
  */
811
819
  async function discoverPlugins(rootDir, loader = (url) => import(url)) {
812
- const pkg = await readJson$1(join(rootDir, "package.json"));
820
+ const pkg = await readJson(join(rootDir, "package.json"));
813
821
  if (!pkg) return [];
814
822
  const depNames = [.../* @__PURE__ */ new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
815
823
  const plugins = (await Promise.allSettled(depNames.map((name) => loadOne(rootDir, name, loader)))).filter((r) => r.status === "fulfilled" && r.value !== null).map((r) => r.value);
@@ -830,7 +838,7 @@ async function discoverPlugins(rootDir, loader = (url) => import(url)) {
830
838
  async function findDevPackageName(wizardPath) {
831
839
  const dir = dirname(wizardPath);
832
840
  for (const candidate of [dir, resolve(dir, "..")]) {
833
- const pkg = await readJson$1(join(candidate, "package.json"));
841
+ const pkg = await readJson(join(candidate, "package.json"));
834
842
  if (typeof pkg?.name === "string") return pkg.name;
835
843
  }
836
844
  return basename(dir);
@@ -973,6 +981,7 @@ async function promptOutputs() {
973
981
  hint: "app mode with dev server and optional PWA support"
974
982
  }
975
983
  ],
984
+ initialValues: ["loader"],
976
985
  required: false
977
986
  });
978
987
  cancelIfAborted(picks);
@@ -987,6 +996,11 @@ async function promptFeatures() {
987
996
  label: "Signals",
988
997
  hint: "signal-backed @Prop/@State for cross-framework reactive interop"
989
998
  },
999
+ {
1000
+ value: "exportMaps",
1001
+ label: "Export maps",
1002
+ hint: "keep package.json \"exports\" in sync with your outputs and components on each build"
1003
+ },
990
1004
  {
991
1005
  value: "globalStyle",
992
1006
  label: "Global style",
@@ -1004,6 +1018,7 @@ async function promptFeatures() {
1004
1018
  const set = new Set(picks);
1005
1019
  return {
1006
1020
  signals: set.has("signals"),
1021
+ exportMaps: set.has("exportMaps"),
1007
1022
  globalStyle: set.has("globalStyle"),
1008
1023
  globalScript: set.has("globalScript")
1009
1024
  };
@@ -1133,6 +1148,35 @@ async function promptAddCapabilities(installable, configurable) {
1133
1148
  }
1134
1149
  //#endregion
1135
1150
  //#region src/wizard/project.ts
1151
+ const PACKAGE_MANAGERS = [
1152
+ "npm",
1153
+ "pnpm",
1154
+ "yarn",
1155
+ "bun"
1156
+ ];
1157
+ /**
1158
+ * Resolve the package manager for `cwd`: a `packageManager` field / lockfile in the project
1159
+ * or its workspace wins, then whichever package manager launched this process, then npm.
1160
+ * @param cwd The directory to detect from. Parent directories are searched up to, but not
1161
+ * including, the home directory - a lockfile there doesn't describe this project.
1162
+ * @returns The package manager name.
1163
+ */
1164
+ async function detectPackageManager$1(cwd) {
1165
+ const home = homedir();
1166
+ let dir = cwd;
1167
+ while (true) {
1168
+ const fromProject = await detectPackageManager(dir, {
1169
+ ignoreArgv: true,
1170
+ includeParentDirs: false
1171
+ });
1172
+ if (fromProject) return fromProject.name;
1173
+ const parent = dirname(dir);
1174
+ if (parent === dir || parent === home) break;
1175
+ dir = parent;
1176
+ }
1177
+ const invoker = process.env.npm_config_user_agent?.split("/")[0];
1178
+ return PACKAGE_MANAGERS.find((name) => name === invoker) ?? "npm";
1179
+ }
1136
1180
  /**
1137
1181
  * Extracts the stable, plugin-relevant fields from a fully-resolved compiler config.
1138
1182
  * @param validated The fully-resolved compiler config.
@@ -1149,7 +1193,8 @@ function toProjectConfig(validated) {
1149
1193
  globalScript: validated.globalScript,
1150
1194
  globalStyle: validated.globalStyle,
1151
1195
  compat: validated.compat,
1152
- signalBacking: validated.signalBacking
1196
+ signalBacking: validated.signalBacking,
1197
+ generateExportMaps: validated.generateExportMaps
1153
1198
  };
1154
1199
  }
1155
1200
  /**
@@ -1208,9 +1253,19 @@ async function isExistingStencilProject(dir) {
1208
1253
  return false;
1209
1254
  }
1210
1255
  }
1256
+ /**
1257
+ * npm silently omits devDependencies when this CLI is itself running as a nested child
1258
+ * process (e.g. via `npx create-stencil` / `npm init stencil`). Root cause: npm/exec only
1259
+ * needs @stencil/cli's own regular dependencies to resolve+run it, so that install computes
1260
+ * `omit: ['dev']` - and per npm's own config flattening
1261
+ * (@npmcli/config/lib/definitions/definitions.js). Causing NODE_ENV === 'production'.
1262
+ */
1263
+ function clearInheritedProductionEnv() {
1264
+ if (process.env.NODE_ENV === "production") delete process.env.NODE_ENV;
1265
+ }
1211
1266
  //#endregion
1212
1267
  //#region src/wizard/splash.ts
1213
- const CLI_VERSION = "5.0.0-beta.2";
1268
+ const CLI_VERSION = "5.0.0-beta.21";
1214
1269
  const isTTY = process.stdout.isTTY;
1215
1270
  const noColor = !isTTY || "NO_COLOR" in process.env;
1216
1271
  const RESET = noColor ? "" : "\x1B[0m";
@@ -1299,6 +1354,7 @@ async function taskAdd(packages, strictConfig) {
1299
1354
  p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil add`.");
1300
1355
  process.exit(1);
1301
1356
  }
1357
+ clearInheritedProductionEnv();
1302
1358
  let packagesToInstall = packages;
1303
1359
  let pluginsToReconfigure = [];
1304
1360
  if (packages.length === 0) ({packagesToInstall, pluginsToReconfigure} = await selectInteractive(cwd));
@@ -1344,10 +1400,10 @@ async function taskAdd(packages, strictConfig) {
1344
1400
  * @param config the Stencil configuration associated with the currently compiled project
1345
1401
  * @param currentVersion the Stencil compiler's version string
1346
1402
  * @param flags the CLI flags (owned by CLI, not part of core config)
1347
- * @returns a reference to `checkVersion`, or `null` if one does not exist on the current `CompilerSystem`
1403
+ * @returns a reference to `checkVersion`, or `null` if the check is skipped
1348
1404
  */
1349
1405
  const startCheckVersion = async (config, currentVersion, flags) => {
1350
- if (config.devMode && !flags.ci && !currentVersion.includes("-dev.") && isFunction(config.sys.checkVersion)) return config.sys.checkVersion(config.logger, currentVersion);
1406
+ if (config.devMode && !flags.ci && !currentVersion.includes("-dev.")) return config.sys.checkVersion(config.logger, currentVersion);
1351
1407
  return null;
1352
1408
  };
1353
1409
  /**
@@ -1966,11 +2022,23 @@ const formAssociatedRule = {
1966
2022
  * Migration mapping:
1967
2023
  * - `addGlobalStyleToComponents: true` → `inject: 'all'`
1968
2024
  * - `addGlobalStyleToComponents: 'client'` → `inject: 'client'`
1969
- * - `addGlobalStyleToComponents: false` → omit (default is 'none')
2025
+ * - `addGlobalStyleToComponents: false` → `inject: 'none'` (a stylesheet from `globalStyle` defaults
2026
+ * to `'client'`, so omitting it would start injecting)
2027
+ *
2028
+ * The top-level `globalStyle` option moves into the new output target as well, so the config
2029
+ * isn't left describing one stylesheet in two places:
2030
+ *
2031
+ * ```ts
2032
+ * { type: 'global-style', input: 'src/global/app.css', fileName: 'my-lib.css', inject: 'none', copyToLoaderBrowser: true }
2033
+ * ```
1970
2034
  *
1971
- * Note: This migration only acts on explicitly set `addGlobalStyleToComponents`.
1972
- * Users who relied on the implicit v4 default ('client') will need to manually
1973
- * add `inject: 'client'` to their global-style output target if desired.
2035
+ * `fileName` is written (from `namespace`) because a target with an explicit `input` otherwise
2036
+ * names its output after the input file, where `globalStyle` used `{namespace}.css`.
2037
+ * When `globalStyle` isn't a string literal in the config (e.g. the stylesheet is auto-detected
2038
+ * from `src/global.*`), only `{ type: 'global-style', inject }` is written.
2039
+ *
2040
+ * Note: This migration only acts on explicitly set `addGlobalStyleToComponents`. A config
2041
+ * without it keeps `globalStyle` as it is, which still injects on the client as v4 did.
1974
2042
  */
1975
2043
  const globalStyleInjectRule = {
1976
2044
  id: "global-style-inject",
@@ -2002,79 +2070,97 @@ const globalStyleInjectRule = {
2002
2070
  return matches;
2003
2071
  },
2004
2072
  transform(sourceFile, matches) {
2005
- if (matches.length === 0) return sourceFile.getFullText();
2006
- let text = sourceFile.getFullText();
2073
+ const original = sourceFile.getFullText();
2074
+ if (matches.length === 0) return original;
2007
2075
  const matchNode = matches[0].node;
2008
- if (!ts.isPropertyAssignment(matchNode)) return text;
2076
+ if (!ts.isPropertyAssignment(matchNode)) return original;
2009
2077
  let injectValue = null;
2010
2078
  if (matchNode.initializer.kind === ts.SyntaxKind.TrueKeyword) injectValue = "all";
2011
2079
  else if (ts.isStringLiteral(matchNode.initializer) && matchNode.initializer.text === "client") injectValue = "client";
2012
- let insertionOffset = 0;
2013
- if (injectValue) {
2014
- const result = addGlobalStyleOutputTarget(text, sourceFile, injectValue);
2015
- insertionOffset = result.length - text.length;
2016
- text = result;
2017
- }
2018
- let start = matchNode.getStart();
2019
- let end = matchNode.getEnd();
2020
- const outputTargetsEnd = findOutputTargetsEnd(sourceFile);
2021
- if (insertionOffset !== 0 && outputTargetsEnd !== null && matchNode.getStart() > outputTargetsEnd) {
2022
- start += insertionOffset;
2023
- end += insertionOffset;
2024
- }
2025
- const afterProp = text.slice(end).match(/^\s*,/);
2026
- if (afterProp) end = end + afterProp[0].length;
2027
- else {
2028
- const beforeProp = text.slice(0, start).match(/,\s*$/);
2029
- if (beforeProp) {
2030
- text = text.slice(0, start - beforeProp[0].length) + text.slice(end);
2031
- end = -1;
2080
+ else if (matchNode.initializer.kind === ts.SyntaxKind.FalseKeyword) injectValue = "none";
2081
+ const edits = [removalOf(original, matchNode)];
2082
+ const outputTargets = findTopLevelProperty(sourceFile, "outputTargets");
2083
+ const hasGlobalStyleTarget = original.includes("type: 'global-style'");
2084
+ if (injectValue && !hasGlobalStyleTarget && outputTargets && ts.isArrayLiteralExpression(outputTargets.initializer)) {
2085
+ const globalStyle = findTopLevelProperty(sourceFile, "globalStyle");
2086
+ const namespace = findTopLevelProperty(sourceFile, "namespace");
2087
+ const props = [`type: 'global-style'`];
2088
+ if (globalStyle && ts.isStringLiteralLike(globalStyle.initializer)) {
2089
+ props.push(`input: ${globalStyle.initializer.getText()}`);
2090
+ if (namespace && ts.isStringLiteralLike(namespace.initializer)) props.push(`fileName: '${namespace.initializer.text.toLowerCase().trim()}.css'`);
2091
+ edits.push(removalOf(original, globalStyle));
2032
2092
  }
2093
+ props.push(`inject: '${injectValue}'`);
2094
+ if (props.length > 2) props.push(`copyToLoaderBrowser: true`);
2095
+ edits.push(insertionOfOutputTarget(original, outputTargets.initializer, props));
2033
2096
  }
2034
- if (end !== -1) text = text.slice(0, start) + text.slice(end);
2035
- text = cleanupEmptyExtras$1(text);
2036
- return text;
2097
+ let text = original;
2098
+ for (const edit of edits.sort((a, b) => b.start - a.start)) text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
2099
+ return cleanupEmptyExtras$1(text);
2037
2100
  }
2038
2101
  };
2039
2102
  /**
2040
- * Find the end position of the outputTargets array in the source file.
2103
+ * Find a property of the exported config object, e.g. `globalStyle` or `outputTargets`.
2041
2104
  * @param sourceFile The source file to search
2042
- * @returns The end position of the outputTargets array, or null if not found
2105
+ * @param name The property name
2106
+ * @returns The property assignment, or null if the config has no such top-level property
2043
2107
  */
2044
- function findOutputTargetsEnd(sourceFile) {
2045
- let endPos = null;
2046
- const visit = (node) => {
2047
- if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets") endPos = node.getEnd();
2048
- ts.forEachChild(node, visit);
2108
+ function findTopLevelProperty(sourceFile, name) {
2109
+ let found = null;
2110
+ const visit = (node, depth) => {
2111
+ if (found) return;
2112
+ if (ts.isObjectLiteralExpression(node)) {
2113
+ if (depth > 0) return;
2114
+ for (const prop of node.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === name) {
2115
+ found = prop;
2116
+ return;
2117
+ }
2118
+ return;
2119
+ }
2120
+ ts.forEachChild(node, (child) => visit(child, depth));
2049
2121
  };
2050
- visit(sourceFile);
2051
- return endPos;
2122
+ visit(sourceFile, 0);
2123
+ return found;
2052
2124
  }
2053
2125
  /**
2054
- * Clean up empty extras object after removing addGlobalStyleToComponents.
2055
- * @param text The source text to clean up
2056
- * @returns The cleaned up text with empty extras removed
2126
+ * Build the edit that removes a property, together with its trailing comma and its own line.
2127
+ * @param text The original source text
2128
+ * @param node The property to remove
2129
+ * @returns The edit
2057
2130
  */
2058
- function cleanupEmptyExtras$1(text) {
2059
- return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
2131
+ function removalOf(text, node) {
2132
+ let start = node.getStart();
2133
+ let end = node.getEnd();
2134
+ const trailingComma = text.slice(end).match(/^\s*,/);
2135
+ if (trailingComma) end += trailingComma[0].length;
2136
+ else {
2137
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
2138
+ if (leadingComma) return {
2139
+ start: start - leadingComma[0].length,
2140
+ end,
2141
+ text: ""
2142
+ };
2143
+ }
2144
+ const lineStart = text.lastIndexOf("\n", start - 1) + 1;
2145
+ const restOfLine = text.slice(end).match(/^[ \t]*\n/);
2146
+ if (/^[ \t]*$/.test(text.slice(lineStart, start)) && restOfLine) {
2147
+ start = lineStart;
2148
+ end += restOfLine[0].length;
2149
+ }
2150
+ return {
2151
+ start,
2152
+ end,
2153
+ text: ""
2154
+ };
2060
2155
  }
2061
2156
  /**
2062
- * Add a global-style output target with the specified inject value.
2063
- * @param text The source text to modify
2064
- * @param sourceFile The source file for position info
2065
- * @param injectValue The inject value to set on the new global-style output target
2066
- * @returns The modified text with the new global-style output target added
2157
+ * Build the edit that appends a `global-style` output target to the `outputTargets` array.
2158
+ * @param text The original source text
2159
+ * @param array The `outputTargets` array
2160
+ * @param props The new output target's properties, as source text
2161
+ * @returns The edit
2067
2162
  */
2068
- function addGlobalStyleOutputTarget(text, sourceFile, injectValue) {
2069
- if (text.includes("type: 'global-style'")) return text;
2070
- let outputTargetsArray = null;
2071
- const findOutputTargets = (node) => {
2072
- if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) outputTargetsArray = node.initializer;
2073
- ts.forEachChild(node, findOutputTargets);
2074
- };
2075
- findOutputTargets(sourceFile);
2076
- if (!outputTargetsArray) return text;
2077
- const array = outputTargetsArray;
2163
+ function insertionOfOutputTarget(text, array, props) {
2078
2164
  let indent = " ";
2079
2165
  if (array.elements.length > 0) {
2080
2166
  const elemStart = array.elements[0].getStart();
@@ -2082,19 +2168,33 @@ function addGlobalStyleOutputTarget(text, sourceFile, injectValue) {
2082
2168
  const leadingWhitespace = text.slice(lineStart, elemStart);
2083
2169
  if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
2084
2170
  }
2171
+ const newTarget = `{\n${props.map((prop) => `${indent} ${prop},\n`).join("")}${indent}}`;
2085
2172
  const lastElement = array.elements[array.elements.length - 1];
2086
2173
  if (!lastElement) {
2087
2174
  const arrayStart = array.getStart() + 1;
2088
- const newTarget = `\n${indent}{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}\n${indent.slice(2)}`;
2089
- return text.slice(0, arrayStart) + newTarget + text.slice(arrayStart);
2175
+ return {
2176
+ start: arrayStart,
2177
+ end: arrayStart,
2178
+ text: `\n${indent}${newTarget}\n${indent.slice(2)}`
2179
+ };
2090
2180
  }
2091
2181
  let insertPos = lastElement.getEnd();
2092
2182
  const afterLastElement = text.slice(insertPos).match(/^(\s*,)?/);
2093
2183
  const hasTrailingComma = afterLastElement && afterLastElement[1];
2094
2184
  if (hasTrailingComma) insertPos += afterLastElement[0].length;
2095
- const newTarget = `{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}`;
2096
- const insertion = (hasTrailingComma ? "" : ",") + "\n" + indent + newTarget;
2097
- return text.slice(0, insertPos) + insertion + text.slice(insertPos);
2185
+ return {
2186
+ start: insertPos,
2187
+ end: insertPos,
2188
+ text: (hasTrailingComma ? "" : ",") + "\n" + indent + newTarget
2189
+ };
2190
+ }
2191
+ /**
2192
+ * Clean up empty extras object after removing addGlobalStyleToComponents.
2193
+ * @param text The source text to clean up
2194
+ * @returns The cleaned up text with empty extras removed
2195
+ */
2196
+ function cleanupEmptyExtras$1(text) {
2197
+ return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
2098
2198
  }
2099
2199
  //#endregion
2100
2200
  //#region src/migrations/rules/hash-file-names.ts
@@ -3143,7 +3243,6 @@ const taskWatch = async (coreCompiler, config, flags) => {
3143
3243
  const versionChecker = startCheckVersion(config, coreCompiler.version, flags);
3144
3244
  const compiler = await coreCompiler.createCompiler(config);
3145
3245
  const watcher = await compiler.createWatcher();
3146
- if (!config.sys.onProcessInterrupt) throw new Error(`Environment doesn't provide required function: onProcessInterrupt`);
3147
3246
  if (flags.serve) {
3148
3247
  const { start } = await import("@stencil/dev-server");
3149
3248
  devServer = await start(config.devServer, config.logger, watcher);
@@ -3173,473 +3272,6 @@ const taskWatch = async (coreCompiler, config, flags) => {
3173
3272
  if (exitCode > 0) return config.sys.exit(exitCode);
3174
3273
  };
3175
3274
  //#endregion
3176
- //#region src/telemetry/helpers.ts
3177
- const tryFn = async (fn, ...args) => {
3178
- try {
3179
- return await fn(...args);
3180
- } catch {}
3181
- return null;
3182
- };
3183
- const isInteractive = (sys, flags, object) => {
3184
- const terminalInfo = object || Object.freeze({
3185
- tty: sys.isTTY(),
3186
- ci: [
3187
- "CI",
3188
- "BUILD_ID",
3189
- "BUILD_NUMBER",
3190
- "BITBUCKET_COMMIT",
3191
- "CODEBUILD_BUILD_ARN"
3192
- ].filter((v) => !!sys.getEnvironmentVar?.(v)).length > 0 || !!flags.ci
3193
- });
3194
- return terminalInfo.tty && !terminalInfo.ci;
3195
- };
3196
- const UUID_REGEX = /* @__PURE__ */ new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i);
3197
- function uuidv4() {
3198
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
3199
- const r = Math.random() * 16 | 0;
3200
- return (c == "x" ? r : r & 3 | 8).toString(16);
3201
- });
3202
- }
3203
- /**
3204
- * Reads and parses a JSON file from the given `path`
3205
- * @param sys The system where the command is invoked
3206
- * @param path the path on the file system to read and parse
3207
- * @returns the parsed JSON
3208
- */
3209
- async function readJson(sys, path) {
3210
- const file = await sys.readFile(path);
3211
- return file ? JSON.parse(file) : null;
3212
- }
3213
- /**
3214
- * Does the command have the debug flag?
3215
- * @param flags The configuration flags passed into the Stencil command
3216
- * @returns true if --debug has been passed, otherwise false
3217
- */
3218
- function hasDebug(flags) {
3219
- return !!flags.debug;
3220
- }
3221
- /**
3222
- * Does the command have the verbose and debug flags?
3223
- * @param flags The configuration flags passed into the Stencil command
3224
- * @returns true if both --debug and --verbose have been passed, otherwise false
3225
- */
3226
- function hasVerbose(flags) {
3227
- return !!flags.verbose && hasDebug(flags);
3228
- }
3229
- //#endregion
3230
- //#region src/ionic-config.ts
3231
- const isTest = () => process.env.JEST_WORKER_ID !== void 0;
3232
- const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest() ? "tmp-config.json" : "config.json"}`);
3233
- const defaultConfigDirectory = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic`);
3234
- /**
3235
- * Reads an Ionic configuration file from disk, parses it, and performs any necessary corrections to it if certain
3236
- * values are deemed to be malformed
3237
- * @param sys The system where the command is invoked
3238
- * @returns the config read from disk that has been potentially been updated
3239
- */
3240
- async function readConfig(sys) {
3241
- let config = await readJson(sys, defaultConfig(sys));
3242
- if (!config) {
3243
- config = {
3244
- "tokens.telemetry": uuidv4(),
3245
- "telemetry.stencil": true
3246
- };
3247
- await writeConfig(sys, config);
3248
- } else if (!config["tokens.telemetry"] || !UUID_REGEX.test(config["tokens.telemetry"])) {
3249
- const newUuid = uuidv4();
3250
- await writeConfig(sys, {
3251
- ...config,
3252
- "tokens.telemetry": newUuid
3253
- });
3254
- config["tokens.telemetry"] = newUuid;
3255
- }
3256
- return config;
3257
- }
3258
- /**
3259
- * Writes an Ionic configuration file to disk.
3260
- * @param sys The system where the command is invoked
3261
- * @param config The config passed into the Stencil command
3262
- * @returns boolean If the command was successful
3263
- */
3264
- async function writeConfig(sys, config) {
3265
- let result = false;
3266
- try {
3267
- await sys.createDir(defaultConfigDirectory(sys), { recursive: true });
3268
- await sys.writeFile(defaultConfig(sys), JSON.stringify(config, null, 2));
3269
- result = true;
3270
- } catch (error) {
3271
- console.error(`Stencil Telemetry: couldn't write configuration file to ${defaultConfig(sys)} - ${error}.`);
3272
- }
3273
- return result;
3274
- }
3275
- /**
3276
- * Update a subset of the Ionic config.
3277
- * @param sys The system where the command is invoked
3278
- * @param newOptions The new options to save
3279
- * @returns boolean If the command was successful
3280
- */
3281
- async function updateConfig(sys, newOptions) {
3282
- const config = await readConfig(sys);
3283
- return await writeConfig(sys, Object.assign(config, newOptions));
3284
- }
3285
- //#endregion
3286
- //#region src/telemetry/shouldTrack.ts
3287
- /**
3288
- * Used to determine if tracking should occur.
3289
- * @param sys The system where the command is invoked
3290
- * @param flags The CLI flags (owned by CLI, not part of core config)
3291
- * @param ci whether or not the process is running in a Continuous Integration (CI) environment
3292
- * @returns true if telemetry should be sent, false otherwise
3293
- */
3294
- async function shouldTrack(sys, flags, ci) {
3295
- return !ci && isInteractive(sys, flags) && await checkTelemetry(sys);
3296
- }
3297
- //#endregion
3298
- //#region src/telemetry/telemetry.ts
3299
- /**
3300
- * Used to within taskBuild to provide the component_count property.
3301
- *
3302
- * @param sys The system where the command is invoked
3303
- * @param config The config passed into the Stencil command
3304
- * @param coreCompiler The compiler used to do builds
3305
- * @param result The results of a compiler build.
3306
- * @param flags The CLI flags (owned by CLI, not part of core config)
3307
- */
3308
- async function telemetryBuildFinishedAction(sys, config, coreCompiler, result, flags) {
3309
- if (!await shouldTrack(sys, flags, !!flags.ci)) return;
3310
- const component_count = result.componentGraph ? Object.keys(result.componentGraph).length : void 0;
3311
- const data = await prepareData(coreCompiler, config, sys, flags, result.duration, component_count);
3312
- await sendMetric(sys, flags, "stencil_cli_command", data);
3313
- config.logger.debug(`${config.logger.blue("Telemetry")}: ${config.logger.gray(JSON.stringify(data))}`);
3314
- }
3315
- /**
3316
- * A function to wrap a compiler task function around. Will send telemetry if, and only if, the machine allows.
3317
- *
3318
- * @param sys The system where the command is invoked
3319
- * @param config The config passed into the Stencil command
3320
- * @param coreCompiler The compiler used to do builds
3321
- * @param flags The CLI flags (owned by CLI, not part of core config)
3322
- * @param action A Promise-based function to call in order to get the duration of any given command.
3323
- * @returns void
3324
- */
3325
- async function telemetryAction(sys, config, coreCompiler, flags, action) {
3326
- const tracking = await shouldTrack(sys, flags, !!flags.ci);
3327
- let duration = void 0;
3328
- let error;
3329
- if (action) {
3330
- const start = /* @__PURE__ */ new Date();
3331
- try {
3332
- await action();
3333
- } catch (e) {
3334
- error = e;
3335
- }
3336
- duration = (/* @__PURE__ */ new Date()).getTime() - start.getTime();
3337
- }
3338
- if (!tracking || flags.task == "build" && !flags.args.includes("--watch")) return;
3339
- const data = await prepareData(coreCompiler, config, sys, flags, duration);
3340
- await sendMetric(sys, flags, "stencil_cli_command", data);
3341
- config.logger.debug(`${config.logger.blue("Telemetry")}: ${config.logger.gray(JSON.stringify(data))}`);
3342
- if (error) throw error;
3343
- }
3344
- /**
3345
- * Helper function to determine if a Stencil configuration builds an application.
3346
- *
3347
- * This function is a rough approximation whether an application is generated as a part of a Stencil build, based on
3348
- * contents of the project's `stencil.config.ts` file.
3349
- *
3350
- * @param config the configuration used by the Stencil project
3351
- * @returns true if we believe the project generates an application, false otherwise
3352
- */
3353
- function hasAppTarget(config) {
3354
- return config.outputTargets.some((target) => isOutputTargetWww(target) && (!!target.serviceWorker || !!target.baseUrl && target.baseUrl !== "/"));
3355
- }
3356
- function isUsingYarn(sys) {
3357
- return sys.getEnvironmentVar?.("npm_execpath")?.includes("yarn") || false;
3358
- }
3359
- /**
3360
- * Build a list of the different types of output targets used in a Stencil configuration.
3361
- *
3362
- * Duplicate entries will not be returned from the list
3363
- *
3364
- * @param config the configuration used by the Stencil project
3365
- * @returns a unique list of output target types found in the Stencil configuration
3366
- */
3367
- function getActiveTargets(config) {
3368
- const result = config.outputTargets.map((t) => t.type);
3369
- return Array.from(new Set(result));
3370
- }
3371
- /**
3372
- * Prepare data for telemetry
3373
- *
3374
- * @param coreCompiler the core compiler
3375
- * @param config the current Stencil config
3376
- * @param sys the compiler system instance in use
3377
- * @param flags the CLI flags (owned by CLI, not part of core config)
3378
- * @param duration_ms the duration of the action being tracked
3379
- * @param component_count the number of components being built (optional)
3380
- * @returns a Promise wrapping data for the telemetry endpoint
3381
- */
3382
- const prepareData = async (coreCompiler, config, sys, flags, duration_ms, component_count = void 0) => {
3383
- const { typescript, rolldown } = coreCompiler.versions || {
3384
- typescript: "unknown",
3385
- rolldown: "unknown"
3386
- };
3387
- const { packages, packagesNoVersions } = await getInstalledPackages(sys, flags);
3388
- const targets = getActiveTargets(config);
3389
- const yarn = isUsingYarn(sys);
3390
- const stencil = coreCompiler.version || "unknown";
3391
- const system = `${sys.name} ${sys.version}`;
3392
- const os_name = sys.details?.platform;
3393
- const os_version = sys.details?.release;
3394
- const cpu_model = sys.details?.cpuModel;
3395
- const build = coreCompiler.buildId || "unknown";
3396
- const has_app_pwa_config = hasAppTarget(config);
3397
- const anonymizedConfig = anonymizeConfigForTelemetry(config);
3398
- return {
3399
- arguments: flags.args,
3400
- build,
3401
- component_count,
3402
- config: anonymizedConfig,
3403
- cpu_model,
3404
- duration_ms,
3405
- has_app_pwa_config,
3406
- os_name,
3407
- os_version,
3408
- packages,
3409
- packages_no_versions: packagesNoVersions,
3410
- rolldown,
3411
- stencil,
3412
- system,
3413
- system_major: getMajorVersion(system),
3414
- targets,
3415
- task: flags.task,
3416
- typescript,
3417
- yarn
3418
- };
3419
- };
3420
- const OUTPUT_TARGET_KEYS_TO_KEEP = ["type"];
3421
- const CONFIG_PROPS_TO_ANONYMIZE = [
3422
- "rootDir",
3423
- "fsNamespace",
3424
- "packageJsonFilePath",
3425
- "namespace",
3426
- "srcDir",
3427
- "srcIndexHtml",
3428
- "buildLogFilePath",
3429
- "cacheDir",
3430
- "configPath",
3431
- "tsconfig"
3432
- ];
3433
- const CONFIG_PROPS_TO_DELETE = [
3434
- "devServer",
3435
- "env",
3436
- "logger",
3437
- "rolldownConfig",
3438
- "sys",
3439
- "tsCompilerOptions"
3440
- ];
3441
- /**
3442
- * Anonymize the config for telemetry, replacing potentially revealing config props
3443
- * with a placeholder string if they are present (this lets us still track how frequently
3444
- * these config options are being used)
3445
- *
3446
- * @param config the config to anonymize
3447
- * @returns an anonymized copy of the same config
3448
- */
3449
- const anonymizeConfigForTelemetry = (config) => {
3450
- const anonymizedConfig = { ...config };
3451
- for (const prop of CONFIG_PROPS_TO_ANONYMIZE) if (anonymizedConfig[prop] !== void 0) anonymizedConfig[prop] = "omitted";
3452
- anonymizedConfig.outputTargets = config.outputTargets.map((target) => {
3453
- const anonymizedOT = JSON.parse(JSON.stringify(target, (key, value) => {
3454
- if (!(typeof value === "string")) return value;
3455
- if (OUTPUT_TARGET_KEYS_TO_KEEP.includes(key)) return value;
3456
- return "omitted";
3457
- }));
3458
- if (isOutputTargetSsr(target) && target.external) anonymizedOT["external"] = target.external.concat();
3459
- return anonymizedOT;
3460
- });
3461
- for (const prop of CONFIG_PROPS_TO_DELETE) delete anonymizedConfig[prop];
3462
- return anonymizedConfig;
3463
- };
3464
- /**
3465
- * Reads package-lock.json, yarn.lock, and package.json files in order to cross-reference
3466
- * the dependencies and devDependencies properties. Pulls up the current installed version
3467
- * of each package under the @stencil, @ionic, and @capacitor scopes.
3468
- *
3469
- * @param sys the system instance where telemetry is invoked
3470
- * @param flags the CLI flags (owned by CLI, not part of core config)
3471
- * @returns an object listing all dev and production dependencies under the aforementioned scopes
3472
- */
3473
- async function getInstalledPackages(sys, flags) {
3474
- let packages = [];
3475
- let packagesNoVersions = [];
3476
- const yarn = isUsingYarn(sys);
3477
- try {
3478
- const appRootDir = sys.getCurrentDirectory();
3479
- const packageJson = await tryFn(readJson, sys, sys.resolvePath(appRootDir + "/package.json"));
3480
- if (!packageJson) return {
3481
- packages,
3482
- packagesNoVersions
3483
- };
3484
- const ionicPackages = Object.entries({
3485
- ...packageJson.devDependencies,
3486
- ...packageJson.dependencies
3487
- }).filter(([k]) => k.startsWith("@stencil/") || k.startsWith("@ionic/") || k.startsWith("@capacitor/"));
3488
- try {
3489
- packages = yarn ? await yarnPackages(sys, ionicPackages) : await npmPackages(sys, ionicPackages);
3490
- } catch {
3491
- packages = ionicPackages.map(([k, v]) => `${k}@${v.replace("^", "")}`);
3492
- }
3493
- packagesNoVersions = ionicPackages.map(([k]) => `${k}`);
3494
- return {
3495
- packages,
3496
- packagesNoVersions
3497
- };
3498
- } catch (err) {
3499
- if (hasDebug(flags)) console.error(err);
3500
- return {
3501
- packages,
3502
- packagesNoVersions
3503
- };
3504
- }
3505
- }
3506
- /**
3507
- * Visits the npm lock file to find the exact versions that are installed
3508
- * @param sys The system where the command is invoked
3509
- * @param ionicPackages a list of the found packages matching `@stencil`, `@capacitor`, or `@ionic` from the package.json file.
3510
- * @returns an array of strings of all the packages and their versions.
3511
- */
3512
- async function npmPackages(sys, ionicPackages) {
3513
- const appRootDir = sys.getCurrentDirectory();
3514
- const packageLockJson = await tryFn(readJson, sys, sys.resolvePath(appRootDir + "/package-lock.json"));
3515
- return ionicPackages.map(([k, v]) => {
3516
- let version = packageLockJson?.dependencies[k]?.version ?? packageLockJson?.devDependencies[k]?.version ?? v;
3517
- version = version.includes("file:") ? sanitizeDeclaredVersion(v) : version;
3518
- return `${k}@${version}`;
3519
- });
3520
- }
3521
- /**
3522
- * Visits the yarn lock file to find the exact versions that are installed
3523
- * @param sys The system where the command is invoked
3524
- * @param ionicPackages a list of the found packages matching `@stencil`, `@capacitor`, or `@ionic` from the package.json file.
3525
- * @returns an array of strings of all the packages and their versions.
3526
- */
3527
- async function yarnPackages(sys, ionicPackages) {
3528
- const appRootDir = sys.getCurrentDirectory();
3529
- const yarnLock = sys.readFileSync(sys.resolvePath(appRootDir + "/yarn.lock"));
3530
- const yarnLockYml = sys.parseYarnLockFile?.(yarnLock);
3531
- return ionicPackages.map(([k, v]) => {
3532
- const identifiedVersion = `${k}@${v}`;
3533
- let version = yarnLockYml?.object[identifiedVersion]?.version;
3534
- version = version && version.includes("undefined") ? sanitizeDeclaredVersion(identifiedVersion) : version;
3535
- return `${k}@${version}`;
3536
- });
3537
- }
3538
- /**
3539
- * This function is used for fallback purposes, where an npm or yarn lock file doesn't exist in the consumers directory.
3540
- * This will strip away '*', '^' and '~' from the declared package versions in a package.json.
3541
- * @param version the raw semver pattern identifier version string
3542
- * @returns a cleaned up representation without any qualifiers
3543
- */
3544
- function sanitizeDeclaredVersion(version) {
3545
- return version.replace(/[*^~]/g, "");
3546
- }
3547
- /**
3548
- * If telemetry is enabled, send a metric to an external data store
3549
- *
3550
- * @param sys the system instance where telemetry is invoked
3551
- * @param flags the CLI flags (owned by CLI, not part of core config)
3552
- * @param name the name of a trackable metric. Note this name is not necessarily a scalar value to track, like
3553
- * "Stencil Version". For example, "stencil_cli_command" is a name that is used to track all CLI command information.
3554
- * @param value the data to send to the external data store under the provided name argument
3555
- */
3556
- async function sendMetric(sys, flags, name, value) {
3557
- const session_id = await getTelemetryToken(sys);
3558
- await sendTelemetry(sys, flags, {
3559
- name,
3560
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3561
- source: "stencil_cli",
3562
- value,
3563
- session_id
3564
- });
3565
- }
3566
- /**
3567
- * Used to read the config file's tokens.telemetry property.
3568
- *
3569
- * @param sys The system where the command is invoked
3570
- * @returns string
3571
- */
3572
- async function getTelemetryToken(sys) {
3573
- const config = await readConfig(sys);
3574
- if (config["tokens.telemetry"] === void 0) {
3575
- config["tokens.telemetry"] = uuidv4();
3576
- await writeConfig(sys, config);
3577
- }
3578
- return config["tokens.telemetry"];
3579
- }
3580
- /**
3581
- * Issues a request to the telemetry server.
3582
- * @param sys The system where the command is invoked
3583
- * @param flags The CLI flags (owned by CLI, not part of core config)
3584
- * @param data Data to be tracked
3585
- */
3586
- async function sendTelemetry(sys, flags, data) {
3587
- try {
3588
- const now = (/* @__PURE__ */ new Date()).toISOString();
3589
- const body = {
3590
- metrics: [data],
3591
- sent_at: now
3592
- };
3593
- if (!sys.fetch) throw new Error("No fetch implementation available");
3594
- const response = await sys.fetch("https://api.ionicjs.com/events/metrics", {
3595
- method: "POST",
3596
- headers: { "Content-Type": "application/json" },
3597
- body: JSON.stringify(body)
3598
- });
3599
- if (hasVerbose(flags)) console.debug("\nSent %O metric to events service (status: %O)", data.name, response.status, "\n");
3600
- if (response.status !== 204 && hasVerbose(flags)) console.debug("\nBad response from events service. Request body: %O", response.body.toString(), "\n");
3601
- } catch (e) {
3602
- if (hasVerbose(flags)) console.debug("Telemetry request failed:", e);
3603
- }
3604
- }
3605
- /**
3606
- * Checks if telemetry is enabled on this machine
3607
- * @param sys The system where the command is invoked
3608
- * @returns true if telemetry is enabled, false otherwise
3609
- */
3610
- async function checkTelemetry(sys) {
3611
- const config = await readConfig(sys);
3612
- if (config["telemetry.stencil"] === void 0) {
3613
- config["telemetry.stencil"] = true;
3614
- await writeConfig(sys, config);
3615
- }
3616
- return config["telemetry.stencil"];
3617
- }
3618
- /**
3619
- * Writes to the config file, enabling telemetry for this machine.
3620
- * @param sys The system where the command is invoked
3621
- * @returns true if writing the file was successful, false otherwise
3622
- */
3623
- async function enableTelemetry(sys) {
3624
- return await updateConfig(sys, { "telemetry.stencil": true });
3625
- }
3626
- /**
3627
- * Writes to the config file, disabling telemetry for this machine.
3628
- * @param sys The system where the command is invoked
3629
- * @returns true if writing the file was successful, false otherwise
3630
- */
3631
- async function disableTelemetry(sys) {
3632
- return await updateConfig(sys, { "telemetry.stencil": false });
3633
- }
3634
- /**
3635
- * Takes in a semver string in order to return the major version.
3636
- * @param version The fully qualified semver version
3637
- * @returns a string of the major version
3638
- */
3639
- function getMajorVersion(version) {
3640
- return version.split(".")[0];
3641
- }
3642
- //#endregion
3643
3275
  //#region src/task-build.ts
3644
3276
  const taskBuild = async (coreCompiler, config, flags) => {
3645
3277
  if (flags.watch) {
@@ -3669,7 +3301,6 @@ const taskBuild = async (coreCompiler, config, flags) => {
3669
3301
  const versionChecker = startCheckVersion(config, coreCompiler.version, flags);
3670
3302
  const compiler = await coreCompiler.createCompiler(config);
3671
3303
  const results = await compiler.build();
3672
- await telemetryBuildFinishedAction(config.sys, config, coreCompiler, results, flags);
3673
3304
  await compiler.destroy();
3674
3305
  if (results.hasError) {
3675
3306
  const migrationResult = await detectMigrations(coreCompiler, config);
@@ -3841,26 +3472,48 @@ const taskGenerate = async (config, flags) => {
3841
3472
  config.logger.error(tagError);
3842
3473
  return config.sys.exit(1);
3843
3474
  }
3844
- const styleOptions = [
3845
- {
3846
- value: "css",
3847
- label: "CSS (.css)"
3848
- },
3849
- ...[...new Set(generateContribs.flatMap((c) => c.styleExtensions ?? []))].map((ext) => ({
3850
- value: ext,
3851
- label: `${ext.toUpperCase()} (.${ext})`
3852
- })),
3853
- {
3854
- value: "",
3855
- label: "None"
3856
- }
3857
- ];
3858
- const stylePick = await p.select({
3859
- message: "Stylesheet format:",
3860
- options: styleOptions
3475
+ const componentType = await p.select({
3476
+ message: "Component type:",
3477
+ options: [{
3478
+ value: "component",
3479
+ label: "Component",
3480
+ hint: "@Component decorator, TSX"
3481
+ }, {
3482
+ value: "css-only",
3483
+ label: "CSS-only component",
3484
+ hint: "pure CSS, no JS class or runtime"
3485
+ }]
3861
3486
  });
3862
- cancelIfAborted(stylePick);
3863
- const styleExtension = stylePick || void 0;
3487
+ cancelIfAborted(componentType);
3488
+ const isCssOnly = componentType === "css-only";
3489
+ if (isCssOnly && config.enableCssOnlyComponents === false) p.note("`enableCssOnlyComponents` is disabled in your stencil.config - this component will not be discovered until it is re-enabled.", "Warning");
3490
+ const styleExtOptions = [{
3491
+ value: "css",
3492
+ label: "CSS (.css)"
3493
+ }, ...[...new Set(generateContribs.flatMap((c) => c.styleExtensions ?? []))].map((ext) => ({
3494
+ value: ext,
3495
+ label: `${ext.toUpperCase()} (.${ext})`
3496
+ }))];
3497
+ let styleExtension;
3498
+ let cssOnlyExtension = "css";
3499
+ if (isCssOnly) {
3500
+ const stylePick = await p.select({
3501
+ message: "Stylesheet format:",
3502
+ options: styleExtOptions
3503
+ });
3504
+ cancelIfAborted(stylePick);
3505
+ cssOnlyExtension = stylePick;
3506
+ } else {
3507
+ const stylePick = await p.select({
3508
+ message: "Stylesheet format:",
3509
+ options: [...styleExtOptions, {
3510
+ value: "",
3511
+ label: "None"
3512
+ }]
3513
+ });
3514
+ cancelIfAborted(stylePick);
3515
+ styleExtension = stylePick || void 0;
3516
+ }
3864
3517
  const demoPick = await p.select({
3865
3518
  message: "Demo:",
3866
3519
  options: [
@@ -3883,6 +3536,7 @@ const taskGenerate = async (config, flags) => {
3883
3536
  cancelIfAborted(demoPick);
3884
3537
  const generateCtx = {
3885
3538
  tagName: componentName,
3539
+ cssOnly: isCssOnly,
3886
3540
  config: toProjectConfig(config),
3887
3541
  prompts: p,
3888
3542
  nypm
@@ -3906,20 +3560,26 @@ const taskGenerate = async (config, flags) => {
3906
3560
  const outDir = join(srcDir, "components", dir, componentName);
3907
3561
  const className = toPascalCase(componentName);
3908
3562
  const filesToWrite = [];
3909
- filesToWrite.push({
3910
- absPath: normalizePath(join(outDir, `${componentName}.tsx`)),
3911
- content: getComponentBoilerplate(componentName, styleExtension)
3912
- });
3913
- if (styleExtension) filesToWrite.push({
3914
- absPath: normalizePath(join(outDir, `${componentName}.${styleExtension}`)),
3915
- content: getStyleBoilerplate(styleExtension)
3563
+ if (isCssOnly) filesToWrite.push({
3564
+ absPath: normalizePath(join(outDir, `${componentName}.${cssOnlyExtension}`)),
3565
+ content: getCssOnlyComponentBoilerplate(componentName, cssOnlyExtension)
3916
3566
  });
3567
+ else {
3568
+ filesToWrite.push({
3569
+ absPath: normalizePath(join(outDir, `${componentName}.tsx`)),
3570
+ content: getComponentBoilerplate(componentName, styleExtension)
3571
+ });
3572
+ if (styleExtension) filesToWrite.push({
3573
+ absPath: normalizePath(join(outDir, `${componentName}.${styleExtension}`)),
3574
+ content: getStyleBoilerplate(styleExtension)
3575
+ });
3576
+ }
3917
3577
  for (const ext of pickedExtensions) {
3918
3578
  const tmpl = allFileTemplates.find((ft) => ft.extension === ext);
3919
3579
  const absPath = normalizePath(join(outDir, tmpl.subdirectory ?? "", `${componentName}.${ext}`));
3920
3580
  filesToWrite.push({
3921
3581
  absPath,
3922
- content: tmpl.template(componentName, className)
3582
+ content: tmpl.template(componentName, className, { cssOnly: isCssOnly })
3923
3583
  });
3924
3584
  }
3925
3585
  if (demoPick === "usage") filesToWrite.push({
@@ -3943,50 +3603,13 @@ const taskGenerate = async (config, flags) => {
3943
3603
  p.outro(`stencil generate ${input}`);
3944
3604
  };
3945
3605
  //#endregion
3946
- //#region src/task-telemetry.ts
3947
- /**
3948
- * Entrypoint for the Telemetry task
3949
- * @param flags configuration flags provided to Stencil when a task was called (either this task or a task that invokes
3950
- * telemetry)
3951
- * @param sys the abstraction for interfacing with the operating system
3952
- * @param logger a logging implementation to log the results out to the user
3953
- */
3954
- const taskTelemetry = async (flags, sys, logger) => {
3955
- const prompt = logger.dim(sys.details?.platform === "windows" ? ">" : "$");
3956
- const isEnabling = flags.args.includes("on");
3957
- const isDisabling = flags.args.includes("off");
3958
- const INFORMATION = `Opt in or out of telemetry. Information about the data we collect is available on our website: ${logger.bold("https://stenciljs.com/telemetry")}`;
3959
- const ENABLED_MESSAGE = `${logger.green("Enabled")}. Thank you for helping to make Stencil better! 💖\n\n`;
3960
- const DISABLED_MESSAGE = `${logger.red("Disabled")}\n\n`;
3961
- const hasTelemetry = await checkTelemetry(sys);
3962
- if (isEnabling) {
3963
- if (await enableTelemetry(sys)) console.log(`\n ${logger.bold("Telemetry is now ") + ENABLED_MESSAGE}`);
3964
- else console.log(`Something went wrong when enabling Telemetry.`);
3965
- return;
3966
- }
3967
- if (isDisabling) {
3968
- if (await disableTelemetry(sys)) console.log(`\n ${logger.bold("Telemetry is now ") + DISABLED_MESSAGE}`);
3969
- else console.log(`Something went wrong when disabling Telemetry.`);
3970
- return;
3971
- }
3972
- console.log(` ${logger.bold("Telemetry:")} ${logger.dim(INFORMATION)}`);
3973
- console.log(`\n ${logger.bold("Status")}: ${hasTelemetry ? ENABLED_MESSAGE : DISABLED_MESSAGE}`);
3974
- console.log(` ${prompt} ${logger.green("stencil telemetry [off|on]")}
3975
-
3976
- ${logger.cyan("off")} ${logger.dim(".............")} Disable sharing anonymous usage data
3977
- ${logger.cyan("on")} ${logger.dim("..............")} Enable sharing anonymous usage data
3978
- `);
3979
- };
3980
- //#endregion
3981
3606
  //#region src/task-help.ts
3982
3607
  /**
3983
3608
  * Entrypoint for the Help task, providing Stencil usage context to the user
3984
- * @param flags configuration flags provided to Stencil when a task was call (either this task or a task that invokes
3985
- * telemetry)
3986
3609
  * @param logger a logging implementation to log the results out to the user
3987
3610
  * @param sys the abstraction for interfacing with the operating system
3988
3611
  */
3989
- const taskHelp = async (flags, logger, sys) => {
3612
+ const taskHelp = async (logger, sys) => {
3990
3613
  const prompt = logger.dim(sys.details?.platform === "windows" ? ">" : "$");
3991
3614
  console.log(`
3992
3615
  ${logger.bold("Init:")} ${logger.dim("Scaffold a new project, or add capabilities to an existing one.")}
@@ -4012,10 +3635,10 @@ const taskHelp = async (flags, logger, sys) => {
4012
3635
  ${logger.cyan("--watch")} ${logger.dim("...........")} Rebuild when files update
4013
3636
  ${logger.cyan("--serve")} ${logger.dim("...........")} Start the dev-server (requires --watch)
4014
3637
  ${logger.cyan("--prerender")} ${logger.dim(".......")} Prerender the application
4015
- ${logger.cyan("--docs")} ${logger.dim("............")} Generate component readme.md docs
3638
+ ${logger.cyan("--docs")} ${logger.dim("............")} Also generate docs output targets in a --dev build
4016
3639
  ${logger.cyan("--ssr")} ${logger.dim(".............")} Build a server-side-rendering bundle
4017
3640
  ${logger.cyan("--config")} ${logger.dim("..........")} Set stencil config file
4018
- ${logger.cyan("--maxWorkers")} ${logger.dim("......")} Max number of workers, e.g. --maxWorkers 4 or --maxWorkers 50%
3641
+ ${logger.cyan("--maxWorkers")} ${logger.dim("......")} Max number of workers, e.g. --maxWorkers 4
4019
3642
  ${logger.cyan("--no-cache")} ${logger.dim("........")} Disable the build cache
4020
3643
  ${logger.cyan("--stats")} ${logger.dim("...........")} Write stats, optional file path (default: stencil-stats.json)
4021
3644
  ${logger.cyan("--log")} ${logger.dim(".............")} Write stencil-build.log file
@@ -4025,10 +3648,11 @@ const taskHelp = async (flags, logger, sys) => {
4025
3648
 
4026
3649
  ${logger.bold("Serve:")} ${logger.dim("Start the dev-server without building or watching.")}
4027
3650
 
4028
- ${prompt} ${logger.green("stencil serve [--root] [--no-open]")}
3651
+ ${prompt} ${logger.green("stencil serve [--root] [--port] [--open]")}
4029
3652
 
4030
3653
  ${logger.cyan("--root")} ${logger.dim("............")} Directory to serve (default: current directory)
4031
- ${logger.cyan("--no-open")} ${logger.dim(".........")} Don't open the browser automatically
3654
+ ${logger.cyan("--port")} ${logger.dim("............")} Port to listen on
3655
+ ${logger.cyan("--open")} ${logger.dim("............")} Open the browser
4032
3656
 
4033
3657
 
4034
3658
  ${logger.bold("Docs:")} ${logger.dim("Generate configured docs output targets.")}
@@ -4038,9 +3662,9 @@ const taskHelp = async (flags, logger, sys) => {
4038
3662
  ${logger.cyan("--docsJson")} ${logger.dim("........")} Write a docs.json file to the given path
4039
3663
 
4040
3664
 
4041
- ${logger.bold("Prerender:")} ${logger.dim("Prerender a hydrate app script against the source index.html.")}
3665
+ ${logger.bold("Prerender:")} ${logger.dim("Prerender with an already-built ssr script, against the source index.html.")}
4042
3666
 
4043
- ${prompt} ${logger.green("stencil prerender <hydrate-app-path>")}
3667
+ ${prompt} ${logger.green("stencil prerender <ssr-script-path>")}
4044
3668
 
4045
3669
 
4046
3670
  ${logger.bold("Migrate:")} ${logger.dim("Codemod a project for the latest major version breaking changes.")}
@@ -4060,7 +3684,6 @@ const taskHelp = async (flags, logger, sys) => {
4060
3684
  ${prompt} ${logger.green("stencil version")} or ${logger.green("stencil --version")}
4061
3685
 
4062
3686
  `);
4063
- await taskTelemetry(flags, sys, logger);
4064
3687
  console.log(`
4065
3688
  ${logger.bold("Examples:")}
4066
3689
 
@@ -4070,7 +3693,6 @@ const taskHelp = async (flags, logger, sys) => {
4070
3693
  ${prompt} ${logger.green("stencil build --prerender")}
4071
3694
  ${prompt} ${logger.green("stencil serve --root www")}
4072
3695
  ${prompt} ${logger.green("stencil migrate --dry-run")}
4073
- ${prompt} ${logger.green("stencil telemetry on")}
4074
3696
  `);
4075
3697
  };
4076
3698
  //#endregion
@@ -4234,7 +3856,7 @@ async function writeStencilConfig(rootDir, content) {
4234
3856
  async function writeGlobalStyle(rootDir) {
4235
3857
  const path = join(rootDir, "src", "global.css");
4236
3858
  await mkdir(dirname(path), { recursive: true });
4237
- await writeIfAbsent(path, `@import "stencil-globals";\n@import "stencil-hydrate";\n`);
3859
+ await writeIfAbsent(path, `@import "stencil-component-globals";\n@import "stencil-hydrate";\n`);
4238
3860
  }
4239
3861
  async function writeGlobalScript(rootDir) {
4240
3862
  const path = join(rootDir, "src", "global.ts");
@@ -4265,8 +3887,8 @@ function workspaceBuildScript(pm, coreName) {
4265
3887
  */
4266
3888
  async function scaffoldWorkspaceRoot(cwd, projectName, coreName) {
4267
3889
  await mkdir(join(cwd, "packages"), { recursive: true });
4268
- const pm = await detectPackageManager(cwd);
4269
- const usePnpmYaml = pm?.name === "pnpm";
3890
+ const pm = await detectPackageManager$1(cwd);
3891
+ const usePnpmYaml = pm === "pnpm";
4270
3892
  const pkgPath = join(cwd, "package.json");
4271
3893
  let pkg;
4272
3894
  try {
@@ -4278,7 +3900,7 @@ async function scaffoldWorkspaceRoot(cwd, projectName, coreName) {
4278
3900
  pkg.version ??= "0.0.1";
4279
3901
  pkg.private = true;
4280
3902
  pkg.scripts = {
4281
- build: workspaceBuildScript(pm?.name, coreName),
3903
+ build: workspaceBuildScript(pm, coreName),
4282
3904
  ...pkg.scripts
4283
3905
  };
4284
3906
  if (!usePnpmYaml) pkg.workspaces = ["packages/*"];
@@ -4318,31 +3940,24 @@ async function verifyInstalled(rootDir, packageNames) {
4318
3940
  p.log.error(`Install reported success but ${missing.join(", ")} could not be found in ${rootDir}. Your package manager may have silently failed to write to node_modules - check its logs and try again.`);
4319
3941
  process.exit(1);
4320
3942
  }
3943
+ const OUTPUT_TYPES = {
3944
+ loader: "loader-bundle",
3945
+ standalone: "standalone",
3946
+ ssr: "ssr",
3947
+ "ssr-wasm": "ssr-wasm",
3948
+ www: "www"
3949
+ };
3950
+ function outputKeysToTargets(keys) {
3951
+ return keys.length > 0 ? keys.map((k) => ({ type: OUTPUT_TYPES[k] })) : [{ type: "loader-bundle" }];
3952
+ }
4321
3953
  /**
4322
- * npm silently omits devDependencies when this CLI is itself running as a nested child
4323
- * process (e.g. via `npx create-stencil` / `npm init stencil`). Root cause: npm/exec only
4324
- * needs @stencil/cli's own regular dependencies to resolve+run it, so that install computes
4325
- * `omit: ['dev']` - and per npm's own config flattening
4326
- * (@npmcli/config/lib/definitions/definitions.js), whenever `omit` includes 'dev' npm sets
4327
- * `process.env.NODE_ENV = 'production'` on itself. We inherit that env var from the outer
4328
- * npm/npx process, and every child process we (or a wizard plugin) spawn from here would
4329
- * inherit it right back, causing nested `npm install`s to also compute `omit: ['dev']` and
4330
- * silently drop (or, worse, actively remove) every devDependency in the scaffolded project.
4331
- * Clearing it once, up front, fixes every install call transitively - ours and every wizard
4332
- * plugin's - without needing to special-case npm invocations one by one.
3954
+ * Reads which outputs a config file declares.
3955
+ * @param configPath Absolute path to the `stencil.config.ts`.
3956
+ * @returns The output keys present in its `outputTargets` array.
4333
3957
  */
4334
- function clearInheritedProductionEnv() {
4335
- if (process.env.NODE_ENV === "production") delete process.env.NODE_ENV;
4336
- }
4337
- function outputKeysToTargets(keys) {
4338
- const map = {
4339
- loader: "loader-bundle",
4340
- standalone: "standalone",
4341
- ssr: "ssr",
4342
- "ssr-wasm": "ssr-wasm",
4343
- www: "www"
4344
- };
4345
- return keys.length > 0 ? keys.map((k) => ({ type: map[k] })) : [{ type: "loader-bundle" }];
3958
+ async function readConfigOutputKeys(configPath) {
3959
+ const editor = await openStencilConfig(configPath);
3960
+ return Object.keys(OUTPUT_TYPES).filter((key) => [`'`, `"`].some((q) => editor.outputTargetsContains(`type: ${q}${OUTPUT_TYPES[key]}${q}`)));
4346
3961
  }
4347
3962
  async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4348
3963
  clearInheritedProductionEnv();
@@ -4375,8 +3990,9 @@ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4375
3990
  namespace,
4376
3991
  outputs,
4377
3992
  signals: features.signals,
3993
+ exportMaps: features.exportMaps,
4378
3994
  docs
4379
- }) ?? (needsStencilConfig(selectedIntegrations) ? `import { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n outputTargets: [{ type: 'loader-bundle' }],\n};\n` : null);
3995
+ }) ?? (needsStencilConfig(selectedIntegrations) ? `import type { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n};\n` : null);
4380
3996
  const summaryLines = [
4381
3997
  `Template: component-starter`,
4382
3998
  `Name: ${projectName}`,
@@ -4390,6 +4006,7 @@ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4390
4006
  if (selectedIntegrations.length > 0) summaryLines.push(`Add: ${selectedIntegrations.map((i) => i.displayName).join(", ")}`);
4391
4007
  p.note(summaryLines.join("\n"), "Summary");
4392
4008
  const coreDir = monorepo ? join(cwd, "packages", coreName) : cwd;
4009
+ const pm = await detectPackageManager$1(cwd);
4393
4010
  const s1 = p.spinner();
4394
4011
  s1.start("Scaffolding project files");
4395
4012
  if (monorepo) await scaffoldWorkspaceRoot(cwd, projectName, coreName);
@@ -4408,7 +4025,8 @@ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4408
4025
  s2.start("Installing dependencies");
4409
4026
  await nypm.installDependencies({
4410
4027
  cwd,
4411
- silent: true
4028
+ silent: true,
4029
+ packageManager: pm
4412
4030
  });
4413
4031
  s2.stop("Dependencies installed");
4414
4032
  await verifyInstalled(coreDir, ["@stencil/core"]);
@@ -4435,17 +4053,24 @@ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4435
4053
  ...toProjectConfig(resolvedValidated),
4436
4054
  rootDir: coreDir
4437
4055
  } : defaultProjectConfig(coreDir, { namespace });
4438
- for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run({
4439
- isNewProject: true,
4440
- prompts: p,
4441
- nypm,
4442
- config: projectConfig,
4443
- workspaceRoot: monorepo ? cwd : void 0,
4444
- ts,
4445
- openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4446
- });
4056
+ let ranWizard = false;
4057
+ for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) {
4058
+ ranWizard = true;
4059
+ await d.plugin.init.run({
4060
+ isNewProject: true,
4061
+ prompts: p,
4062
+ nypm,
4063
+ config: projectConfig,
4064
+ workspaceRoot: monorepo ? cwd : void 0,
4065
+ ts,
4066
+ openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4067
+ });
4068
+ }
4069
+ if (ranWizard && configSource) {
4070
+ const finalOutputs = await readConfigOutputKeys(join(coreDir, "stencil.config.ts"));
4071
+ await applyPackageJsonFields(coreDir, generatePackageJsonFields(finalOutputs));
4072
+ }
4447
4073
  }
4448
- const pm = (await nypm.detectPackageManager(cwd))?.name ?? "npm";
4449
4074
  const devDir = monorepo ? `packages/${coreName}` : null;
4450
4075
  const devCmd = `${pm} run dev`;
4451
4076
  p.outro(devDir ? `Your project is ready!\n cd ${devDir}\n ${devCmd}` : `Your project is ready! Run: ${devCmd}`);
@@ -4501,7 +4126,7 @@ async function addCapabilities(cwd, strictConfig) {
4501
4126
  ts,
4502
4127
  openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4503
4128
  });
4504
- p.outro("Done! Run pnpm run dev to continue.");
4129
+ p.outro(`Done! Run ${await detectPackageManager$1(cwd)} run dev to continue.`);
4505
4130
  }
4506
4131
  function toNamespace(name) {
4507
4132
  const base = name.replace(/^@[^/]+\//, "");
@@ -4517,7 +4142,6 @@ const taskServe = async (config, flags) => {
4517
4142
  config.devServer.websocket = false;
4518
4143
  config.maxConcurrentWorkers = 1;
4519
4144
  config.devServer.root = isString(flags.root) ? flags.root : config.sys.getCurrentDirectory();
4520
- if (!config.sys.onProcessInterrupt) throw new Error(`Environment doesn't provide required function: onProcessInterrupt`);
4521
4145
  const devServer = await start(config.devServer, config.logger);
4522
4146
  console.log(`${config.logger.cyan(" Root:")} ${devServer.root}`);
4523
4147
  console.log(`${config.logger.cyan(" Address:")} ${devServer.address}`);
@@ -4550,17 +4174,13 @@ const run = async (init) => {
4550
4174
  const task = flags.task;
4551
4175
  if (flags.debug || flags.verbose) logger.setLevel("debug");
4552
4176
  if (flags.ci) logger.enableColors(false);
4553
- if (isFunction(sys.applyGlobalPatch)) sys.applyGlobalPatch(sys.getCurrentDirectory());
4554
4177
  if (task && task === "version" || flags.version) {
4555
4178
  const coreCompiler = await loadCoreCompiler(sys);
4556
4179
  console.log(coreCompiler.version);
4557
4180
  return;
4558
4181
  }
4559
4182
  if (!task || task === "help" || flags.help) {
4560
- await taskHelp(createConfigFlags({
4561
- task: "help",
4562
- args
4563
- }), logger, sys);
4183
+ await taskHelp(logger, sys);
4564
4184
  return;
4565
4185
  }
4566
4186
  if (task === "test") {
@@ -4630,10 +4250,7 @@ const run = async (init) => {
4630
4250
  logger.printDiagnostics(validated.diagnostics);
4631
4251
  if (hasError(validated.diagnostics)) return sys.exit(1);
4632
4252
  }
4633
- if (isFunction(sys.applyGlobalPatch)) sys.applyGlobalPatch(validated.config.rootDir);
4634
- await telemetryAction(sys, validated.config, coreCompiler, flags, async () => {
4635
- await runTask(coreCompiler, validated.config, task, sys, flags);
4636
- });
4253
+ await runTask(coreCompiler, validated.config, task, sys, flags);
4637
4254
  } catch (e) {
4638
4255
  if (!shouldIgnoreError(e)) {
4639
4256
  const details = `${logger.getLevel() === "debug" && e instanceof Error ? e.stack : ""}`;
@@ -4673,7 +4290,7 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
4673
4290
  await taskGenerate(strictConfig, resolvedFlags);
4674
4291
  break;
4675
4292
  case "help":
4676
- await taskHelp(resolvedFlags, strictConfig.logger, sys);
4293
+ await taskHelp(strictConfig.logger, sys);
4677
4294
  break;
4678
4295
  case "init":
4679
4296
  await taskInit(coreCompiler, strictConfig);
@@ -4687,15 +4304,12 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
4687
4304
  case "serve":
4688
4305
  await taskServe(strictConfig, resolvedFlags);
4689
4306
  break;
4690
- case "telemetry":
4691
- await taskTelemetry(resolvedFlags, sys, strictConfig.logger);
4692
- break;
4693
4307
  case "version":
4694
4308
  console.log(coreCompiler.version);
4695
4309
  break;
4696
4310
  default:
4697
4311
  strictConfig.logger.error(`${strictConfig.logger.emoji("❌ ")}Invalid stencil command, please see the options below:`);
4698
- await taskHelp(resolvedFlags, strictConfig.logger, sys);
4312
+ await taskHelp(strictConfig.logger, sys);
4699
4313
  return configWithFlags.sys.exit(1);
4700
4314
  }
4701
4315
  };