@stencil/core 5.0.0-alpha.1 → 5.0.0-alpha.3

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.
Files changed (42) hide show
  1. package/dist/{client-B1nuvCd2.mjs → client-CSm3x5ke.mjs} +81 -60
  2. package/dist/compiler/index.d.mts +3 -3
  3. package/dist/compiler/index.mjs +2 -2
  4. package/dist/compiler/utils/index.d.mts +2 -2
  5. package/dist/compiler/utils/index.mjs +3 -3
  6. package/dist/{compiler-LX4_RKKd.mjs → compiler-D6iP7Bzb.mjs} +1391 -1631
  7. package/dist/declarations/stencil-public-compiler.d.ts +4031 -2
  8. package/dist/declarations/stencil-public-compiler.js +0 -1
  9. package/dist/declarations/stencil-public-docs.d.ts +494 -1
  10. package/dist/declarations/stencil-public-runtime.d.ts +1943 -2
  11. package/dist/{index-fIuYTL9f.d.mts → index-CXHCTQNt.d.mts} +14 -2
  12. package/dist/{index-BONzXKJt.d.ts → index-CyrGY82h.d.ts} +5 -7
  13. package/dist/{index-CHjZtib0.d.ts → index-hS-KBdAP.d.ts} +1 -1
  14. package/dist/{index-D-LlB2nw.d.mts → index-tUR6pD3J.d.mts} +145 -809
  15. package/dist/index.d.mts +1 -0
  16. package/dist/index.mjs +2 -2
  17. package/dist/{jsx-runtime-DBzBJLKk.d.ts → jsx-runtime-DlDkTqps.d.ts} +1 -1
  18. package/dist/jsx-runtime.d.ts +1 -1
  19. package/dist/jsx-runtime.js +1 -1
  20. package/dist/{node-SxQIOCZE.mjs → node-Bg-mO5dw.mjs} +3 -14
  21. package/dist/regular-expression-D5pGVpCu.mjs +415 -0
  22. package/dist/runtime/app-data/index.d.ts +1 -1
  23. package/dist/runtime/app-data/index.js +1 -2
  24. package/dist/runtime/client/index.d.ts +14 -4
  25. package/dist/runtime/client/index.js +103 -192
  26. package/dist/runtime/index.d.ts +16 -4
  27. package/dist/runtime/index.js +2 -2
  28. package/dist/runtime/server/index.d.mts +1 -3
  29. package/dist/runtime/server/index.mjs +103 -192
  30. package/dist/runtime/server/runner.d.mts +1 -17
  31. package/dist/runtime/server/runner.mjs +12 -368
  32. package/dist/{runtime-CF9DJtSu.js → runtime-BBCnuprF.js} +103 -192
  33. package/dist/sys/node/index.d.mts +1 -1
  34. package/dist/sys/node/index.mjs +1 -1
  35. package/dist/sys/node/worker.mjs +2 -2
  36. package/dist/testing/index.d.mts +3 -3
  37. package/dist/testing/index.mjs +18 -17
  38. package/dist/{validation-CaCgjw-f.mjs → validation-Byxie0Uk.mjs} +28 -24
  39. package/package.json +9 -13
  40. package/dist/serialize-BkYHk7Mi.mjs +0 -766
  41. package/dist/stencil-public-compiler-C_X1iolo.d.ts +0 -4455
  42. package/dist/stencil-public-runtime-DlV8o7-z.d.ts +0 -1845
@@ -1,8 +1,8 @@
1
1
  import { n as __require } from "./chunk-CjcI7cDX.mjs";
2
- import { C as HYDRATED_CSS, h as scopeCss } from "./client-B1nuvCd2.mjs";
3
- import { C as toDashCase, D as CMP_FLAGS, F as DIST_GLOBAL_STYLES, G as EVENT_FLAGS, H as DOCS_JSON, I as DIST_HYDRATE_SCRIPT, K as GENERATED_DTS, L as DIST_LAZY, N as DIST_COLLECTION, O as COLLECTION_MANIFEST_FILE_NAME, P as DIST_CUSTOM_ELEMENTS, R as DIST_LAZY_LOADER, T as unique, U as DOCS_README, _ as isString$1, b as pluck, c as flatOne, g as isObject, h as isNumber$1, it as VALID_CONFIG_OUTPUT_TARGETS, k as COPY, l as fromEntries, m as isIterable, o as dashToPascalCase, ot as WATCH_FLAGS, p as isFunction, tt as STATS, u as isBoolean$1, v as mergeIntoWith, w as toTitleCase, x as sortBy, y as noop, z as DIST_TYPES } from "./serialize-BkYHk7Mi.mjs";
4
- import { $ as join$1, A as isOutputTargetCustom, B as isOutputTargetDocsCustomElementsManifest, Ct as stringifyRuntimeData, D as getComponentsFromModules, E as getComponentsDtsTypesFilePath, F as isOutputTargetDistLazy, G as isOutputTargetStats, H as isOutputTargetDocsReadme, I as isOutputTargetDistLazyLoader, J as relativeImport, K as isOutputTargetWww, L as isOutputTargetDistTypes, M as isOutputTargetDistCollection, N as isOutputTargetDistCustomElements, O as isEligiblePrimaryPackageOutputTarget, P as isOutputTargetDistGlobalStyles, Q as loadTypeScriptDiagnostics, R as isOutputTargetDocs, S as ok, T as getComponentsDtsSrcFilePath, U as isOutputTargetDocsVscode, V as isOutputTargetDocsJson, W as isOutputTargetHydrate, X as augmentDiagnosticWithNode, Z as loadTypeScriptDiagnostic, _ as getSourceMappingUrlForEndOfFile, _t as hasWarning, a as getTextDocs, at as resolve$1, b as err, bt as isGlob, ct as escapeHtml, d as isTsxFile, f as parsePackageJson, ft as buildError, g as getInlineSourceMappingUrlLinker, gt as hasError, h as isRemoteUrl, ht as catchError, i as generatePreamble, it as relative$1, j as isOutputTargetDist, k as isOutputTargetCopy, lt as normalizeDiagnostics, m as readPackageJson, mt as buildWarn, n as addDocBlock, nt as normalizeFsPathQuery, o as hasDependency, ot as createOnWarnFn, p as readOnlyArrayHasStringMember, pt as buildJsonFileError, q as isValidConfigOutputTarget, r as createJsVarName, rt as normalizePath, s as isDtsFile, st as loadRollupDiagnostics, t as validateComponentTag, tt as normalizeFsPath, u as isTsFile, ut as splitLineBreaks, w as filterExcludedComponents, wt as byteSize, x as map, xt as formatComponentRuntimeMeta, y as rollupToStencilSourceMap, yt as isRootPath, z as isOutputTargetDocsCustom } from "./validation-CaCgjw-f.mjs";
5
- import { i as CustomElementsExportBehaviorOptions, o as buildEvents, r as createNodeLogger, t as createNodeSys } from "./node-SxQIOCZE.mjs";
2
+ import { m as scopeCss, w as HYDRATED_CSS } from "./client-CSm3x5ke.mjs";
3
+ import { A as DIST_CUSTOM_ELEMENTS, C as CMP_FLAGS, F as DIST_TYPES, H as GENERATED_DTS, J as STATS, M as DIST_HYDRATE_SCRIPT, N as DIST_LAZY, P as DIST_LAZY_LOADER, R as DOCS_JSON, T as COPY, V as EVENT_FLAGS, X as VALID_CONFIG_OUTPUT_TARGETS, Z as WATCH_FLAGS, _ as sortBy, a as fromEntries, b as toTitleCase, d as isNumber$1, f as isObject, g as pluck, h as noop, i as flatOne, j as DIST_GLOBAL_STYLES, k as DIST_COLLECTION, l as isFunction, m as mergeIntoWith, n as dashToPascalCase, o as isBoolean$1, p as isString$1, u as isIterable, w as COLLECTION_MANIFEST_FILE_NAME, x as unique, y as toDashCase, z as DOCS_README } from "./regular-expression-D5pGVpCu.mjs";
4
+ import { $ as join$1, A as isOutputTargetCustom, B as isOutputTargetDocsCustomElementsManifest, Ct as stringifyRuntimeData, D as getComponentsFromModules, E as getComponentsDtsTypesFilePath, F as isOutputTargetDistLazy, G as isOutputTargetStats, H as isOutputTargetDocsReadme, I as isOutputTargetDistLazyLoader, J as relativeImport, K as isOutputTargetWww, L as isOutputTargetDistTypes, M as isOutputTargetDistCollection, N as isOutputTargetDistCustomElements, O as isEligiblePrimaryPackageOutputTarget, P as isOutputTargetDistGlobalStyles, Q as loadTypeScriptDiagnostics, R as isOutputTargetDocs, S as ok, T as getComponentsDtsSrcFilePath, U as isOutputTargetDocsVscode, V as isOutputTargetDocsJson, W as isOutputTargetHydrate, X as augmentDiagnosticWithNode, Z as loadTypeScriptDiagnostic, _ as getSourceMappingUrlForEndOfFile, _t as hasWarning, a as getTextDocs, at as resolve$1, b as err, bt as isGlob, d as isTsxFile, f as parsePackageJson, ft as buildError, g as getInlineSourceMappingUrlLinker, gt as hasError, h as isRemoteUrl, ht as catchError, i as generatePreamble, it as relative$1, j as isOutputTargetDist, k as isOutputTargetCopy, lt as normalizeDiagnostics, m as readPackageJson, mt as buildWarn, n as addDocBlock, nt as normalizeFsPathQuery, o as hasDependency, ot as createOnWarnFn, p as readOnlyArrayHasStringMember, pt as buildJsonFileError, q as isValidConfigOutputTarget, r as createJsVarName, rt as normalizePath, s as isDtsFile, st as loadRolldownDiagnostics, t as validateComponentTag, tt as normalizeFsPath, u as isTsFile, ut as splitLineBreaks, w as filterExcludedComponents, wt as byteSize, x as map, xt as formatComponentRuntimeMeta, y as rolldownToStencilSourceMap, yt as isRootPath, z as isOutputTargetDocsCustom } from "./validation-Byxie0Uk.mjs";
5
+ import { i as CustomElementsExportBehaviorOptions, o as buildEvents, r as createNodeLogger, t as createNodeSys } from "./node-Bg-mO5dw.mjs";
6
6
  import ts, { default as ts$1 } from "typescript";
7
7
  import { readFileSync } from "node:fs";
8
8
  import { basename, dirname, join } from "node:path";
@@ -13,25 +13,22 @@ import { cloneDocument, createDocument, serializeNodeToHtml } from "@stencil/moc
13
13
  import postcss from "postcss";
14
14
  import postcssSafeParser from "postcss-safe-parser";
15
15
  import postcssSelectorParser from "postcss-selector-parser";
16
- import rollupCommonjsPlugin from "@rollup/plugin-commonjs";
17
- import rollupJsonPlugin from "@rollup/plugin-json";
18
- import rollupNodeResolvePlugin from "@rollup/plugin-node-resolve";
19
- import rollupReplacePlugin from "@rollup/plugin-replace";
20
- import { rollup } from "rollup";
16
+ import { rolldown } from "rolldown";
21
17
  import MagicString from "magic-string";
22
18
  import resolve from "resolve";
23
- import sourceMapMerge from "merge-source-map";
24
19
  import { minify } from "terser";
25
20
  import { SelectorType, parse, stringify } from "css-what";
26
21
  import * as os from "os";
27
22
  import { execSync } from "child_process";
28
23
  import { createHash } from "crypto";
24
+ import browserslist from "browserslist";
25
+ import { browserslistToTargets, transform } from "lightningcss";
29
26
  import * as process$1 from "process";
30
27
  import { dataToEsm } from "@rollup/pluginutils";
31
28
  //#region src/version.ts
32
- const version = "5.0.0-alpha.1-dev.1775057990.e8a69f2";
33
- const buildId = "1775057990";
34
- const vermoji = "🍖";
29
+ const version = "5.0.0-alpha.3-dev.1775606156.754db56";
30
+ const buildId = "1775606156";
31
+ const vermoji = "🍹";
35
32
  /**
36
33
  * Get the installed version of a tool/dependency.
37
34
  * Handles packages with exports maps that point to subdirectories.
@@ -67,8 +64,8 @@ const versions = {
67
64
  get typescript() {
68
65
  return getToolVersion("typescript");
69
66
  },
70
- get rollup() {
71
- return getToolVersion("rollup");
67
+ get rolldown() {
68
+ return getToolVersion("rolldown");
72
69
  },
73
70
  get terser() {
74
71
  return getToolVersion("terser");
@@ -106,10 +103,10 @@ var CompilerContext = class {
106
103
  moduleMap = /* @__PURE__ */ new Map();
107
104
  nodeMap = /* @__PURE__ */ new WeakMap();
108
105
  resolvedCollections = /* @__PURE__ */ new Set();
109
- rollupCache = /* @__PURE__ */ new Map();
110
- rollupCacheHydrate = null;
111
- rollupCacheLazy = null;
112
- rollupCacheNative = null;
106
+ rolldownCache = /* @__PURE__ */ new Map();
107
+ rolldownCacheHydrate = null;
108
+ rolldownCacheLazy = null;
109
+ rolldownCacheNative = null;
113
110
  cachedGlobalStyle;
114
111
  styleModeNames = /* @__PURE__ */ new Set();
115
112
  worker = null;
@@ -120,9 +117,9 @@ var CompilerContext = class {
120
117
  this.collections.length = 0;
121
118
  this.compilerOptions = null;
122
119
  this.hasSuccessfulBuild = false;
123
- this.rollupCacheHydrate = null;
124
- this.rollupCacheLazy = null;
125
- this.rollupCacheNative = null;
120
+ this.rolldownCacheHydrate = null;
121
+ this.rolldownCacheLazy = null;
122
+ this.rolldownCacheNative = null;
126
123
  this.moduleMap.clear();
127
124
  this.resolvedCollections.clear();
128
125
  if (this.fs != null) this.fs.clearCache();
@@ -240,15 +237,18 @@ const resetModuleLegacy = (moduleFile) => {
240
237
  * @returns an object containing TypeScript compiler options
241
238
  */
242
239
  const getTsOptionsToExtend = (config) => {
240
+ const cacheDir = config.cacheDir || config.sys.tmpDirSync();
243
241
  return {
244
242
  experimentalDecorators: true,
245
243
  declaration: config.outputTargets.some(isOutputTargetDistTypes),
246
244
  module: config.tsCompilerOptions?.module || ts.ModuleKind.ESNext,
247
245
  moduleResolution: config.tsCompilerOptions?.moduleResolution === ts.ModuleResolutionKind.Bundler ? ts.ModuleResolutionKind.Bundler : ts.ModuleResolutionKind.NodeJs,
248
246
  noEmitOnError: config.tsCompilerOptions?.noEmitOnError || false,
249
- outDir: config.cacheDir || config.sys.tmpDirSync(),
247
+ outDir: cacheDir,
250
248
  sourceMap: config.sourceMap,
251
- inlineSources: config.sourceMap
249
+ inlineSources: config.sourceMap,
250
+ incremental: config.enableCache !== false,
251
+ tsBuildInfoFile: config.enableCache !== false ? join$1(cacheDir, ".tsbuildinfo") : void 0
252
252
  };
253
253
  };
254
254
  //#endregion
@@ -956,7 +956,7 @@ function getSymbolForType(type) {
956
956
  * - For CommonJS, the component class is left as is
957
957
  * - For ESM, the component class is re-written as a variable statement
958
958
  *
959
- * @param transformOpts the options provided to TypeScript + Rollup for transforming the AST node
959
+ * @param transformOpts the options provided to TypeScript + Rolldown for transforming the AST node
960
960
  * @param classNode the node in the AST pertaining to the Stencil component class to transform
961
961
  * @param heritageClauses a collection of heritage clauses associated with the provided class node
962
962
  * @param members a collection of members attached to the provided class node
@@ -983,7 +983,7 @@ const updateComponentClass = (transformOpts, classNode, heritageClauses, members
983
983
  * ```ts
984
984
  * const MyComponent = class {}
985
985
  * ```
986
- * @param transformOpts the options provided to TypeScript + Rollup for transforming the AST node
986
+ * @param transformOpts the options provided to TypeScript + Rolldown for transforming the AST node
987
987
  * @param classNode the node in the AST pertaining to the Stencil component class to transform
988
988
  * @param heritageClauses a collection of heritage clauses associated with the provided class node
989
989
  * @param members a collection of members attached to the provided class node
@@ -2010,20 +2010,27 @@ const serializeCollectionDependencies = (compilerCtx) => {
2010
2010
  //#endregion
2011
2011
  //#region src/compiler/output-targets/dist-lazy/lazy-component-plugin.ts
2012
2012
  const lazyComponentPlugin = (buildCtx) => {
2013
- const entrys = /* @__PURE__ */ new Map();
2013
+ const entryModuleMap = new Map(buildCtx.entryModules.map((em) => [em.entryKey, em]));
2014
+ const exportCache = /* @__PURE__ */ new Map();
2014
2015
  return {
2015
2016
  name: "lazyComponentPlugin",
2016
- resolveId(importee) {
2017
- const entryModule = buildCtx.entryModules.find((em) => em.entryKey === importee);
2018
- if (entryModule) {
2019
- entrys.set(importee, entryModule);
2020
- return importee;
2017
+ resolveId: {
2018
+ filter: { id: /\.entry$/ },
2019
+ handler(importee) {
2020
+ if (entryModuleMap.has(importee)) return importee;
2021
+ return null;
2021
2022
  }
2022
- return null;
2023
2023
  },
2024
2024
  load(id) {
2025
- const entryModule = entrys.get(id);
2026
- if (entryModule) return entryModule.cmps.map(createComponentExport).join("\n");
2025
+ const entryModule = entryModuleMap.get(id);
2026
+ if (entryModule) {
2027
+ let exports = exportCache.get(id);
2028
+ if (!exports) {
2029
+ exports = entryModule.cmps.map(createComponentExport).join("\n");
2030
+ exportCache.set(id, exports);
2031
+ }
2032
+ return exports;
2033
+ }
2027
2034
  return null;
2028
2035
  }
2029
2036
  };
@@ -2072,26 +2079,29 @@ const USER_INDEX_ENTRY_ID = "@user-index-entrypoint";
2072
2079
  //#endregion
2073
2080
  //#region src/compiler/bundle/app-data-plugin.ts
2074
2081
  /**
2075
- * A Rollup plugin which bundles application data.
2082
+ * A Rolldown plugin which bundles application data.
2076
2083
  *
2077
2084
  * @param config the Stencil configuration for a particular project
2078
2085
  * @param compilerCtx the current compiler context
2079
2086
  * @param buildCtx the current build context
2080
2087
  * @param buildConditionals the set build conditionals for the build
2081
2088
  * @param platform the platform that is being built
2082
- * @returns a Rollup plugin which carries out the necessary work
2089
+ * @returns a Rolldown plugin which carries out the necessary work
2083
2090
  */
2084
2091
  const appDataPlugin = (config, compilerCtx, buildCtx, buildConditionals, platform) => {
2085
2092
  if (!platform) return { name: "appDataPlugin" };
2086
2093
  const globalScripts = getGlobalScriptData(config, compilerCtx);
2087
2094
  return {
2088
2095
  name: "appDataPlugin",
2089
- resolveId(id, importer) {
2090
- if (id === "@stencil/core/runtime/app-data" || id === "@stencil/core/runtime/app-globals") {
2091
- if (platform === "worker") this.error("@stencil/core packages cannot be imported from a worker.");
2092
- return id;
2096
+ resolveId: {
2097
+ filter: { id: /^@stencil\/core\/runtime\/app-(data|globals)$/ },
2098
+ handler(id, importer) {
2099
+ if (id === "@stencil/core/runtime/app-data" || id === "@stencil/core/runtime/app-globals") {
2100
+ if (platform === "worker") this.error("@stencil/core packages cannot be imported from a worker.");
2101
+ return id;
2102
+ }
2103
+ return null;
2093
2104
  }
2094
- return null;
2095
2105
  },
2096
2106
  async load(id) {
2097
2107
  if (id === "@stencil/core/runtime/app-globals") {
@@ -2397,76 +2407,79 @@ const coreResolvePlugin = (config, compilerCtx, platform, externalRuntime, lazyL
2397
2407
  const compilerExe = config.sys.getCompilerExecutingPath();
2398
2408
  const internalClient = getStencilInternalModule(config, compilerExe, "client/index.js");
2399
2409
  const internalHydrate = getStencilInternalModule(config, compilerExe, "server/index.mjs");
2410
+ const transformedCodeCache = /* @__PURE__ */ new Map();
2411
+ const hydratedFlag = config.hydratedFlag;
2412
+ const hydratedFlagHead = hydratedFlag ? getHydratedFlagHead(hydratedFlag) : null;
2413
+ const hydratedReplacements = hydratedFlag && hydratedFlagHead !== "{visibility:hidden}.hydrated{visibility:inherit}" ? buildHydratedReplacements(hydratedFlag, hydratedFlagHead) : null;
2414
+ const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2400
2415
  return {
2401
2416
  name: "coreResolvePlugin",
2402
- resolveId(id) {
2403
- if (id === "@stencil/core" || id === "@stencil/core/runtime") {
2404
- if (platform === "client") {
2405
- if (externalRuntime) return {
2406
- id: STENCIL_INTERNAL_CLIENT_PLATFORM_ID,
2407
- external: true
2408
- };
2409
- if (lazyLoad) return internalClient + APP_DATA_CONDITIONAL;
2410
- return internalClient;
2417
+ resolveId: {
2418
+ filter: { id: /^@stencil\/core/ },
2419
+ handler(id) {
2420
+ if (id === "@stencil/core" || id === "@stencil/core/runtime") {
2421
+ if (platform === "client") {
2422
+ if (externalRuntime) return {
2423
+ id: STENCIL_INTERNAL_CLIENT_PLATFORM_ID,
2424
+ external: true
2425
+ };
2426
+ if (lazyLoad) return internalClient + APP_DATA_CONDITIONAL;
2427
+ return internalClient;
2428
+ }
2429
+ if (platform === "hydrate") return internalHydrate;
2411
2430
  }
2412
- if (platform === "hydrate") return internalHydrate;
2413
- }
2414
- if (id === "@stencil/core/runtime/client") {
2415
- if (externalRuntime) return {
2416
- id: STENCIL_INTERNAL_CLIENT_PLATFORM_ID,
2417
- external: true
2418
- };
2419
- return internalClient;
2420
- }
2421
- if (id === "@stencil/core/runtime/server") return internalHydrate;
2422
- if (id === "@stencil/core/jsx-runtime" || id === "@stencil/core/jsx-dev-runtime") {
2423
- if (platform === "client") {
2431
+ if (id === "@stencil/core/runtime/client") {
2424
2432
  if (externalRuntime) return {
2425
2433
  id: STENCIL_INTERNAL_CLIENT_PLATFORM_ID,
2426
2434
  external: true
2427
2435
  };
2428
- if (lazyLoad) return internalClient + APP_DATA_CONDITIONAL;
2429
2436
  return internalClient;
2430
2437
  }
2431
- if (platform === "hydrate") return internalHydrate;
2438
+ if (id === "@stencil/core/runtime/server") return internalHydrate;
2439
+ if (id === "@stencil/core/jsx-runtime" || id === "@stencil/core/jsx-dev-runtime") {
2440
+ if (platform === "client") {
2441
+ if (externalRuntime) return {
2442
+ id: STENCIL_INTERNAL_CLIENT_PLATFORM_ID,
2443
+ external: true
2444
+ };
2445
+ if (lazyLoad) return internalClient + APP_DATA_CONDITIONAL;
2446
+ return internalClient;
2447
+ }
2448
+ if (platform === "hydrate") return internalHydrate;
2449
+ }
2450
+ return null;
2432
2451
  }
2433
- return null;
2434
2452
  },
2435
- async load(filePath) {
2436
- if (filePath && !filePath.startsWith("\0")) {
2437
- filePath = normalizeFsPath(filePath);
2438
- if (filePath === internalClient || filePath === internalHydrate) {
2439
- if (platform === "worker") return `
2453
+ load: {
2454
+ filter: { id: new RegExp(`^(${escapeRegex(internalClient)}|${escapeRegex(internalHydrate)})(\\?.*)?$`) },
2455
+ async handler(filePath) {
2456
+ if (filePath && !filePath.startsWith("\0")) {
2457
+ filePath = normalizeFsPath(filePath);
2458
+ if (filePath === internalClient || filePath === internalHydrate) {
2459
+ if (platform === "worker") return `
2440
2460
  export const Build = {
2441
2461
  isDev: ${config.devMode},
2442
2462
  isBrowser: true,
2443
2463
  isServer: false,
2444
2464
  isTesting: false,
2445
2465
  };`;
2446
- let code = await compilerCtx.fs.readFile(filePath);
2447
- if (typeof code !== "string" && isRemoteUrl(compilerExe)) {
2448
- const url = getStencilModuleUrl(compilerExe, filePath);
2449
- code = await fetchModuleAsync(config.sys, compilerCtx.fs, packageVersions, url, filePath);
2450
- }
2451
- if (typeof code === "string") {
2452
- const hydratedFlag = config.hydratedFlag;
2453
- if (hydratedFlag) {
2454
- const hydratedFlagHead = getHydratedFlagHead(hydratedFlag);
2455
- if ("{visibility:hidden}.hydrated{visibility:inherit}" !== hydratedFlagHead) {
2456
- code = code.replace(HYDRATED_CSS, hydratedFlagHead);
2457
- if (hydratedFlag.name !== "hydrated") {
2458
- code = code.replace(`.classList.add("hydrated")`, `.classList.add("${hydratedFlag.name}")`);
2459
- code = code.replace(`.classList.add('hydrated')`, `.classList.add('${hydratedFlag.name}')`);
2460
- code = code.replace(`.setAttribute("hydrated",`, `.setAttribute("${hydratedFlag.name}",`);
2461
- code = code.replace(`.setAttribute('hydrated',`, `.setAttribute('${hydratedFlag.name}',`);
2462
- }
2463
- }
2464
- } else code = code.replace(HYDRATED_CSS, "{}");
2466
+ const cached = transformedCodeCache.get(filePath);
2467
+ if (cached) return cached;
2468
+ let code = await compilerCtx.fs.readFile(filePath);
2469
+ if (typeof code !== "string" && isRemoteUrl(compilerExe)) {
2470
+ const url = getStencilModuleUrl(compilerExe, filePath);
2471
+ code = await fetchModuleAsync(config.sys, compilerCtx.fs, packageVersions, url, filePath);
2472
+ }
2473
+ if (typeof code === "string") {
2474
+ if (hydratedReplacements) for (const [search, replace] of hydratedReplacements) code = code.replace(search, replace);
2475
+ else if (!hydratedFlag) code = code.replace(HYDRATED_CSS, "{}");
2476
+ transformedCodeCache.set(filePath, code);
2477
+ }
2478
+ return code;
2465
2479
  }
2466
- return code;
2467
2480
  }
2481
+ return null;
2468
2482
  }
2469
- return null;
2470
2483
  }
2471
2484
  };
2472
2485
  };
@@ -2488,6 +2501,18 @@ const getHydratedFlagHead = (h) => {
2488
2501
  else hydrated = `${selector}{${h.property}:${h.hydratedValue}}`;
2489
2502
  return initial + hydrated;
2490
2503
  };
2504
+ /**
2505
+ * Pre-build all hydrated flag string replacements to avoid repeated computation.
2506
+ * Returns an array of [search, replace] tuples to apply in sequence.
2507
+ * @param hydratedFlag the hydrated flag configuration
2508
+ * @param hydratedFlagHead the pre-computed CSS string for the hydrated flag
2509
+ * @returns an array of [search, replace] tuples for string replacement
2510
+ */
2511
+ const buildHydratedReplacements = (hydratedFlag, hydratedFlagHead) => {
2512
+ const replacements = [[HYDRATED_CSS, hydratedFlagHead]];
2513
+ if (hydratedFlag.name !== "hydrated") replacements.push([`.classList.add("hydrated")`, `.classList.add("${hydratedFlag.name}")`], [`.classList.add('hydrated')`, `.classList.add('${hydratedFlag.name}')`], [`.setAttribute("hydrated",`, `.setAttribute("${hydratedFlag.name}",`], [`.setAttribute('hydrated',`, `.setAttribute('${hydratedFlag.name}',`]);
2514
+ return replacements;
2515
+ };
2491
2516
  //#endregion
2492
2517
  //#region src/compiler/bundle/constants.ts
2493
2518
  const DEV_MODULE_DIR = `~dev-module`;
@@ -3185,13 +3210,13 @@ const parseImportPath = (importPath) => {
3185
3210
  //#region src/compiler/bundle/ext-transforms-plugin.ts
3186
3211
  const allCmpStyles = /* @__PURE__ */ new Map();
3187
3212
  /**
3188
- * A Rollup plugin which bundles up some transformation of CSS imports as well
3213
+ * A Rolldown plugin which bundles up some transformation of CSS imports as well
3189
3214
  * as writing some files to disk for the `DIST_COLLECTION` output target.
3190
3215
  *
3191
3216
  * @param config a user-supplied configuration
3192
3217
  * @param compilerCtx the current compiler context
3193
3218
  * @param buildCtx the current build context
3194
- * @returns a Rollup plugin which carries out the necessary work
3219
+ * @returns a Rolldown plugin which carries out the necessary work
3195
3220
  */
3196
3221
  const extTransformsPlugin = (config, compilerCtx, buildCtx) => {
3197
3222
  return {
@@ -3302,49 +3327,40 @@ const fileLoadPlugin = (fs) => {
3302
3327
  };
3303
3328
  //#endregion
3304
3329
  //#region src/compiler/bundle/loader-plugin.ts
3330
+ const escapeRegex$1 = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3305
3331
  /**
3306
- * Rollup plugin that aids in resolving the entry points (1 or more files) for a Stencil project. For example, a project
3332
+ * Rolldown plugin that aids in resolving the entry points (1 or more files) for a Stencil project. For example, a project
3307
3333
  * using the `dist-custom-elements` output target may have a single 'entry point' for each file containing a component.
3308
- * Each of those files will be independently resolved and loaded by this plugin for further processing by Rollup later
3334
+ * Each of those files will be independently resolved and loaded by this plugin for further processing by Rolldown later
3309
3335
  * in the bundling process.
3310
3336
  *
3311
3337
  * @param entries the Stencil project files to process. It should be noted that the keys in this object may not
3312
- * necessarily be an absolute or relative path to a file, but may be a Rollup Virtual Module (which begin with \0).
3313
- * @returns the rollup plugin that loads and process a Stencil project's entry points
3338
+ * necessarily be an absolute or relative path to a file, but may be a Rolldown Virtual Module (which begin with \0).
3339
+ * @returns the rolldown plugin that loads and process a Stencil project's entry points
3314
3340
  */
3315
3341
  const loaderPlugin = (entries = {}) => {
3342
+ const entryKeys = Object.keys(entries);
3343
+ const entryFilter = entryKeys.length > 0 ? new RegExp(`^(${entryKeys.map(escapeRegex$1).join("|")})$`) : /^$/;
3316
3344
  return {
3317
3345
  name: "stencilLoaderPlugin",
3318
- resolveId(id) {
3319
- if (id in entries) return { id };
3320
- return null;
3346
+ resolveId: {
3347
+ filter: { id: entryFilter },
3348
+ handler(id) {
3349
+ if (id in entries) return { id };
3350
+ return null;
3351
+ }
3321
3352
  },
3322
- load(id) {
3323
- if (id in entries) return entries[id];
3324
- return null;
3353
+ load: {
3354
+ filter: { id: entryFilter },
3355
+ handler(id) {
3356
+ if (id in entries) return entries[id];
3357
+ return null;
3358
+ }
3325
3359
  }
3326
3360
  };
3327
3361
  };
3328
3362
  //#endregion
3329
3363
  //#region src/compiler/bundle/plugin-helper.ts
3330
- const pluginHelper = (config, builtCtx, platform) => {
3331
- return {
3332
- name: "pluginHelper",
3333
- resolveId(importee, importer) {
3334
- if (/\0/.test(importee)) return null;
3335
- if (importee.endsWith("/")) importee = importee.slice(0, -1);
3336
- if (builtIns.has(importee)) {
3337
- let fromMsg = "";
3338
- if (importer) fromMsg = ` from ${relative$1(config.rootDir, importer)}`;
3339
- const diagnostic = buildError(builtCtx.diagnostics);
3340
- diagnostic.header = `Node Polyfills Required`;
3341
- diagnostic.messageText = `For the import "${importee}" to be bundled${fromMsg}, ensure the "rollup-plugin-node-polyfills" plugin is installed and added to the stencil config plugins (${platform}). Please see the bundling docs for more information.
3342
- Further information: https://stenciljs.com/docs/module-bundling`;
3343
- }
3344
- return null;
3345
- }
3346
- };
3347
- };
3348
3364
  const builtIns = new Set([
3349
3365
  "child_process",
3350
3366
  "cluster",
@@ -3387,8 +3403,30 @@ const builtIns = new Set([
3387
3403
  "vm",
3388
3404
  "zlib"
3389
3405
  ]);
3406
+ const BUILT_INS_FILTER = new RegExp(`^(${[...builtIns].join("|")})$`);
3407
+ const pluginHelper = (config, builtCtx, platform) => {
3408
+ return {
3409
+ name: "pluginHelper",
3410
+ resolveId: {
3411
+ filter: { id: BUILT_INS_FILTER },
3412
+ handler(importee, importer) {
3413
+ if (importee.endsWith("/")) importee = importee.slice(0, -1);
3414
+ if (builtIns.has(importee)) {
3415
+ let fromMsg = "";
3416
+ if (importer) fromMsg = ` from ${relative$1(config.rootDir, importer)}`;
3417
+ const diagnostic = buildError(builtCtx.diagnostics);
3418
+ diagnostic.header = `Node Polyfills Required`;
3419
+ diagnostic.messageText = `For the import "${importee}" to be bundled${fromMsg}, ensure the "rolldown-plugin-node-polyfills" plugin is installed and added to the stencil config plugins (${platform}). Please see the bundling docs for more information.
3420
+ Further information: https://stenciljs.com/docs/module-bundling`;
3421
+ }
3422
+ return null;
3423
+ }
3424
+ }
3425
+ };
3426
+ };
3390
3427
  //#endregion
3391
3428
  //#region src/compiler/bundle/server-plugin.ts
3429
+ const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3392
3430
  const serverPlugin = (config, platform) => {
3393
3431
  const isHydrateBundle = platform === "hydrate";
3394
3432
  const serverVarid = `@removed-server-code`;
@@ -3400,205 +3438,38 @@ const serverPlugin = (config, platform) => {
3400
3438
  return false;
3401
3439
  };
3402
3440
  const externals = isHydrateBundle ? config.outputTargets.filter(isOutputTargetHydrate).flatMap((o) => o.external) : [];
3441
+ const filterPatterns = [escapeRegex(serverVarid), "\\.server"];
3442
+ if (externals.length > 0) filterPatterns.push(...externals.map(escapeRegex));
3403
3443
  return {
3404
3444
  name: "serverPlugin",
3405
- resolveId(id, importer) {
3406
- if (id === serverVarid) return id;
3407
- if (isHydrateBundle) {
3408
- if (externals.includes(id)) return {
3409
- id,
3410
- external: true
3411
- };
3412
- if (isServerOnlyModule(importer) && !id.startsWith(".") && !isAbsolute(id)) return {
3413
- id,
3414
- external: true
3415
- };
3416
- } else if (isServerOnlyModule(id)) return serverVarid;
3417
- return null;
3445
+ resolveId: {
3446
+ filter: { id: new RegExp(`(${filterPatterns.join("|")})`) },
3447
+ handler(id, importer) {
3448
+ if (id === serverVarid) return id;
3449
+ if (isHydrateBundle) {
3450
+ if (externals.includes(id)) return {
3451
+ id,
3452
+ external: true
3453
+ };
3454
+ if (isServerOnlyModule(importer) && !id.startsWith(".") && !isAbsolute(id)) return {
3455
+ id,
3456
+ external: true
3457
+ };
3458
+ } else if (isServerOnlyModule(id)) return serverVarid;
3459
+ return null;
3460
+ }
3418
3461
  },
3419
- load(id) {
3420
- if (id === serverVarid) return {
3421
- code: "export default {};",
3422
- syntheticNamedExports: true
3423
- };
3424
- return null;
3425
- }
3426
- };
3427
- };
3428
- const IS_CASE_SENSITIVE_FILE_NAMES = !(process.platform === "win32");
3429
- //#endregion
3430
- //#region src/compiler/sys/typescript/typescript-sys.ts
3431
- const patchTsSystemFileSystem = (config, compilerSys, inMemoryFs, tsSys) => {
3432
- const realpath = (path) => {
3433
- const rp = compilerSys.realpathSync(path);
3434
- if (isString$1(rp)) return rp;
3435
- return path;
3436
- };
3437
- const getAccessibleFileSystemEntries = (path) => {
3438
- try {
3439
- const entries = compilerSys.readDirSync(path || ".").sort();
3440
- const files = [];
3441
- const directories = [];
3442
- for (const absPath of entries) {
3443
- const stat = inMemoryFs.statSync(absPath);
3444
- if (!stat) continue;
3445
- const entry = basename$1(absPath);
3446
- if (stat.isFile) files.push(entry);
3447
- else if (stat.isDirectory) directories.push(entry);
3462
+ load: {
3463
+ filter: { id: /^@removed-server-code$/ },
3464
+ handler(id) {
3465
+ if (id === serverVarid) return {
3466
+ code: "export default {};",
3467
+ syntheticNamedExports: true
3468
+ };
3469
+ return null;
3448
3470
  }
3449
- return {
3450
- files,
3451
- directories
3452
- };
3453
- } catch {
3454
- return {
3455
- files: [],
3456
- directories: []
3457
- };
3458
- }
3459
- };
3460
- tsSys.createDirectory = (p) => {
3461
- compilerSys.createDirSync(p, { recursive: true });
3462
- };
3463
- tsSys.directoryExists = (p) => {
3464
- if (inMemoryFs) return inMemoryFs.statSync(p).isDirectory;
3465
- else return compilerSys.statSync(p).isDirectory;
3466
- };
3467
- tsSys.exit = compilerSys.exit;
3468
- tsSys.fileExists = (p) => {
3469
- let filePath = p;
3470
- if (isRemoteUrl(p)) filePath = getTypescriptPathFromUrl(config, tsSys.getExecutingFilePath(), p);
3471
- if (inMemoryFs) {
3472
- const s = inMemoryFs.statSync(filePath);
3473
- return !!(s && s.isFile);
3474
- } else {
3475
- const s = compilerSys.statSync(filePath);
3476
- return !!(s && s.isFile);
3477
3471
  }
3478
3472
  };
3479
- tsSys.getCurrentDirectory = compilerSys.getCurrentDirectory;
3480
- tsSys.getExecutingFilePath = () => {
3481
- try {
3482
- return __require.resolve("typescript");
3483
- } catch {
3484
- return compilerSys.getCompilerExecutingPath();
3485
- }
3486
- };
3487
- tsSys.getDirectories = (p) => {
3488
- return compilerSys.readDirSync(p).filter((itemPath) => {
3489
- if (inMemoryFs) {
3490
- const s = inMemoryFs.statSync(itemPath);
3491
- return !!(s && s.exists && s.isDirectory);
3492
- } else {
3493
- const s = compilerSys.statSync(itemPath);
3494
- return !!(s && s.isDirectory);
3495
- }
3496
- });
3497
- };
3498
- tsSys.readDirectory = (path, extensions, exclude, include, depth) => {
3499
- const cwd = compilerSys.getCurrentDirectory();
3500
- return ts.matchFiles(path, extensions, exclude, include, IS_CASE_SENSITIVE_FILE_NAMES, cwd, depth, getAccessibleFileSystemEntries, realpath);
3501
- };
3502
- tsSys.readFile = (filePath) => {
3503
- return inMemoryFs ? inMemoryFs.readFileSync(filePath, { useCache: false }) : compilerSys.readFileSync(filePath);
3504
- };
3505
- tsSys.writeFile = (p, data) => inMemoryFs ? inMemoryFs.writeFile(p, data) : compilerSys.writeFile(p, data);
3506
- return tsSys;
3507
- };
3508
- const patchTsSystemWatch = (compilerSystem, tsSys) => {
3509
- tsSys.watchDirectory = (p, cb, recursive) => {
3510
- const watcher = compilerSystem.watchDirectory(p, (filePath) => {
3511
- cb(filePath);
3512
- }, recursive);
3513
- return { close() {
3514
- watcher.close();
3515
- } };
3516
- };
3517
- tsSys.watchFile = (p, cb) => {
3518
- const watcher = compilerSystem.watchFile(p, (filePath, eventKind) => {
3519
- if (eventKind === "fileAdd") cb(filePath, ts.FileWatcherEventKind.Created);
3520
- else if (eventKind === "fileUpdate") cb(filePath, ts.FileWatcherEventKind.Changed);
3521
- else if (eventKind === "fileDelete") cb(filePath, ts.FileWatcherEventKind.Deleted);
3522
- });
3523
- return { close() {
3524
- watcher.close();
3525
- } };
3526
- };
3527
- };
3528
- const patchTypescript = (config, inMemoryFs) => {
3529
- if (!ts.__patched) {
3530
- patchTsSystemFileSystem(config, config.sys, inMemoryFs, ts.sys);
3531
- patchTsSystemWatch(config.sys, ts.sys);
3532
- ts.__patched = true;
3533
- }
3534
- };
3535
- const patchTypeScriptSysMinimum = () => {
3536
- if (!ts.sys) ts.sys = {
3537
- args: [],
3538
- createDirectory: noop,
3539
- directoryExists: () => false,
3540
- exit: noop,
3541
- fileExists: () => false,
3542
- getCurrentDirectory: process.cwd,
3543
- getDirectories: () => [],
3544
- getExecutingFilePath: () => "./",
3545
- readDirectory: () => [],
3546
- readFile: noop,
3547
- newLine: "\n",
3548
- resolvePath: resolve$1,
3549
- useCaseSensitiveFileNames: false,
3550
- write: noop,
3551
- writeFile: noop
3552
- };
3553
- };
3554
- patchTypeScriptSysMinimum();
3555
- const getTypescriptPathFromUrl = (config, tsExecutingUrl, url) => {
3556
- const tsBaseUrl = new URL("..", tsExecutingUrl).href;
3557
- if (url.startsWith(tsBaseUrl)) {
3558
- const tsFilePath = url.replace(tsBaseUrl, "/");
3559
- return normalizePath(config.sys.getLocalModulePath({
3560
- rootDir: config.rootDir,
3561
- moduleId: "@stencil/core",
3562
- path: tsFilePath
3563
- }));
3564
- }
3565
- return url;
3566
- };
3567
- //#endregion
3568
- //#region src/compiler/sys/typescript/typescript-resolve-module.ts
3569
- const tsResolveModuleName = (config, compilerCtx, moduleName, containingFile) => {
3570
- const resolveModuleName = ts.__resolveModuleName || ts.resolveModuleName;
3571
- if (moduleName && resolveModuleName && config.tsCompilerOptions) {
3572
- const host = patchTsSystemFileSystem(config, config.sys, compilerCtx.fs, ts.sys);
3573
- const compilerOptions = { ...config.tsCompilerOptions };
3574
- compilerOptions.resolveJsonModule = true;
3575
- return resolveModuleName(moduleName, containingFile, compilerOptions, host);
3576
- }
3577
- return null;
3578
- };
3579
- const tsGetSourceFile = (config, module) => {
3580
- if (!module || !module.resolvedModule) return null;
3581
- const compilerOptions = { ...config.tsCompilerOptions };
3582
- const host = ts.createCompilerHost(compilerOptions);
3583
- return ts.createProgram([module.resolvedModule.resolvedFileName], compilerOptions, host).getSourceFile(module.resolvedModule.resolvedFileName);
3584
- };
3585
- const tsResolveModuleNamePackageJsonPath = (config, compilerCtx, moduleName, containingFile) => {
3586
- try {
3587
- const resolvedModule = tsResolveModuleName(config, compilerCtx, moduleName, containingFile);
3588
- if (resolvedModule && resolvedModule.resolvedModule && resolvedModule.resolvedModule.resolvedFileName) {
3589
- const rootDir = resolve$1("/");
3590
- let resolvedFileName = resolvedModule.resolvedModule.resolvedFileName;
3591
- for (let i = 0; i < 30; i++) {
3592
- if (rootDir === resolvedFileName) return null;
3593
- resolvedFileName = dirname$1(resolvedFileName);
3594
- const pkgJsonPath = join$1(resolvedFileName, "package.json");
3595
- if (config.sys.accessSync(pkgJsonPath)) return normalizePath(pkgJsonPath);
3596
- }
3597
- }
3598
- } catch (e) {
3599
- config.logger.error(e);
3600
- }
3601
- return null;
3602
3473
  };
3603
3474
  //#endregion
3604
3475
  //#region src/compiler/transpile/transpiled-module.ts
@@ -3660,11 +3531,11 @@ const createModule = (staticSourceFile, staticSourceFileText, emitFilepath) => (
3660
3531
  //#endregion
3661
3532
  //#region src/compiler/bundle/typescript-plugin.ts
3662
3533
  /**
3663
- * Rollup plugin that aids in resolving the TypeScript files and performing the transpilation step.
3534
+ * Rolldown plugin that aids in resolving the TypeScript files and performing the transpilation step.
3664
3535
  * @param compilerCtx the current compiler context
3665
- * @param bundleOpts Rollup bundling options to apply during TypeScript compilation
3536
+ * @param bundleOpts Rolldown bundling options to apply during TypeScript compilation
3666
3537
  * @param config the Stencil configuration for the project
3667
- * @returns the rollup plugin for handling TypeScript files.
3538
+ * @returns the rolldown plugin for handling TypeScript files.
3668
3539
  */
3669
3540
  const typescriptPlugin = (compilerCtx, bundleOpts, config) => {
3670
3541
  return {
@@ -3707,36 +3578,28 @@ const typescriptPlugin = (compilerCtx, bundleOpts, config) => {
3707
3578
  }
3708
3579
  };
3709
3580
  };
3710
- const resolveIdWithTypeScript = (config, compilerCtx) => {
3711
- return {
3712
- name: `resolveIdWithTypeScript`,
3713
- async resolveId(importee, importer) {
3714
- if (/\0/.test(importee) || !isString$1(importer)) return null;
3715
- const tsResolved = tsResolveModuleName(config, compilerCtx, importee, importer);
3716
- if (tsResolved && tsResolved.resolvedModule) {
3717
- const tsResolvedPath = tsResolved.resolvedModule.resolvedFileName;
3718
- if (isString$1(tsResolvedPath) && !isDtsFile(tsResolvedPath)) return tsResolvedPath;
3719
- }
3720
- return null;
3721
- }
3722
- };
3723
- };
3724
- //#endregion
3725
- //#region src/compiler/bundle/user-index-plugin.ts
3726
- const userIndexPlugin = (config, compilerCtx) => {
3581
+ //#endregion
3582
+ //#region src/compiler/bundle/user-index-plugin.ts
3583
+ const userIndexPlugin = (config, compilerCtx) => {
3727
3584
  return {
3728
3585
  name: "userIndexPlugin",
3729
- async resolveId(importee) {
3730
- if (importee === "@user-index-entrypoint") {
3731
- const usersIndexJsPath = join$1(config.srcDir, "index.ts");
3732
- if (await compilerCtx.fs.access(usersIndexJsPath)) return usersIndexJsPath;
3733
- return importee;
3586
+ resolveId: {
3587
+ filter: { id: /^@user-index-entrypoint$/ },
3588
+ async handler(importee) {
3589
+ if (importee === "@user-index-entrypoint") {
3590
+ const usersIndexJsPath = join$1(config.srcDir, "index.ts");
3591
+ if (await compilerCtx.fs.access(usersIndexJsPath)) return usersIndexJsPath;
3592
+ return importee;
3593
+ }
3594
+ return null;
3734
3595
  }
3735
- return null;
3736
3596
  },
3737
- async load(id) {
3738
- if (id === "@user-index-entrypoint") return `//! Autogenerated index`;
3739
- return null;
3597
+ load: {
3598
+ filter: { id: /^@user-index-entrypoint$/ },
3599
+ handler(id) {
3600
+ if (id === "@user-index-entrypoint") return `//! Autogenerated index`;
3601
+ return null;
3602
+ }
3740
3603
  }
3741
3604
  };
3742
3605
  };
@@ -3867,7 +3730,7 @@ const MINIFY_CHAR_BREAK = new Set([
3867
3730
  * @returns the minified JavaScript result
3868
3731
  */
3869
3732
  const optimizeModule = async (config, compilerCtx, opts) => {
3870
- if (!opts.minify && opts.sourceTarget !== "es5" || opts.input === "") return {
3733
+ if (!opts.minify || opts.input === "") return {
3871
3734
  output: opts.input,
3872
3735
  diagnostics: [],
3873
3736
  sourceMap: opts.sourceMap
@@ -3883,35 +3746,30 @@ const optimizeModule = async (config, compilerCtx, opts) => {
3883
3746
  sourceMap: cachedMap ? JSON.parse(cachedMap) : null
3884
3747
  };
3885
3748
  }
3886
- let minifyOpts;
3887
- let code = opts.input;
3888
- if (opts.isCore) code = code.replace(/\/\* IS_ESM_BUILD \*\//g, "&& false /* IS_SYSTEM_JS_BUILD */");
3889
- if (opts.sourceTarget === "es5" || opts.minify) {
3890
- minifyOpts = getTerserOptions(config, opts.sourceTarget, isDebug);
3891
- if (config.sourceMap) minifyOpts.sourceMap = { content: opts.sourceMap != null ? {
3892
- ...opts.sourceMap,
3893
- version: 3
3894
- } : void 0 };
3895
- const compressOpts = minifyOpts.compress;
3896
- const mangleOptions = minifyOpts.mangle;
3897
- if (opts.sourceTarget !== "es5" && opts.isCore) {
3898
- if (!isDebug) {
3899
- compressOpts.passes = 2;
3900
- compressOpts.global_defs = { supportsListenerOptions: true };
3901
- compressOpts.pure_funcs = compressOpts.pure_funcs || [];
3902
- compressOpts.pure_funcs = ["getHostRef", ...compressOpts.pure_funcs];
3903
- }
3904
- mangleOptions.properties = {
3905
- debug: isDebug,
3906
- ...getTerserManglePropertiesConfig()
3907
- };
3908
- compressOpts.inline = 1;
3909
- compressOpts.unsafe = true;
3910
- compressOpts.unsafe_undefined = true;
3911
- }
3749
+ const minifyOpts = getTerserOptions(config, opts.sourceTarget, isDebug);
3750
+ const code = opts.input;
3751
+ if (config.sourceMap) minifyOpts.sourceMap = { content: opts.sourceMap != null ? {
3752
+ ...opts.sourceMap,
3753
+ version: 3
3754
+ } : void 0 };
3755
+ const compressOpts = minifyOpts.compress;
3756
+ const mangleOptions = minifyOpts.mangle;
3757
+ if (opts.isCore) {
3758
+ if (!isDebug) {
3759
+ compressOpts.passes = 2;
3760
+ compressOpts.global_defs = { supportsListenerOptions: true };
3761
+ compressOpts.pure_funcs = compressOpts.pure_funcs || [];
3762
+ compressOpts.pure_funcs = ["getHostRef", ...compressOpts.pure_funcs];
3763
+ }
3764
+ mangleOptions.properties = {
3765
+ debug: isDebug,
3766
+ ...getTerserManglePropertiesConfig()
3767
+ };
3768
+ compressOpts.inline = 1;
3769
+ compressOpts.unsafe = true;
3770
+ compressOpts.unsafe_undefined = true;
3912
3771
  }
3913
- const shouldTranspile = opts.sourceTarget === "es5";
3914
- const results = await compilerCtx.worker.prepareModule(code, minifyOpts, shouldTranspile, !!opts.inlineHelpers);
3772
+ const results = await compilerCtx.worker.prepareModule(code, minifyOpts);
3915
3773
  if (results != null && typeof results.output === "string" && results.diagnostics.length === 0 && compilerCtx != null) {
3916
3774
  if (opts.isCore) results.output = results.output.replace(/disconnectedCallback\(\)\{\},/g, "");
3917
3775
  await compilerCtx.cache.put(cacheKey, results.output);
@@ -3933,25 +3791,19 @@ const getTerserOptions = (config, sourceTarget, prettyOutput) => {
3933
3791
  format: {},
3934
3792
  sourceMap: config.sourceMap
3935
3793
  };
3936
- if (sourceTarget === "es5") {
3937
- opts.ecma = opts.format.ecma = 5;
3938
- opts.compress = false;
3939
- opts.mangle = { properties: getTerserManglePropertiesConfig() };
3940
- } else {
3941
- opts.mangle = { properties: getTerserManglePropertiesConfig() };
3942
- opts.compress = {
3943
- pure_getters: true,
3944
- keep_fargs: false,
3945
- passes: 2
3946
- };
3947
- opts.ecma = opts.format.ecma = opts.compress.ecma = 2018;
3948
- opts.toplevel = true;
3949
- opts.module = true;
3950
- opts.mangle.toplevel = true;
3951
- opts.compress.arrows = true;
3952
- opts.compress.module = true;
3953
- opts.compress.toplevel = true;
3954
- }
3794
+ opts.mangle = { properties: getTerserManglePropertiesConfig() };
3795
+ opts.compress = {
3796
+ pure_getters: true,
3797
+ keep_fargs: false,
3798
+ passes: 2
3799
+ };
3800
+ opts.ecma = opts.format.ecma = opts.compress.ecma = 2018;
3801
+ opts.toplevel = true;
3802
+ opts.module = true;
3803
+ opts.mangle.toplevel = true;
3804
+ opts.compress.arrows = true;
3805
+ opts.compress.module = true;
3806
+ opts.compress.toplevel = true;
3955
3807
  if (prettyOutput) {
3956
3808
  opts.mangle = {
3957
3809
  keep_fnames: true,
@@ -3983,54 +3835,28 @@ function getTerserManglePropertiesConfig() {
3983
3835
  * This method is likely to be called by a worker on the compiler context, rather than directly.
3984
3836
  * @param input the source code to minify
3985
3837
  * @param minifyOpts options to be used by the minifier
3986
- * @param transpileToEs5 if true, use the TypeScript compiler to transpile the input to ES5 prior to minification
3987
- * @param inlineHelpers when true, emits less terse JavaScript by allowing global helpers created by the TypeScript
3988
- * compiler to be added directly to the transpiled source. Used only if `transpileToEs5` is true.
3989
3838
  * @returns minified input, as JavaScript
3990
3839
  */
3991
- const prepareModule = async (input, minifyOpts, transpileToEs5, inlineHelpers) => {
3992
- const results = {
3840
+ const prepareModule = async (input, minifyOpts) => {
3841
+ if (minifyOpts) return minifyJs(input, minifyOpts);
3842
+ return {
3993
3843
  output: input,
3994
3844
  diagnostics: [],
3995
3845
  sourceMap: null
3996
3846
  };
3997
- if (transpileToEs5) {
3998
- const tsResults = ts.transpileModule(input, {
3999
- fileName: "module.ts",
4000
- compilerOptions: {
4001
- sourceMap: !!minifyOpts.sourceMap,
4002
- allowJs: true,
4003
- target: ts.ScriptTarget.ES5,
4004
- module: ts.ModuleKind.ESNext,
4005
- removeComments: false,
4006
- isolatedModules: true,
4007
- skipLibCheck: true,
4008
- noEmitHelpers: !inlineHelpers,
4009
- importHelpers: !inlineHelpers
4010
- },
4011
- reportDiagnostics: false
4012
- });
4013
- results.output = tsResults.outputText;
4014
- if (tsResults.sourceMapText) {
4015
- const mergeMap = sourceMapMerge(minifyOpts.sourceMap?.content, JSON.parse(tsResults.sourceMapText));
4016
- if (mergeMap != null) minifyOpts.sourceMap = { content: {
4017
- ...mergeMap,
4018
- sources: mergeMap.sources ?? [],
4019
- version: 3
4020
- } };
4021
- }
4022
- }
4023
- if (minifyOpts) return minifyJs(results.output, minifyOpts);
4024
- return results;
4025
3847
  };
4026
3848
  //#endregion
4027
3849
  //#region src/compiler/bundle/worker-plugin.ts
3850
+ const WORKER_FILTER = /(\?worker(-inline)?|\.worker(\.tsx?|\/index\.tsx?))$/;
4028
3851
  const workerPlugin = (config, compilerCtx, buildCtx, platform, inlineWorkers) => {
4029
3852
  if (platform === "worker" || platform === "hydrate") return {
4030
3853
  name: "workerPlugin",
4031
- transform(_, id) {
4032
- if (id.endsWith("?worker") || id.endsWith("?worker-inline")) return getMockedWorkerMain();
4033
- return null;
3854
+ transform: {
3855
+ filter: { id: /\?worker(-inline)?$/ },
3856
+ handler(_, id) {
3857
+ if (id.endsWith("?worker") || id.endsWith("?worker-inline")) return getMockedWorkerMain();
3858
+ return null;
3859
+ }
4034
3860
  }
4035
3861
  };
4036
3862
  const workersMap = /* @__PURE__ */ new Map();
@@ -4039,61 +3865,70 @@ const workerPlugin = (config, compilerCtx, buildCtx, platform, inlineWorkers) =>
4039
3865
  buildStart() {
4040
3866
  workersMap.clear();
4041
3867
  },
4042
- resolveId(id) {
4043
- if (id === WORKER_HELPER_ID) return {
4044
- id,
4045
- moduleSideEffects: false
4046
- };
4047
- return null;
4048
- },
4049
- load(id) {
4050
- if (id === WORKER_HELPER_ID) return WORKER_HELPERS;
4051
- return null;
4052
- },
4053
- async transform(_, id) {
4054
- if (/\0/.test(id)) return null;
4055
- if (id.endsWith("?worker")) {
4056
- const workerEntryPath = normalizeFsPath(id);
4057
- const workerName = getWorkerName(workerEntryPath);
4058
- const { code, dependencies, workerMsgId } = await getWorker(config, compilerCtx, buildCtx, this, workersMap, workerEntryPath);
4059
- const referenceId = this.emitFile({
4060
- type: "asset",
4061
- source: code,
4062
- name: workerName + ".js"
4063
- });
4064
- dependencies.forEach((dep) => this.addWatchFile(dep));
4065
- return {
4066
- code: getWorkerMain(referenceId, workerName, workerMsgId),
4067
- moduleSideEffects: false
4068
- };
4069
- } else if (id.endsWith("?worker-inline")) {
4070
- const workerEntryPath = normalizeFsPath(id);
4071
- const workerName = getWorkerName(workerEntryPath);
4072
- const { code, dependencies, workerMsgId } = await getWorker(config, compilerCtx, buildCtx, this, workersMap, workerEntryPath);
4073
- const referenceId = this.emitFile({
4074
- type: "asset",
4075
- source: code,
4076
- name: workerName + ".js"
4077
- });
4078
- dependencies.forEach((dep) => this.addWatchFile(dep));
4079
- return {
4080
- code: getInlineWorker(referenceId, workerName, workerMsgId),
3868
+ resolveId: {
3869
+ filter: { id: /^@worker-helper$/ },
3870
+ handler(id) {
3871
+ if (id === WORKER_HELPER_ID) return {
3872
+ id,
4081
3873
  moduleSideEffects: false
4082
3874
  };
3875
+ return null;
4083
3876
  }
4084
- const workerEntryPath = getWorkerEntryPath(id);
4085
- if (workerEntryPath != null) {
4086
- const worker = await getWorker(config, compilerCtx, buildCtx, this, workersMap, workerEntryPath);
4087
- if (worker) if (inlineWorkers) return {
4088
- code: getInlineWorkerProxy(workerEntryPath, worker.workerMsgId, worker.exports),
4089
- moduleSideEffects: false
4090
- };
4091
- else return {
4092
- code: getWorkerProxy(workerEntryPath, worker.exports),
4093
- moduleSideEffects: false
4094
- };
3877
+ },
3878
+ load: {
3879
+ filter: { id: /^@worker-helper$/ },
3880
+ handler(id) {
3881
+ if (id === WORKER_HELPER_ID) return WORKER_HELPERS;
3882
+ return null;
3883
+ }
3884
+ },
3885
+ transform: {
3886
+ filter: { id: WORKER_FILTER },
3887
+ async handler(_, id) {
3888
+ if (/\0/.test(id)) return null;
3889
+ if (id.endsWith("?worker")) {
3890
+ const workerEntryPath = normalizeFsPath(id);
3891
+ const workerName = getWorkerName(workerEntryPath);
3892
+ const { code, dependencies, workerMsgId } = await getWorker(config, compilerCtx, buildCtx, this, workersMap, workerEntryPath);
3893
+ const referenceId = this.emitFile({
3894
+ type: "asset",
3895
+ source: code,
3896
+ name: workerName + ".js"
3897
+ });
3898
+ dependencies.forEach((dep) => this.addWatchFile(dep));
3899
+ return {
3900
+ code: getWorkerMain(referenceId, workerName, workerMsgId),
3901
+ moduleSideEffects: false
3902
+ };
3903
+ } else if (id.endsWith("?worker-inline")) {
3904
+ const workerEntryPath = normalizeFsPath(id);
3905
+ const workerName = getWorkerName(workerEntryPath);
3906
+ const { code, dependencies, workerMsgId } = await getWorker(config, compilerCtx, buildCtx, this, workersMap, workerEntryPath);
3907
+ const referenceId = this.emitFile({
3908
+ type: "asset",
3909
+ source: code,
3910
+ name: workerName + ".js"
3911
+ });
3912
+ dependencies.forEach((dep) => this.addWatchFile(dep));
3913
+ return {
3914
+ code: getInlineWorker(referenceId, workerName, workerMsgId),
3915
+ moduleSideEffects: false
3916
+ };
3917
+ }
3918
+ const workerEntryPath = getWorkerEntryPath(id);
3919
+ if (workerEntryPath != null) {
3920
+ const worker = await getWorker(config, compilerCtx, buildCtx, this, workersMap, workerEntryPath);
3921
+ if (worker) if (inlineWorkers) return {
3922
+ code: getInlineWorkerProxy(workerEntryPath, worker.workerMsgId, worker.exports),
3923
+ moduleSideEffects: false
3924
+ };
3925
+ else return {
3926
+ code: getWorkerProxy(workerEntryPath, worker.exports),
3927
+ moduleSideEffects: false
3928
+ };
3929
+ }
3930
+ return null;
4095
3931
  }
4096
- return null;
4097
3932
  }
4098
3933
  };
4099
3934
  };
@@ -4121,7 +3956,7 @@ const buildWorker = async (config, compilerCtx, buildCtx, ctx, workerEntryPath)
4121
3956
  platform: "worker",
4122
3957
  id: workerName,
4123
3958
  inputs: { [workerName]: workerEntryPath },
4124
- inlineDynamicImports: true
3959
+ codeSplitting: false
4125
3960
  });
4126
3961
  if (build) {
4127
3962
  const entryPoint = (await build.generate({
@@ -4136,7 +3971,7 @@ const buildWorker = async (config, compilerCtx, buildCtx, ctx, workerEntryPath)
4136
3971
  let code = entryPoint.code;
4137
3972
  const results = await optimizeModule(config, compilerCtx, {
4138
3973
  input: code,
4139
- sourceTarget: config.buildEs5 ? "es5" : "es2017",
3974
+ sourceTarget: "es2017",
4140
3975
  isCore: false,
4141
3976
  minify: config.minifyJs,
4142
3977
  inlineHelpers: true
@@ -4336,7 +4171,7 @@ const getWorkerMain = (referenceId, workerName, workerMsgId) => {
4336
4171
  import { createWorker } from '${WORKER_HELPER_ID}';
4337
4172
  export const workerName = '${workerName}';
4338
4173
  export const workerMsgId = '${workerMsgId}';
4339
- export const workerPath = /*@__PURE__*/import.meta.ROLLUP_FILE_URL_${referenceId};
4174
+ export const workerPath = /*@__PURE__*/import.meta.ROLLDOWN_FILE_URL_${referenceId};
4340
4175
  export const worker = /*@__PURE__*/createWorker(workerPath, workerName, workerMsgId);
4341
4176
  `;
4342
4177
  };
@@ -4345,7 +4180,7 @@ const getInlineWorker = (referenceId, workerName, workerMsgId) => {
4345
4180
  import { createWorker } from '${WORKER_HELPER_ID}';
4346
4181
  export const workerName = '${workerName}';
4347
4182
  export const workerMsgId = '${workerMsgId}';
4348
- export const workerPath = /*@__PURE__*/import.meta.ROLLUP_FILE_URL_${referenceId};
4183
+ export const workerPath = /*@__PURE__*/import.meta.ROLLDOWN_FILE_URL_${referenceId};
4349
4184
  export let worker;
4350
4185
  try {
4351
4186
  // first try directly starting the worker with the URL
@@ -4389,91 +4224,34 @@ ${exportedMethods.map((exportedMethod) => {
4389
4224
  //#region src/compiler/bundle/bundle-output.ts
4390
4225
  const bundleOutput = async (config, compilerCtx, buildCtx, bundleOpts) => {
4391
4226
  try {
4392
- const rollupBuild = await rollup(getRollupOptions(config, compilerCtx, buildCtx, bundleOpts));
4393
- compilerCtx.rollupCache.set(bundleOpts.id, rollupBuild.cache);
4394
- return rollupBuild;
4227
+ return await rolldown(getRolldownOptions(config, compilerCtx, buildCtx, bundleOpts));
4395
4228
  } catch (e) {
4396
- if (!buildCtx.hasError) loadRollupDiagnostics(config, compilerCtx, buildCtx, e);
4229
+ if (!buildCtx.hasError) loadRolldownDiagnostics(config, compilerCtx, buildCtx, e);
4397
4230
  }
4398
4231
  };
4399
4232
  /**
4400
- * Build the rollup options that will be used to transpile, minify, and otherwise transform a Stencil project
4233
+ * Build the rolldown options that will be used to transpile, minify, and otherwise transform a Stencil project
4401
4234
  * @param config the Stencil configuration for the project
4402
4235
  * @param compilerCtx the current compiler context
4403
4236
  * @param buildCtx a context object containing information about the current build
4404
- * @param bundleOpts Rollup bundling options to apply to the base configuration setup by this function
4405
- * @returns the rollup options to be used
4406
- */
4407
- const getRollupOptions = (config, compilerCtx, buildCtx, bundleOpts) => {
4408
- const nodeResolvePlugin = rollupNodeResolvePlugin({
4409
- mainFields: [
4410
- "collection:main",
4411
- "jsnext:main",
4412
- "es2017",
4413
- "es2015",
4414
- "module",
4415
- "main"
4416
- ],
4417
- browser: bundleOpts.platform !== "hydrate",
4418
- rootDir: config.rootDir,
4419
- exportConditions: [
4420
- "default",
4421
- "module",
4422
- "import",
4423
- "require"
4424
- ],
4425
- extensions: [
4426
- ".tsx",
4427
- ".ts",
4428
- ".mts",
4429
- ".cts",
4430
- ".js",
4431
- ".mjs",
4432
- ".cjs",
4433
- ".json",
4434
- ".d.ts",
4435
- ".d.mts",
4436
- ".d.cts"
4437
- ],
4438
- ...config.nodeResolve
4439
- });
4440
- nodeResolvePlugin.resolve = async function() {};
4441
- nodeResolvePlugin.warn = (log) => {
4442
- const onWarn = createOnWarnFn(buildCtx.diagnostics);
4443
- if (typeof log === "string") onWarn({ message: log });
4444
- else if (typeof log === "function") {
4445
- const result = log();
4446
- if (typeof result === "string") onWarn({ message: result });
4447
- else onWarn(result);
4448
- } else onWarn(log);
4449
- };
4450
- assertIsObjectHook(nodeResolvePlugin.resolveId);
4451
- nodeResolvePlugin.resolveId.order = null;
4452
- const orgNodeResolveId = nodeResolvePlugin.resolveId.handler;
4453
- const orgNodeResolveId2 = nodeResolvePlugin.resolveId.handler = async function(importee, importer) {
4454
- const [realImportee, query] = importee.split("?");
4455
- const resolved = await orgNodeResolveId.call(nodeResolvePlugin, realImportee, importer, {
4456
- attributes: {},
4457
- isEntry: true
4458
- });
4459
- if (resolved) {
4460
- if (isString$1(resolved)) return query ? resolved + "?" + query : resolved;
4461
- return {
4462
- ...resolved,
4463
- id: query ? resolved.id + "?" + query : resolved.id
4464
- };
4237
+ * @param bundleOpts Rolldown bundling options to apply to the base configuration setup by this function
4238
+ * @returns the rolldown options to be used
4239
+ */
4240
+ const getRolldownOptions = (config, compilerCtx, buildCtx, bundleOpts) => {
4241
+ const beforePlugins = config.rolldownPlugins.before || [];
4242
+ const afterPlugins = config.rolldownPlugins.after || [];
4243
+ const devModulePlugin = config.devServer?.experimentalDevModules ? {
4244
+ name: "stencil-dev-module-resolve",
4245
+ async resolveId(importee, importer) {
4246
+ const resolved = await this.resolve(importee, importer, { skipSelf: true });
4247
+ if (resolved) return devNodeModuleResolveId(config, compilerCtx.fs, resolved, importee);
4248
+ return null;
4465
4249
  }
4466
- return resolved;
4467
- };
4468
- if (config.devServer?.experimentalDevModules) nodeResolvePlugin.resolveId = async function(importee, importer) {
4469
- const resolvedId = await orgNodeResolveId2.call(nodeResolvePlugin, importee, importer);
4470
- return devNodeModuleResolveId(config, compilerCtx.fs, resolvedId, importee);
4471
- };
4472
- const beforePlugins = config.rollupPlugins.before || [];
4473
- const afterPlugins = config.rollupPlugins.after || [];
4250
+ } : null;
4474
4251
  return {
4475
4252
  input: bundleOpts.inputs,
4476
- output: { inlineDynamicImports: bundleOpts.inlineDynamicImports ?? false },
4253
+ platform: bundleOpts.platform === "hydrate" ? "node" : "browser",
4254
+ tsconfig: config.tsconfig,
4477
4255
  plugins: [
4478
4256
  coreResolvePlugin(config, compilerCtx, bundleOpts.platform, !!bundleOpts.externalRuntime, bundleOpts.conditionals?.lazyLoad ?? false),
4479
4257
  appDataPlugin(config, compilerCtx, buildCtx, bundleOpts.conditionals, bundleOpts.platform),
@@ -4486,44 +4264,82 @@ const getRollupOptions = (config, compilerCtx, buildCtx, bundleOpts) => {
4486
4264
  workerPlugin(config, compilerCtx, buildCtx, bundleOpts.platform, !!bundleOpts.inlineWorkers),
4487
4265
  serverPlugin(config, bundleOpts.platform),
4488
4266
  ...beforePlugins,
4489
- nodeResolvePlugin,
4490
- resolveIdWithTypeScript(config, compilerCtx),
4491
- rollupCommonjsPlugin({
4492
- include: /node_modules/,
4493
- sourceMap: config.sourceMap,
4494
- transformMixedEsModules: false,
4495
- ...config.commonjs
4496
- }),
4267
+ devModulePlugin,
4497
4268
  ...afterPlugins,
4498
4269
  pluginHelper(config, buildCtx, bundleOpts.platform),
4499
- rollupJsonPlugin({ preferConst: true }),
4500
- rollupReplacePlugin({
4501
- "process.env.NODE_ENV": config.devMode ? "\"development\"" : "\"production\"",
4502
- preventAssignment: true
4503
- }),
4504
4270
  fileLoadPlugin(compilerCtx.fs)
4505
- ],
4271
+ ].filter(Boolean),
4272
+ resolve: {
4273
+ mainFields: [
4274
+ "collection:main",
4275
+ "jsnext:main",
4276
+ "es2017",
4277
+ "es2015",
4278
+ "module",
4279
+ "main"
4280
+ ],
4281
+ conditionNames: bundleOpts.platform === "hydrate" ? [
4282
+ "node",
4283
+ "import",
4284
+ "require",
4285
+ "default"
4286
+ ] : [
4287
+ "browser",
4288
+ "default",
4289
+ "import",
4290
+ "module",
4291
+ "require"
4292
+ ],
4293
+ extensions: [
4294
+ ".tsx",
4295
+ ".ts",
4296
+ ".mts",
4297
+ ".cts",
4298
+ ".js",
4299
+ ".mjs",
4300
+ ".cjs",
4301
+ ".json",
4302
+ ".d.ts",
4303
+ ".d.mts",
4304
+ ".d.cts"
4305
+ ],
4306
+ ...config.nodeResolve
4307
+ },
4308
+ transform: { define: { "process.env.NODE_ENV": config.devMode ? "\"development\"" : "\"production\"" } },
4309
+ checks: {
4310
+ preferBuiltinFeature: false,
4311
+ pluginTimings: config.devMode
4312
+ },
4313
+ moduleTypes: {
4314
+ ".css": "js",
4315
+ ".scss": "js",
4316
+ ".sass": "js",
4317
+ ".less": "js",
4318
+ ".styl": "js",
4319
+ ".stylus": "js",
4320
+ ".pcss": "js",
4321
+ ".txt": "js",
4322
+ ".frag": "js",
4323
+ ".vert": "js",
4324
+ ".svg": "js"
4325
+ },
4506
4326
  treeshake: getTreeshakeOption(config, bundleOpts),
4507
4327
  preserveEntrySignatures: bundleOpts.preserveEntrySignatures ?? "strict",
4508
- onwarn: createOnWarnFn(buildCtx.diagnostics),
4509
- cache: compilerCtx.rollupCache.get(bundleOpts.id),
4510
- external: config.rollupConfig.inputOptions.external,
4511
- maxParallelFileOps: config.rollupConfig.inputOptions.maxParallelFileOps
4328
+ external: config.rolldownConfig.inputOptions.external,
4329
+ onwarn: createOnWarnFn(buildCtx.diagnostics)
4512
4330
  };
4513
4331
  };
4514
4332
  const getTreeshakeOption = (config, bundleOpts) => {
4515
4333
  if (bundleOpts.platform === "hydrate") return {
4516
- propertyReadSideEffects: false,
4517
- tryCatchDeoptimization: false
4334
+ moduleSideEffects: false,
4335
+ propertyReadSideEffects: false
4336
+ };
4337
+ if (config.devMode || config.rolldownConfig.inputOptions.treeshake === false) return false;
4338
+ return {
4339
+ moduleSideEffects: false,
4340
+ propertyReadSideEffects: false
4518
4341
  };
4519
- return !config.devMode && config.rollupConfig.inputOptions.treeshake !== false ? {
4520
- propertyReadSideEffects: false,
4521
- tryCatchDeoptimization: false
4522
- } : false;
4523
4342
  };
4524
- function assertIsObjectHook(hook) {
4525
- if (typeof hook !== "object") throw new Error(`expected the rollup plugin hook ${hook} to be an object`);
4526
- }
4527
4343
  //#endregion
4528
4344
  //#region src/compiler/transformers/add-tag-transform.ts
4529
4345
  /**
@@ -5374,7 +5190,7 @@ const createStyleIdentifier = (cmp, style) => {
5374
5190
  const externalStyles = getExternalStyles(style);
5375
5191
  /**
5376
5192
  * Set a styleIdentifier which will be propagated to the component and
5377
- * later picked up by rollup when it injects the parsed CSS directly into
5193
+ * later picked up by rolldown when it injects the parsed CSS directly into
5378
5194
  * the component, see `compilerCtx.worker.transformCssToEsm` in
5379
5195
  * `src/compiler/bundle/ext-transforms-plugin.ts`
5380
5196
  */
@@ -5788,6 +5604,7 @@ const KEEP_IMPORTS = new Set([
5788
5604
  "writeTask",
5789
5605
  "readTask",
5790
5606
  "getElement",
5607
+ "getShadowRoot",
5791
5608
  "forceUpdate",
5792
5609
  "getRenderingRef",
5793
5610
  "forceModeUpdate",
@@ -5823,7 +5640,6 @@ const getBuildFeatures = (cmps) => {
5823
5640
  hostListenerTargetWindow: cmps.some((c) => c.hasListenerTargetWindow),
5824
5641
  hostListenerTargetDocument: cmps.some((c) => c.hasListenerTargetDocument),
5825
5642
  hostListenerTargetBody: cmps.some((c) => c.hasListenerTargetBody),
5826
- hostListenerTargetParent: cmps.some((c) => c.hasListenerTargetParent),
5827
5643
  hostListenerTarget: cmps.some((c) => c.hasListenerTarget),
5828
5644
  member: cmps.some((c) => c.hasMember),
5829
5645
  method: cmps.some((c) => c.hasMethod),
@@ -5840,6 +5656,7 @@ const getBuildFeatures = (cmps) => {
5840
5656
  serializer: cmps.some((c) => c.hasSerializer),
5841
5657
  shadowDom,
5842
5658
  shadowDelegatesFocus: shadowDom && cmps.some((c) => c.shadowDelegatesFocus),
5659
+ shadowModeClosed: shadowDom && cmps.some((c) => c.shadowMode === "closed"),
5843
5660
  shadowSlotAssignmentManual: shadowDom && cmps.some((c) => c.slotAssignment === "manual"),
5844
5661
  slot,
5845
5662
  slotRelocation,
@@ -5858,7 +5675,11 @@ const getBuildFeatures = (cmps) => {
5858
5675
  vdomRender: cmps.some((c) => c.hasVdomRender),
5859
5676
  vdomStyle: cmps.some((c) => c.hasVdomStyle),
5860
5677
  vdomText: cmps.some((c) => c.hasVdomText),
5861
- taskQueue: true
5678
+ taskQueue: true,
5679
+ patchAll: cmps.some((c) => c.hasPatchAll),
5680
+ patchChildren: cmps.some((c) => c.hasPatchChildren),
5681
+ patchClone: cmps.some((c) => c.hasPatchClone),
5682
+ patchInsert: cmps.some((c) => c.hasPatchInsert)
5862
5683
  };
5863
5684
  f.vdomAttribute = f.vdomAttribute || f.reflect;
5864
5685
  f.vdomPropOrAttr = f.vdomPropOrAttr || f.reflect;
@@ -5972,7 +5793,7 @@ const getCustomElementsBuildConditionals = (config, cmps) => {
5972
5793
  //#endregion
5973
5794
  //#region src/compiler/output-targets/dist-custom-elements/generate-loader-module.ts
5974
5795
  /**
5975
- * Generate the auto-loader module content that will be bundled via Rollup.
5796
+ * Generate the auto-loader module content that will be bundled via Rolldown.
5976
5797
  * This loader uses MutationObserver to lazily load and define custom elements
5977
5798
  * as they appear in the DOM.
5978
5799
  *
@@ -6169,7 +5990,7 @@ ${autoStart ? "\n// Auto-start the loader\nstart();" : ""}
6169
5990
  /**
6170
5991
  * Main output target function for `dist-custom-elements`. This function just
6171
5992
  * does some organizational work to call the other functions in this module,
6172
- * which do actual work of generating the rollup configuration, creating an
5993
+ * which do actual work of generating the rolldown configuration, creating an
6173
5994
  * entry chunk, running, the build, etc.
6174
5995
  *
6175
5996
  * @param config the validated compiler configuration we're using
@@ -6188,13 +6009,13 @@ const outputCustomElements = async (config, compilerCtx, buildCtx) => {
6188
6009
  };
6189
6010
  /**
6190
6011
  * Get bundle options for our current build and compiler context which we'll use
6191
- * to generate a Rollup build and so on.
6012
+ * to generate a Rolldown build and so on.
6192
6013
  *
6193
6014
  * @param config a validated Stencil configuration object
6194
6015
  * @param buildCtx the current build context
6195
6016
  * @param compilerCtx the current compiler context
6196
6017
  * @param outputTarget the outputTarget we're currently dealing with
6197
- * @returns bundle options suitable for generating a rollup configuration
6018
+ * @returns bundle options suitable for generating a rolldown configuration
6198
6019
  */
6199
6020
  const getBundleOptions = (config, buildCtx, compilerCtx, outputTarget) => ({
6200
6021
  id: "customElements",
@@ -6208,7 +6029,7 @@ const getBundleOptions = (config, buildCtx, compilerCtx, outputTarget) => ({
6208
6029
  preserveEntrySignatures: "allow-extension"
6209
6030
  });
6210
6031
  /**
6211
- * Get bundle options for rollup, run the rollup build, optionally minify the
6032
+ * Get bundle options for rolldown, run the rolldown build, optionally minify the
6212
6033
  * output, and write files to disk.
6213
6034
  *
6214
6035
  * @param config the validated Stencil configuration we're using
@@ -6223,7 +6044,7 @@ const bundleCustomElements = async (config, compilerCtx, buildCtx, outputTarget)
6223
6044
  addCustomElementInputs(buildCtx, bundleOpts, outputTarget);
6224
6045
  const build = await bundleOutput(config, compilerCtx, buildCtx, bundleOpts);
6225
6046
  if (build) {
6226
- const rollupOutput = await build.generate({
6047
+ const rolldownOutput = await build.generate({
6227
6048
  banner: generatePreamble(config),
6228
6049
  format: "esm",
6229
6050
  sourcemap: config.sourceMap,
@@ -6242,10 +6063,10 @@ const bundleCustomElements = async (config, compilerCtx, buildCtx, outputTarget)
6242
6063
  return;
6243
6064
  }
6244
6065
  const minify = isBoolean$1(outputTarget.minify) ? outputTarget.minify : config.minifyJs;
6245
- const files = rollupOutput.output.map(async (bundle) => {
6066
+ const files = rolldownOutput.output.map(async (bundle) => {
6246
6067
  if (bundle.type === "chunk") {
6247
6068
  let code = bundle.code;
6248
- let sourceMap = bundle.map ? rollupToStencilSourceMap(bundle.map) : void 0;
6069
+ let sourceMap = bundle.map ? rolldownToStencilSourceMap(bundle.map) : void 0;
6249
6070
  const optimizeResults = await optimizeModule(config, compilerCtx, {
6250
6071
  input: code,
6251
6072
  isCore: bundle.isEntry,
@@ -6487,14 +6308,14 @@ const getHydrateBuildConditionals = (config, cmps) => {
6487
6308
  //#endregion
6488
6309
  //#region src/compiler/output-targets/dist-hydrate-script/bundle-hydrate-factory.ts
6489
6310
  /**
6490
- * Marshall some Rollup options for the hydrate factory and then pass it to our
6311
+ * Marshall some Rolldown options for the hydrate factory and then pass it to our
6491
6312
  * {@link bundleOutput} helper
6492
6313
  *
6493
6314
  * @param config a validated Stencil configuration
6494
6315
  * @param compilerCtx the current compiler context
6495
6316
  * @param buildCtx the current build context
6496
6317
  * @param appFactoryEntryCode an entry code for the app factory
6497
- * @returns a promise wrapping a rollup build object
6318
+ * @returns a promise wrapping a rolldown build object
6498
6319
  */
6499
6320
  const bundleHydrateFactory = async (config, compilerCtx, buildCtx, appFactoryEntryCode) => {
6500
6321
  try {
@@ -6503,12 +6324,12 @@ const bundleHydrateFactory = async (config, compilerCtx, buildCtx, appFactoryEnt
6503
6324
  platform: "hydrate",
6504
6325
  conditionals: getHydrateBuildConditionals(config, buildCtx.components),
6505
6326
  customBeforeTransformers: getCustomBeforeTransformers$1(config, compilerCtx, buildCtx),
6506
- inlineDynamicImports: true,
6327
+ codeSplitting: false,
6507
6328
  inputs: { "@stencil/core/runtime/server/hydrate-factory": "@stencil/core/runtime/server/hydrate-factory" },
6508
6329
  loader: { "@stencil/core/runtime/server/hydrate-factory": appFactoryEntryCode }
6509
6330
  });
6510
6331
  } catch (e) {
6511
- if (!buildCtx.hasError) loadRollupDiagnostics(config, compilerCtx, buildCtx, e);
6332
+ if (!buildCtx.hasError) loadRolldownDiagnostics(config, compilerCtx, buildCtx, e);
6512
6333
  }
6513
6334
  };
6514
6335
  /**
@@ -6549,7 +6370,7 @@ const MODE_RESOLUTION_CHAIN_DECLARATION = `modeResolutionChain = [];`;
6549
6370
  * one module resolution chain across hydrate and core runtime.
6550
6371
  */
6551
6372
  const HYDRATE_FACTORY_INTRO = `
6552
- // let ${MODE_RESOLUTION_CHAIN_DECLARATION}
6373
+ //! let ${MODE_RESOLUTION_CHAIN_DECLARATION}
6553
6374
 
6554
6375
  // Capture native setTimeout/clearTimeout at module scope (before globalThis can be shadowed inside the factory).
6555
6376
  // Used for the hydrate timeout timer to avoid being affected by constrainTimeouts.
@@ -6729,34 +6550,24 @@ const relocateHydrateContextConst = (config, compilerCtx, code) => {
6729
6550
  };
6730
6551
  //#endregion
6731
6552
  //#region src/compiler/output-targets/dist-hydrate-script/write-hydrate-outputs.ts
6732
- const writeHydrateOutputs = (config, compilerCtx, buildCtx, outputTargets, rollupOutput) => {
6553
+ const writeHydrateOutputs = (config, compilerCtx, buildCtx, outputTargets, rolldownOutput) => {
6733
6554
  return Promise.all(outputTargets.map((outputTarget) => {
6734
- return writeHydrateOutput(config, compilerCtx, buildCtx, outputTarget, rollupOutput);
6555
+ return writeHydrateOutput(config, compilerCtx, buildCtx, outputTarget, rolldownOutput);
6735
6556
  }));
6736
6557
  };
6737
- const writeHydrateOutput = async (config, compilerCtx, buildCtx, outputTarget, rollupOutput) => {
6738
- const hydratePackageName = await getHydratePackageName(config, compilerCtx);
6558
+ const writeHydrateOutput = async (config, compilerCtx, buildCtx, outputTarget, rolldownOutput) => {
6739
6559
  const hydrateAppDirPath = outputTarget.dir;
6740
6560
  if (!hydrateAppDirPath) throw new Error(`outputTarget config missing the "dir" property`);
6741
- const hydrateCoreIndexPath = join$1(hydrateAppDirPath, "index.js");
6742
- const hydrateCoreIndexPathESM = join$1(hydrateAppDirPath, "index.mjs");
6743
- const hydrateCoreIndexDtsFilePath = join$1(hydrateAppDirPath, "index.d.ts");
6744
- const writeOperations = [copyHydrateRunnerDts(config, compilerCtx, hydrateAppDirPath)];
6745
- if (outputTarget.generatePackageJson) {
6746
- const pkgJsonPath = join$1(hydrateAppDirPath, "package.json");
6747
- const pkgJsonCode = getHydratePackageJson(config, hydrateCoreIndexPath, hydrateCoreIndexPathESM, hydrateCoreIndexDtsFilePath, hydratePackageName);
6748
- writeOperations.push(compilerCtx.fs.writeFile(pkgJsonPath, pkgJsonCode));
6749
- }
6750
- await Promise.all(writeOperations);
6751
- buildCtx.hydrateAppFilePath = hydrateCoreIndexPath;
6561
+ await copyHydrateRunnerDts(config, compilerCtx, hydrateAppDirPath);
6562
+ buildCtx.hydrateAppFilePath = join$1(hydrateAppDirPath, "index.js");
6752
6563
  const minify = outputTarget.minify === true;
6753
- await Promise.all(rollupOutput.output.map(async (output) => {
6564
+ await Promise.all(rolldownOutput.output.map(async (output) => {
6754
6565
  if (output.type === "chunk") {
6755
6566
  let code = relocateHydrateContextConst(config, compilerCtx, output.code);
6756
6567
  /**
6757
6568
  * Enable the line where we define `modeResolutionChain` for the hydrate module.
6758
6569
  */
6759
- code = code.replace(`// let ${MODE_RESOLUTION_CHAIN_DECLARATION}`, `let ${MODE_RESOLUTION_CHAIN_DECLARATION}`);
6570
+ code = code.replace(`//! let ${MODE_RESOLUTION_CHAIN_DECLARATION}`, `let ${MODE_RESOLUTION_CHAIN_DECLARATION}`);
6760
6571
  if (code.match(/function (setTagTransformer|transformTag)\(/)) {
6761
6572
  const injectCode = `\n// Tag transform state object for factory closure\nvar $stencilTagTransform = { setTagTransformer: setTagTransformer, transformTag: transformTag };\n`;
6762
6573
  const lastTransformTagIndex = code.lastIndexOf("function transformTag(");
@@ -6793,28 +6604,6 @@ const writeHydrateOutput = async (config, compilerCtx, buildCtx, outputTarget, r
6793
6604
  }
6794
6605
  }));
6795
6606
  };
6796
- const getHydratePackageJson = (config, hydrateAppFilePathCJS, hydrateAppFilePathESM, hydrateDtsFilePath, hydratePackageName) => {
6797
- const pkg = {
6798
- name: hydratePackageName,
6799
- description: `${config.namespace} component hydration app.`,
6800
- main: basename$1(hydrateAppFilePathCJS),
6801
- types: basename$1(hydrateDtsFilePath),
6802
- exports: { ".": {
6803
- require: `./${basename$1(hydrateAppFilePathCJS)}`,
6804
- import: `./${basename$1(hydrateAppFilePathESM)}`
6805
- } }
6806
- };
6807
- return JSON.stringify(pkg, null, 2);
6808
- };
6809
- const getHydratePackageName = async (config, compilerCtx) => {
6810
- const directoryName = basename$1(config.rootDir);
6811
- try {
6812
- const rootPkgFilePath = join$1(config.rootDir, "package.json");
6813
- const pkgStr = await compilerCtx.fs.readFile(rootPkgFilePath);
6814
- return `${JSON.parse(pkgStr).name || directoryName}/hydrate`;
6815
- } catch {}
6816
- return `${config.fsNamespace || directoryName}/hydrate`;
6817
- };
6818
6607
  const copyHydrateRunnerDts = async (config, compilerCtx, hydrateAppDirPath) => {
6819
6608
  const srcHydrateDir = join$1(join$1(config.sys.getCompilerExecutingPath(), "..", ".."), "runtime", "server", "runner.d.mts");
6820
6609
  const runnerDtsDestPath = join$1(hydrateAppDirPath, "index.d.ts");
@@ -6822,9 +6611,9 @@ const copyHydrateRunnerDts = async (config, compilerCtx, hydrateAppDirPath) => {
6822
6611
  };
6823
6612
  //#endregion
6824
6613
  //#region src/compiler/output-targets/dist-hydrate-script/generate-hydrate-app.ts
6825
- const buildHydrateAppFor = async (format, rollupBuild, config, compilerCtx, buildCtx, outputTargets) => {
6826
- const file = format === "esm" ? "index.mjs" : "index.js";
6827
- await writeHydrateOutputs(config, compilerCtx, buildCtx, outputTargets, await rollupBuild.generate({
6614
+ const buildHydrateAppFor = async (format, rolldownBuild, config, compilerCtx, buildCtx, outputTargets) => {
6615
+ const file = format === "esm" ? "index.js" : "index.cjs";
6616
+ await writeHydrateOutputs(config, compilerCtx, buildCtx, outputTargets, await rolldownBuild.generate({
6828
6617
  banner: generatePreamble(config),
6829
6618
  format,
6830
6619
  file
@@ -6843,52 +6632,62 @@ const generateHydrateApp = async (config, compilerCtx, buildCtx, outputTargets)
6843
6632
  const packageDir = join$1(config.sys.getCompilerExecutingPath(), "..", "..");
6844
6633
  const input = join$1(packageDir, "runtime", "server", "runner.mjs");
6845
6634
  const appData = join$1(packageDir, "runtime", "app-data", "index.js");
6846
- const rollupAppBuild = await rollup({
6847
- ...config.rollupConfig.inputOptions,
6635
+ const rolldownAppBuild = await rolldown({
6636
+ ...config.rolldownConfig.inputOptions,
6848
6637
  external: ["node:stream"],
6849
6638
  input,
6850
6639
  plugins: [{
6851
6640
  name: "hydrateAppPlugin",
6852
- resolveId(id) {
6853
- if (id === "@stencil/core/runtime/server/hydrate-factory") return STENCIL_HYDRATE_FACTORY_ID;
6854
- if (id === "@stencil/core/runtime/app-data") return appData;
6855
- return null;
6641
+ resolveId: {
6642
+ filter: { id: /^@stencil\/core\/runtime\/(server\/hydrate-factory|app-data)$/ },
6643
+ handler(id) {
6644
+ if (id === "@stencil/core/runtime/server/hydrate-factory") return STENCIL_HYDRATE_FACTORY_ID;
6645
+ if (id === "@stencil/core/runtime/app-data") return appData;
6646
+ return null;
6647
+ }
6856
6648
  },
6857
- load(id) {
6858
- if (id === "@stencil/core/runtime/server/hydrate-factory") return generateHydrateFactory(config, compilerCtx, buildCtx);
6859
- return null;
6649
+ load: {
6650
+ filter: { id: /^@stencil\/core\/runtime\/server\/hydrate-factory$/ },
6651
+ handler(id) {
6652
+ if (id === "@stencil/core/runtime/server/hydrate-factory") return generateHydrateFactory(config, compilerCtx, buildCtx);
6653
+ return null;
6654
+ }
6860
6655
  },
6861
- transform(code) {
6656
+ transform(code, _id) {
6862
6657
  /**
6863
6658
  * Remove the modeResolutionChain variable from the generated code.
6864
6659
  * This variable is redefined in `HYDRATE_FACTORY_INTRO` to ensure we can
6865
6660
  * use it within the hydrate and global runtime.
6866
6661
  */
6867
6662
  const searchPattern = `const ${MODE_RESOLUTION_CHAIN_DECLARATION}`;
6663
+ if (!code.includes(searchPattern)) return null;
6868
6664
  return code.replaceAll(searchPattern, "");
6869
6665
  }
6870
6666
  }],
6871
6667
  treeshake: false,
6872
- onwarn: createOnWarnFn(buildCtx.diagnostics)
6668
+ onwarn: createOnWarnFn(buildCtx.diagnostics),
6669
+ checks: { pluginTimings: config.devMode }
6873
6670
  });
6874
- await Promise.all([buildHydrateAppFor("cjs", rollupAppBuild, config, compilerCtx, buildCtx, outputTargets), buildHydrateAppFor("esm", rollupAppBuild, config, compilerCtx, buildCtx, outputTargets)]);
6671
+ const buildPromises = [buildHydrateAppFor("esm", rolldownAppBuild, config, compilerCtx, buildCtx, outputTargets)];
6672
+ if (outputTargets.some((o) => o.cjs)) buildPromises.push(buildHydrateAppFor("cjs", rolldownAppBuild, config, compilerCtx, buildCtx, outputTargets));
6673
+ await Promise.all(buildPromises);
6875
6674
  } catch (e) {
6876
- if (!buildCtx.hasError) loadRollupDiagnostics(config, compilerCtx, buildCtx, e);
6675
+ if (!buildCtx.hasError) loadRolldownDiagnostics(config, compilerCtx, buildCtx, e);
6877
6676
  }
6878
6677
  };
6879
6678
  const generateHydrateFactory = async (config, compilerCtx, buildCtx) => {
6880
6679
  if (!buildCtx.hasError) try {
6881
- const rollupFactoryBuild = await bundleHydrateFactory(config, compilerCtx, buildCtx, await generateHydrateFactoryEntry(buildCtx));
6882
- if (rollupFactoryBuild != null) {
6883
- const rollupOutput = await rollupFactoryBuild.generate({
6680
+ const rolldownFactoryBuild = await bundleHydrateFactory(config, compilerCtx, buildCtx, await generateHydrateFactoryEntry(buildCtx));
6681
+ if (rolldownFactoryBuild != null) {
6682
+ const rolldownOutput = await rolldownFactoryBuild.generate({
6884
6683
  format: "cjs",
6885
6684
  esModule: false,
6886
6685
  strict: false,
6887
6686
  intro: HYDRATE_FACTORY_INTRO,
6888
6687
  outro: HYDRATE_FACTORY_OUTRO,
6889
- inlineDynamicImports: true
6688
+ codeSplitting: false
6890
6689
  });
6891
- if (!buildCtx.hasError && rollupOutput != null && Array.isArray(rollupOutput.output)) return rollupOutput.output[0].code;
6690
+ if (!buildCtx.hasError && rolldownOutput != null && Array.isArray(rolldownOutput.output)) return rolldownOutput.output[0].code;
6892
6691
  }
6893
6692
  } catch (e) {
6894
6693
  catchError(buildCtx.diagnostics, e);
@@ -7136,7 +6935,7 @@ const generateModuleGraph = (cmps, bundleModules) => {
7136
6935
  const cmpMap = /* @__PURE__ */ new Map();
7137
6936
  cmps.forEach((cmp) => {
7138
6937
  const bundle = bundleModules.find((b) => b.cmps.includes(cmp));
7139
- if (bundle) cmpMap.set(getScopeId(cmp.tagName), bundle.rollupResult.imports);
6938
+ if (bundle) cmpMap.set(getScopeId(cmp.tagName), bundle.rolldownResult.imports);
7140
6939
  });
7141
6940
  return cmpMap;
7142
6941
  };
@@ -7228,16 +7027,16 @@ const lazyComponentTransform = (compilerCtx, transformOpts, buildCtx) => {
7228
7027
  //#endregion
7229
7028
  //#region src/compiler/app-core/bundle-app-core.ts
7230
7029
  /**
7231
- * Generate rollup output based on a rollup build and a series of options.
7030
+ * Generate rolldown output based on a rolldown build and a series of options.
7232
7031
  *
7233
- * @param build a rollup build
7234
- * @param options output options for rollup
7032
+ * @param build a rolldown build
7033
+ * @param options output options for rolldown
7235
7034
  * @param config a user-supplied configuration object
7236
7035
  * @param entryModules a list of entry modules, for checking which chunks
7237
7036
  * contain components
7238
7037
  * @returns a Promise wrapping either build results or `null`
7239
7038
  */
7240
- const generateRollupOutput = async (build, options, config, entryModules) => {
7039
+ const generateRolldownOutput = async (build, options, config, entryModules) => {
7241
7040
  if (build == null) return null;
7242
7041
  const { output } = await build.generate(options);
7243
7042
  return output.map((chunk) => {
@@ -7269,8 +7068,8 @@ const generateRollupOutput = async (build, options, config, entryModules) => {
7269
7068
  };
7270
7069
  //#endregion
7271
7070
  //#region src/compiler/output-targets/dist-lazy/write-lazy-entry-module.ts
7272
- const writeLazyModule = async (compilerCtx, outputTargetType, destinations, code, sourceMap, rollupResult) => {
7273
- const fileName = rollupResult.fileName;
7071
+ const writeLazyModule = async (compilerCtx, outputTargetType, destinations, code, sourceMap, rolldownResult) => {
7072
+ const fileName = rolldownResult.fileName;
7274
7073
  const bundleId = fileName.replace(".entry.js", "");
7275
7074
  if (sourceMap) code = code + getSourceMappingUrlForEndOfFile(fileName);
7276
7075
  await Promise.all(destinations.map((dst) => {
@@ -7291,20 +7090,20 @@ const writeLazyModule = async (compilerCtx, outputTargetType, destinations, code
7291
7090
  const generateLazyModules = async (config, compilerCtx, buildCtx, outputTargetType, destinations, results, sourceTarget, isBrowserBuild) => {
7292
7091
  if (!Array.isArray(destinations) || destinations.length === 0) return [];
7293
7092
  const shouldMinify = !!(config.minifyJs && isBrowserBuild);
7294
- const rollupResults = results.filter((r) => r.type === "chunk");
7295
- const entryComponentsResults = rollupResults.filter((rollupResult) => rollupResult.isComponent);
7296
- const chunkResults = rollupResults.filter((rollupResult) => !rollupResult.isComponent && !rollupResult.isEntry);
7297
- const bundleModules = await Promise.all(entryComponentsResults.map((rollupResult) => {
7298
- return generateLazyEntryModule(config, compilerCtx, buildCtx, rollupResult, outputTargetType, destinations, sourceTarget, shouldMinify, isBrowserBuild);
7093
+ const rolldownResults = results.filter((r) => r.type === "chunk");
7094
+ const entryComponentsResults = rolldownResults.filter((rolldownResult) => rolldownResult.isComponent);
7095
+ const chunkResults = rolldownResults.filter((rolldownResult) => !rolldownResult.isComponent && !rolldownResult.isEntry);
7096
+ const bundleModules = await Promise.all(entryComponentsResults.map((rolldownResult) => {
7097
+ return generateLazyEntryModule(config, compilerCtx, buildCtx, rolldownResult, outputTargetType, destinations, sourceTarget, shouldMinify, isBrowserBuild);
7299
7098
  }));
7300
- if ((!!config.extras.experimentalImportInjection || !!config.extras.enableImportInjection) && !isBrowserBuild) addStaticImports(rollupResults, bundleModules);
7301
- await Promise.all(chunkResults.map((rollupResult) => {
7302
- return writeLazyChunk(config, compilerCtx, buildCtx, rollupResult, outputTargetType, destinations, sourceTarget, shouldMinify, isBrowserBuild);
7099
+ if (config.extras.enableImportInjection && !isBrowserBuild) addStaticImports(rolldownResults, bundleModules);
7100
+ await Promise.all(chunkResults.map((rolldownResult) => {
7101
+ return writeLazyChunk(config, compilerCtx, buildCtx, rolldownResult, outputTargetType, destinations, sourceTarget, shouldMinify, isBrowserBuild);
7303
7102
  }));
7304
7103
  const lazyRuntimeData = formatLazyBundlesRuntimeMeta(bundleModules);
7305
- const entryResults = rollupResults.filter((rollupResult) => !rollupResult.isComponent && rollupResult.isEntry);
7306
- await Promise.all(entryResults.map((rollupResult) => {
7307
- return writeLazyEntry(config, compilerCtx, buildCtx, rollupResult, outputTargetType, destinations, lazyRuntimeData, sourceTarget, shouldMinify, isBrowserBuild);
7104
+ const entryResults = rolldownResults.filter((rolldownResult) => !rolldownResult.isComponent && rolldownResult.isEntry);
7105
+ await Promise.all(entryResults.map((rolldownResult) => {
7106
+ return writeLazyEntry(config, compilerCtx, buildCtx, rolldownResult, outputTargetType, destinations, lazyRuntimeData, sourceTarget, shouldMinify, isBrowserBuild);
7308
7107
  }));
7309
7108
  await Promise.all(results.filter((r) => r.type === "asset").map((r) => {
7310
7109
  return Promise.all(destinations.map((dest) => {
@@ -7314,14 +7113,14 @@ const generateLazyModules = async (config, compilerCtx, buildCtx, outputTargetTy
7314
7113
  return bundleModules;
7315
7114
  };
7316
7115
  /**
7317
- * Add imports for each bundle to Stencil's lazy loader. Some bundlers that are built atop of Rollup strictly impose
7318
- * the limitations that are laid out in https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations.
7116
+ * Add imports for each bundle to Stencil's lazy loader. Some bundlers that are built atop of Rolldown strictly impose
7117
+ * the limitations that are laid out in https://github.com/rolldown/plugins/tree/master/packages/dynamic-import-vars#limitations.
7319
7118
  * This function injects an explicit import statement for each bundle that can be lazily loaded.
7320
- * @param rollupChunkResults the results of running Rollup across a Stencil project
7119
+ * @param rolldownChunkResults the results of running Rolldown across a Stencil project
7321
7120
  * @param bundleModules lazy-loadable modules that can be resolved at runtime
7322
7121
  */
7323
- const addStaticImports = (rollupChunkResults, bundleModules) => {
7324
- rollupChunkResults.filter(isStencilCoreResult).forEach((index) => {
7122
+ const addStaticImports = (rolldownChunkResults, bundleModules) => {
7123
+ rolldownChunkResults.filter(isStencilCoreResult).forEach((index) => {
7325
7124
  const generateCjs = isCjsFormat(index) ? generateCaseClauseCjs : generateCaseClause;
7326
7125
  index.code = index.code.replace("/*!__STENCIL_STATIC_IMPORT_SWITCH__*/", `
7327
7126
  if (!hmrVersionId || !BUILD.hotModuleReplacement) {
@@ -7336,20 +7135,20 @@ const addStaticImports = (rollupChunkResults, bundleModules) => {
7336
7135
  });
7337
7136
  };
7338
7137
  /**
7339
- * Determine if a Rollup output chunk contains Stencil runtime code
7340
- * @param rollupChunkResult the rollup chunk output to test
7138
+ * Determine if a Rolldown output chunk contains Stencil runtime code
7139
+ * @param rolldownChunkResult the rolldown chunk output to test
7341
7140
  * @returns true if the output chunk contains Stencil runtime code, false otherwise
7342
7141
  */
7343
- const isStencilCoreResult = (rollupChunkResult) => {
7344
- return rollupChunkResult.isCore && rollupChunkResult.entryKey === "index" && (rollupChunkResult.moduleFormat === "es" || rollupChunkResult.moduleFormat === "esm" || isCjsFormat(rollupChunkResult));
7142
+ const isStencilCoreResult = (rolldownChunkResult) => {
7143
+ return rolldownChunkResult.isCore && !rolldownChunkResult.isComponent && (rolldownChunkResult.moduleFormat === "es" || rolldownChunkResult.moduleFormat === "esm" || isCjsFormat(rolldownChunkResult));
7345
7144
  };
7346
7145
  /**
7347
- * Helper function to determine if a Rollup chunk has a commonjs module format
7348
- * @param rollupChunkResult the Rollup result to test
7349
- * @returns true if the Rollup chunk has a commonjs module format, false otherwise
7146
+ * Helper function to determine if a Rolldown chunk has a commonjs module format
7147
+ * @param rolldownChunkResult the Rolldown result to test
7148
+ * @returns true if the Rolldown chunk has a commonjs module format, false otherwise
7350
7149
  */
7351
- const isCjsFormat = (rollupChunkResult) => {
7352
- return rollupChunkResult.moduleFormat === "cjs" || rollupChunkResult.moduleFormat === "commonjs";
7150
+ const isCjsFormat = (rolldownChunkResult) => {
7151
+ return rolldownChunkResult.moduleFormat === "cjs" || rolldownChunkResult.moduleFormat === "commonjs";
7353
7152
  };
7354
7153
  /**
7355
7154
  * Generate a 'case' clause to be used within a `switch` statement. The case clause generated will key-off the provided
@@ -7377,40 +7176,40 @@ const generateCaseClauseCjs = (bundleId) => {
7377
7176
  /* webpackMode: "lazy" */
7378
7177
  './${bundleId}.entry.js')); }).then(processMod, consoleError);`;
7379
7178
  };
7380
- const generateLazyEntryModule = async (config, compilerCtx, buildCtx, rollupResult, outputTargetType, destinations, sourceTarget, shouldMinify, isBrowserBuild) => {
7381
- const entryModule = buildCtx.entryModules.find((em) => em.entryKey === rollupResult.entryKey);
7382
- const { code, sourceMap } = await convertChunk(config, compilerCtx, buildCtx, sourceTarget, shouldMinify, false, isBrowserBuild, rollupResult.code, rollupResult.map);
7383
- const output = await writeLazyModule(compilerCtx, outputTargetType, destinations, code, sourceMap, rollupResult);
7179
+ const generateLazyEntryModule = async (config, compilerCtx, buildCtx, rolldownResult, outputTargetType, destinations, sourceTarget, shouldMinify, isBrowserBuild) => {
7180
+ const entryModule = buildCtx.entryModules.find((em) => em.entryKey === rolldownResult.entryKey);
7181
+ const { code, sourceMap } = await convertChunk(config, compilerCtx, buildCtx, sourceTarget, shouldMinify, false, isBrowserBuild, rolldownResult.code, rolldownResult.map);
7182
+ const output = await writeLazyModule(compilerCtx, outputTargetType, destinations, code, sourceMap, rolldownResult);
7384
7183
  return {
7385
- rollupResult,
7386
- entryKey: rollupResult.entryKey,
7184
+ rolldownResult,
7185
+ entryKey: rolldownResult.entryKey,
7387
7186
  cmps: entryModule.cmps,
7388
7187
  output
7389
7188
  };
7390
7189
  };
7391
- const writeLazyChunk = async (config, compilerCtx, buildCtx, rollupResult, outputTargetType, destinations, sourceTarget, shouldMinify, isBrowserBuild) => {
7392
- const { code, sourceMap } = await convertChunk(config, compilerCtx, buildCtx, sourceTarget, shouldMinify, rollupResult.isCore, isBrowserBuild, rollupResult.code, rollupResult.map);
7190
+ const writeLazyChunk = async (config, compilerCtx, buildCtx, rolldownResult, outputTargetType, destinations, sourceTarget, shouldMinify, isBrowserBuild) => {
7191
+ const { code, sourceMap } = await convertChunk(config, compilerCtx, buildCtx, sourceTarget, shouldMinify, rolldownResult.isCore, isBrowserBuild, rolldownResult.code, rolldownResult.map);
7393
7192
  await Promise.all(destinations.map((dst) => {
7394
- const filePath = join$1(dst, rollupResult.fileName);
7193
+ const filePath = join$1(dst, rolldownResult.fileName);
7395
7194
  let fileCode = code;
7396
7195
  const writes = [];
7397
7196
  if (sourceMap) {
7398
- fileCode = code + getSourceMappingUrlForEndOfFile(rollupResult.fileName);
7197
+ fileCode = code + getSourceMappingUrlForEndOfFile(rolldownResult.fileName);
7399
7198
  writes.push(compilerCtx.fs.writeFile(filePath + ".map", JSON.stringify(sourceMap), { outputTargetType }));
7400
7199
  }
7401
7200
  writes.push(compilerCtx.fs.writeFile(filePath, fileCode, { outputTargetType }));
7402
7201
  return Promise.all(writes);
7403
7202
  }));
7404
7203
  };
7405
- const writeLazyEntry = async (config, compilerCtx, buildCtx, rollupResult, outputTargetType, destinations, lazyRuntimeData, sourceTarget, shouldMinify, isBrowserBuild) => {
7406
- if (isBrowserBuild && ["loader"].includes(rollupResult.entryKey)) return;
7407
- const { code, sourceMap } = await convertChunk(config, compilerCtx, buildCtx, sourceTarget, shouldMinify, false, isBrowserBuild, rollupResult.code.replace(`[/*!__STENCIL_LAZY_DATA__*/]`, `${lazyRuntimeData}`), rollupResult.map);
7204
+ const writeLazyEntry = async (config, compilerCtx, buildCtx, rolldownResult, outputTargetType, destinations, lazyRuntimeData, sourceTarget, shouldMinify, isBrowserBuild) => {
7205
+ if (isBrowserBuild && ["loader"].includes(rolldownResult.entryKey)) return;
7206
+ const { code, sourceMap } = await convertChunk(config, compilerCtx, buildCtx, sourceTarget, shouldMinify, false, isBrowserBuild, rolldownResult.code.replace(`["__STENCIL_LAZY_DATA__"]`, `${lazyRuntimeData}`), rolldownResult.map);
7408
7207
  await Promise.all(destinations.map((dst) => {
7409
- const filePath = join$1(dst, rollupResult.fileName);
7208
+ const filePath = join$1(dst, rolldownResult.fileName);
7410
7209
  let fileCode = code;
7411
7210
  const writes = [];
7412
7211
  if (sourceMap) {
7413
- fileCode = code + getSourceMappingUrlForEndOfFile(rollupResult.fileName);
7212
+ fileCode = code + getSourceMappingUrlForEndOfFile(rolldownResult.fileName);
7414
7213
  writes.push(compilerCtx.fs.writeFile(filePath + ".map", JSON.stringify(sourceMap), { outputTargetType }));
7415
7214
  }
7416
7215
  writes.push(compilerCtx.fs.writeFile(filePath, fileCode, { outputTargetType }));
@@ -7420,7 +7219,7 @@ const writeLazyEntry = async (config, compilerCtx, buildCtx, rollupResult, outpu
7420
7219
  /**
7421
7220
  * Sorts, formats, and stringifies the bundles for a lazy build of a Stencil project.
7422
7221
  *
7423
- * @param bundleModules The modules for the Stencil lazy build emitted from Rollup.
7222
+ * @param bundleModules The modules for the Stencil lazy build emitted from Rolldown.
7424
7223
  * @returns A stringified representation of the lazy bundles.
7425
7224
  */
7426
7225
  const formatLazyBundlesRuntimeMeta = (bundleModules) => {
@@ -7500,8 +7299,8 @@ const sortBundleComponents = (a, b) => {
7500
7299
  if (a.tagName > b.tagName) return 1;
7501
7300
  return 0;
7502
7301
  };
7503
- const convertChunk = async (config, compilerCtx, buildCtx, sourceTarget, shouldMinify, isCore, isBrowserBuild, code, rollupSrcMap) => {
7504
- let sourceMap = rollupToStencilSourceMap(rollupSrcMap);
7302
+ const convertChunk = async (config, compilerCtx, buildCtx, sourceTarget, shouldMinify, isCore, isBrowserBuild, code, rolldownSrcMap) => {
7303
+ let sourceMap = rolldownToStencilSourceMap(rolldownSrcMap);
7505
7304
  const inlineHelpers = isBrowserBuild || !hasDependency(buildCtx, "tslib");
7506
7305
  const optimizeResults = await optimizeModule(config, compilerCtx, {
7507
7306
  input: code,
@@ -7522,13 +7321,13 @@ const convertChunk = async (config, compilerCtx, buildCtx, sourceTarget, shouldM
7522
7321
  //#endregion
7523
7322
  //#region src/compiler/output-targets/dist-lazy/lazy-bundleid-plugin.ts
7524
7323
  /**
7525
- * A Rollup plugin to generate unique bundle IDs for lazy-loaded modules.
7324
+ * A Rolldown plugin to generate unique bundle IDs for lazy-loaded modules.
7526
7325
  * @param buildCtx The build context
7527
7326
  * @param config The validated configuration
7528
7327
  * @param shouldHash Whether to hash the bundle ID
7529
7328
  * @param suffix The suffix to append to the bundle ID
7530
7329
  * @param isBrowserBuild Whether this is a browser build
7531
- * @returns A Rollup plugin
7330
+ * @returns A Rolldown plugin
7532
7331
  */
7533
7332
  const lazyBundleIdPlugin = (buildCtx, config, shouldHash, suffix, isBrowserBuild) => {
7534
7333
  const getBundleId = async (entryKey, code, fileSuffix) => {
@@ -7584,7 +7383,7 @@ const lazyBundleIdPlugin = (buildCtx, config, shouldHash, suffix, isBrowserBuild
7584
7383
  };
7585
7384
  //#endregion
7586
7385
  //#region src/compiler/output-targets/dist-lazy/generate-cjs.ts
7587
- const generateCjs = async (config, compilerCtx, buildCtx, rollupBuild, outputTargets) => {
7386
+ const generateCjs = async (config, compilerCtx, buildCtx, rolldownBuild, outputTargets) => {
7588
7387
  const cjsOutputs = outputTargets.filter((o) => !!o.cjsDir);
7589
7388
  if (cjsOutputs.length > 0) {
7590
7389
  const outputTargetType = cjsOutputs[0].type;
@@ -7596,11 +7395,8 @@ const generateCjs = async (config, compilerCtx, buildCtx, rollupBuild, outputTar
7596
7395
  sourcemap: config.sourceMap,
7597
7396
  plugins: [lazyBundleIdPlugin(buildCtx, config, false, ".cjs")]
7598
7397
  };
7599
- if (!!config.extras.experimentalImportInjection || !!config.extras.enableImportInjection) {
7600
- esmOpts.interop = "auto";
7601
- esmOpts.dynamicImportInCjs = false;
7602
- }
7603
- const results = await generateRollupOutput(rollupBuild, esmOpts, config, buildCtx.entryModules);
7398
+ if (config.extras.enableImportInjection) esmOpts.dynamicImportInCjs = false;
7399
+ const results = await generateRolldownOutput(rolldownBuild, esmOpts, config, buildCtx.entryModules);
7604
7400
  if (results != null) {
7605
7401
  buildCtx.commonJsComponentBundle = await generateLazyModules(config, compilerCtx, buildCtx, outputTargetType, cjsOutputs.map((o) => o.cjsDir).filter((cjsDir) => typeof cjsDir === "string"), results, "es2017", false);
7606
7402
  await generateShortcuts$1(compilerCtx, results, cjsOutputs);
@@ -7611,8 +7407,8 @@ const generateCjs = async (config, compilerCtx, buildCtx, rollupBuild, outputTar
7611
7407
  buildCtx
7612
7408
  };
7613
7409
  };
7614
- const generateShortcuts$1 = (compilerCtx, rollupResult, outputTargets) => {
7615
- const indexFilename = rollupResult.find((r) => r.type === "chunk" && r.isIndex).fileName;
7410
+ const generateShortcuts$1 = (compilerCtx, rolldownResult, outputTargets) => {
7411
+ const indexFilename = rolldownResult.find((r) => r.type === "chunk" && r.isIndex).fileName;
7616
7412
  return Promise.all(outputTargets.map(async (o) => {
7617
7413
  if (o.cjsIndexFile) {
7618
7414
  const entryPointPath = join$1(o.cjsDir, indexFilename);
@@ -7623,10 +7419,9 @@ const generateShortcuts$1 = (compilerCtx, rollupResult, outputTargets) => {
7623
7419
  };
7624
7420
  //#endregion
7625
7421
  //#region src/compiler/output-targets/dist-lazy/generate-esm.ts
7626
- const generateEsm = async (config, compilerCtx, buildCtx, rollupBuild, outputTargets) => {
7627
- const esmEs5Outputs = config.buildEs5 ? outputTargets.filter((o) => !!o.esmEs5Dir && !o.isBrowserBuild) : [];
7422
+ const generateEsm = async (config, compilerCtx, buildCtx, rolldownBuild, outputTargets) => {
7628
7423
  const esmOutputs = outputTargets.filter((o) => !!o.esmDir && !o.isBrowserBuild);
7629
- if (esmOutputs.length + esmEs5Outputs.length > 0) {
7424
+ if (esmOutputs.length > 0) {
7630
7425
  const esmOpts = {
7631
7426
  banner: generatePreamble(config),
7632
7427
  format: "es",
@@ -7636,11 +7431,9 @@ const generateEsm = async (config, compilerCtx, buildCtx, rollupBuild, outputTar
7636
7431
  plugins: [lazyBundleIdPlugin(buildCtx, config, false, "")]
7637
7432
  };
7638
7433
  const outputTargetType = esmOutputs[0].type;
7639
- const output = await generateRollupOutput(rollupBuild, esmOpts, config, buildCtx.entryModules);
7434
+ const output = await generateRolldownOutput(rolldownBuild, esmOpts, config, buildCtx.entryModules);
7640
7435
  if (output != null) {
7641
7436
  buildCtx.esmComponentBundle = await generateLazyModules(config, compilerCtx, buildCtx, outputTargetType, esmOutputs.map((o) => o.esmDir).filter((esmDir) => typeof esmDir === "string"), output, "es2017", false);
7642
- buildCtx.es5ComponentBundle = await generateLazyModules(config, compilerCtx, buildCtx, outputTargetType, esmEs5Outputs.map((o) => o.esmEs5Dir).filter((esmEs5Dir) => typeof esmEs5Dir === "string"), output, "es5", false);
7643
- if (config.buildEs5) await copyPolyfills(config, compilerCtx, esmOutputs);
7644
7437
  await generateShortcuts(config, compilerCtx, outputTargets, output);
7645
7438
  }
7646
7439
  }
@@ -7649,31 +7442,11 @@ const generateEsm = async (config, compilerCtx, buildCtx, rollupBuild, outputTar
7649
7442
  buildCtx
7650
7443
  };
7651
7444
  };
7652
- /**
7653
- * Copy polyfills from `$INSTALL_DIR/internal/client/polyfills` to the lazy
7654
- * loader output directory where $INSTALL_DIR is the directory in which the
7655
- * `@stencil/core` package is installed.
7656
- *
7657
- * @param config a validated Stencil configuration
7658
- * @param compilerCtx the current compiler context
7659
- * @param outputTargets dist-lazy output targets
7660
- */
7661
- const copyPolyfills = async (config, compilerCtx, outputTargets) => {
7662
- const destinations = outputTargets.filter((o) => o.polyfills).map((o) => o.esmDir).filter((esmDir) => typeof esmDir === "string");
7663
- if (destinations.length === 0) return;
7664
- const src = join$1(config.sys.getCompilerExecutingPath(), "..", "..", "internal", "client", "polyfills");
7665
- const files = await compilerCtx.fs.readdir(src);
7666
- await Promise.all(destinations.map((dest) => {
7667
- return Promise.all(files.map((f) => {
7668
- return compilerCtx.fs.copyFile(f.absPath, join$1(dest, "polyfills", f.relPath));
7669
- }));
7670
- }));
7671
- };
7672
- const generateShortcuts = (config, compilerCtx, outputTargets, rollupResult) => {
7673
- const indexFilename = rollupResult.find((r) => r.type === "chunk" && r.isIndex).fileName;
7445
+ const generateShortcuts = (_config, compilerCtx, outputTargets, rolldownResult) => {
7446
+ const indexFilename = rolldownResult.find((r) => r.type === "chunk" && r.isIndex).fileName;
7674
7447
  return Promise.all(outputTargets.map(async (o) => {
7675
7448
  if (o.esmDir && o.esmIndexFile) {
7676
- const entryPointPath = config.buildEs5 && o.esmEs5Dir ? join$1(o.esmEs5Dir, indexFilename) : join$1(o.esmDir, indexFilename);
7449
+ const entryPointPath = join$1(o.esmDir, indexFilename);
7677
7450
  const shortcutContent = `export * from '${relativeImport(o.esmIndexFile, entryPointPath)}';`;
7678
7451
  await compilerCtx.fs.writeFile(o.esmIndexFile, shortcutContent, { outputTargetType: o.type });
7679
7452
  }
@@ -7681,11 +7454,11 @@ const generateShortcuts = (config, compilerCtx, outputTargets, rollupResult) =>
7681
7454
  };
7682
7455
  //#endregion
7683
7456
  //#region src/compiler/output-targets/dist-lazy/generate-esm-browser.ts
7684
- const generateEsmBrowser = async (config, compilerCtx, buildCtx, rollupBuild, outputTargets) => {
7457
+ const generateEsmBrowser = async (config, compilerCtx, buildCtx, rolldownBuild, outputTargets) => {
7685
7458
  const esmOutputs = outputTargets.filter((o) => !!o.esmDir && !!o.isBrowserBuild);
7686
7459
  if (esmOutputs.length) {
7687
7460
  const outputTargetType = esmOutputs[0].type;
7688
- const output = await generateRollupOutput(rollupBuild, {
7461
+ const output = await generateRolldownOutput(rolldownBuild, {
7689
7462
  banner: generatePreamble(config),
7690
7463
  format: "es",
7691
7464
  entryFileNames: "[name].esm.js",
@@ -7702,96 +7475,11 @@ const generateEsmBrowser = async (config, compilerCtx, buildCtx, rollupBuild, ou
7702
7475
  };
7703
7476
  };
7704
7477
  //#endregion
7705
- //#region src/compiler/app-core/app-polyfills.ts
7706
- const getClientPolyfill = async (config, compilerCtx, polyfillFile) => {
7707
- const polyfillFilePath = join$1(config.sys.getCompilerExecutingPath(), "..", "..", "internal", "client", "polyfills", polyfillFile);
7708
- return compilerCtx.fs.readFile(polyfillFilePath);
7709
- };
7710
- const getAppBrowserCorePolyfills = async (config, compilerCtx) => {
7711
- const polyfills = INLINE_POLYFILLS.slice();
7712
- return (await Promise.all(polyfills.map((polyfillFile) => getClientPolyfill(config, compilerCtx, polyfillFile)))).join("\n").trim();
7713
- };
7714
- const INLINE_POLYFILLS = [
7715
- "core-js.js",
7716
- "dom.js",
7717
- "es5-html-element.js",
7718
- "system.js"
7719
- ];
7720
- //#endregion
7721
- //#region src/compiler/output-targets/dist-lazy/generate-system.ts
7722
- const generateSystem = async (config, compilerCtx, buildCtx, rollupBuild, outputTargets) => {
7723
- const systemOutputs = outputTargets.filter((o) => !!o.systemDir);
7724
- if (systemOutputs.length > 0) {
7725
- const results = await generateRollupOutput(rollupBuild, {
7726
- banner: generatePreamble(config),
7727
- format: "system",
7728
- entryFileNames: config.hashFileNames ? "p-[hash].system.js" : "[name].system.js",
7729
- chunkFileNames: config.hashFileNames ? "p-[hash].system.js" : "[name]-[hash].system.js",
7730
- assetFileNames: config.hashFileNames ? "p-[hash][extname]" : "[name]-[hash][extname]",
7731
- sourcemap: config.sourceMap,
7732
- plugins: [lazyBundleIdPlugin(buildCtx, config, config.hashFileNames, ".system", true)]
7733
- }, config, buildCtx.entryModules);
7734
- if (results != null) {
7735
- const destinations = systemOutputs.map((o) => o.esmDir).filter((esmDir) => typeof esmDir === "string");
7736
- buildCtx.systemComponentBundle = await generateLazyModules(config, compilerCtx, buildCtx, outputTargets[0].type, destinations, results, "es5", true);
7737
- await generateSystemLoaders(config, compilerCtx, results, systemOutputs);
7738
- }
7739
- }
7740
- return {
7741
- name: "system",
7742
- buildCtx
7743
- };
7744
- };
7745
- const generateSystemLoaders = (config, compilerCtx, rollupResult, systemOutputs) => {
7746
- const loaderFilename = rollupResult.find((r) => r.type === "chunk" && r.isBrowserLoader).fileName;
7747
- return Promise.all(systemOutputs.map((o) => writeSystemLoader(config, compilerCtx, loaderFilename, o)));
7748
- };
7749
- const writeSystemLoader = async (config, compilerCtx, loaderFilename, outputTarget) => {
7750
- if (outputTarget.systemLoaderFile) {
7751
- const entryPointPath = join$1(outputTarget.systemDir, loaderFilename);
7752
- const loaderContent = await getSystemLoader(config, compilerCtx, relativeImport(outputTarget.systemLoaderFile, entryPointPath), !!outputTarget.polyfills);
7753
- await compilerCtx.fs.writeFile(outputTarget.systemLoaderFile, loaderContent, { outputTargetType: outputTarget.type });
7754
- }
7755
- };
7756
- const getSystemLoader = async (config, compilerCtx, corePath, includePolyfills) => {
7757
- return `
7758
- 'use strict';
7759
- (function () {
7760
- var currentScript = document.currentScript;
7761
-
7762
- // Safari 10 support type="module" but still download and executes the nomodule script
7763
- if (!currentScript || !currentScript.hasAttribute('nomodule') || !('onbeforeload' in currentScript)) {
7764
-
7765
- ${includePolyfills ? await getAppBrowserCorePolyfills(config, compilerCtx) : "/* polyfills excluded */"}
7766
-
7767
- // Figure out currentScript (for IE11, since it does not support currentScript)
7768
- var regex = /\\/${config.fsNamespace}(\\.esm)?\\.js($|\\?|#)/;
7769
- var scriptElm = currentScript || Array.from(document.querySelectorAll('script')).find(function(s) {
7770
- return regex.test(s.src) || s.getAttribute('data-stencil-namespace') === "${config.fsNamespace}";
7771
- });
7772
-
7773
- var resourcesUrl = scriptElm ? scriptElm.getAttribute('data-resources-url') || scriptElm.src : '';
7774
- var start = function() {
7775
- // if src is not present then origin is "null", and new URL() throws TypeError: Failed to construct 'URL': Invalid base URL
7776
- var url = new URL('${corePath}', new URL(resourcesUrl, window.location.origin !== 'null' ? window.location.origin : undefined));
7777
- System.import(url.href);
7778
- };
7779
-
7780
- start();
7781
-
7782
- // Note: using .call(window) here because the self-executing function needs
7783
- // to be scoped to the window object for the ES6Promise polyfill to work
7784
- }
7785
- }).call(window);
7786
- `;
7787
- };
7788
- //#endregion
7789
7478
  //#region src/compiler/output-targets/dist-lazy/lazy-build-conditionals.ts
7790
7479
  const getLazyBuildConditionals = (config, cmps) => {
7791
7480
  const build = getBuildFeatures(cmps);
7792
7481
  build.lazyLoad = true;
7793
7482
  build.hydrateServerSide = false;
7794
- build.transformTagName = config.extras.tagNameTransform;
7795
7483
  build.asyncQueue = config.taskQueue === "congestionAsync";
7796
7484
  build.taskQueue = config.taskQueue !== "immediate";
7797
7485
  build.initializeNextTick = config.extras.initializeNextTick;
@@ -7827,20 +7515,16 @@ const outputLazy = async (config, compilerCtx, buildCtx) => {
7827
7515
  buildCtx.entryModules.forEach((entryModule) => {
7828
7516
  bundleOpts.inputs[entryModule.entryKey] = entryModule.entryKey;
7829
7517
  });
7830
- const rollupBuild = await bundleOutput(config, compilerCtx, buildCtx, bundleOpts);
7831
- if (rollupBuild != null) {
7518
+ const rolldownBuild = await bundleOutput(config, compilerCtx, buildCtx, bundleOpts);
7519
+ if (rolldownBuild != null) {
7832
7520
  (await Promise.all([
7833
- generateEsmBrowser(config, compilerCtx, buildCtx, rollupBuild, outputTargets),
7834
- generateEsm(config, compilerCtx, buildCtx, rollupBuild, outputTargets),
7835
- generateSystem(config, compilerCtx, buildCtx, rollupBuild, outputTargets),
7836
- generateCjs(config, compilerCtx, buildCtx, rollupBuild, outputTargets)
7521
+ generateEsmBrowser(config, compilerCtx, buildCtx, rolldownBuild, outputTargets),
7522
+ generateEsm(config, compilerCtx, buildCtx, rolldownBuild, outputTargets),
7523
+ generateCjs(config, compilerCtx, buildCtx, rolldownBuild, outputTargets)
7837
7524
  ])).forEach((result) => {
7838
7525
  if (result.name === "cjs") buildCtx.commonJsComponentBundle = result.buildCtx.commonJsComponentBundle;
7839
- else if (result.name === "system") buildCtx.systemComponentBundle = result.buildCtx.systemComponentBundle;
7840
- else if (result.name === "esm") {
7841
- buildCtx.esmComponentBundle = result.buildCtx.esmComponentBundle;
7842
- buildCtx.es5ComponentBundle = result.buildCtx.es5ComponentBundle;
7843
- } else if (result.name === "esm-browser") {
7526
+ else if (result.name === "esm") buildCtx.esmComponentBundle = result.buildCtx.esmComponentBundle;
7527
+ else if (result.name === "esm-browser") {
7844
7528
  buildCtx.esmBrowserComponentBundle = result.buildCtx.esmBrowserComponentBundle;
7845
7529
  buildCtx.buildResults = result.buildCtx.buildResults;
7846
7530
  buildCtx.components = result.buildCtx.components;
@@ -7919,14 +7603,14 @@ const getLazyEntry = (isBrowser) => {
7919
7603
  s.append(`import { globalScripts } from '${STENCIL_APP_GLOBALS_ID}';\n`);
7920
7604
  s.append(`(async () => {\n`);
7921
7605
  s.append(` await globalScripts();\n`);
7922
- s.append(` bootstrapLazy([/*!__STENCIL_LAZY_DATA__*/]);\n`);
7606
+ s.append(` bootstrapLazy(["__STENCIL_LAZY_DATA__"]);\n`);
7923
7607
  s.append(`})();\n`);
7924
7608
  } else {
7925
7609
  s.append(`import { globalScripts } from '${STENCIL_APP_GLOBALS_ID}';\n`);
7926
7610
  s.append(`export const defineCustomElements = async (win, options) => {\n`);
7927
7611
  s.append(` if (typeof window === 'undefined') return undefined;\n`);
7928
7612
  s.append(` await globalScripts();\n`);
7929
- s.append(` return bootstrapLazy([/*!__STENCIL_LAZY_DATA__*/], options);\n`);
7613
+ s.append(` return bootstrapLazy(["__STENCIL_LAZY_DATA__"], options);\n`);
7930
7614
  s.append(`};\n`);
7931
7615
  }
7932
7616
  return s.toString();
@@ -8106,10 +7790,6 @@ const validateDist = (config, userOutputs) => {
8106
7790
  outputs.push({
8107
7791
  type: DIST_LAZY,
8108
7792
  esmDir: lazyDir,
8109
- systemDir: config.buildEs5 ? lazyDir : void 0,
8110
- systemLoaderFile: config.buildEs5 ? join$1(lazyDir, namespace + ".js") : void 0,
8111
- legacyLoaderFile: join$1(distOutputTarget.buildDir, namespace + ".js"),
8112
- polyfills: outputTarget.polyfills !== void 0 ? !!distOutputTarget.polyfills : true,
8113
7793
  isBrowserBuild: true,
8114
7794
  empty: distOutputTarget.empty
8115
7795
  });
@@ -8149,23 +7829,19 @@ const validateDist = (config, userOutputs) => {
8149
7829
  });
8150
7830
  }
8151
7831
  const esmDir = join$1(distOutputTarget.dir, "esm");
8152
- const esmEs5Dir = config.buildEs5 ? join$1(distOutputTarget.dir, "esm-es5") : void 0;
8153
- const cjsDir = join$1(distOutputTarget.dir, "cjs");
7832
+ const cjsDir = distOutputTarget.cjs ? join$1(distOutputTarget.dir, "cjs") : void 0;
8154
7833
  outputs.push({
8155
7834
  type: DIST_LAZY,
8156
7835
  esmDir,
8157
- esmEs5Dir,
8158
7836
  cjsDir,
8159
- cjsIndexFile: join$1(distOutputTarget.dir, "index.cjs.js"),
7837
+ cjsIndexFile: distOutputTarget.cjs ? join$1(distOutputTarget.dir, "index.cjs.js") : void 0,
8160
7838
  esmIndexFile: join$1(distOutputTarget.dir, "index.js"),
8161
- polyfills: true,
8162
7839
  empty: distOutputTarget.empty
8163
7840
  });
8164
7841
  outputs.push({
8165
7842
  type: DIST_LAZY_LOADER,
8166
7843
  dir: distOutputTarget.esmLoaderPath,
8167
7844
  esmDir,
8168
- esmEs5Dir,
8169
7845
  cjsDir,
8170
7846
  componentDts: getComponentsDtsTypesFilePath(distOutputTarget),
8171
7847
  empty: distOutputTarget.empty
@@ -8194,10 +7870,10 @@ const validateOutputTargetDist = (config, o) => {
8194
7870
  typesDir: o.typesDir || DEFAULT_TYPES_DIR,
8195
7871
  esmLoaderPath: o.esmLoaderPath || DEFAULT_ESM_LOADER_DIR,
8196
7872
  copy: validateCopy(o.copy ?? [], []),
8197
- polyfills: isBoolean$1(o.polyfills) ? o.polyfills : false,
8198
7873
  empty: isBoolean$1(o.empty) ? o.empty : true,
8199
7874
  transformAliasedImportPathsInCollection: isBoolean$1(o.transformAliasedImportPathsInCollection) ? o.transformAliasedImportPathsInCollection : true,
8200
- isPrimaryPackageOutputTarget: o.isPrimaryPackageOutputTarget ?? false
7875
+ isPrimaryPackageOutputTarget: o.isPrimaryPackageOutputTarget ?? false,
7876
+ cjs: isBoolean$1(o.cjs) ? o.cjs : false
8201
7877
  };
8202
7878
  if (!isAbsolute(outputTarget.buildDir)) outputTarget.buildDir = join$1(outputTarget.dir, outputTarget.buildDir);
8203
7879
  if (outputTarget.collectionDir && !isAbsolute(outputTarget.collectionDir)) outputTarget.collectionDir = join$1(outputTarget.dir, outputTarget.collectionDir);
@@ -8305,7 +7981,7 @@ const validateHydrateScript = (config, userOutputs) => {
8305
7981
  if (!isAbsolute(outputTarget.dir)) outputTarget.dir = join$1(config.rootDir, outputTarget.dir);
8306
7982
  if (!isBoolean$1(outputTarget.empty)) outputTarget.empty = true;
8307
7983
  if (!isBoolean$1(outputTarget.minify)) outputTarget.minify = false;
8308
- if (!isBoolean$1(outputTarget.generatePackageJson)) outputTarget.generatePackageJson = true;
7984
+ if (!isBoolean$1(outputTarget.cjs)) outputTarget.cjs = false;
8309
7985
  outputTarget.external = outputTarget.external || [];
8310
7986
  outputTarget.external.push("fs");
8311
7987
  outputTarget.external.push("path");
@@ -8318,13 +7994,9 @@ const validateHydrateScript = (config, userOutputs) => {
8318
7994
  //#region src/compiler/config/outputs/validate-lazy.ts
8319
7995
  const validateLazy = (config, userOutputs) => {
8320
7996
  return userOutputs.filter(isOutputTargetDistLazy).map((o) => {
8321
- const dir = getAbsolutePath(config, o.dir || join$1("dist", config.fsNamespace));
8322
7997
  return {
8323
7998
  type: DIST_LAZY,
8324
- esmDir: dir,
8325
- systemDir: config.buildEs5 ? dir : void 0,
8326
- systemLoaderFile: config.buildEs5 ? join$1(dir, `${config.fsNamespace}.js`) : void 0,
8327
- polyfills: !!o.polyfills,
7999
+ esmDir: getAbsolutePath(config, o.dir || join$1("dist", config.fsNamespace)),
8328
8000
  isBrowserBuild: true,
8329
8001
  empty: isBoolean$1(o.empty) ? o.empty : true
8330
8002
  };
@@ -8437,9 +8109,8 @@ const DEFAULT_FILENAME = "sw.js";
8437
8109
  //#region src/compiler/config/outputs/validate-www.ts
8438
8110
  const validateWww = (config, diagnostics, userOutputs) => {
8439
8111
  const hasOutputTargets = userOutputs.length > 0;
8440
- const hasE2eTests = !!config.e2eTests;
8441
8112
  const userWwwOutputs = userOutputs.filter(isOutputTargetWww);
8442
- if (!hasOutputTargets || hasE2eTests && !userOutputs.some(isOutputTargetWww) && !userOutputs.some(isOutputTargetDist)) userWwwOutputs.push({ type: "www" });
8113
+ if (!hasOutputTargets) userWwwOutputs.push({ type: "www" });
8443
8114
  if (config.prerender && userWwwOutputs.length === 0) {
8444
8115
  const err = buildError(diagnostics);
8445
8116
  err.messageText = `You need at least one "www" output target configured in your stencil.config.ts, when the "--prerender" flag is used`;
@@ -8452,9 +8123,6 @@ const validateWww = (config, diagnostics, userOutputs) => {
8452
8123
  type: DIST_LAZY,
8453
8124
  dir: buildDir,
8454
8125
  esmDir: buildDir,
8455
- systemDir: config.buildEs5 ? buildDir : void 0,
8456
- systemLoaderFile: config.buildEs5 ? join$1(buildDir, `${config.fsNamespace}.js`) : void 0,
8457
- polyfills: outputTarget.polyfills,
8458
8126
  isBrowserBuild: true
8459
8127
  });
8460
8128
  outputs.push({
@@ -8494,8 +8162,6 @@ const validateWwwOutputTarget = (config, outputTarget, diagnostics) => {
8494
8162
  if (!isBoolean$1(outputTarget.empty)) outputTarget.empty = true;
8495
8163
  validatePrerender(config, diagnostics, outputTarget);
8496
8164
  validateServiceWorker(config, outputTarget);
8497
- if (outputTarget.polyfills === void 0) outputTarget.polyfills = true;
8498
- outputTarget.polyfills = !!outputTarget.polyfills;
8499
8165
  return outputTarget;
8500
8166
  };
8501
8167
  //#endregion
@@ -8603,7 +8269,7 @@ const validateDevServer = (config, diagnostics) => {
8603
8269
  err.messageText = `dev server excludeHmr must be an array of glob strings`;
8604
8270
  }
8605
8271
  } else devServer.excludeHmr = [];
8606
- if (!config.devMode || config.buildEs5) devServer.experimentalDevModules = false;
8272
+ if (!config.devMode) devServer.experimentalDevModules = false;
8607
8273
  else devServer.experimentalDevModules = !!devServer.experimentalDevModules;
8608
8274
  return devServer;
8609
8275
  };
@@ -8873,34 +8539,34 @@ const DEFAULT_SRC_DIR = "src";
8873
8539
  //#region src/compiler/config/validate-plugins.ts
8874
8540
  const validatePlugins = (config, diagnostics) => {
8875
8541
  const userPlugins = config.plugins;
8876
- if (!config.rollupPlugins) config.rollupPlugins = {};
8542
+ if (!config.rolldownPlugins) config.rolldownPlugins = {};
8877
8543
  if (!Array.isArray(userPlugins)) {
8878
8544
  config.plugins = [];
8879
8545
  return;
8880
8546
  }
8881
- const rollupPlugins = userPlugins.filter((plugin) => {
8547
+ const rolldownPlugins = userPlugins.filter((plugin) => {
8882
8548
  return !!(plugin && typeof plugin === "object" && !plugin.pluginType);
8883
8549
  });
8884
- const hasResolveNode = rollupPlugins.some((p) => p.name === "node-resolve");
8885
- if (rollupPlugins.some((p) => p.name === "commonjs")) {
8550
+ const hasResolveNode = rolldownPlugins.some((p) => p.name === "node-resolve");
8551
+ if (rolldownPlugins.some((p) => p.name === "commonjs")) {
8886
8552
  const warn = buildWarn(diagnostics);
8887
- warn.messageText = `Stencil already uses "@rollup/plugin-commonjs", please remove it from your "stencil.config.ts" plugins.
8553
+ warn.messageText = `Stencil already uses "@rolldown/plugin-commonjs", please remove it from your "stencil.config.ts" plugins.
8888
8554
  You can configure the commonjs settings using the "commonjs" property in "stencil.config.ts`;
8889
8555
  }
8890
8556
  if (hasResolveNode) {
8891
8557
  const warn = buildWarn(diagnostics);
8892
- warn.messageText = `Stencil already uses "@rollup/plugin-commonjs", please remove it from your "stencil.config.ts" plugins.
8558
+ warn.messageText = `Stencil already uses "@rolldown/plugin-commonjs", please remove it from your "stencil.config.ts" plugins.
8893
8559
  You can configure the commonjs settings using the "commonjs" property in "stencil.config.ts`;
8894
8560
  }
8895
- config.rollupPlugins.before = [...config.rollupPlugins.before || [], ...rollupPlugins.filter(({ name }) => name !== "node-resolve" && name !== "commonjs")];
8561
+ config.rolldownPlugins.before = [...config.rolldownPlugins.before || [], ...rolldownPlugins.filter(({ name }) => name !== "node-resolve" && name !== "commonjs")];
8896
8562
  config.plugins = userPlugins.filter((plugin) => {
8897
8563
  return !!(plugin && typeof plugin === "object" && plugin.pluginType);
8898
8564
  });
8899
8565
  };
8900
8566
  //#endregion
8901
- //#region src/compiler/config/validate-rollup-config.ts
8567
+ //#region src/compiler/config/validate-rolldown-config.ts
8902
8568
  /**
8903
- * Ensure that a valid baseline rollup configuration is set on the validated
8569
+ * Ensure that a valid baseline rolldown configuration is set on the validated
8904
8570
  * config.
8905
8571
  *
8906
8572
  * If a config is present this will return a new config based on the user
@@ -8909,15 +8575,15 @@ const validatePlugins = (config, diagnostics) => {
8909
8575
  * If no config is present, this will return a default config.
8910
8576
  *
8911
8577
  * @param config a validated user-supplied configuration object
8912
- * @returns a validated rollup configuration
8913
- */
8914
- const validateRollupConfig = (config) => {
8915
- let cleanRollupConfig = { ...DEFAULT_ROLLUP_CONFIG };
8916
- const rollupConfig = config.rollupConfig;
8917
- if (!rollupConfig || !isObject(rollupConfig)) return cleanRollupConfig;
8918
- if (rollupConfig.inputOptions && isObject(rollupConfig.inputOptions)) cleanRollupConfig = {
8919
- ...cleanRollupConfig,
8920
- inputOptions: pluck(rollupConfig.inputOptions, [
8578
+ * @returns a validated rolldown configuration
8579
+ */
8580
+ const validateRolldownConfig = (config) => {
8581
+ let cleanRolldownConfig = { ...DEFAULT_ROLLDOWN_CONFIG };
8582
+ const rolldownConfig = config.rolldownConfig;
8583
+ if (!rolldownConfig || !isObject(rolldownConfig)) return cleanRolldownConfig;
8584
+ if (rolldownConfig.inputOptions && isObject(rolldownConfig.inputOptions)) cleanRolldownConfig = {
8585
+ ...cleanRolldownConfig,
8586
+ inputOptions: pluck(rolldownConfig.inputOptions, [
8921
8587
  "context",
8922
8588
  "moduleContext",
8923
8589
  "treeshake",
@@ -8925,13 +8591,13 @@ const validateRollupConfig = (config) => {
8925
8591
  "maxParallelFileOps"
8926
8592
  ])
8927
8593
  };
8928
- if (rollupConfig.outputOptions && isObject(rollupConfig.outputOptions)) cleanRollupConfig = {
8929
- ...cleanRollupConfig,
8930
- outputOptions: pluck(rollupConfig.outputOptions, ["globals"])
8594
+ if (rolldownConfig.outputOptions && isObject(rolldownConfig.outputOptions)) cleanRolldownConfig = {
8595
+ ...cleanRolldownConfig,
8596
+ outputOptions: pluck(rolldownConfig.outputOptions, ["globals"])
8931
8597
  };
8932
- return cleanRollupConfig;
8598
+ return cleanRolldownConfig;
8933
8599
  };
8934
- const DEFAULT_ROLLUP_CONFIG = {
8600
+ const DEFAULT_ROLLDOWN_CONFIG = {
8935
8601
  inputOptions: {},
8936
8602
  outputOptions: {}
8937
8603
  };
@@ -8983,7 +8649,6 @@ const validateConfig = (userConfig = {}, bootstrapConfig) => {
8983
8649
  const validatedConfig = {
8984
8650
  devServer: {},
8985
8651
  ...config,
8986
- buildEs5: config.buildEs5 === true || !devMode && config.buildEs5 === "prod",
8987
8652
  devMode,
8988
8653
  extras: config.extras || {},
8989
8654
  generateExportMaps: isBoolean$1(config.generateExportMaps) ? config.generateExportMaps : false,
@@ -8995,19 +8660,18 @@ const validateConfig = (userConfig = {}, bootstrapConfig) => {
8995
8660
  minifyCss: config.minifyCss ?? !devMode,
8996
8661
  minifyJs: config.minifyJs ?? !devMode,
8997
8662
  outputTargets: config.outputTargets ?? [],
8998
- rollupConfig: validateRollupConfig(config),
8663
+ rolldownConfig: validateRolldownConfig(config),
8999
8664
  sourceMap: config.sourceMap === true || devMode && (config.sourceMap === "dev" || typeof config.sourceMap === "undefined"),
9000
8665
  sys: config.sys ?? bootstrapConfig.sys ?? createNodeSys({ logger }),
9001
- testing: config.testing ?? {},
9002
8666
  docs: validateDocs(config, logger),
9003
8667
  transformAliasedImportPaths: isBoolean$1(userConfig.transformAliasedImportPaths) ? userConfig.transformAliasedImportPaths : true,
9004
8668
  validatePrimaryPackageOutputTarget: userConfig.validatePrimaryPackageOutputTarget ?? false,
9005
8669
  ...validateNamespace(config.namespace, config.fsNamespace, diagnostics),
9006
8670
  ...validatePaths(config)
9007
8671
  };
8672
+ if (validatedConfig.buildLogFilePath) logger.setLogFilePath(validatedConfig.buildLogFilePath);
9008
8673
  validatedConfig.extras.lifecycleDOMEvents = !!validatedConfig.extras.lifecycleDOMEvents;
9009
8674
  validatedConfig.extras.initializeNextTick = !!validatedConfig.extras.initializeNextTick;
9010
- validatedConfig.extras.tagNameTransform = !!validatedConfig.extras.tagNameTransform;
9011
8675
  validatedConfig.extras.additionalTagTransformers = validatedConfig.extras.additionalTagTransformers === true || !devMode && validatedConfig.extras.additionalTagTransformers === "prod";
9012
8676
  validatedConfig.extras.addGlobalStyleToComponents = isBoolean$1(validatedConfig.extras.addGlobalStyleToComponents) ? validatedConfig.extras.addGlobalStyleToComponents : "client";
9013
8677
  if (validatedConfig.extras.experimentalSlotFixes === true) {
@@ -9040,11 +8704,11 @@ const validateConfig = (userConfig = {}, bootstrapConfig) => {
9040
8704
  }
9041
8705
  setBooleanConfig(validatedConfig, "watch", false);
9042
8706
  setBooleanConfig(validatedConfig, "buildDocs", !validatedConfig.devMode);
9043
- setBooleanConfig(validatedConfig, "buildDist", !validatedConfig.devMode || !!validatedConfig.buildEs5);
8707
+ setBooleanConfig(validatedConfig, "buildDist", !validatedConfig.devMode);
9044
8708
  setBooleanConfig(validatedConfig, "profile", validatedConfig.devMode);
9045
8709
  setBooleanConfig(validatedConfig, "writeLog", false);
9046
8710
  setBooleanConfig(validatedConfig, "buildAppCore", true);
9047
- setBooleanConfig(validatedConfig, "autoprefixCss", validatedConfig.buildEs5);
8711
+ setBooleanConfig(validatedConfig, "autoprefixCss", false);
9048
8712
  setBooleanConfig(validatedConfig, "validateTypes", !validatedConfig._isTesting);
9049
8713
  setBooleanConfig(validatedConfig, "allowInlineScripts", true);
9050
8714
  setBooleanConfig(validatedConfig, "suppressReservedPublicNameWarnings", false);
@@ -9075,10 +8739,6 @@ const validateConfig = (userConfig = {}, bootstrapConfig) => {
9075
8739
  if (reg instanceof RegExp) arr.push(reg);
9076
8740
  return arr;
9077
8741
  }, []);
9078
- if (validatedConfig.nodeResolve?.customResolveOptions) {
9079
- const warn = buildWarn(diagnostics);
9080
- warn.messageText = `nodeResolve.customResolveOptions is a deprecated option in a Stencil Configuration file. If you need this option, please open a new issue in the Stencil repository (https://github.com/stenciljs/core/issues/new/choose)`;
9081
- }
9082
8742
  CACHED_VALIDATED_CONFIG = validatedConfig;
9083
8743
  return {
9084
8744
  config: validatedConfig,
@@ -9106,8 +8766,6 @@ var BuildContext = class {
9106
8766
  buildStats = void 0;
9107
8767
  esmBrowserComponentBundle;
9108
8768
  esmComponentBundle;
9109
- es5ComponentBundle;
9110
- systemComponentBundle;
9111
8769
  commonJsComponentBundle;
9112
8770
  diagnostics = [];
9113
8771
  dirsAdded = [];
@@ -10443,39 +10101,19 @@ const outputLazyLoader = async (config, compilerCtx) => {
10443
10101
  };
10444
10102
  const generateLoader = async (config, compilerCtx, outputTarget) => {
10445
10103
  const loaderPath = outputTarget.dir;
10446
- const es2017Dir = outputTarget.esmDir;
10447
- const es5Dir = outputTarget.esmEs5Dir || es2017Dir;
10104
+ const esmDir = outputTarget.esmDir;
10448
10105
  const cjsDir = outputTarget.cjsDir;
10449
- if (!loaderPath || !es2017Dir || !cjsDir) return;
10450
- const es5HtmlElement = await getClientPolyfill(config, compilerCtx, "es5-html-element.js");
10451
- const polyfillsExport = `export * from '${relative$1(loaderPath, join$1(es2017Dir, "polyfills/index.js"))}';`;
10452
- const es5EntryPoint = join$1(es5Dir, "loader.js");
10453
- const indexContent = filterAndJoin([
10454
- generatePreamble(config),
10455
- es5HtmlElement,
10456
- config.buildEs5 ? polyfillsExport : null,
10457
- `export * from '${relative$1(loaderPath, es5EntryPoint)}';`
10458
- ]);
10459
- const es2017EntryPoint = join$1(es2017Dir, "loader.js");
10460
- const indexES2017Content = filterAndJoin([
10461
- generatePreamble(config),
10462
- config.buildEs5 ? polyfillsExport : null,
10463
- `export * from '${relative$1(loaderPath, es2017EntryPoint)}';`
10464
- ]);
10465
- const cjsEntryPoint = join$1(cjsDir, "loader.cjs.js");
10466
- const indexCjsContent = filterAndJoin([
10467
- generatePreamble(config),
10468
- `module.exports = require('${relative$1(loaderPath, cjsEntryPoint)}');`,
10469
- config.buildEs5 ? `module.exports.applyPolyfills = function() { return Promise.resolve() };` : null
10470
- ]);
10106
+ if (!loaderPath || !esmDir) return;
10107
+ const esmEntryPoint = join$1(esmDir, "loader.js");
10108
+ const indexContent = filterAndJoin([generatePreamble(config), `export * from '${relative$1(loaderPath, esmEntryPoint)}';`]);
10471
10109
  const indexDtsPath = join$1(loaderPath, "index.d.ts");
10472
- await Promise.all([
10473
- compilerCtx.fs.writeFile(join$1(loaderPath, "index.d.ts"), generateIndexDts(indexDtsPath, outputTarget.componentDts)),
10474
- compilerCtx.fs.writeFile(join$1(loaderPath, "index.js"), indexContent),
10475
- compilerCtx.fs.writeFile(join$1(loaderPath, "index.cjs.js"), indexCjsContent),
10476
- compilerCtx.fs.writeFile(join$1(loaderPath, "cdn.js"), indexCjsContent),
10477
- compilerCtx.fs.writeFile(join$1(loaderPath, "index.es2017.js"), indexES2017Content)
10478
- ]);
10110
+ const writes = [compilerCtx.fs.writeFile(join$1(loaderPath, "index.d.ts"), generateIndexDts(indexDtsPath, outputTarget.componentDts)), compilerCtx.fs.writeFile(join$1(loaderPath, "index.js"), indexContent)];
10111
+ if (cjsDir) {
10112
+ const cjsEntryPoint = join$1(cjsDir, "loader.cjs.js");
10113
+ const indexCjsContent = filterAndJoin([generatePreamble(config), `module.exports = require('${relative$1(loaderPath, cjsEntryPoint)}');`]);
10114
+ writes.push(compilerCtx.fs.writeFile(join$1(loaderPath, "index.cjs.js"), indexCjsContent), compilerCtx.fs.writeFile(join$1(loaderPath, "cdn.js"), indexCjsContent));
10115
+ }
10116
+ await Promise.all(writes);
10479
10117
  };
10480
10118
  const generateIndexDts = (indexDtsPath, componentsDtsPath) => {
10481
10119
  return `export * from '${relativeImport(indexDtsPath, componentsDtsPath, ".d.ts")}';
@@ -10488,10 +10126,6 @@ export interface CustomElementsDefineOptions {
10488
10126
  rel?: (el: EventTarget, eventName: string, listener: EventListenerOrEventListenerObject, options: boolean | AddEventListenerOptions) => void;
10489
10127
  }
10490
10128
  export declare function defineCustomElements(win?: Window, opts?: CustomElementsDefineOptions): void;
10491
- /**
10492
- * @deprecated
10493
- */
10494
- export declare function applyPolyfills(): Promise<void>;
10495
10129
 
10496
10130
  /**
10497
10131
  * Used to specify a nonce value that corresponds with an application's CSP.
@@ -11524,142 +11158,6 @@ const outputTypes = async (config, compilerCtx, buildCtx) => {
11524
11158
  timespan.finish(`generate types finished`);
11525
11159
  };
11526
11160
  //#endregion
11527
- //#region src/compiler/app-core/app-es5-disabled.ts
11528
- const generateEs5DisabledMessage = async (config, compilerCtx, outputTarget) => {
11529
- const fileName = `${config.fsNamespace}.js`;
11530
- const filePath = join$1(outputTarget.buildDir, fileName);
11531
- await compilerCtx.fs.writeFile(filePath, getDisabledMessageScript(config));
11532
- return fileName;
11533
- };
11534
- const getDisabledMessageScript = (config) => {
11535
- const style = `
11536
- <style>
11537
- body {
11538
- display: block !important;
11539
- font-family: sans-serif;
11540
- padding: 20px;
11541
- line-height:22px;
11542
- }
11543
- h1 {
11544
- font-size: 18px;
11545
- }
11546
- h2 {
11547
- font-size: 14px;
11548
- margin-top: 40px;
11549
- }
11550
- </style>
11551
- `;
11552
- const htmlLegacy = `
11553
- ${style}
11554
-
11555
- <h1>This Stencil app is disabled for this browser.</h1>
11556
-
11557
- <h2>Developers:</h2>
11558
- <ul>
11559
- <li>ES5 builds are disabled <strong>during development</strong> to take advantage of 2x faster build times.</li>
11560
- <li>Please see the example below or our <a href="https://stenciljs.com/docs/stencil-config" target="_blank" rel="noopener noreferrer">config docs</a> if you would like to develop on a browser that does not fully support ES2017 and custom elements.</li>
11561
- <li>Note that as of Stencil v2, ES5 builds and polyfills are <strong>disabled</strong> during production builds. You can enable these <a href="https://stenciljs.com/docs/config#buildes5" target="_blank" rel="noopener noreferrer">in your stencil.config.ts file</a>.</li>
11562
- <li>When testing browsers it is recommended to always test in production mode, and ES5 builds should always be enabled during production builds.</li>
11563
- <li><em>This is only an experiment and if it slows down app development then we will revert this and enable ES5 builds during dev.</em></li>
11564
- </ul>
11565
-
11566
-
11567
- <h2>Enabling ES5 builds during development:</h2>
11568
- <pre>
11569
- <code>npm run dev --es5</code>
11570
- </pre>
11571
- <p>For stencil-component-starter, use:</p>
11572
- <pre>
11573
- <code>npm start --es5</code>
11574
- </pre>
11575
-
11576
-
11577
- <h2>Enabling full production builds during development:</h2>
11578
- <pre>
11579
- <code>npm run dev --prod</code>
11580
- </pre>
11581
- <p>For stencil-component-starter, use:</p>
11582
- <pre>
11583
- <code>npm start --prod</code>
11584
- </pre>
11585
-
11586
- <h2>Current Browser's Support:</h2>
11587
- <ul>
11588
- <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">ES Module Imports</a>: <span id="es-modules-test"></span></li>
11589
- <li><a href="http://2ality.com/2017/01/import-operator.html">ES Dynamic Imports</a>: <span id="es-dynamic-modules-test"></span></li>
11590
- <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/customElements">Custom Elements</a>: <span id="custom-elements-test"></span></li>
11591
- <li><a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM">Shadow DOM</a>: <span id="shadow-dom-test"></span></li>
11592
- <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch</a>: <span id="fetch-test"></span></li>
11593
- <li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables">CSS Variables</a>: <span id="css-variables-test"></span></li>
11594
- </ul>
11595
-
11596
- <h2>Current Browser:</h2>
11597
- <pre>
11598
- <code id="current-browser-output"></code>
11599
- </pre>
11600
- `;
11601
- const htmlUpdate = `
11602
- ${style}
11603
-
11604
- <h1>Update src/index.html</h1>
11605
-
11606
- <p>Stencil recently changed how scripts are loaded in order to improve performance.</p>
11607
-
11608
- <h2>BEFORE:</h2>
11609
- <p>Previously, a single script was included that handled loading the correct JavaScript based on browser support.</p>
11610
- <pre>
11611
- <code>${escapeHtml(`<script src="/build/${config.fsNamespace}.js"><\/script>
11612
- `)}</code>
11613
- </pre>
11614
-
11615
- <h2 style="margin-top:0">AFTER:</h2>
11616
- <p>The index.html should now include two scripts using the modern ES Module script pattern.
11617
- Note that only one file will actually be requested and loaded based on the browser's native support for ES Modules.
11618
- For more info, please see <a href="https://developers.google.com/web/fundamentals/primers/modules#browser" target="_blank" rel="noopener noreferrer">Using JavaScript modules on the web</a>.
11619
- </p>
11620
- <pre>
11621
- <code>${escapeHtml(`<script`)} <span style="background:yellow">type="module"</span> src="/build/${config.fsNamespace}<span style="background:yellow">.esm</span>.js"${escapeHtml(`><\/script>`)}
11622
- ${escapeHtml(`<script`)} <span style="background:yellow">nomodule</span> ${escapeHtml(`src="/build/${config.fsNamespace}.js"><\/script>`)}</code>
11623
- </pre>
11624
- `;
11625
- return `${generatePreamble(config)}
11626
- (function() {
11627
- function checkSupport() {
11628
- if (!document.body) {
11629
- setTimeout(checkSupport);
11630
- return;
11631
- }
11632
- function supportsDynamicImports() {
11633
- try {
11634
- new Function('import("")');
11635
- return true;
11636
- } catch {}
11637
- return false;
11638
- }
11639
- var supportsEsModules = !!('noModule' in document.createElement('script'));
11640
-
11641
- if (!supportsEsModules) {
11642
- document.body.innerHTML = '${inlineHTML(htmlLegacy)}';
11643
-
11644
- document.getElementById('current-browser-output').textContent = window.navigator.userAgent;
11645
- document.getElementById('es-modules-test').textContent = supportsEsModules;
11646
- document.getElementById('es-dynamic-modules-test').textContent = supportsDynamicImports();
11647
- document.getElementById('shadow-dom-test').textContent = !!(document.head.attachShadow);
11648
- document.getElementById('custom-elements-test').textContent = !!(window.customElements);
11649
- document.getElementById('css-variables-test').textContent = !!(window.CSS && window.CSS.supports && window.CSS.supports('color', 'var(--c)'));
11650
- document.getElementById('fetch-test').textContent = !!(window.fetch);
11651
- } else {
11652
- document.body.innerHTML = '${inlineHTML(htmlUpdate)}';
11653
- }
11654
- }
11655
-
11656
- setTimeout(checkSupport);
11657
- })();`;
11658
- };
11659
- const inlineHTML = (html) => {
11660
- return html.replace(/\n/g, "\\n").replace(/'/g, `\\'`).trim();
11661
- };
11662
- //#endregion
11663
11161
  //#region src/compiler/html/html-utils.ts
11664
11162
  /**
11665
11163
  * Get the path to the build directory where files written for the `www` output
@@ -12066,7 +11564,6 @@ const getCriticalPath = (buildCtx) => {
12066
11564
  * @param outputTarget the www output target of interest
12067
11565
  */
12068
11566
  const generateWww = async (config, compilerCtx, buildCtx, criticalPath, outputTarget) => {
12069
- if (!config.buildEs5) await generateEs5DisabledMessage(config, compilerCtx, outputTarget);
12070
11567
  if (buildCtx.indexDoc && outputTarget.indexHtml) await generateIndexHtml(config, compilerCtx, buildCtx, criticalPath, outputTarget);
12071
11568
  await generateHostConfig(compilerCtx, outputTarget);
12072
11569
  };
@@ -12129,7 +11626,7 @@ const generateOutputTargets = async (config, compilerCtx, buildCtx) => {
12129
11626
  const timeSpan = buildCtx.createTimeSpan("generate outputs started", true);
12130
11627
  const changedModuleFiles = Array.from(compilerCtx.changedModules).map((filename) => compilerCtx.moduleMap.get(filename)).filter((mod) => mod && !mod.isCollectionDependency);
12131
11628
  compilerCtx.changedModules.clear();
12132
- invalidateRollupCaches(compilerCtx);
11629
+ invalidateRolldownCaches(compilerCtx);
12133
11630
  await Promise.all([
12134
11631
  outputCollection(config, compilerCtx, buildCtx, changedModuleFiles),
12135
11632
  outputCustomElements(config, compilerCtx, buildCtx),
@@ -12146,11 +11643,11 @@ const generateOutputTargets = async (config, compilerCtx, buildCtx) => {
12146
11643
  ]);
12147
11644
  timeSpan.finish("generate outputs finished");
12148
11645
  };
12149
- const invalidateRollupCaches = (compilerCtx) => {
11646
+ const invalidateRolldownCaches = (compilerCtx) => {
12150
11647
  const invalidatedIds = compilerCtx.changedFiles;
12151
- compilerCtx.rollupCache.forEach((cache) => {
12152
- cache.modules.forEach((mod) => {
12153
- if (mod.transformDependencies.some((id) => invalidatedIds.has(id))) mod.originalCode = null;
11648
+ compilerCtx.rolldownCache.forEach((cache) => {
11649
+ if (cache?.modules) cache.modules.forEach((mod) => {
11650
+ if (mod?.transformDependencies?.some((id) => invalidatedIds.has(id))) mod.originalCode = null;
12154
11651
  });
12155
11652
  });
12156
11653
  };
@@ -12277,51 +11774,439 @@ const hasChangedImportContent = async (config, compilerCtx, buildCtx, filePath,
12277
11774
  return (await Promise.all(promises)).includes(true);
12278
11775
  };
12279
11776
  //#endregion
12280
- //#region src/compiler/entries/resolve-component-dependencies.ts
12281
- /**
12282
- * For each entry in the provided collection of compiler metadata, generate several lists:
12283
- * - dependencies that the component has (both directly and indirectly/transitively)
12284
- * - dependencies that the component has (only directly)
12285
- * - components that are dependent on a particular component (both directly and indirectly/transitively)
12286
- * - components that are dependent on a particular component (only directly)
12287
- *
12288
- * This information is stored directly on each entry in the provided collection
12289
- *
12290
- * @param cmps the compiler metadata of the components whose dependencies and dependents ought to be calculated
12291
- */
12292
- function resolveComponentDependencies(cmps) {
12293
- computeDependencies(cmps);
12294
- computeDependents(cmps);
12295
- }
12296
- /**
12297
- * Compute the direct and transitive dependencies for each entry in the provided collection of component metadata.
12298
- *
12299
- * This function mutates each entry in the provided collection.
12300
- *
12301
- * @param cmps the metadata for the components whose dependencies ought to be calculated.
12302
- */
12303
- function computeDependencies(cmps) {
12304
- const visited = /* @__PURE__ */ new Set();
12305
- cmps.forEach((cmp) => {
12306
- resolveTransitiveDependencies(cmp, cmps, visited);
12307
- cmp.dependencies = unique(cmp.dependencies).sort();
12308
- });
12309
- }
11777
+ //#region src/compiler/transformers/decorators-to-static/decorator-utils.ts
11778
+ const getDecoratorParameters = (decorator, typeChecker, diagnostics) => {
11779
+ if (!ts.isCallExpression(decorator.expression)) return [];
11780
+ return decorator.expression.arguments.map((arg) => getDecoratorParameter(arg, typeChecker, diagnostics, decorator.expression));
11781
+ };
11782
+ const getDecoratorParameter = (arg, typeChecker, diagnostics, errorNode) => {
11783
+ if (ts.isCallExpression(arg)) {
11784
+ const expression = arg.expression;
11785
+ if (ts.isIdentifier(expression) && expression.text === "resolveVar" || ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.name) && expression.name.text === "resolveVar") {
11786
+ if (arg.arguments.length !== 1) {
11787
+ const err = buildError(diagnostics);
11788
+ err.messageText = "resolveVar() expects exactly one argument.";
11789
+ if (errorNode) augmentDiagnosticWithNode(err, errorNode);
11790
+ throw new Error(err.messageText);
11791
+ }
11792
+ const resolveArg = arg.arguments[0];
11793
+ return resolveVariableValue(resolveArg, typeChecker, diagnostics, resolveArg);
11794
+ }
11795
+ }
11796
+ if (ts.isObjectLiteralExpression(arg)) return objectLiteralToObjectMap(arg, typeChecker, diagnostics, errorNode);
11797
+ else if (ts.isStringLiteral(arg)) return arg.text;
11798
+ else if (ts.isPropertyAccessExpression(arg) || ts.isIdentifier(arg)) {
11799
+ const type = typeChecker.getTypeAtLocation(arg);
11800
+ if (type !== void 0 && type.isLiteral())
11801
+ /**
11802
+ * Using enums or variables require us to resolve the value for
11803
+ * the computed property/identifier via the TS type checker. As long
11804
+ * as the type resolves to a literal, we can grab its value to be used
11805
+ * as the `@Watch()` decorator argument.
11806
+ */
11807
+ return type.value;
11808
+ }
11809
+ throw new Error(`invalid decorator argument: ${arg.getText()}`);
11810
+ };
12310
11811
  /**
12311
- * Compute the direct and transitive dependents for each entry in the provided collection of component metadata.
12312
- *
12313
- * @param cmps the component metadata whose entries will have their dependents calculated
11812
+ * Resolves a variable or object property to its string literal value at compile time.
11813
+ * Supports const variables and object properties with string literal values.
11814
+ * @param node - the expression to resolve
11815
+ * @param typeChecker - the TypeScript type checker
11816
+ * @param diagnostics - optional diagnostics array for error reporting
11817
+ * @param errorNode - optional node for error location
11818
+ * @returns the resolved string value
12314
11819
  */
12315
- function computeDependents(cmps) {
12316
- cmps.forEach((cmp) => {
12317
- resolveTransitiveDependents(cmp, cmps);
12318
- });
12319
- }
12320
- /**
12321
- * Calculate the direct and transitive dependencies of a particular component.
12322
- *
12323
- * For example, given a component `foo-bar` whose `render` function references another web component `baz-buzz`:
12324
- * ```tsx
11820
+ const resolveVariableValue = (node, typeChecker, diagnostics, errorNode) => {
11821
+ if (ts.isIdentifier(node)) {
11822
+ const symbol = typeChecker.getSymbolAtLocation(node);
11823
+ if (!symbol || !symbol.valueDeclaration) {
11824
+ const err = buildError(diagnostics);
11825
+ err.messageText = `resolveVar() cannot resolve the value of "${node.text}" at compile time. Only const variables and object properties with string literal values are supported.`;
11826
+ if (errorNode) augmentDiagnosticWithNode(err, errorNode);
11827
+ throw new Error(err.messageText);
11828
+ }
11829
+ const declaration = symbol.valueDeclaration;
11830
+ if (ts.isVariableDeclaration(declaration)) {
11831
+ const type = typeChecker.getTypeAtLocation(node);
11832
+ if (type && type.isLiteral() && typeof type.value === "string") return type.value;
11833
+ if (declaration.initializer) {
11834
+ const initializerValue = extractStringFromExpression(declaration.initializer, typeChecker);
11835
+ if (initializerValue !== null) return initializerValue;
11836
+ }
11837
+ }
11838
+ const err = buildError(diagnostics);
11839
+ err.messageText = `resolveVar() cannot resolve the value of "${node.text}" at compile time. Only const variables and object properties with string literal values are supported.`;
11840
+ if (errorNode) augmentDiagnosticWithNode(err, errorNode);
11841
+ throw new Error(err.messageText);
11842
+ }
11843
+ if (ts.isPropertyAccessExpression(node)) {
11844
+ const objectType = typeChecker.getTypeAtLocation(node.expression);
11845
+ if (!objectType) {
11846
+ const err = buildError(diagnostics);
11847
+ err.messageText = `resolveVar() cannot resolve the object type for "${node.getText()}" at compile time.`;
11848
+ if (errorNode) augmentDiagnosticWithNode(err, errorNode);
11849
+ throw new Error(err.messageText);
11850
+ }
11851
+ const propertyName = node.name.text;
11852
+ const property = typeChecker.getPropertyOfType(objectType, propertyName);
11853
+ if (!property) {
11854
+ const err = buildError(diagnostics);
11855
+ err.messageText = `resolveVar() cannot find property "${propertyName}" on object "${node.expression.getText()}" at compile time.`;
11856
+ if (errorNode) augmentDiagnosticWithNode(err, errorNode);
11857
+ throw new Error(err.messageText);
11858
+ }
11859
+ const propertyType = typeChecker.getTypeOfSymbolAtLocation(property, node);
11860
+ if (propertyType && propertyType.isLiteral() && typeof propertyType.value === "string") return propertyType.value;
11861
+ if (property.valueDeclaration) {
11862
+ if (ts.isPropertyDeclaration(property.valueDeclaration)) {
11863
+ const initializer = property.valueDeclaration.initializer;
11864
+ if (initializer) {
11865
+ const value = extractStringFromExpression(initializer, typeChecker);
11866
+ if (value !== null) return value;
11867
+ }
11868
+ } else if (ts.isPropertySignature(property.valueDeclaration)) {} else if (ts.isVariableDeclaration(property.valueDeclaration)) {
11869
+ const initializer = property.valueDeclaration.initializer;
11870
+ if (initializer) {
11871
+ const value = extractStringFromExpression(initializer, typeChecker);
11872
+ if (value !== null) return value;
11873
+ }
11874
+ }
11875
+ }
11876
+ const err = buildError(diagnostics);
11877
+ err.messageText = `resolveVar() cannot resolve the value of "${node.getText()}" at compile time. Only const variables and object properties with string literal values are supported.`;
11878
+ if (errorNode) augmentDiagnosticWithNode(err, errorNode);
11879
+ throw new Error(err.messageText);
11880
+ }
11881
+ const err = buildError(diagnostics);
11882
+ err.messageText = `resolveVar() can only be used with const variables or object properties. "${node.getText()}" is not supported.`;
11883
+ if (errorNode) augmentDiagnosticWithNode(err, errorNode);
11884
+ throw new Error(err.messageText);
11885
+ };
11886
+ /**
11887
+ * Extracts a string value from a TypeScript expression.
11888
+ * Returns null if the expression doesn't represent a string literal.
11889
+ * @param expr - the expression to extract from
11890
+ * @param typeChecker - the TypeScript type checker
11891
+ * @returns the extracted string value or null
11892
+ */
11893
+ const extractStringFromExpression = (expr, typeChecker) => {
11894
+ if (ts.isStringLiteral(expr)) return expr.text;
11895
+ if (ts.isNoSubstitutionTemplateLiteral(expr)) return expr.text;
11896
+ const type = typeChecker.getTypeAtLocation(expr);
11897
+ if (type && type.isLiteral() && typeof type.value === "string") return type.value;
11898
+ return null;
11899
+ };
11900
+ /**
11901
+ * Returns a function that checks if a decorator:
11902
+ * - is a call expression. these are decorators that are immediately followed by open/close parenthesis with optional
11903
+ * arg(s), e.g. `@Prop()`
11904
+ * - the name of the decorator matches the provided `propName`
11905
+ *
11906
+ * @param propName the name of the decorator to match against
11907
+ * @returns true if the conditions above are both true, false otherwise
11908
+ */
11909
+ const isDecoratorNamed = (propName) => {
11910
+ return (dec) => {
11911
+ return ts.isCallExpression(dec.expression) && dec.expression.expression.getText() === propName;
11912
+ };
11913
+ };
11914
+ //#endregion
11915
+ //#region src/compiler/transformers/decorators-to-static/style-to-static.ts
11916
+ const styleToStatic = (newMembers, componentOptions) => {
11917
+ const defaultModeStyles = [];
11918
+ if (componentOptions.styleUrls) if (Array.isArray(componentOptions.styleUrls)) defaultModeStyles.push(...normalizeStyleUrl(componentOptions.styleUrls));
11919
+ else defaultModeStyles.push(...normalizeStyleUrl(componentOptions.styleUrls["$"]));
11920
+ if (componentOptions.styleUrl) defaultModeStyles.push(...normalizeStyleUrl(componentOptions.styleUrl));
11921
+ let styleUrls = {};
11922
+ if (componentOptions.styleUrls && !Array.isArray(componentOptions.styleUrls)) styleUrls = normalizeStyleUrls(componentOptions.styleUrls);
11923
+ if (defaultModeStyles.length > 0) styleUrls["$"] = defaultModeStyles;
11924
+ if (Object.keys(styleUrls).length > 0) {
11925
+ const originalStyleUrls = convertValueToLiteral(styleUrls);
11926
+ newMembers.push(createStaticGetter("originalStyleUrls", originalStyleUrls));
11927
+ const normalizedStyleExp = convertValueToLiteral(normalizeExtension(styleUrls));
11928
+ newMembers.push(createStaticGetter("styleUrls", normalizedStyleExp));
11929
+ }
11930
+ if (typeof componentOptions.styles === "string") {
11931
+ const styles = componentOptions.styles.trim();
11932
+ if (styles.length > 0) newMembers.push(createStaticGetter("styles", ts.factory.createStringLiteral(styles)));
11933
+ } else if (componentOptions.styles) {
11934
+ const convertIdentifier = componentOptions.styles;
11935
+ if (convertIdentifier.__identifier) {
11936
+ const stylesIdentifier = convertIdentifier.__escapedText;
11937
+ newMembers.push(createStaticGetter("styles", ts.factory.createIdentifier(stylesIdentifier)));
11938
+ } else if (typeof convertIdentifier === "object") {
11939
+ if (Object.keys(convertIdentifier).length > 0) newMembers.push(createStaticGetter("styles", convertValueToLiteral(convertIdentifier)));
11940
+ }
11941
+ }
11942
+ };
11943
+ const normalizeExtension = (styleUrls) => {
11944
+ const compilerStyleUrls = {};
11945
+ Object.keys(styleUrls).forEach((key) => {
11946
+ compilerStyleUrls[key] = styleUrls[key].map((s) => useCss(s));
11947
+ });
11948
+ return compilerStyleUrls;
11949
+ };
11950
+ const useCss = (stylePath) => {
11951
+ return join$1(dirname$1(stylePath), basename$1(stylePath, extname(stylePath)) + ".css");
11952
+ };
11953
+ const normalizeStyleUrls = (styleUrls) => {
11954
+ const compilerStyleUrls = {};
11955
+ Object.keys(styleUrls).forEach((key) => {
11956
+ compilerStyleUrls[key] = normalizeStyleUrl(styleUrls[key]);
11957
+ });
11958
+ return compilerStyleUrls;
11959
+ };
11960
+ const normalizeStyleUrl = (style) => {
11961
+ if (Array.isArray(style)) return style;
11962
+ if (style) return [style];
11963
+ return [];
11964
+ };
11965
+ //#endregion
11966
+ //#region src/compiler/transformers/decorators-to-static/component-decorator.ts
11967
+ let hasShownDeprecatedApiError = false;
11968
+ /**
11969
+ * Reset the deprecated API error flag. Call this at the start of each build.
11970
+ */
11971
+ const resetDeprecatedApiWarning = () => {
11972
+ hasShownDeprecatedApiError = false;
11973
+ };
11974
+ /**
11975
+ * Perform code generation to create new class members for a Stencil component
11976
+ * which will drive the runtime functionality specified by various options
11977
+ * passed to the `@Component` decorator.
11978
+ *
11979
+ * Inputs are validated (@see {@link validateComponent}) before code generation
11980
+ * is performed.
11981
+ *
11982
+ * **Note**: in this function and in functions that it calls the `newMembers`
11983
+ * parameter is treated as an out parameter and mutated, with new class members
11984
+ * added to it.
11985
+ *
11986
+ * @param config a user-supplied config
11987
+ * @param typeChecker a TypeScript type checker instance
11988
+ * @param diagnostics an array of diagnostics for surfacing errors and warnings
11989
+ * @param cmpNode a TypeScript class declaration node corresponding to a
11990
+ * Stencil component
11991
+ * @param newMembers an out param to hold newly generated class members
11992
+ * @param componentDecorator the TypeScript decorator node for the `@Component`
11993
+ * decorator
11994
+ */
11995
+ const componentDecoratorToStatic = (config, typeChecker, diagnostics, cmpNode, newMembers, componentDecorator) => {
11996
+ const [componentOptions] = getDecoratorParameters(componentDecorator, typeChecker, diagnostics);
11997
+ if (!componentOptions) return;
11998
+ if (!checkForDeprecatedApi(diagnostics, componentOptions, componentDecorator)) return;
11999
+ if (!validateComponent(config, diagnostics, typeChecker, componentOptions, cmpNode, componentDecorator)) return;
12000
+ newMembers.push(createStaticGetter("is", convertValueToLiteral(componentOptions.tag.trim())));
12001
+ if (componentOptions.encapsulation) {
12002
+ const enc = componentOptions.encapsulation;
12003
+ if (enc.type === "shadow") {
12004
+ newMembers.push(createStaticGetter("encapsulation", convertValueToLiteral("shadow")));
12005
+ if (enc.mode === "closed") newMembers.push(createStaticGetter("shadowMode", convertValueToLiteral("closed")));
12006
+ if (enc.delegatesFocus === true) newMembers.push(createStaticGetter("delegatesFocus", convertValueToLiteral(true)));
12007
+ if (enc.slotAssignment === "manual") newMembers.push(createStaticGetter("slotAssignment", convertValueToLiteral("manual")));
12008
+ } else if (enc.type === "scoped") {
12009
+ newMembers.push(createStaticGetter("encapsulation", convertValueToLiteral("scoped")));
12010
+ if (enc.patches && enc.patches.length > 0) newMembers.push(createStaticGetter("patches", convertValueToLiteral(enc.patches)));
12011
+ } else if (enc.type === "none") {
12012
+ if (enc.patches && enc.patches.length > 0) newMembers.push(createStaticGetter("patches", convertValueToLiteral(enc.patches)));
12013
+ }
12014
+ }
12015
+ styleToStatic(newMembers, componentOptions);
12016
+ const assetsDirs = componentOptions.assetsDirs || [];
12017
+ if (assetsDirs.length > 0) newMembers.push(createStaticGetter("assetsDirs", convertValueToLiteral(assetsDirs)));
12018
+ };
12019
+ /**
12020
+ * Check for usage of deprecated API properties and emit helpful error messages.
12021
+ * Returns false if deprecated API is detected (halts compilation).
12022
+ * Only shows detailed error once per build to avoid flooding the console.
12023
+ *
12024
+ * @param diagnostics an array of diagnostics for surfacing errors
12025
+ * @param componentOptions the options passed to the `@Component` decorator
12026
+ * @param componentDecorator the TypeScript decorator node
12027
+ * @returns whether the component uses only the new API (true = valid)
12028
+ */
12029
+ const checkForDeprecatedApi = (diagnostics, componentOptions, componentDecorator) => {
12030
+ const deprecatedProps = [];
12031
+ if (componentOptions.shadow !== void 0) deprecatedProps.push("shadow");
12032
+ if (componentOptions.scoped !== void 0) deprecatedProps.push("scoped");
12033
+ if (componentOptions.formAssociated !== void 0) deprecatedProps.push("formAssociated");
12034
+ if (deprecatedProps.length > 0) {
12035
+ if (!hasShownDeprecatedApiError) {
12036
+ hasShownDeprecatedApiError = true;
12037
+ const err = buildError(diagnostics);
12038
+ err.messageText = `@Component() uses deprecated API removed in Stencil v5.
12039
+
12040
+ The "shadow", "scoped", and "formAssociated" properties have been replaced:
12041
+ • shadow: true → encapsulation: { type: "shadow" }
12042
+ • scoped: true → encapsulation: { type: "scoped" }
12043
+ • formAssociated: true → Use @AttachInternals() decorator
12044
+
12045
+ Run 'npx stencil migrate --dry-run' to see all affected files.
12046
+ Run 'npx stencil migrate' to automatically update your components.`;
12047
+ augmentDiagnosticWithNode(err, findTagNode(deprecatedProps[0], componentDecorator));
12048
+ }
12049
+ return false;
12050
+ }
12051
+ return true;
12052
+ };
12053
+ /**
12054
+ * Perform validation on a Stencil component in preparation for some
12055
+ * component-level code generation, checking that the class declaration node
12056
+ * itself doesn't have any problems and that the options passed to the
12057
+ * `@Component` decorator are valid.
12058
+ *
12059
+ * @param config a user-supplied config
12060
+ * @param diagnostics an array of diagnostics for surfacing errors and warnings
12061
+ * @param typeChecker a TypeScript type checker instance
12062
+ * @param componentOptions the options passed to the `@Component` director
12063
+ * @param cmpNode a TypeScript class declaration node corresponding to a
12064
+ * Stencil component
12065
+ * @param componentDecorator the TypeScript decorator node for the `@Component`
12066
+ * decorator
12067
+ * @returns whether or not the component is valid
12068
+ */
12069
+ const validateComponent = (config, diagnostics, typeChecker, componentOptions, cmpNode, componentDecorator) => {
12070
+ if (componentOptions.encapsulation) {
12071
+ const enc = componentOptions.encapsulation;
12072
+ if (enc.type === "shadow") {
12073
+ if (enc.slotAssignment && enc.slotAssignment !== "manual" && enc.slotAssignment !== "named") {
12074
+ const err = buildError(diagnostics);
12075
+ err.messageText = `The "slotAssignment" option must be either "manual" or "named".`;
12076
+ augmentDiagnosticWithNode(err, findTagNode("slotAssignment", componentDecorator));
12077
+ return false;
12078
+ }
12079
+ if (enc.mode && enc.mode !== "open" && enc.mode !== "closed") {
12080
+ const err = buildError(diagnostics);
12081
+ err.messageText = `The "mode" option must be either "open" or "closed".`;
12082
+ augmentDiagnosticWithNode(err, findTagNode("mode", componentDecorator));
12083
+ return false;
12084
+ }
12085
+ }
12086
+ if ((enc.type === "none" || enc.type === "scoped") && enc.patches) {
12087
+ const validPatches = [
12088
+ "all",
12089
+ "children",
12090
+ "clone",
12091
+ "insert"
12092
+ ];
12093
+ for (const patch of enc.patches) if (!validPatches.includes(patch)) {
12094
+ const err = buildError(diagnostics);
12095
+ err.messageText = `Invalid patch "${patch}". Valid patches are: ${validPatches.join(", ")}.`;
12096
+ augmentDiagnosticWithNode(err, findTagNode("patches", componentDecorator));
12097
+ return false;
12098
+ }
12099
+ }
12100
+ }
12101
+ const constructor = cmpNode.members.find(ts.isConstructorDeclaration);
12102
+ if (constructor && constructor.parameters.length > 0) {
12103
+ const err = buildError(diagnostics);
12104
+ err.messageText = `Classes decorated with @Component can not have a "constructor" that takes arguments.
12105
+ All data required by a component must be passed by using class properties decorated with @Prop()`;
12106
+ augmentDiagnosticWithNode(err, constructor.parameters[0]);
12107
+ return false;
12108
+ }
12109
+ const otherDecorator = retrieveTsDecorators(cmpNode)?.find((d) => d !== componentDecorator);
12110
+ if (otherDecorator) {
12111
+ const err = buildError(diagnostics);
12112
+ err.messageText = `Classes decorated with @Component can not be decorated with more decorators.
12113
+ Stencil performs extensive static analysis on top of your components in order to generate the necessary metadata, runtime decorators at the components level make this task very hard.`;
12114
+ augmentDiagnosticWithNode(err, otherDecorator);
12115
+ return false;
12116
+ }
12117
+ const tag = componentOptions.tag;
12118
+ if (typeof tag !== "string" || tag.trim().length === 0) {
12119
+ const err = buildError(diagnostics);
12120
+ err.messageText = `tag missing in component decorator`;
12121
+ augmentDiagnosticWithNode(err, componentDecorator);
12122
+ return false;
12123
+ }
12124
+ const tagError = validateComponentTag(tag);
12125
+ if (tagError) {
12126
+ const err = buildError(diagnostics);
12127
+ err.messageText = `${tagError}. Please refer to https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name for more info.`;
12128
+ augmentDiagnosticWithNode(err, findTagNode("tag", componentDecorator));
12129
+ return false;
12130
+ }
12131
+ if (!config._isTesting) {
12132
+ const nonTypeExports = typeChecker.getExportsOfModule(typeChecker.getSymbolAtLocation(cmpNode.getSourceFile())).filter((symbol) => (symbol.flags & (ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Enum)) === 0).filter((symbol) => symbol.name !== cmpNode.name.text);
12133
+ nonTypeExports.forEach((symbol) => {
12134
+ const err = buildError(diagnostics);
12135
+ err.messageText = `To allow efficient bundling, modules using @Component() can only have a single export which is the component class itself.
12136
+ Any other exports should be moved to a separate file.
12137
+ For further information check out: https://stenciljs.com/docs/module-bundling`;
12138
+ augmentDiagnosticWithNode(err, symbol.valueDeclaration ? symbol.valueDeclaration : symbol.declarations[0]);
12139
+ });
12140
+ if (nonTypeExports.length > 0) return false;
12141
+ }
12142
+ return true;
12143
+ };
12144
+ /**
12145
+ * Given a TypeScript Decorator node, try to find a property with a given name
12146
+ * on an object possibly passed to it as an argument. If found, return the node
12147
+ * to initialize the value, and if no such property is found return the
12148
+ * decorator instead.
12149
+ *
12150
+ * @param propName the name of the argument to search for
12151
+ * @param node the decorator node to search within
12152
+ * @returns the initializer for the property (if found) or the decorator
12153
+ */
12154
+ const findTagNode = (propName, node) => {
12155
+ let out = node;
12156
+ if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {
12157
+ const arg = node.expression.arguments[0];
12158
+ if (ts.isObjectLiteralExpression(arg)) arg.properties.forEach((prop) => {
12159
+ if (ts.isPropertyAssignment(prop) && prop.name.getText() === propName) out = prop.initializer;
12160
+ });
12161
+ }
12162
+ return out;
12163
+ };
12164
+ //#endregion
12165
+ //#region src/compiler/entries/resolve-component-dependencies.ts
12166
+ /**
12167
+ * For each entry in the provided collection of compiler metadata, generate several lists:
12168
+ * - dependencies that the component has (both directly and indirectly/transitively)
12169
+ * - dependencies that the component has (only directly)
12170
+ * - components that are dependent on a particular component (both directly and indirectly/transitively)
12171
+ * - components that are dependent on a particular component (only directly)
12172
+ *
12173
+ * This information is stored directly on each entry in the provided collection
12174
+ *
12175
+ * @param cmps the compiler metadata of the components whose dependencies and dependents ought to be calculated
12176
+ */
12177
+ function resolveComponentDependencies(cmps) {
12178
+ computeDependencies(cmps);
12179
+ computeDependents(cmps);
12180
+ }
12181
+ /**
12182
+ * Compute the direct and transitive dependencies for each entry in the provided collection of component metadata.
12183
+ *
12184
+ * This function mutates each entry in the provided collection.
12185
+ *
12186
+ * @param cmps the metadata for the components whose dependencies ought to be calculated.
12187
+ */
12188
+ function computeDependencies(cmps) {
12189
+ const visited = /* @__PURE__ */ new Set();
12190
+ cmps.forEach((cmp) => {
12191
+ resolveTransitiveDependencies(cmp, cmps, visited);
12192
+ cmp.dependencies = unique(cmp.dependencies).sort();
12193
+ });
12194
+ }
12195
+ /**
12196
+ * Compute the direct and transitive dependents for each entry in the provided collection of component metadata.
12197
+ *
12198
+ * @param cmps the component metadata whose entries will have their dependents calculated
12199
+ */
12200
+ function computeDependents(cmps) {
12201
+ cmps.forEach((cmp) => {
12202
+ resolveTransitiveDependents(cmp, cmps);
12203
+ });
12204
+ }
12205
+ /**
12206
+ * Calculate the direct and transitive dependencies of a particular component.
12207
+ *
12208
+ * For example, given a component `foo-bar` whose `render` function references another web component `baz-buzz`:
12209
+ * ```tsx
12325
12210
  * // foo-bar.ts
12326
12211
  * render() {
12327
12212
  * return <baz-buzz></baz-buzz>;
@@ -12512,186 +12397,48 @@ function isJSXElWithAttrs(node) {
12512
12397
  }
12513
12398
  /**
12514
12399
  * Given a JSX syntax tree node update it to include a unique key attribute.
12515
- * This will respect any attributes already set on the node, including a
12516
- * pre-existing, user-defined `key` attribute.
12517
- *
12518
- * @param jsxElement a typescript JSX syntax tree node
12519
- * @returns an updated JSX element, with a key added.
12520
- */
12521
- function addKeyAttr(jsxElement) {
12522
- if (jsxElement.attributes.properties.some(isKeyAttr)) return jsxElement;
12523
- const updatedAttributes = ts.factory.createJsxAttributes([ts.factory.createJsxAttribute(ts.factory.createIdentifier("key"), ts.factory.createStringLiteral(deriveJSXKey(jsxElement))), ...jsxElement.attributes.properties]);
12524
- if (ts.isJsxOpeningElement(jsxElement)) return ts.factory.updateJsxOpeningElement(jsxElement, jsxElement.tagName, jsxElement.typeArguments, updatedAttributes);
12525
- else return ts.factory.updateJsxSelfClosingElement(jsxElement, jsxElement.tagName, jsxElement.typeArguments, updatedAttributes);
12526
- }
12527
- /**
12528
- * Check whether or not a JSX attribute node (well, technically a
12529
- * {@link ts.JsxAttributeLike} node) has the name `"key"` or not
12530
- *
12531
- * @param attr the JSX attribute node to check
12532
- * @returns whether or not this node has the name 'key'
12533
- */
12534
- function isKeyAttr(attr) {
12535
- return !!attr.name && attrNameToString(attr) === "key";
12536
- }
12537
- /**
12538
- * Given a JSX attribute get its name as a string
12539
- *
12540
- * @param attr the attribute of interest
12541
- * @returns the attribute's name, formatted as a string
12542
- */
12543
- function attrNameToString(attr) {
12544
- switch (attr.name?.kind) {
12545
- case ts.SyntaxKind.Identifier:
12546
- case ts.SyntaxKind.PrivateIdentifier:
12547
- case ts.SyntaxKind.StringLiteral:
12548
- case ts.SyntaxKind.NumericLiteral: return attr.name.text;
12549
- case ts.SyntaxKind.JsxNamespacedName: return attr.name.getText();
12550
- case ts.SyntaxKind.ComputedPropertyName:
12551
- const expression = attr.name.expression;
12552
- if (ts.isStringLiteral(expression) || ts.isNumericLiteral(expression)) return expression.text;
12553
- return "";
12554
- default: return "";
12555
- }
12556
- }
12557
- //#endregion
12558
- //#region src/compiler/transformers/decorators-to-static/decorator-utils.ts
12559
- const getDecoratorParameters = (decorator, typeChecker, diagnostics) => {
12560
- if (!ts.isCallExpression(decorator.expression)) return [];
12561
- return decorator.expression.arguments.map((arg) => getDecoratorParameter(arg, typeChecker, diagnostics, decorator.expression));
12562
- };
12563
- const getDecoratorParameter = (arg, typeChecker, diagnostics, errorNode) => {
12564
- if (ts.isCallExpression(arg)) {
12565
- const expression = arg.expression;
12566
- if (ts.isIdentifier(expression) && expression.text === "resolveVar" || ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.name) && expression.name.text === "resolveVar") {
12567
- if (arg.arguments.length !== 1) {
12568
- const err = buildError(diagnostics);
12569
- err.messageText = "resolveVar() expects exactly one argument.";
12570
- if (errorNode) augmentDiagnosticWithNode(err, errorNode);
12571
- throw new Error(err.messageText);
12572
- }
12573
- const resolveArg = arg.arguments[0];
12574
- return resolveVariableValue(resolveArg, typeChecker, diagnostics, resolveArg);
12575
- }
12576
- }
12577
- if (ts.isObjectLiteralExpression(arg)) return objectLiteralToObjectMap(arg, typeChecker, diagnostics, errorNode);
12578
- else if (ts.isStringLiteral(arg)) return arg.text;
12579
- else if (ts.isPropertyAccessExpression(arg) || ts.isIdentifier(arg)) {
12580
- const type = typeChecker.getTypeAtLocation(arg);
12581
- if (type !== void 0 && type.isLiteral())
12582
- /**
12583
- * Using enums or variables require us to resolve the value for
12584
- * the computed property/identifier via the TS type checker. As long
12585
- * as the type resolves to a literal, we can grab its value to be used
12586
- * as the `@Watch()` decorator argument.
12587
- */
12588
- return type.value;
12589
- }
12590
- throw new Error(`invalid decorator argument: ${arg.getText()}`);
12591
- };
12592
- /**
12593
- * Resolves a variable or object property to its string literal value at compile time.
12594
- * Supports const variables and object properties with string literal values.
12595
- * @param node - the expression to resolve
12596
- * @param typeChecker - the TypeScript type checker
12597
- * @param diagnostics - optional diagnostics array for error reporting
12598
- * @param errorNode - optional node for error location
12599
- * @returns the resolved string value
12600
- */
12601
- const resolveVariableValue = (node, typeChecker, diagnostics, errorNode) => {
12602
- if (ts.isIdentifier(node)) {
12603
- const symbol = typeChecker.getSymbolAtLocation(node);
12604
- if (!symbol || !symbol.valueDeclaration) {
12605
- const err = buildError(diagnostics);
12606
- err.messageText = `resolveVar() cannot resolve the value of "${node.text}" at compile time. Only const variables and object properties with string literal values are supported.`;
12607
- if (errorNode) augmentDiagnosticWithNode(err, errorNode);
12608
- throw new Error(err.messageText);
12609
- }
12610
- const declaration = symbol.valueDeclaration;
12611
- if (ts.isVariableDeclaration(declaration)) {
12612
- const type = typeChecker.getTypeAtLocation(node);
12613
- if (type && type.isLiteral() && typeof type.value === "string") return type.value;
12614
- if (declaration.initializer) {
12615
- const initializerValue = extractStringFromExpression(declaration.initializer, typeChecker);
12616
- if (initializerValue !== null) return initializerValue;
12617
- }
12618
- }
12619
- const err = buildError(diagnostics);
12620
- err.messageText = `resolveVar() cannot resolve the value of "${node.text}" at compile time. Only const variables and object properties with string literal values are supported.`;
12621
- if (errorNode) augmentDiagnosticWithNode(err, errorNode);
12622
- throw new Error(err.messageText);
12623
- }
12624
- if (ts.isPropertyAccessExpression(node)) {
12625
- const objectType = typeChecker.getTypeAtLocation(node.expression);
12626
- if (!objectType) {
12627
- const err = buildError(diagnostics);
12628
- err.messageText = `resolveVar() cannot resolve the object type for "${node.getText()}" at compile time.`;
12629
- if (errorNode) augmentDiagnosticWithNode(err, errorNode);
12630
- throw new Error(err.messageText);
12631
- }
12632
- const propertyName = node.name.text;
12633
- const property = typeChecker.getPropertyOfType(objectType, propertyName);
12634
- if (!property) {
12635
- const err = buildError(diagnostics);
12636
- err.messageText = `resolveVar() cannot find property "${propertyName}" on object "${node.expression.getText()}" at compile time.`;
12637
- if (errorNode) augmentDiagnosticWithNode(err, errorNode);
12638
- throw new Error(err.messageText);
12639
- }
12640
- const propertyType = typeChecker.getTypeOfSymbolAtLocation(property, node);
12641
- if (propertyType && propertyType.isLiteral() && typeof propertyType.value === "string") return propertyType.value;
12642
- if (property.valueDeclaration) {
12643
- if (ts.isPropertyDeclaration(property.valueDeclaration)) {
12644
- const initializer = property.valueDeclaration.initializer;
12645
- if (initializer) {
12646
- const value = extractStringFromExpression(initializer, typeChecker);
12647
- if (value !== null) return value;
12648
- }
12649
- } else if (ts.isPropertySignature(property.valueDeclaration)) {} else if (ts.isVariableDeclaration(property.valueDeclaration)) {
12650
- const initializer = property.valueDeclaration.initializer;
12651
- if (initializer) {
12652
- const value = extractStringFromExpression(initializer, typeChecker);
12653
- if (value !== null) return value;
12654
- }
12655
- }
12656
- }
12657
- const err = buildError(diagnostics);
12658
- err.messageText = `resolveVar() cannot resolve the value of "${node.getText()}" at compile time. Only const variables and object properties with string literal values are supported.`;
12659
- if (errorNode) augmentDiagnosticWithNode(err, errorNode);
12660
- throw new Error(err.messageText);
12661
- }
12662
- const err = buildError(diagnostics);
12663
- err.messageText = `resolveVar() can only be used with const variables or object properties. "${node.getText()}" is not supported.`;
12664
- if (errorNode) augmentDiagnosticWithNode(err, errorNode);
12665
- throw new Error(err.messageText);
12666
- };
12400
+ * This will respect any attributes already set on the node, including a
12401
+ * pre-existing, user-defined `key` attribute.
12402
+ *
12403
+ * @param jsxElement a typescript JSX syntax tree node
12404
+ * @returns an updated JSX element, with a key added.
12405
+ */
12406
+ function addKeyAttr(jsxElement) {
12407
+ if (jsxElement.attributes.properties.some(isKeyAttr)) return jsxElement;
12408
+ const updatedAttributes = ts.factory.createJsxAttributes([ts.factory.createJsxAttribute(ts.factory.createIdentifier("key"), ts.factory.createStringLiteral(deriveJSXKey(jsxElement))), ...jsxElement.attributes.properties]);
12409
+ if (ts.isJsxOpeningElement(jsxElement)) return ts.factory.updateJsxOpeningElement(jsxElement, jsxElement.tagName, jsxElement.typeArguments, updatedAttributes);
12410
+ else return ts.factory.updateJsxSelfClosingElement(jsxElement, jsxElement.tagName, jsxElement.typeArguments, updatedAttributes);
12411
+ }
12667
12412
  /**
12668
- * Extracts a string value from a TypeScript expression.
12669
- * Returns null if the expression doesn't represent a string literal.
12670
- * @param expr - the expression to extract from
12671
- * @param typeChecker - the TypeScript type checker
12672
- * @returns the extracted string value or null
12413
+ * Check whether or not a JSX attribute node (well, technically a
12414
+ * {@link ts.JsxAttributeLike} node) has the name `"key"` or not
12415
+ *
12416
+ * @param attr the JSX attribute node to check
12417
+ * @returns whether or not this node has the name 'key'
12673
12418
  */
12674
- const extractStringFromExpression = (expr, typeChecker) => {
12675
- if (ts.isStringLiteral(expr)) return expr.text;
12676
- if (ts.isNoSubstitutionTemplateLiteral(expr)) return expr.text;
12677
- const type = typeChecker.getTypeAtLocation(expr);
12678
- if (type && type.isLiteral() && typeof type.value === "string") return type.value;
12679
- return null;
12680
- };
12419
+ function isKeyAttr(attr) {
12420
+ return !!attr.name && attrNameToString(attr) === "key";
12421
+ }
12681
12422
  /**
12682
- * Returns a function that checks if a decorator:
12683
- * - is a call expression. these are decorators that are immediately followed by open/close parenthesis with optional
12684
- * arg(s), e.g. `@Prop()`
12685
- * - the name of the decorator matches the provided `propName`
12423
+ * Given a JSX attribute get its name as a string
12686
12424
  *
12687
- * @param propName the name of the decorator to match against
12688
- * @returns true if the conditions above are both true, false otherwise
12425
+ * @param attr the attribute of interest
12426
+ * @returns the attribute's name, formatted as a string
12689
12427
  */
12690
- const isDecoratorNamed = (propName) => {
12691
- return (dec) => {
12692
- return ts.isCallExpression(dec.expression) && dec.expression.expression.getText() === propName;
12693
- };
12694
- };
12428
+ function attrNameToString(attr) {
12429
+ switch (attr.name?.kind) {
12430
+ case ts.SyntaxKind.Identifier:
12431
+ case ts.SyntaxKind.PrivateIdentifier:
12432
+ case ts.SyntaxKind.StringLiteral:
12433
+ case ts.SyntaxKind.NumericLiteral: return attr.name.text;
12434
+ case ts.SyntaxKind.JsxNamespacedName: return attr.name.getText();
12435
+ case ts.SyntaxKind.ComputedPropertyName:
12436
+ const expression = attr.name.expression;
12437
+ if (ts.isStringLiteral(expression) || ts.isNumericLiteral(expression)) return expression.text;
12438
+ return "";
12439
+ default: return "";
12440
+ }
12441
+ }
12695
12442
  //#endregion
12696
12443
  //#region src/compiler/transformers/decorators-to-static/attach-internals.ts
12697
12444
  /**
@@ -12733,236 +12480,69 @@ const attachInternalsDecoratorsToStatic = (diagnostics, decoratedMembers, newMem
12733
12480
  const { staticName: name } = tsPropDeclName(decoratedProp, typeChecker);
12734
12481
  const decorator = retrieveTsDecorators(decoratedProp)?.find(isDecoratorNamed(decoratorName));
12735
12482
  const customStates = parseCustomStatesFromDecorator(decorator, typeChecker);
12483
+ const formAssociated = parseFormAssociatedFromDecorator(decorator);
12736
12484
  newMembers.push(createStaticGetter("attachInternalsMemberName", convertValueToLiteral(name)));
12737
12485
  if (customStates.length > 0) newMembers.push(createStaticGetter("attachInternalsCustomStates", convertValueToLiteral(customStates)));
12486
+ if (formAssociated) newMembers.push(createStaticGetter("formAssociated", convertValueToLiteral(true)));
12738
12487
  };
12739
12488
  /**
12740
- * Parse custom states from the decorator AST, including JSDoc comments.
12741
- *
12742
- * Supports JSDoc comments on state properties:
12743
- * ```ts
12744
- * @AttachInternals({
12745
- * states: {
12746
- * hovered: false,
12747
- * /&#42;&#42; Whether is currently active &#42;/
12748
- * active: true
12749
- * }
12750
- * })
12751
- * ```
12489
+ * Parse the formAssociated option from the decorator.
12490
+ * Returns true (form-associated) unless explicitly set to false.
12752
12491
  *
12753
12492
  * @param decorator the decorator node to parse
12754
- * @param typeChecker a TypeScript typechecker for resolving symbols
12755
- * @returns array of custom state metadata with docs
12493
+ * @returns whether the component should be form-associated
12756
12494
  */
12757
- function parseCustomStatesFromDecorator(decorator, typeChecker) {
12758
- if (!decorator || !ts.isCallExpression(decorator.expression)) return [];
12495
+ function parseFormAssociatedFromDecorator(decorator) {
12496
+ if (!decorator || !ts.isCallExpression(decorator.expression)) return true;
12759
12497
  const [firstArg] = decorator.expression.arguments;
12760
- if (!firstArg || !ts.isObjectLiteralExpression(firstArg)) return [];
12761
- const statesProp = firstArg.properties.find((prop) => ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === "states");
12762
- if (!statesProp || !ts.isObjectLiteralExpression(statesProp.initializer)) return [];
12763
- const customStates = [];
12764
- for (const prop of statesProp.initializer.properties) {
12765
- if (!ts.isPropertyAssignment(prop)) continue;
12766
- const stateName = ts.isIdentifier(prop.name) ? prop.name.text : ts.isStringLiteral(prop.name) ? prop.name.text : null;
12767
- if (!stateName) continue;
12768
- let initialValue = false;
12769
- if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) initialValue = true;
12770
- else if (prop.initializer.kind === ts.SyntaxKind.FalseKeyword) initialValue = false;
12771
- const symbol = typeChecker.getSymbolAtLocation(prop.name);
12772
- const docs = symbol ? ts.displayPartsToString(symbol.getDocumentationComment(typeChecker)) : "";
12773
- customStates.push({
12774
- name: stateName,
12775
- initialValue,
12776
- docs
12777
- });
12778
- }
12779
- return customStates;
12498
+ if (!firstArg || !ts.isObjectLiteralExpression(firstArg)) return true;
12499
+ const formAssociatedProp = firstArg.properties.find((prop) => ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === "formAssociated");
12500
+ if (!formAssociatedProp) return true;
12501
+ if (formAssociatedProp.initializer.kind === ts.SyntaxKind.FalseKeyword) return false;
12502
+ return true;
12780
12503
  }
12781
- //#endregion
12782
- //#region src/compiler/transformers/decorators-to-static/style-to-static.ts
12783
- const styleToStatic = (newMembers, componentOptions) => {
12784
- const defaultModeStyles = [];
12785
- if (componentOptions.styleUrls) if (Array.isArray(componentOptions.styleUrls)) defaultModeStyles.push(...normalizeStyleUrl(componentOptions.styleUrls));
12786
- else defaultModeStyles.push(...normalizeStyleUrl(componentOptions.styleUrls["$"]));
12787
- if (componentOptions.styleUrl) defaultModeStyles.push(...normalizeStyleUrl(componentOptions.styleUrl));
12788
- let styleUrls = {};
12789
- if (componentOptions.styleUrls && !Array.isArray(componentOptions.styleUrls)) styleUrls = normalizeStyleUrls(componentOptions.styleUrls);
12790
- if (defaultModeStyles.length > 0) styleUrls["$"] = defaultModeStyles;
12791
- if (Object.keys(styleUrls).length > 0) {
12792
- const originalStyleUrls = convertValueToLiteral(styleUrls);
12793
- newMembers.push(createStaticGetter("originalStyleUrls", originalStyleUrls));
12794
- const normalizedStyleExp = convertValueToLiteral(normalizeExtension(styleUrls));
12795
- newMembers.push(createStaticGetter("styleUrls", normalizedStyleExp));
12796
- }
12797
- if (typeof componentOptions.styles === "string") {
12798
- const styles = componentOptions.styles.trim();
12799
- if (styles.length > 0) newMembers.push(createStaticGetter("styles", ts.factory.createStringLiteral(styles)));
12800
- } else if (componentOptions.styles) {
12801
- const convertIdentifier = componentOptions.styles;
12802
- if (convertIdentifier.__identifier) {
12803
- const stylesIdentifier = convertIdentifier.__escapedText;
12804
- newMembers.push(createStaticGetter("styles", ts.factory.createIdentifier(stylesIdentifier)));
12805
- } else if (typeof convertIdentifier === "object") {
12806
- if (Object.keys(convertIdentifier).length > 0) newMembers.push(createStaticGetter("styles", convertValueToLiteral(convertIdentifier)));
12807
- }
12808
- }
12809
- };
12810
- const normalizeExtension = (styleUrls) => {
12811
- const compilerStyleUrls = {};
12812
- Object.keys(styleUrls).forEach((key) => {
12813
- compilerStyleUrls[key] = styleUrls[key].map((s) => useCss(s));
12814
- });
12815
- return compilerStyleUrls;
12816
- };
12817
- const useCss = (stylePath) => {
12818
- return join$1(dirname$1(stylePath), basename$1(stylePath, extname(stylePath)) + ".css");
12819
- };
12820
- const normalizeStyleUrls = (styleUrls) => {
12821
- const compilerStyleUrls = {};
12822
- Object.keys(styleUrls).forEach((key) => {
12823
- compilerStyleUrls[key] = normalizeStyleUrl(styleUrls[key]);
12824
- });
12825
- return compilerStyleUrls;
12826
- };
12827
- const normalizeStyleUrl = (style) => {
12828
- if (Array.isArray(style)) return style;
12829
- if (style) return [style];
12830
- return [];
12831
- };
12832
- //#endregion
12833
- //#region src/compiler/transformers/decorators-to-static/component-decorator.ts
12834
- /**
12835
- * Perform code generation to create new class members for a Stencil component
12836
- * which will drive the runtime functionality specified by various options
12837
- * passed to the `@Component` decorator.
12838
- *
12839
- * Inputs are validated (@see {@link validateComponent}) before code generation
12840
- * is performed.
12841
- *
12842
- * **Note**: in this function and in functions that it calls the `newMembers`
12843
- * parameter is treated as an out parameter and mutated, with new class members
12844
- * added to it.
12845
- *
12846
- * @param config a user-supplied config
12847
- * @param typeChecker a TypeScript type checker instance
12848
- * @param diagnostics an array of diagnostics for surfacing errors and warnings
12849
- * @param cmpNode a TypeScript class declaration node corresponding to a
12850
- * Stencil component
12851
- * @param newMembers an out param to hold newly generated class members
12852
- * @param componentDecorator the TypeScript decorator node for the `@Component`
12853
- * decorator
12854
- */
12855
- const componentDecoratorToStatic = (config, typeChecker, diagnostics, cmpNode, newMembers, componentDecorator) => {
12856
- const [componentOptions] = getDecoratorParameters(componentDecorator, typeChecker, diagnostics);
12857
- if (!componentOptions) return;
12858
- if (!validateComponent(config, diagnostics, typeChecker, componentOptions, cmpNode, componentDecorator)) return;
12859
- newMembers.push(createStaticGetter("is", convertValueToLiteral(componentOptions.tag.trim())));
12860
- if (componentOptions.shadow) {
12861
- newMembers.push(createStaticGetter("encapsulation", convertValueToLiteral("shadow")));
12862
- if (typeof componentOptions.shadow !== "boolean") {
12863
- if (componentOptions.shadow.delegatesFocus === true) newMembers.push(createStaticGetter("delegatesFocus", convertValueToLiteral(true)));
12864
- if (componentOptions.shadow.slotAssignment === "manual") newMembers.push(createStaticGetter("slotAssignment", convertValueToLiteral("manual")));
12865
- }
12866
- } else if (componentOptions.scoped) newMembers.push(createStaticGetter("encapsulation", convertValueToLiteral("scoped")));
12867
- if (componentOptions.formAssociated === true) newMembers.push(createStaticGetter("formAssociated", convertValueToLiteral(true)));
12868
- styleToStatic(newMembers, componentOptions);
12869
- const assetsDirs = componentOptions.assetsDirs || [];
12870
- if (assetsDirs.length > 0) newMembers.push(createStaticGetter("assetsDirs", convertValueToLiteral(assetsDirs)));
12871
- };
12872
12504
  /**
12873
- * Perform validation on a Stencil component in preparation for some
12874
- * component-level code generation, checking that the class declaration node
12875
- * itself doesn't have any problems and that the options passed to the
12876
- * `@Component` decorator are valid.
12505
+ * Parse custom states from the decorator AST, including JSDoc comments.
12877
12506
  *
12878
- * @param config a user-supplied config
12879
- * @param diagnostics an array of diagnostics for surfacing errors and warnings
12880
- * @param typeChecker a TypeScript type checker instance
12881
- * @param componentOptions the options passed to the `@Component` director
12882
- * @param cmpNode a TypeScript class declaration node corresponding to a
12883
- * Stencil component
12884
- * @param componentDecorator the TypeScript decorator node for the `@Component`
12885
- * decorator
12886
- * @returns whether or not the component is valid
12887
- */
12888
- const validateComponent = (config, diagnostics, typeChecker, componentOptions, cmpNode, componentDecorator) => {
12889
- if (componentOptions.shadow && componentOptions.scoped) {
12890
- const err = buildError(diagnostics);
12891
- err.messageText = `Components cannot be "scoped" and "shadow" at the same time, they are mutually exclusive configurations.`;
12892
- augmentDiagnosticWithNode(err, findTagNode("scoped", componentDecorator));
12893
- return false;
12894
- }
12895
- if (typeof componentOptions.shadow === "object" && componentOptions.shadow.slotAssignment) {
12896
- if (componentOptions.shadow.slotAssignment !== "manual" && componentOptions.shadow.slotAssignment !== "named") {
12897
- const err = buildError(diagnostics);
12898
- err.messageText = `The "slotAssignment" option must be either "manual" or "named".`;
12899
- augmentDiagnosticWithNode(err, findTagNode("slotAssignment", componentDecorator));
12900
- return false;
12901
- }
12902
- }
12903
- const constructor = cmpNode.members.find(ts.isConstructorDeclaration);
12904
- if (constructor && constructor.parameters.length > 0) {
12905
- const err = buildError(diagnostics);
12906
- err.messageText = `Classes decorated with @Component can not have a "constructor" that takes arguments.
12907
- All data required by a component must be passed by using class properties decorated with @Prop()`;
12908
- augmentDiagnosticWithNode(err, constructor.parameters[0]);
12909
- return false;
12910
- }
12911
- const otherDecorator = retrieveTsDecorators(cmpNode)?.find((d) => d !== componentDecorator);
12912
- if (otherDecorator) {
12913
- const err = buildError(diagnostics);
12914
- err.messageText = `Classes decorated with @Component can not be decorated with more decorators.
12915
- Stencil performs extensive static analysis on top of your components in order to generate the necessary metadata, runtime decorators at the components level make this task very hard.`;
12916
- augmentDiagnosticWithNode(err, otherDecorator);
12917
- return false;
12918
- }
12919
- const tag = componentOptions.tag;
12920
- if (typeof tag !== "string" || tag.trim().length === 0) {
12921
- const err = buildError(diagnostics);
12922
- err.messageText = `tag missing in component decorator`;
12923
- augmentDiagnosticWithNode(err, componentDecorator);
12924
- return false;
12925
- }
12926
- const tagError = validateComponentTag(tag);
12927
- if (tagError) {
12928
- const err = buildError(diagnostics);
12929
- err.messageText = `${tagError}. Please refer to https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name for more info.`;
12930
- augmentDiagnosticWithNode(err, findTagNode("tag", componentDecorator));
12931
- return false;
12932
- }
12933
- if (!config._isTesting) {
12934
- const nonTypeExports = typeChecker.getExportsOfModule(typeChecker.getSymbolAtLocation(cmpNode.getSourceFile())).filter((symbol) => (symbol.flags & (ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Enum)) === 0).filter((symbol) => symbol.name !== cmpNode.name.text);
12935
- nonTypeExports.forEach((symbol) => {
12936
- const err = buildError(diagnostics);
12937
- err.messageText = `To allow efficient bundling, modules using @Component() can only have a single export which is the component class itself.
12938
- Any other exports should be moved to a separate file.
12939
- For further information check out: https://stenciljs.com/docs/module-bundling`;
12940
- augmentDiagnosticWithNode(err, symbol.valueDeclaration ? symbol.valueDeclaration : symbol.declarations[0]);
12941
- });
12942
- if (nonTypeExports.length > 0) return false;
12943
- }
12944
- return true;
12945
- };
12946
- /**
12947
- * Given a TypeScript Decorator node, try to find a property with a given name
12948
- * on an object possibly passed to it as an argument. If found, return the node
12949
- * to initialize the value, and if no such property is found return the
12950
- * decorator instead.
12507
+ * Supports JSDoc comments on state properties:
12508
+ * ```ts
12509
+ * @AttachInternals({
12510
+ * states: {
12511
+ * hovered: false,
12512
+ * /&#42;&#42; Whether is currently active &#42;/
12513
+ * active: true
12514
+ * }
12515
+ * })
12516
+ * ```
12951
12517
  *
12952
- * @param propName the name of the argument to search for
12953
- * @param node the decorator node to search within
12954
- * @returns the initializer for the property (if found) or the decorator
12518
+ * @param decorator the decorator node to parse
12519
+ * @param typeChecker a TypeScript typechecker for resolving symbols
12520
+ * @returns array of custom state metadata with docs
12955
12521
  */
12956
- const findTagNode = (propName, node) => {
12957
- let out = node;
12958
- if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {
12959
- const arg = node.expression.arguments[0];
12960
- if (ts.isObjectLiteralExpression(arg)) arg.properties.forEach((prop) => {
12961
- if (ts.isPropertyAssignment(prop) && prop.name.getText() === propName) out = prop.initializer;
12522
+ function parseCustomStatesFromDecorator(decorator, typeChecker) {
12523
+ if (!decorator || !ts.isCallExpression(decorator.expression)) return [];
12524
+ const [firstArg] = decorator.expression.arguments;
12525
+ if (!firstArg || !ts.isObjectLiteralExpression(firstArg)) return [];
12526
+ const statesProp = firstArg.properties.find((prop) => ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === "states");
12527
+ if (!statesProp || !ts.isObjectLiteralExpression(statesProp.initializer)) return [];
12528
+ const customStates = [];
12529
+ for (const prop of statesProp.initializer.properties) {
12530
+ if (!ts.isPropertyAssignment(prop)) continue;
12531
+ const stateName = ts.isIdentifier(prop.name) ? prop.name.text : ts.isStringLiteral(prop.name) ? prop.name.text : null;
12532
+ if (!stateName) continue;
12533
+ let initialValue = false;
12534
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) initialValue = true;
12535
+ else if (prop.initializer.kind === ts.SyntaxKind.FalseKeyword) initialValue = false;
12536
+ const symbol = typeChecker.getSymbolAtLocation(prop.name);
12537
+ const docs = symbol ? ts.displayPartsToString(symbol.getDocumentationComment(typeChecker)) : "";
12538
+ customStates.push({
12539
+ name: stateName,
12540
+ initialValue,
12541
+ docs
12962
12542
  });
12963
12543
  }
12964
- return out;
12965
- };
12544
+ return customStates;
12545
+ }
12966
12546
  //#endregion
12967
12547
  //#region src/compiler/transformers/decorators-to-static/decorators-constants.ts
12968
12548
  /**
@@ -14447,7 +14027,6 @@ const setComponentBuildConditionals = (cmpMeta) => {
14447
14027
  cmpMeta.hasListenerTargetWindow = cmpMeta.listeners.some((l) => l.target === "window");
14448
14028
  cmpMeta.hasListenerTargetDocument = cmpMeta.listeners.some((l) => l.target === "document");
14449
14029
  cmpMeta.hasListenerTargetBody = cmpMeta.listeners.some((l) => l.target === "body");
14450
- cmpMeta.hasListenerTargetParent = cmpMeta.listeners.some((l) => l.target === "parent");
14451
14030
  cmpMeta.hasListenerTarget = cmpMeta.listeners.some((l) => !!l.target);
14452
14031
  }
14453
14032
  cmpMeta.hasMember = cmpMeta.hasProp || cmpMeta.hasState || cmpMeta.hasElement || cmpMeta.hasMethod || cmpMeta.formAssociated;
@@ -14458,6 +14037,12 @@ const setComponentBuildConditionals = (cmpMeta) => {
14458
14037
  }
14459
14038
  cmpMeta.hasLifecycle = cmpMeta.hasComponentWillLoadFn || cmpMeta.hasComponentDidLoadFn || cmpMeta.hasComponentShouldUpdateFn || cmpMeta.hasComponentWillUpdateFn || cmpMeta.hasComponentDidUpdateFn || cmpMeta.hasComponentWillRenderFn || cmpMeta.hasComponentDidRenderFn;
14460
14039
  cmpMeta.isPlain = !cmpMeta.hasMember && !cmpMeta.hasStyle && !cmpMeta.hasLifecycle && !cmpMeta.hasListener && !cmpMeta.hasVdomRender;
14040
+ if (cmpMeta.patches) {
14041
+ cmpMeta.hasPatchAll = !!cmpMeta.patches.all;
14042
+ cmpMeta.hasPatchChildren = !!cmpMeta.patches.children;
14043
+ cmpMeta.hasPatchClone = !!cmpMeta.patches.clone;
14044
+ cmpMeta.hasPatchInsert = !!cmpMeta.patches.insert;
14045
+ }
14461
14046
  };
14462
14047
  //#endregion
14463
14048
  //#region src/compiler/transformers/detect-modern-prop-decls.ts
@@ -14532,6 +14117,181 @@ const parseAttachInternalsCustomStates = (staticMembers) => {
14532
14117
  }));
14533
14118
  return [];
14534
14119
  };
14120
+ const IS_CASE_SENSITIVE_FILE_NAMES = !(process.platform === "win32");
14121
+ //#endregion
14122
+ //#region src/compiler/sys/typescript/typescript-sys.ts
14123
+ const patchTsSystemFileSystem = (config, compilerSys, inMemoryFs, tsSys) => {
14124
+ const realpath = (path) => {
14125
+ const rp = compilerSys.realpathSync(path);
14126
+ if (isString$1(rp)) return rp;
14127
+ return path;
14128
+ };
14129
+ const getAccessibleFileSystemEntries = (path) => {
14130
+ try {
14131
+ const entries = compilerSys.readDirSync(path || ".").sort();
14132
+ const files = [];
14133
+ const directories = [];
14134
+ for (const absPath of entries) {
14135
+ const stat = inMemoryFs.statSync(absPath);
14136
+ if (!stat) continue;
14137
+ const entry = basename$1(absPath);
14138
+ if (stat.isFile) files.push(entry);
14139
+ else if (stat.isDirectory) directories.push(entry);
14140
+ }
14141
+ return {
14142
+ files,
14143
+ directories
14144
+ };
14145
+ } catch {
14146
+ return {
14147
+ files: [],
14148
+ directories: []
14149
+ };
14150
+ }
14151
+ };
14152
+ tsSys.createDirectory = (p) => {
14153
+ compilerSys.createDirSync(p, { recursive: true });
14154
+ };
14155
+ tsSys.directoryExists = (p) => {
14156
+ if (inMemoryFs) return inMemoryFs.statSync(p).isDirectory;
14157
+ else return compilerSys.statSync(p).isDirectory;
14158
+ };
14159
+ tsSys.exit = compilerSys.exit;
14160
+ tsSys.fileExists = (p) => {
14161
+ let filePath = p;
14162
+ if (isRemoteUrl(p)) filePath = getTypescriptPathFromUrl(config, tsSys.getExecutingFilePath(), p);
14163
+ if (inMemoryFs) {
14164
+ const s = inMemoryFs.statSync(filePath);
14165
+ return !!(s && s.isFile);
14166
+ } else {
14167
+ const s = compilerSys.statSync(filePath);
14168
+ return !!(s && s.isFile);
14169
+ }
14170
+ };
14171
+ tsSys.getCurrentDirectory = compilerSys.getCurrentDirectory;
14172
+ tsSys.getExecutingFilePath = () => {
14173
+ try {
14174
+ return __require.resolve("typescript");
14175
+ } catch {
14176
+ return compilerSys.getCompilerExecutingPath();
14177
+ }
14178
+ };
14179
+ tsSys.getDirectories = (p) => {
14180
+ return compilerSys.readDirSync(p).filter((itemPath) => {
14181
+ if (inMemoryFs) {
14182
+ const s = inMemoryFs.statSync(itemPath);
14183
+ return !!(s && s.exists && s.isDirectory);
14184
+ } else {
14185
+ const s = compilerSys.statSync(itemPath);
14186
+ return !!(s && s.isDirectory);
14187
+ }
14188
+ });
14189
+ };
14190
+ tsSys.readDirectory = (path, extensions, exclude, include, depth) => {
14191
+ const cwd = compilerSys.getCurrentDirectory();
14192
+ return ts.matchFiles(path, extensions, exclude, include, IS_CASE_SENSITIVE_FILE_NAMES, cwd, depth, getAccessibleFileSystemEntries, realpath);
14193
+ };
14194
+ tsSys.readFile = (filePath) => {
14195
+ return inMemoryFs ? inMemoryFs.readFileSync(filePath, { useCache: false }) : compilerSys.readFileSync(filePath);
14196
+ };
14197
+ tsSys.writeFile = (p, data) => inMemoryFs ? inMemoryFs.writeFile(p, data) : compilerSys.writeFile(p, data);
14198
+ return tsSys;
14199
+ };
14200
+ const patchTsSystemWatch = (compilerSystem, tsSys) => {
14201
+ tsSys.watchDirectory = (p, cb, recursive) => {
14202
+ const watcher = compilerSystem.watchDirectory(p, (filePath) => {
14203
+ cb(filePath);
14204
+ }, recursive);
14205
+ return { close() {
14206
+ watcher.close();
14207
+ } };
14208
+ };
14209
+ tsSys.watchFile = (p, cb) => {
14210
+ const watcher = compilerSystem.watchFile(p, (filePath, eventKind) => {
14211
+ if (eventKind === "fileAdd") cb(filePath, ts.FileWatcherEventKind.Created);
14212
+ else if (eventKind === "fileUpdate") cb(filePath, ts.FileWatcherEventKind.Changed);
14213
+ else if (eventKind === "fileDelete") cb(filePath, ts.FileWatcherEventKind.Deleted);
14214
+ });
14215
+ return { close() {
14216
+ watcher.close();
14217
+ } };
14218
+ };
14219
+ };
14220
+ const patchTypescript = (config, inMemoryFs) => {
14221
+ if (!ts.__patched) {
14222
+ patchTsSystemFileSystem(config, config.sys, inMemoryFs, ts.sys);
14223
+ patchTsSystemWatch(config.sys, ts.sys);
14224
+ ts.__patched = true;
14225
+ }
14226
+ };
14227
+ const patchTypeScriptSysMinimum = () => {
14228
+ if (!ts.sys) ts.sys = {
14229
+ args: [],
14230
+ createDirectory: noop,
14231
+ directoryExists: () => false,
14232
+ exit: noop,
14233
+ fileExists: () => false,
14234
+ getCurrentDirectory: process.cwd,
14235
+ getDirectories: () => [],
14236
+ getExecutingFilePath: () => "./",
14237
+ readDirectory: () => [],
14238
+ readFile: noop,
14239
+ newLine: "\n",
14240
+ resolvePath: resolve$1,
14241
+ useCaseSensitiveFileNames: false,
14242
+ write: noop,
14243
+ writeFile: noop
14244
+ };
14245
+ };
14246
+ patchTypeScriptSysMinimum();
14247
+ const getTypescriptPathFromUrl = (config, tsExecutingUrl, url) => {
14248
+ const tsBaseUrl = new URL("..", tsExecutingUrl).href;
14249
+ if (url.startsWith(tsBaseUrl)) {
14250
+ const tsFilePath = url.replace(tsBaseUrl, "/");
14251
+ return normalizePath(config.sys.getLocalModulePath({
14252
+ rootDir: config.rootDir,
14253
+ moduleId: "@stencil/core",
14254
+ path: tsFilePath
14255
+ }));
14256
+ }
14257
+ return url;
14258
+ };
14259
+ //#endregion
14260
+ //#region src/compiler/sys/typescript/typescript-resolve-module.ts
14261
+ const tsResolveModuleName = (config, compilerCtx, moduleName, containingFile) => {
14262
+ const resolveModuleName = ts.__resolveModuleName || ts.resolveModuleName;
14263
+ if (moduleName && resolveModuleName && config.tsCompilerOptions) {
14264
+ const host = patchTsSystemFileSystem(config, config.sys, compilerCtx.fs, ts.sys);
14265
+ const compilerOptions = { ...config.tsCompilerOptions };
14266
+ compilerOptions.resolveJsonModule = true;
14267
+ return resolveModuleName(moduleName, containingFile, compilerOptions, host);
14268
+ }
14269
+ return null;
14270
+ };
14271
+ const tsGetSourceFile = (config, module) => {
14272
+ if (!module || !module.resolvedModule) return null;
14273
+ const compilerOptions = { ...config.tsCompilerOptions };
14274
+ const host = ts.createCompilerHost(compilerOptions);
14275
+ return ts.createProgram([module.resolvedModule.resolvedFileName], compilerOptions, host).getSourceFile(module.resolvedModule.resolvedFileName);
14276
+ };
14277
+ const tsResolveModuleNamePackageJsonPath = (config, compilerCtx, moduleName, containingFile) => {
14278
+ try {
14279
+ const resolvedModule = tsResolveModuleName(config, compilerCtx, moduleName, containingFile);
14280
+ if (resolvedModule && resolvedModule.resolvedModule && resolvedModule.resolvedModule.resolvedFileName) {
14281
+ const rootDir = resolve$1("/");
14282
+ let resolvedFileName = resolvedModule.resolvedModule.resolvedFileName;
14283
+ for (let i = 0; i < 30; i++) {
14284
+ if (rootDir === resolvedFileName) return null;
14285
+ resolvedFileName = dirname$1(resolvedFileName);
14286
+ const pkgJsonPath = join$1(resolvedFileName, "package.json");
14287
+ if (config.sys.accessSync(pkgJsonPath)) return normalizePath(pkgJsonPath);
14288
+ }
14289
+ }
14290
+ } catch (e) {
14291
+ config.logger.error(e);
14292
+ }
14293
+ return null;
14294
+ };
14535
14295
  //#endregion
14536
14296
  //#region src/compiler/transformers/static-to-meta/events.ts
14537
14297
  const parseStaticEvents = (staticMembers) => {
@@ -15037,6 +14797,45 @@ const parseStaticSlotAssignment = (encapsulation, staticMembers) => {
15037
14797
  if (encapsulation === "shadow") return getStaticValue(staticMembers, "slotAssignment") === "manual" ? "manual" : null;
15038
14798
  return null;
15039
14799
  };
14800
+ /**
14801
+ * Find and return the shadow DOM mode for a component.
14802
+ *
14803
+ * @param encapsulation the encapsulation mode to use for a component
14804
+ * @param staticMembers a collection of static getters to search
14805
+ * @returns 'open' (default), 'closed' if explicitly set, or null if not shadow encapsulation
14806
+ */
14807
+ const parseStaticShadowMode = (encapsulation, staticMembers) => {
14808
+ if (encapsulation === "shadow") return getStaticValue(staticMembers, "shadowMode") === "closed" ? "closed" : "open";
14809
+ return null;
14810
+ };
14811
+ /**
14812
+ * Find and return the per-component patches for slot handling.
14813
+ *
14814
+ * @param encapsulation the encapsulation mode to use for a component
14815
+ * @param staticMembers a collection of static getters to search
14816
+ * @returns ComponentPatches object or null if no patches defined
14817
+ */
14818
+ const parseStaticPatches = (encapsulation, staticMembers) => {
14819
+ if (encapsulation === "shadow") return null;
14820
+ const patches = getStaticValue(staticMembers, "patches");
14821
+ if (!Array.isArray(patches) || patches.length === 0) return null;
14822
+ const result = {};
14823
+ for (const patch of patches) switch (patch) {
14824
+ case "all":
14825
+ result.all = true;
14826
+ break;
14827
+ case "children":
14828
+ result.children = true;
14829
+ break;
14830
+ case "clone":
14831
+ result.clone = true;
14832
+ break;
14833
+ case "insert":
14834
+ result.insert = true;
14835
+ break;
14836
+ }
14837
+ return Object.keys(result).length > 0 ? result : null;
14838
+ };
15040
14839
  //#endregion
15041
14840
  //#region src/compiler/transformers/static-to-meta/form-associated.ts
15042
14841
  /**
@@ -15193,7 +14992,9 @@ const parseStaticComponentMeta = (compilerCtx, typeChecker, cmpNode, moduleFile,
15193
14992
  elementRef: parseStaticElementRef(staticMembers),
15194
14993
  encapsulation,
15195
14994
  shadowDelegatesFocus: !!parseStaticShadowDelegatesFocus(encapsulation, staticMembers),
14995
+ shadowMode: parseStaticShadowMode(encapsulation, staticMembers),
15196
14996
  slotAssignment: parseStaticSlotAssignment(encapsulation, staticMembers),
14997
+ patches: parseStaticPatches(encapsulation, staticMembers),
15197
14998
  properties,
15198
14999
  virtualProperties: parseVirtualProps(docs),
15199
15000
  states,
@@ -15231,7 +15032,6 @@ const parseStaticComponentMeta = (compilerCtx, typeChecker, cmpNode, moduleFile,
15231
15032
  hasListenerTargetWindow: false,
15232
15033
  hasListenerTargetDocument: false,
15233
15034
  hasListenerTargetBody: false,
15234
- hasListenerTargetParent: false,
15235
15035
  hasMember: false,
15236
15036
  hasMethod: false,
15237
15037
  hasMode: false,
@@ -15269,7 +15069,11 @@ const parseStaticComponentMeta = (compilerCtx, typeChecker, cmpNode, moduleFile,
15269
15069
  dependents: [],
15270
15070
  dependencies: [],
15271
15071
  directDependents: [],
15272
- directDependencies: []
15072
+ directDependencies: [],
15073
+ hasPatchAll: false,
15074
+ hasPatchChildren: false,
15075
+ hasPatchClone: false,
15076
+ hasPatchInsert: false
15273
15077
  };
15274
15078
  const visitComponentChildNode = (node, ctx) => {
15275
15079
  validateComponentMembers(node, ctx);
@@ -15996,21 +15800,18 @@ function generateBuildStats(config, buildCtx) {
15996
15800
  minifyJs: !!config.minifyJs,
15997
15801
  minifyCss: !!config.minifyCss,
15998
15802
  hashFileNames: !!config.hashFileNames,
15999
- hashedFileNameLength: config.hashedFileNameLength,
16000
- buildEs5: !!config.buildEs5
15803
+ hashedFileNameLength: config.hashedFileNameLength
16001
15804
  },
16002
15805
  formats: {
16003
15806
  esmBrowser: sanitizeBundlesForStats(buildCtx.esmBrowserComponentBundle),
16004
15807
  esm: sanitizeBundlesForStats(buildCtx.esmComponentBundle),
16005
- es5: sanitizeBundlesForStats(buildCtx.es5ComponentBundle),
16006
- system: sanitizeBundlesForStats(buildCtx.systemComponentBundle),
16007
15808
  commonjs: sanitizeBundlesForStats(buildCtx.commonJsComponentBundle)
16008
15809
  },
16009
15810
  components: getComponentsFileMap(config, buildCtx),
16010
15811
  entries: buildCtx.entryModules,
16011
15812
  componentGraph: buildResults.componentGraph ?? {},
16012
15813
  sourceGraph: getSourceGraph(config, buildCtx),
16013
- rollupResults: buildCtx.rollupResults ?? { modules: [] },
15814
+ rolldownResults: buildCtx.rolldownResults ?? { modules: [] },
16014
15815
  collections: getCollections(config, buildCtx)
16015
15816
  });
16016
15817
  } catch (e) {
@@ -16046,8 +15847,8 @@ function sanitizeBundlesForStats(bundleArray) {
16046
15847
  components: bundle.cmps.map((c) => c.tagName),
16047
15848
  bundleId: bundle.output.bundleId,
16048
15849
  fileName: bundle.output.fileName,
16049
- imports: bundle.rollupResult.imports,
16050
- originalByteSize: byteSize(bundle.rollupResult.code)
15850
+ imports: bundle.rolldownResult.imports,
15851
+ originalByteSize: byteSize(bundle.rolldownResult.code)
16051
15852
  };
16052
15853
  });
16053
15854
  }
@@ -16640,6 +16441,7 @@ const writeBuild = async (config, compilerCtx, buildCtx) => {
16640
16441
  const build = async (config, compilerCtx, buildCtx, tsBuilder) => {
16641
16442
  try {
16642
16443
  process.chdir(config.rootDir);
16444
+ resetDeprecatedApiWarning();
16643
16445
  await emptyOutputTargets(config, compilerCtx, buildCtx);
16644
16446
  if (buildCtx.hasError) return buildAbort(buildCtx);
16645
16447
  if (config.srcIndexHtml) {
@@ -16774,12 +16576,12 @@ const compilerRequest = async (config, compilerCtx, data) => {
16774
16576
  const bundleDevModule = async (config, compilerCtx, parsedUrl, results) => {
16775
16577
  const buildCtx = new BuildContext(config, compilerCtx);
16776
16578
  try {
16777
- const inputOpts = getRollupOptions(config, compilerCtx, buildCtx, {
16579
+ const inputOpts = getRolldownOptions(config, compilerCtx, buildCtx, {
16778
16580
  id: parsedUrl.nodeModuleId,
16779
16581
  platform: "client",
16780
16582
  inputs: { index: parsedUrl.nodeResolvedPath }
16781
16583
  });
16782
- const rollupBuild = await rollup(inputOpts);
16584
+ const rolldownBuild = await rolldown(inputOpts);
16783
16585
  const outputOpts = {
16784
16586
  banner: generatePreamble(config),
16785
16587
  format: "es"
@@ -16789,7 +16591,7 @@ const bundleDevModule = async (config, compilerCtx, parsedUrl, results) => {
16789
16591
  outputOpts.intro = `/**\n * Dev Node Module: ${parsedUrl.nodeModuleId}, v${parsedUrl.nodeModuleVersion}\n * Entry: ${commentPath}\n * DEVELOPMENT PURPOSES ONLY!!\n */`;
16790
16592
  inputOpts.input = parsedUrl.nodeResolvedPath;
16791
16593
  }
16792
- const r = await rollupBuild.generate(outputOpts);
16594
+ const r = await rolldownBuild.generate(outputOpts);
16793
16595
  if (buildCtx.hasError) {
16794
16596
  results.status = 500;
16795
16597
  results.content = `console.error(${JSON.stringify(buildCtx.diagnostics)})`;
@@ -16982,6 +16784,7 @@ const isWatchIgnorePath = (config, path) => {
16982
16784
  * - No conflict with @parcel/watcher (no dual file watching)
16983
16785
  * - Explicit cache invalidation when files change
16984
16786
  * - Simpler control flow without setTimeout debouncing
16787
+ * - Persistent .tsbuildinfo file for faster cold builds
16985
16788
  *
16986
16789
  * The builder program is passed to runTsProgram which handles emit with
16987
16790
  * custom transformers.
@@ -17044,7 +16847,7 @@ function createCachingCompilerHost(options) {
17044
16847
  });
17045
16848
  }
17046
16849
  /**
17047
- * Incremental TypeScript compiler for watch mode.
16850
+ * Incremental TypeScript compiler for watch mode and cold builds.
17048
16851
  *
17049
16852
  * Usage:
17050
16853
  * 1. Create once at start: const compiler = new IncrementalCompiler(config)
@@ -17052,12 +16855,15 @@ function createCachingCompilerHost(options) {
17052
16855
  * 3. On file change:
17053
16856
  * - compiler.invalidateFiles([changedPaths])
17054
16857
  * - compiler.rebuild() // returns builder program with only changed files marked for emit
16858
+ *
16859
+ * On cold builds, reads existing .tsbuildinfo from disk to restore incremental state.
17055
16860
  */
17056
16861
  var IncrementalCompiler = class {
17057
16862
  builderProgram;
17058
16863
  host;
17059
16864
  rootNames;
17060
16865
  options;
16866
+ hasRestoredFromDisk = false;
17061
16867
  constructor(config) {
17062
16868
  const optionsToExtend = getTsOptionsToExtend(config);
17063
16869
  const configFile = ts.readConfigFile(config.tsconfig, ts.sys.readFile);
@@ -17078,11 +16884,21 @@ var IncrementalCompiler = class {
17078
16884
  * Rebuild the TypeScript program incrementally.
17079
16885
  * Returns the builder program which can be passed to runTsProgram for emit.
17080
16886
  *
17081
- * TypeScript detects which source files have changed (via sf.version property)
17082
- * and only re-emits those when emit() is called.
16887
+ * On first call (cold build), attempts to read existing .tsbuildinfo from disk
16888
+ * to restore incremental state. TypeScript will then only re-check and re-emit
16889
+ * files that have actually changed since the last build.
16890
+ *
17083
16891
  * @returns the builder program
17084
16892
  */
17085
16893
  rebuild() {
16894
+ if (!this.hasRestoredFromDisk && !this.builderProgram && this.options.incremental) {
16895
+ this.hasRestoredFromDisk = true;
16896
+ const oldProgram = ts.readBuilderProgram(this.options, this.host);
16897
+ if (oldProgram) {
16898
+ this.builderProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram(this.rootNames, this.options, this.host, oldProgram);
16899
+ return this.builderProgram;
16900
+ }
16901
+ }
17086
16902
  this.builderProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram(this.rootNames, this.options, this.host, this.builderProgram);
17087
16903
  return this.builderProgram;
17088
16904
  }
@@ -17101,11 +16917,12 @@ var IncrementalCompiler = class {
17101
16917
  return this.builderProgram?.getProgram();
17102
16918
  }
17103
16919
  /**
17104
- * Force a full rebuild by invalidating all caches
16920
+ * Force a full rebuild by invalidating all caches (including disk cache)
17105
16921
  */
17106
16922
  invalidateAll() {
17107
16923
  this.host.invalidateAll();
17108
16924
  this.builderProgram = void 0;
16925
+ this.hasRestoredFromDisk = false;
17109
16926
  }
17110
16927
  };
17111
16928
  //#endregion
@@ -18432,17 +18249,16 @@ const createWorkerMainContext = (workerCtrl) => ({
18432
18249
  });
18433
18250
  //#endregion
18434
18251
  //#region src/compiler/optimize/autoprefixer.ts
18435
- let cssProcessor;
18436
18252
  /**
18437
- * Autoprefix a CSS string, adding vendor prefixes to make sure that what
18438
- * is written in the CSS will render correctly in our range of supported browsers.
18439
- * This function uses PostCSS in combination with the Autoprefix plugin to
18440
- * automatically add vendor prefixes based on a list of browsers which we want
18441
- * to support.
18253
+ * Autoprefix a CSS string, adding vendor prefixes to ensure that what is
18254
+ * written in the CSS will render correctly across our range of supported
18255
+ * browsers. Uses Lightning CSS to add vendor prefixes based on a browserslist
18256
+ * query.
18442
18257
  *
18443
- * @param cssText the text to be prefixed
18444
- * @param opts an optional param with options for Autoprefixer
18445
- * @returns a Promise wrapping some prefixed CSS as well as diagnostics
18258
+ * @param cssText the CSS text to be prefixed
18259
+ * @param opts options controlling which browsers to target, or `null` to use
18260
+ * the default browser targets
18261
+ * @returns a Promise wrapping the prefixed CSS and any diagnostics
18446
18262
  */
18447
18263
  const autoprefixCss = async (cssText, opts) => {
18448
18264
  const output = {
@@ -18450,94 +18266,42 @@ const autoprefixCss = async (cssText, opts) => {
18450
18266
  diagnostics: []
18451
18267
  };
18452
18268
  try {
18453
- const result = await (await getProcessor(opts != null && typeof opts === "object" ? opts : DEFAULT_AUTOPREFIX_OPTIONS)).process(cssText, { map: null });
18454
- result.warnings().forEach((warning) => {
18455
- output.diagnostics.push({
18456
- header: `Autoprefix CSS: ${warning.plugin}`,
18457
- messageText: warning.text,
18458
- level: "warn",
18459
- type: "css",
18460
- lines: []
18461
- });
18462
- });
18463
- output.output = result.css;
18269
+ const targets = browserslistToTargets(browserslist(opts != null && typeof opts === "object" && Array.isArray(opts.targets) ? opts.targets : DEFAULT_BROWSER_TARGETS));
18270
+ output.output = transform({
18271
+ filename: "style.css",
18272
+ code: Buffer.from(cssText),
18273
+ targets,
18274
+ minify: false
18275
+ }).code.toString();
18464
18276
  } catch (e) {
18465
18277
  const diagnostic = {
18466
18278
  header: `Autoprefix CSS`,
18467
- messageText: `CSS Error` + e,
18279
+ messageText: `CSS Error: ${e}`,
18468
18280
  level: `error`,
18469
18281
  type: `css`,
18470
18282
  lines: []
18471
18283
  };
18472
18284
  if (typeof e.name === "string") diagnostic.header = e.name;
18473
- if (typeof e.reason === "string") diagnostic.messageText = e.reason;
18474
- if (typeof e.source === "string" && typeof e.line === "number") {
18475
- const lines = e.source.replace(/\r/g, "\n").split("\n");
18476
- if (lines.length > 0) {
18477
- const addLine = (lineNumber) => {
18478
- const line = lines[lineNumber];
18479
- if (typeof line === "string") {
18480
- const printLine = {
18481
- lineIndex: -1,
18482
- lineNumber: -1,
18483
- text: line,
18484
- errorCharStart: -1,
18485
- errorLength: -1
18486
- };
18487
- diagnostic.lines = diagnostic.lines || [];
18488
- diagnostic.lines.push(printLine);
18489
- }
18490
- };
18491
- addLine(e.line - 3);
18492
- addLine(e.line - 2);
18493
- addLine(e.line - 1);
18494
- addLine(e.line);
18495
- addLine(e.line + 1);
18496
- addLine(e.line + 2);
18497
- addLine(e.line + 3);
18498
- }
18499
- }
18285
+ if (typeof e.message === "string") diagnostic.messageText = e.message;
18500
18286
  output.diagnostics.push(diagnostic);
18501
18287
  }
18502
18288
  return output;
18503
18289
  };
18504
18290
  /**
18505
- * Get the processor for PostCSS and the Autoprefixer plugin
18506
- *
18507
- * @param autoprefixerOpts Options for Autoprefixer
18508
- * @returns postCSS with the Autoprefixer plugin applied
18509
- */
18510
- const getProcessor = async (autoprefixerOpts) => {
18511
- if (!cssProcessor) {
18512
- const [{ default: postcss }, { default: autoprefixer }] = await Promise.all([import("postcss"), import("autoprefixer")]);
18513
- cssProcessor = postcss([autoprefixer(autoprefixerOpts)]);
18514
- }
18515
- return cssProcessor;
18516
- };
18517
- /**
18518
- * Default options for the Autoprefixer PostCSS plugin. See the documentation:
18519
- * https://github.com/postcss/autoprefixer#options for a complete list.
18520
- *
18521
- * This default option set will:
18522
- *
18523
- * - override the default browser list (`overrideBrowserslist`)
18524
- * - turn off the visual cascade (`cascade`)
18525
- * - disable auto-removing outdated prefixes (`remove`)
18526
- * - set `flexbox` to `"no-2009"`, which limits prefixing for flexbox to the
18527
- * final and IE 10 versions of the specification
18291
+ * Default browserslist targets used when autoprefixing CSS in v5.
18292
+ * Targets modern browsers — IE11, old Edge, and very old mobile browsers
18293
+ * are no longer included since Stencil v5 targets ES2017+ only.
18528
18294
  */
18529
- const DEFAULT_AUTOPREFIX_OPTIONS = {
18530
- overrideBrowserslist: [
18531
- "last 2 versions",
18532
- "iOS >= 9",
18533
- "Android >= 4.4",
18534
- "Explorer >= 11",
18535
- "ExplorerMobile >= 11"
18536
- ],
18537
- cascade: false,
18538
- remove: false,
18539
- flexbox: "no-2009"
18540
- };
18295
+ const DEFAULT_BROWSER_TARGETS = [
18296
+ "last 2 Chrome versions",
18297
+ "last 2 Firefox versions",
18298
+ "last 2 Safari versions",
18299
+ "last 2 Edge versions",
18300
+ "iOS >= 14",
18301
+ "Android >= 6",
18302
+ "> 0.5%",
18303
+ "not dead"
18304
+ ];
18541
18305
  //#endregion
18542
18306
  //#region src/compiler/style/css-parser/css-parse-declarations.ts
18543
18307
  let CssNodeType = /* @__PURE__ */ function(CssNodeType) {
@@ -19549,8 +19313,7 @@ const optimizeJs = async (inputOpts) => {
19549
19313
  sourceMap: null
19550
19314
  };
19551
19315
  try {
19552
- const prettyOutput = !!inputOpts.pretty;
19553
- const minifyOpts = getTerserOptions({}, inputOpts.target === "es5" ? "es5" : "latest", prettyOutput);
19316
+ const minifyOpts = getTerserOptions({}, "latest", !!inputOpts.pretty);
19554
19317
  const minifyResults = await minifyJs(inputOpts.input, minifyOpts);
19555
19318
  if (minifyResults.diagnostics.length > 0) result.diagnostics.push(...minifyResults.diagnostics);
19556
19319
  else {
@@ -19597,13 +19360,11 @@ const minifyScriptElements = async (doc, addMinifiedAttr) => {
19597
19360
  await Promise.all(scriptElms.map(async (scriptElm) => {
19598
19361
  const content = scriptElm.innerHTML.trim();
19599
19362
  if (content.length > 0) {
19600
- const opts = {
19363
+ const optimizeResults = await optimizeJs({
19601
19364
  input: content,
19602
19365
  sourceMap: false,
19603
19366
  target: "latest"
19604
- };
19605
- if (scriptElm.getAttribute("type") !== "module") opts.target = "es5";
19606
- const optimizeResults = await optimizeJs(opts);
19367
+ });
19607
19368
  if (optimizeResults.diagnostics.length === 0) scriptElm.innerHTML = optimizeResults.output;
19608
19369
  if (addMinifiedAttr) scriptElm.setAttribute(dataMinifiedAttr, "");
19609
19370
  }
@@ -20325,7 +20086,7 @@ const validateTsConfig = async (config, sys, init) => {
20325
20086
  if (results.watchOptions) tsconfig.watchOptions = results.watchOptions;
20326
20087
  if (results.options) {
20327
20088
  tsconfig.compilerOptions = results.options;
20328
- const target = tsconfig.compilerOptions.target ?? ts.ScriptTarget.ES5;
20089
+ const target = tsconfig.compilerOptions.target ?? ts.ScriptTarget.ES2017;
20329
20090
  if ([
20330
20091
  ts.ScriptTarget.ES3,
20331
20092
  ts.ScriptTarget.ES5,
@@ -20333,7 +20094,7 @@ const validateTsConfig = async (config, sys, init) => {
20333
20094
  ts.ScriptTarget.ES2016
20334
20095
  ].includes(target)) {
20335
20096
  const warn = buildWarn(tsconfig.diagnostics);
20336
- warn.messageText = `To improve bundling, it is always recommended to set the tsconfig.json target setting to "es2017". Note that the compiler will automatically handle transpilation for ES5-only browsers.`;
20097
+ warn.messageText = `Stencil requires the tsconfig.json "target" setting to be "es2017" or higher. ES5 build output is no longer supported.`;
20337
20098
  }
20338
20099
  if (tsconfig.compilerOptions.module !== ts.ModuleKind.ESNext && !config._isTesting) {
20339
20100
  const warn = buildWarn(tsconfig.diagnostics);
@@ -21537,8 +21298,7 @@ const VALID_TARGET = new Set([
21537
21298
  "es2018",
21538
21299
  "es2017",
21539
21300
  "es2016",
21540
- "es2015",
21541
- "es5"
21301
+ "es2015"
21542
21302
  ]);
21543
21303
  //#endregion
21544
21304
  //#region src/compiler/transformers/static-to-meta/visitor.ts