@stencil/cli 5.0.0-beta.14 → 5.0.0-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -67,6 +67,6 @@ const flags = createConfigFlags({ task: 'build', dev: true });
67
67
  await runTask(coreCompiler, config, 'build', sys, flags);
68
68
  ```
69
69
 
70
- Valid `task` values: `'build'` | `'docs'` | `'generate'` | `'serve'` | `'prerender'` | `'info'` | `'migrate'` | `'init'` | `'add'` | `'telemetry'`
70
+ Valid `task` values: `'build'` | `'docs'` | `'generate'` | `'serve'` | `'prerender'` | `'info'` | `'migrate'` | `'init'` | `'add'`
71
71
 
72
72
  `flags` is optional - if omitted, defaults are derived from the task.
package/dist/index.d.mts CHANGED
@@ -4,13 +4,13 @@ import { ConfigCompat, LogLevel, OutputTarget } from "@stencil/core/compiler";
4
4
  /**
5
5
  * Supported CLI task commands
6
6
  */
7
- type TaskCommand = 'add' | 'build' | 'docs' | 'generate' | 'g' | 'help' | 'info' | 'init' | 'migrate' | 'prerender' | 'serve' | 'telemetry' | 'version';
7
+ type TaskCommand = 'add' | 'build' | 'docs' | 'generate' | 'g' | 'help' | 'info' | 'init' | 'migrate' | 'prerender' | 'serve' | 'version';
8
8
  //#endregion
9
9
  //#region src/config-flags.d.ts
10
10
  /**
11
11
  * All the Boolean options supported by the Stencil CLI
12
12
  */
13
- declare const BOOLEAN_CLI_FLAGS: readonly ["build", "cache", "ci", "debug", "dev", "docs", "dryRun", "help", "log", "open", "prerender", "profile", "serviceWorker", "serve", "ssr", "verbose", "version", "watch"];
13
+ declare const BOOLEAN_CLI_FLAGS: readonly ["cache", "ci", "debug", "dev", "docs", "dryRun", "help", "log", "open", "prerender", "profile", "serviceWorker", "serve", "ssr", "verbose", "version", "watch"];
14
14
  /**
15
15
  * All the Number options supported by the Stencil CLI
16
16
  */
@@ -174,6 +174,11 @@ interface ProjectConfig {
174
174
  compat?: ConfigCompat;
175
175
  /** Enable signal-based reactivity backing (top-level in stencil.config.ts). */
176
176
  signalBacking?: boolean;
177
+ /**
178
+ * Whether the build writes an `exports` map into the project's `package.json`. When `true`,
179
+ * consumers can only import the paths that map lists (e.g. `<pkg>/ssr`, not `<pkg>/dist/ssr`).
180
+ */
181
+ generateExportMaps?: boolean;
177
182
  }
178
183
  /**
179
184
  * Structured editor for `stencil.config.ts`, backed by the TypeScript compiler API.
@@ -323,6 +328,19 @@ interface StencilConfigEditor {
323
328
  * editor.removePlugin('sass(');
324
329
  */
325
330
  removePlugin(substring: string): boolean;
331
+ /**
332
+ * Sets a top-level property on the config object to `expression`, replacing its
333
+ * value if the property already exists, or adding it (after `namespace`, when
334
+ * present) if it doesn't.
335
+ *
336
+ * @param name - The config property, e.g. `'generateExportMaps'`.
337
+ * @param expression - A TypeScript expression, inserted verbatim, e.g. `'true'`.
338
+ *
339
+ * @example
340
+ * editor.setProperty('generateExportMaps', 'true');
341
+ * // > generateExportMaps: true,
342
+ */
343
+ setProperty(name: string, expression: string): void;
326
344
  /** Write all accumulated edits back to disk. */
327
345
  save(): Promise<void>;
328
346
  }
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";
@@ -20,7 +20,6 @@ import { start } from "@stencil/dev-server";
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",
@@ -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;
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}`;
729
752
  },
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;
757
- },
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
  /**
@@ -1210,7 +1255,7 @@ async function isExistingStencilProject(dir) {
1210
1255
  }
1211
1256
  //#endregion
1212
1257
  //#region src/wizard/splash.ts
1213
- const CLI_VERSION = "5.0.0-beta.14";
1258
+ const CLI_VERSION = "5.0.0-beta.16";
1214
1259
  const isTTY = process.stdout.isTTY;
1215
1260
  const noColor = !isTTY || "NO_COLOR" in process.env;
1216
1261
  const RESET = noColor ? "" : "\x1B[0m";
@@ -1344,10 +1389,10 @@ async function taskAdd(packages, strictConfig) {
1344
1389
  * @param config the Stencil configuration associated with the currently compiled project
1345
1390
  * @param currentVersion the Stencil compiler's version string
1346
1391
  * @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`
1392
+ * @returns a reference to `checkVersion`, or `null` if the check is skipped
1348
1393
  */
1349
1394
  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);
1395
+ if (config.devMode && !flags.ci && !currentVersion.includes("-dev.")) return config.sys.checkVersion(config.logger, currentVersion);
1351
1396
  return null;
1352
1397
  };
1353
1398
  /**
@@ -3143,7 +3188,6 @@ const taskWatch = async (coreCompiler, config, flags) => {
3143
3188
  const versionChecker = startCheckVersion(config, coreCompiler.version, flags);
3144
3189
  const compiler = await coreCompiler.createCompiler(config);
3145
3190
  const watcher = await compiler.createWatcher();
3146
- if (!config.sys.onProcessInterrupt) throw new Error(`Environment doesn't provide required function: onProcessInterrupt`);
3147
3191
  if (flags.serve) {
3148
3192
  const { start } = await import("@stencil/dev-server");
3149
3193
  devServer = await start(config.devServer, config.logger, watcher);
@@ -3173,473 +3217,6 @@ const taskWatch = async (coreCompiler, config, flags) => {
3173
3217
  if (exitCode > 0) return config.sys.exit(exitCode);
3174
3218
  };
3175
3219
  //#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
3220
  //#region src/task-build.ts
3644
3221
  const taskBuild = async (coreCompiler, config, flags) => {
3645
3222
  if (flags.watch) {
@@ -3669,7 +3246,6 @@ const taskBuild = async (coreCompiler, config, flags) => {
3669
3246
  const versionChecker = startCheckVersion(config, coreCompiler.version, flags);
3670
3247
  const compiler = await coreCompiler.createCompiler(config);
3671
3248
  const results = await compiler.build();
3672
- await telemetryBuildFinishedAction(config.sys, config, coreCompiler, results, flags);
3673
3249
  await compiler.destroy();
3674
3250
  if (results.hasError) {
3675
3251
  const migrationResult = await detectMigrations(coreCompiler, config);
@@ -3972,50 +3548,13 @@ const taskGenerate = async (config, flags) => {
3972
3548
  p.outro(`stencil generate ${input}`);
3973
3549
  };
3974
3550
  //#endregion
3975
- //#region src/task-telemetry.ts
3976
- /**
3977
- * Entrypoint for the Telemetry task
3978
- * @param flags configuration flags provided to Stencil when a task was called (either this task or a task that invokes
3979
- * telemetry)
3980
- * @param sys the abstraction for interfacing with the operating system
3981
- * @param logger a logging implementation to log the results out to the user
3982
- */
3983
- const taskTelemetry = async (flags, sys, logger) => {
3984
- const prompt = logger.dim(sys.details?.platform === "windows" ? ">" : "$");
3985
- const isEnabling = flags.args.includes("on");
3986
- const isDisabling = flags.args.includes("off");
3987
- 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")}`;
3988
- const ENABLED_MESSAGE = `${logger.green("Enabled")}. Thank you for helping to make Stencil better! 💖\n\n`;
3989
- const DISABLED_MESSAGE = `${logger.red("Disabled")}\n\n`;
3990
- const hasTelemetry = await checkTelemetry(sys);
3991
- if (isEnabling) {
3992
- if (await enableTelemetry(sys)) console.log(`\n ${logger.bold("Telemetry is now ") + ENABLED_MESSAGE}`);
3993
- else console.log(`Something went wrong when enabling Telemetry.`);
3994
- return;
3995
- }
3996
- if (isDisabling) {
3997
- if (await disableTelemetry(sys)) console.log(`\n ${logger.bold("Telemetry is now ") + DISABLED_MESSAGE}`);
3998
- else console.log(`Something went wrong when disabling Telemetry.`);
3999
- return;
4000
- }
4001
- console.log(` ${logger.bold("Telemetry:")} ${logger.dim(INFORMATION)}`);
4002
- console.log(`\n ${logger.bold("Status")}: ${hasTelemetry ? ENABLED_MESSAGE : DISABLED_MESSAGE}`);
4003
- console.log(` ${prompt} ${logger.green("stencil telemetry [off|on]")}
4004
-
4005
- ${logger.cyan("off")} ${logger.dim(".............")} Disable sharing anonymous usage data
4006
- ${logger.cyan("on")} ${logger.dim("..............")} Enable sharing anonymous usage data
4007
- `);
4008
- };
4009
- //#endregion
4010
3551
  //#region src/task-help.ts
4011
3552
  /**
4012
3553
  * Entrypoint for the Help task, providing Stencil usage context to the user
4013
- * @param flags configuration flags provided to Stencil when a task was call (either this task or a task that invokes
4014
- * telemetry)
4015
3554
  * @param logger a logging implementation to log the results out to the user
4016
3555
  * @param sys the abstraction for interfacing with the operating system
4017
3556
  */
4018
- const taskHelp = async (flags, logger, sys) => {
3557
+ const taskHelp = async (logger, sys) => {
4019
3558
  const prompt = logger.dim(sys.details?.platform === "windows" ? ">" : "$");
4020
3559
  console.log(`
4021
3560
  ${logger.bold("Init:")} ${logger.dim("Scaffold a new project, or add capabilities to an existing one.")}
@@ -4089,7 +3628,6 @@ const taskHelp = async (flags, logger, sys) => {
4089
3628
  ${prompt} ${logger.green("stencil version")} or ${logger.green("stencil --version")}
4090
3629
 
4091
3630
  `);
4092
- await taskTelemetry(flags, sys, logger);
4093
3631
  console.log(`
4094
3632
  ${logger.bold("Examples:")}
4095
3633
 
@@ -4099,7 +3637,6 @@ const taskHelp = async (flags, logger, sys) => {
4099
3637
  ${prompt} ${logger.green("stencil build --prerender")}
4100
3638
  ${prompt} ${logger.green("stencil serve --root www")}
4101
3639
  ${prompt} ${logger.green("stencil migrate --dry-run")}
4102
- ${prompt} ${logger.green("stencil telemetry on")}
4103
3640
  `);
4104
3641
  };
4105
3642
  //#endregion
@@ -4294,8 +3831,8 @@ function workspaceBuildScript(pm, coreName) {
4294
3831
  */
4295
3832
  async function scaffoldWorkspaceRoot(cwd, projectName, coreName) {
4296
3833
  await mkdir(join(cwd, "packages"), { recursive: true });
4297
- const pm = await detectPackageManager(cwd);
4298
- const usePnpmYaml = pm?.name === "pnpm";
3834
+ const pm = await detectPackageManager$1(cwd);
3835
+ const usePnpmYaml = pm === "pnpm";
4299
3836
  const pkgPath = join(cwd, "package.json");
4300
3837
  let pkg;
4301
3838
  try {
@@ -4307,7 +3844,7 @@ async function scaffoldWorkspaceRoot(cwd, projectName, coreName) {
4307
3844
  pkg.version ??= "0.0.1";
4308
3845
  pkg.private = true;
4309
3846
  pkg.scripts = {
4310
- build: workspaceBuildScript(pm?.name, coreName),
3847
+ build: workspaceBuildScript(pm, coreName),
4311
3848
  ...pkg.scripts
4312
3849
  };
4313
3850
  if (!usePnpmYaml) pkg.workspaces = ["packages/*"];
@@ -4363,15 +3900,24 @@ async function verifyInstalled(rootDir, packageNames) {
4363
3900
  function clearInheritedProductionEnv() {
4364
3901
  if (process.env.NODE_ENV === "production") delete process.env.NODE_ENV;
4365
3902
  }
3903
+ const OUTPUT_TYPES = {
3904
+ loader: "loader-bundle",
3905
+ standalone: "standalone",
3906
+ ssr: "ssr",
3907
+ "ssr-wasm": "ssr-wasm",
3908
+ www: "www"
3909
+ };
4366
3910
  function outputKeysToTargets(keys) {
4367
- const map = {
4368
- loader: "loader-bundle",
4369
- standalone: "standalone",
4370
- ssr: "ssr",
4371
- "ssr-wasm": "ssr-wasm",
4372
- www: "www"
4373
- };
4374
- return keys.length > 0 ? keys.map((k) => ({ type: map[k] })) : [{ type: "loader-bundle" }];
3911
+ return keys.length > 0 ? keys.map((k) => ({ type: OUTPUT_TYPES[k] })) : [{ type: "loader-bundle" }];
3912
+ }
3913
+ /**
3914
+ * Reads which outputs a config file declares.
3915
+ * @param configPath Absolute path to the `stencil.config.ts`.
3916
+ * @returns The output keys present in its `outputTargets` array.
3917
+ */
3918
+ async function readConfigOutputKeys(configPath) {
3919
+ const editor = await openStencilConfig(configPath);
3920
+ return Object.keys(OUTPUT_TYPES).filter((key) => [`'`, `"`].some((q) => editor.outputTargetsContains(`type: ${q}${OUTPUT_TYPES[key]}${q}`)));
4375
3921
  }
4376
3922
  async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4377
3923
  clearInheritedProductionEnv();
@@ -4404,8 +3950,9 @@ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4404
3950
  namespace,
4405
3951
  outputs,
4406
3952
  signals: features.signals,
3953
+ exportMaps: features.exportMaps,
4407
3954
  docs
4408
- }) ?? (needsStencilConfig(selectedIntegrations) ? `import { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n outputTargets: [{ type: 'loader-bundle' }],\n};\n` : null);
3955
+ }) ?? (needsStencilConfig(selectedIntegrations) ? `import type { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n};\n` : null);
4409
3956
  const summaryLines = [
4410
3957
  `Template: component-starter`,
4411
3958
  `Name: ${projectName}`,
@@ -4419,6 +3966,7 @@ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4419
3966
  if (selectedIntegrations.length > 0) summaryLines.push(`Add: ${selectedIntegrations.map((i) => i.displayName).join(", ")}`);
4420
3967
  p.note(summaryLines.join("\n"), "Summary");
4421
3968
  const coreDir = monorepo ? join(cwd, "packages", coreName) : cwd;
3969
+ const pm = await detectPackageManager$1(cwd);
4422
3970
  const s1 = p.spinner();
4423
3971
  s1.start("Scaffolding project files");
4424
3972
  if (monorepo) await scaffoldWorkspaceRoot(cwd, projectName, coreName);
@@ -4437,7 +3985,8 @@ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4437
3985
  s2.start("Installing dependencies");
4438
3986
  await nypm.installDependencies({
4439
3987
  cwd,
4440
- silent: true
3988
+ silent: true,
3989
+ packageManager: pm
4441
3990
  });
4442
3991
  s2.stop("Dependencies installed");
4443
3992
  await verifyInstalled(coreDir, ["@stencil/core"]);
@@ -4464,17 +4013,24 @@ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4464
4013
  ...toProjectConfig(resolvedValidated),
4465
4014
  rootDir: coreDir
4466
4015
  } : defaultProjectConfig(coreDir, { namespace });
4467
- for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run({
4468
- isNewProject: true,
4469
- prompts: p,
4470
- nypm,
4471
- config: projectConfig,
4472
- workspaceRoot: monorepo ? cwd : void 0,
4473
- ts,
4474
- openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4475
- });
4016
+ let ranWizard = false;
4017
+ for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) {
4018
+ ranWizard = true;
4019
+ await d.plugin.init.run({
4020
+ isNewProject: true,
4021
+ prompts: p,
4022
+ nypm,
4023
+ config: projectConfig,
4024
+ workspaceRoot: monorepo ? cwd : void 0,
4025
+ ts,
4026
+ openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4027
+ });
4028
+ }
4029
+ if (ranWizard && configSource) {
4030
+ const finalOutputs = await readConfigOutputKeys(join(coreDir, "stencil.config.ts"));
4031
+ await applyPackageJsonFields(coreDir, generatePackageJsonFields(finalOutputs));
4032
+ }
4476
4033
  }
4477
- const pm = (await nypm.detectPackageManager(cwd))?.name ?? "npm";
4478
4034
  const devDir = monorepo ? `packages/${coreName}` : null;
4479
4035
  const devCmd = `${pm} run dev`;
4480
4036
  p.outro(devDir ? `Your project is ready!\n cd ${devDir}\n ${devCmd}` : `Your project is ready! Run: ${devCmd}`);
@@ -4530,7 +4086,7 @@ async function addCapabilities(cwd, strictConfig) {
4530
4086
  ts,
4531
4087
  openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4532
4088
  });
4533
- p.outro("Done! Run pnpm run dev to continue.");
4089
+ p.outro(`Done! Run ${await detectPackageManager$1(cwd)} run dev to continue.`);
4534
4090
  }
4535
4091
  function toNamespace(name) {
4536
4092
  const base = name.replace(/^@[^/]+\//, "");
@@ -4546,7 +4102,6 @@ const taskServe = async (config, flags) => {
4546
4102
  config.devServer.websocket = false;
4547
4103
  config.maxConcurrentWorkers = 1;
4548
4104
  config.devServer.root = isString(flags.root) ? flags.root : config.sys.getCurrentDirectory();
4549
- if (!config.sys.onProcessInterrupt) throw new Error(`Environment doesn't provide required function: onProcessInterrupt`);
4550
4105
  const devServer = await start(config.devServer, config.logger);
4551
4106
  console.log(`${config.logger.cyan(" Root:")} ${devServer.root}`);
4552
4107
  console.log(`${config.logger.cyan(" Address:")} ${devServer.address}`);
@@ -4579,17 +4134,13 @@ const run = async (init) => {
4579
4134
  const task = flags.task;
4580
4135
  if (flags.debug || flags.verbose) logger.setLevel("debug");
4581
4136
  if (flags.ci) logger.enableColors(false);
4582
- if (isFunction(sys.applyGlobalPatch)) sys.applyGlobalPatch(sys.getCurrentDirectory());
4583
4137
  if (task && task === "version" || flags.version) {
4584
4138
  const coreCompiler = await loadCoreCompiler(sys);
4585
4139
  console.log(coreCompiler.version);
4586
4140
  return;
4587
4141
  }
4588
4142
  if (!task || task === "help" || flags.help) {
4589
- await taskHelp(createConfigFlags({
4590
- task: "help",
4591
- args
4592
- }), logger, sys);
4143
+ await taskHelp(logger, sys);
4593
4144
  return;
4594
4145
  }
4595
4146
  if (task === "test") {
@@ -4659,10 +4210,7 @@ const run = async (init) => {
4659
4210
  logger.printDiagnostics(validated.diagnostics);
4660
4211
  if (hasError(validated.diagnostics)) return sys.exit(1);
4661
4212
  }
4662
- if (isFunction(sys.applyGlobalPatch)) sys.applyGlobalPatch(validated.config.rootDir);
4663
- await telemetryAction(sys, validated.config, coreCompiler, flags, async () => {
4664
- await runTask(coreCompiler, validated.config, task, sys, flags);
4665
- });
4213
+ await runTask(coreCompiler, validated.config, task, sys, flags);
4666
4214
  } catch (e) {
4667
4215
  if (!shouldIgnoreError(e)) {
4668
4216
  const details = `${logger.getLevel() === "debug" && e instanceof Error ? e.stack : ""}`;
@@ -4702,7 +4250,7 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
4702
4250
  await taskGenerate(strictConfig, resolvedFlags);
4703
4251
  break;
4704
4252
  case "help":
4705
- await taskHelp(resolvedFlags, strictConfig.logger, sys);
4253
+ await taskHelp(strictConfig.logger, sys);
4706
4254
  break;
4707
4255
  case "init":
4708
4256
  await taskInit(coreCompiler, strictConfig);
@@ -4716,15 +4264,12 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
4716
4264
  case "serve":
4717
4265
  await taskServe(strictConfig, resolvedFlags);
4718
4266
  break;
4719
- case "telemetry":
4720
- await taskTelemetry(resolvedFlags, sys, strictConfig.logger);
4721
- break;
4722
4267
  case "version":
4723
4268
  console.log(coreCompiler.version);
4724
4269
  break;
4725
4270
  default:
4726
4271
  strictConfig.logger.error(`${strictConfig.logger.emoji("❌ ")}Invalid stencil command, please see the options below:`);
4727
- await taskHelp(resolvedFlags, strictConfig.logger, sys);
4272
+ await taskHelp(strictConfig.logger, sys);
4728
4273
  return configWithFlags.sys.exit(1);
4729
4274
  }
4730
4275
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stencil/cli",
3
- "version": "5.0.0-beta.14",
3
+ "version": "5.0.0-beta.16",
4
4
  "description": "CLI for Stencil - Web component compiler",
5
5
  "keywords": [
6
6
  "components",
@@ -42,16 +42,16 @@
42
42
  "nypm": "^0.3.12",
43
43
  "std-env": "^3.10.0",
44
44
  "typescript": ">5.0.0 <7.0.0",
45
- "@stencil/dev-server": "5.0.0-beta.14",
46
- "@stencil/templates": "5.0.0-beta.14"
45
+ "@stencil/dev-server": "5.0.0-beta.16",
46
+ "@stencil/templates": "5.0.0-beta.16"
47
47
  },
48
48
  "devDependencies": {
49
49
  "tsdown": "^0.22.14",
50
50
  "vitest": "^4.1.10",
51
- "@stencil/core": "5.0.0-beta.14"
51
+ "@stencil/core": "5.0.0-beta.16"
52
52
  },
53
53
  "peerDependencies": {
54
- "@stencil/core": "^5.0.0 || 5.0.0-beta.14"
54
+ "@stencil/core": "^5.0.0 || 5.0.0-beta.16"
55
55
  },
56
56
  "volta": {
57
57
  "extends": "../../package.json"