@stencil/core 5.0.0-next.0 → 5.0.0-rc.0

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 (58) hide show
  1. package/README.md +94 -0
  2. package/bin/stencil.mjs +1 -1
  3. package/dist/app-data/index.d.ts +2 -0
  4. package/dist/{runtime/app-data → app-data}/index.js +23 -15
  5. package/dist/{runtime/app-globals → app-globals}/index.js +1 -2
  6. package/dist/client-ClM4H9-P.mjs +2496 -0
  7. package/dist/compiler/browser.d.ts +1573 -0
  8. package/dist/compiler/browser.js +16998 -0
  9. package/dist/compiler/index.d.mts +284 -7
  10. package/dist/compiler/index.mjs +3 -9
  11. package/dist/compiler/utils/index.d.mts +272 -3
  12. package/dist/compiler/utils/index.mjs +4 -5
  13. package/dist/{transpile-CJQcQEVa.mjs → compiler-DFanjq9z.mjs} +20984 -15554
  14. package/dist/declarations/stencil-ext-modules.d.ts +8 -8
  15. package/dist/declarations/stencil-public-compiler.d.ts +1016 -840
  16. package/dist/declarations/stencil-public-compiler.js +3 -5
  17. package/dist/declarations/stencil-public-docs.d.ts +441 -376
  18. package/dist/declarations/stencil-public-docs.js +0 -0
  19. package/dist/declarations/stencil-public-runtime.d.ts +361 -113
  20. package/dist/fragment-Di1hWOC8.mjs +4 -0
  21. package/dist/helpers-Cpp3qc3u.mjs +524 -0
  22. package/dist/{index-szczUd2l.d.mts → index-DvfFOkiJ.d.mts} +1466 -2044
  23. package/dist/{stencil-private-Cgcr414u.d.ts → index-XQHZl0MW.d.ts} +308 -114
  24. package/dist/index-aBMJC5F9.d.mts +104 -0
  25. package/dist/index.d.mts +14 -2
  26. package/dist/index.mjs +171 -4
  27. package/dist/jsx-runtime.d.mts +24 -0
  28. package/dist/jsx-runtime.mjs +3 -0
  29. package/dist/mock-doc.mjs +2 -3
  30. package/dist/{node-sys-BGURUNOZ.mjs → node-DJP8JuAS.mjs} +176 -197
  31. package/dist/rolldown-runtime-BhDjJH2R.mjs +15 -0
  32. package/dist/{client-DR9zhmKG.mjs → runtime/client/lazy.js} +3780 -2652
  33. package/dist/runtime/client/{index.d.ts → runtime.d.ts} +516 -227
  34. package/dist/runtime/client/{index.js → runtime.js} +3588 -2856
  35. package/dist/runtime/index.d.ts +90 -72
  36. package/dist/runtime/index.js +3461 -2837
  37. package/dist/runtime/server/index.d.mts +243 -219
  38. package/dist/runtime/server/index.mjs +3763 -3352
  39. package/dist/runtime/server/runner.d.mts +114 -47
  40. package/dist/runtime/server/runner.mjs +12710 -763
  41. package/dist/signals/index.d.ts +58 -0
  42. package/dist/signals/index.js +182 -0
  43. package/dist/sys/node/index.d.mts +1 -3
  44. package/dist/sys/node/index.mjs +2 -7
  45. package/dist/sys/node/worker.d.mts +1 -1
  46. package/dist/sys/node/worker.mjs +3 -12
  47. package/dist/testing/index.d.mts +4763 -12
  48. package/dist/testing/index.mjs +7939 -619
  49. package/dist/util-C-H1H84W.mjs +731 -0
  50. package/dist/validation-ByYYKvnS.mjs +825 -0
  51. package/package.json +91 -59
  52. package/dist/chunk-ClPoSABd.mjs +0 -21
  53. package/dist/index-Bxo2jCf6.d.mts +0 -77
  54. package/dist/runtime/app-data/index.d.ts +0 -30
  55. package/dist/serialize-BJvhE9aQ.mjs +0 -775
  56. package/dist/validation-BdcPruW_.mjs +0 -1451
  57. /package/{LICENSE.md → LICENSE} +0 -0
  58. /package/dist/{runtime/app-globals → app-globals}/index.d.ts +0 -0
@@ -0,0 +1,825 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
+ import { C as CMP_FLAGS, H as LISTENER_FLAGS, W as MEMBER_FLAGS, et as WATCH_FLAGS, f as isString, l as isIterable, y as toTitleCase } from "./helpers-Cpp3qc3u.mjs";
3
+ import { $ as buildWarn, J as relative$1, Y as resolve$1, q as normalizePath } from "./util-C-H1H84W.mjs";
4
+ import nodePath from "node:path";
5
+ //#region src/utils/regular-expression.ts
6
+ /**
7
+ * Utility function that will escape all regular expression special characters in a string.
8
+ *
9
+ * @param text The string potentially containing special characters.
10
+ * @returns The string with all special characters escaped.
11
+ */
12
+ const escapeRegExpSpecialCharacters = (text) => {
13
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14
+ };
15
+ //#endregion
16
+ //#region src/utils/byte-size.ts
17
+ /**
18
+ * Used to learn the size of a string in bytes.
19
+ *
20
+ * @param str The string to measure
21
+ * @returns number
22
+ */
23
+ const byteSize = (str) => Buffer.byteLength(str, "utf8");
24
+ //#endregion
25
+ //#region src/utils/format-component-runtime-meta.ts
26
+ const formatLazyBundleRuntimeMeta = (bundleId, cmps) => {
27
+ return [bundleId, cmps.map((cmp) => formatComponentRuntimeMeta(cmp, true))];
28
+ };
29
+ /**
30
+ * Transform metadata about a component from the compiler to a compact form for
31
+ * use at runtime.
32
+ *
33
+ * @param compilerMeta component metadata gathered during compilation
34
+ * @param includeMethods include methods in the component's members or not
35
+ * @returns a compact format for component metadata, intended for runtime use
36
+ */
37
+ const formatComponentRuntimeMeta = (compilerMeta, includeMethods) => {
38
+ let flags = 0;
39
+ if (compilerMeta.encapsulation === "shadow") {
40
+ flags |= CMP_FLAGS.shadowDomEncapsulation;
41
+ if (compilerMeta.shadowDelegatesFocus) flags |= CMP_FLAGS.shadowDelegatesFocus;
42
+ if (compilerMeta.slotAssignment === "manual") flags |= CMP_FLAGS.shadowSlotAssignmentManual;
43
+ if (compilerMeta.shadowMode === "closed") flags |= CMP_FLAGS.shadowModeClosed;
44
+ if (compilerMeta.shadowClonable) flags |= CMP_FLAGS.shadowClonable;
45
+ if (compilerMeta.shadowSerializable) flags |= CMP_FLAGS.shadowSerializable;
46
+ } else if (compilerMeta.encapsulation === "scoped") flags |= CMP_FLAGS.scopedCssEncapsulation;
47
+ if (compilerMeta.formAssociated) flags |= CMP_FLAGS.formAssociated;
48
+ if (compilerMeta.encapsulation !== "shadow" && compilerMeta.htmlTagNames.includes("slot")) flags |= CMP_FLAGS.hasSlotRelocation;
49
+ if (compilerMeta.hasSlot) flags |= CMP_FLAGS.hasSlot;
50
+ if (compilerMeta.hasMode) flags |= CMP_FLAGS.hasMode;
51
+ if (compilerMeta.hasModernPropertyDecls) flags |= CMP_FLAGS.hasModernPropertyDecls;
52
+ if (compilerMeta.patches) {
53
+ if (compilerMeta.patches.all) flags |= CMP_FLAGS.patchAll;
54
+ if (compilerMeta.patches.children) flags |= CMP_FLAGS.patchChildren;
55
+ if (compilerMeta.patches.clone) flags |= CMP_FLAGS.patchClone;
56
+ if (compilerMeta.patches.insert) flags |= CMP_FLAGS.patchInsert;
57
+ }
58
+ const members = formatComponentRuntimeMembers(compilerMeta, includeMethods);
59
+ const hostListeners = formatHostListeners(compilerMeta);
60
+ const watchers = formatComponentRuntimeReactiveHandlers(compilerMeta, "watchers");
61
+ const serializers = formatComponentRuntimeReactiveHandlers(compilerMeta, "serializers");
62
+ const deserializers = formatComponentRuntimeReactiveHandlers(compilerMeta, "deserializers");
63
+ return trimFalsy([
64
+ flags,
65
+ compilerMeta.tagName,
66
+ Object.keys(members).length > 0 ? members : void 0,
67
+ hostListeners.length > 0 ? hostListeners : void 0,
68
+ Object.keys(watchers).length > 0 ? watchers : void 0,
69
+ Object.keys(serializers).length > 0 ? serializers : void 0,
70
+ Object.keys(deserializers).length > 0 ? deserializers : void 0,
71
+ compilerMeta.encapsulation === "shadow" ? compilerMeta.shadowReferenceTarget : void 0
72
+ ]);
73
+ };
74
+ const stringifyRuntimeData = (data) => {
75
+ const json = JSON.stringify(data);
76
+ if (json.length > 1e4) return `JSON.parse(${JSON.stringify(json)})`;
77
+ return json;
78
+ };
79
+ /**
80
+ * Transforms Stencil compiler metadata into a {@link d.ComponentCompilerMeta} object.
81
+ * This handles processing any compiler metadata transformed from components' uses of `@Watch()`, `@PropSerialize()`, and `@AttrDeserialize()`.
82
+ * The map of watched properties to their callback(s) will be immediately available
83
+ * to the runtime at bootstrap.
84
+ *
85
+ * @param compilerMeta Component metadata gathered during compilation
86
+ * @param decorator The decorator type to be processed: 'watchers', 'serializers', or 'deserializers'
87
+ * @returns An object mapping watched properties to their respective callback(s)
88
+ */
89
+ const formatComponentRuntimeReactiveHandlers = (compilerMeta, decorator) => {
90
+ const handlers = {};
91
+ compilerMeta[decorator]?.forEach(({ propName, methodName, handlerOptions }) => {
92
+ let watcherFlags = 0;
93
+ if (handlerOptions?.immediate) watcherFlags |= WATCH_FLAGS.Immediate;
94
+ handlers[propName] = [...handlers[propName] ?? [], { [methodName]: watcherFlags }];
95
+ });
96
+ return handlers;
97
+ };
98
+ const formatComponentRuntimeMembers = (compilerMeta, includeMethods = true) => {
99
+ return {
100
+ ...formatPropertiesRuntimeMember(compilerMeta.properties),
101
+ ...formatStatesRuntimeMember(compilerMeta.states),
102
+ ...includeMethods ? formatMethodsRuntimeMember(compilerMeta.methods) : {}
103
+ };
104
+ };
105
+ const formatPropertiesRuntimeMember = (properties) => {
106
+ const runtimeMembers = {};
107
+ properties.forEach((member) => {
108
+ runtimeMembers[member.name] = trimFalsy([formatFlags(member), formatAttrName(member)]);
109
+ });
110
+ return runtimeMembers;
111
+ };
112
+ const formatFlags = (compilerProperty) => {
113
+ let type = formatPropType(compilerProperty.type);
114
+ if (compilerProperty.mutable) type |= MEMBER_FLAGS.Mutable;
115
+ if (compilerProperty.reflect) type |= MEMBER_FLAGS.ReflectAttr;
116
+ if (compilerProperty.getter) type |= MEMBER_FLAGS.Getter;
117
+ if (compilerProperty.setter) type |= MEMBER_FLAGS.Setter;
118
+ return type;
119
+ };
120
+ /**
121
+ * We mainly add the alternative kebab-case attribute name because it might
122
+ * be used in an HTML environment (non JSX). Since we support hydration of
123
+ * complex types we provide a kebab-case attribute name for properties with
124
+ * these types.
125
+ */
126
+ const kebabCaseSupportForTypes = ["string", "unknown"];
127
+ const formatAttrName = (compilerProperty) => {
128
+ if (kebabCaseSupportForTypes.includes(typeof compilerProperty.attribute)) {
129
+ if (compilerProperty.name === compilerProperty.attribute) return;
130
+ return compilerProperty.attribute;
131
+ }
132
+ };
133
+ const formatPropType = (type) => {
134
+ if (type === "string") return MEMBER_FLAGS.String;
135
+ if (type === "number") return MEMBER_FLAGS.Number;
136
+ if (type === "boolean") return MEMBER_FLAGS.Boolean;
137
+ if (type === "any") return MEMBER_FLAGS.Any;
138
+ return MEMBER_FLAGS.Unknown;
139
+ };
140
+ const formatStatesRuntimeMember = (states) => {
141
+ const runtimeMembers = {};
142
+ states.forEach((member) => {
143
+ runtimeMembers[member.name] = [MEMBER_FLAGS.State];
144
+ });
145
+ return runtimeMembers;
146
+ };
147
+ const formatMethodsRuntimeMember = (methods) => {
148
+ const runtimeMembers = {};
149
+ methods.forEach((member) => {
150
+ runtimeMembers[member.name] = [MEMBER_FLAGS.Method];
151
+ });
152
+ return runtimeMembers;
153
+ };
154
+ const formatHostListeners = (compilerMeta) => {
155
+ return compilerMeta.listeners.map((compilerListener) => {
156
+ return [
157
+ computeListenerFlags(compilerListener),
158
+ compilerListener.name,
159
+ compilerListener.method
160
+ ];
161
+ });
162
+ };
163
+ const computeListenerFlags = (listener) => {
164
+ let flags = 0;
165
+ if (listener.capture) flags |= LISTENER_FLAGS.Capture;
166
+ if (listener.passive) flags |= LISTENER_FLAGS.Passive;
167
+ switch (listener.target) {
168
+ case "document":
169
+ flags |= LISTENER_FLAGS.TargetDocument;
170
+ break;
171
+ case "window":
172
+ flags |= LISTENER_FLAGS.TargetWindow;
173
+ break;
174
+ case "body": flags |= LISTENER_FLAGS.TargetBody;
175
+ }
176
+ return flags;
177
+ };
178
+ const trimFalsy = (data) => {
179
+ const arr = data;
180
+ for (let i = arr.length - 1; i >= 0; i--) {
181
+ if (arr[i]) break;
182
+ arr.pop();
183
+ }
184
+ return arr;
185
+ };
186
+ //#endregion
187
+ //#region src/utils/is-root-path.ts
188
+ /**
189
+ * Checks if the path is the Operating System (OS) root path, such as "/" or "C:\". This function does not take the OS
190
+ * the code is running on into account when performing this evaluation.
191
+ * @param p the path to check
192
+ * @returns `true` if the path is an OS root path, `false` otherwise
193
+ */
194
+ const isRootPath = (p) => p === "/" || windowsPathRegex.test(p);
195
+ const windowsPathRegex = /^(?:[a-zA-Z]:|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)?[\\/]$/;
196
+ //#endregion
197
+ //#region src/utils/logger/logger-utils.ts
198
+ /**
199
+ * Iterate through a series of diagnostics to provide minor fix-ups for various edge cases, deduplicate messages, etc.
200
+ * @param compilerCtx the current compiler context
201
+ * @param diagnostics the diagnostics to normalize
202
+ * @returns the normalize documents
203
+ */
204
+ const normalizeDiagnostics = (compilerCtx, diagnostics) => {
205
+ const maxErrorsToNormalize = 25;
206
+ const normalizedErrors = [];
207
+ const normalizedOthers = [];
208
+ const dups = /* @__PURE__ */ new Set();
209
+ for (let i = 0; i < diagnostics.length; i++) {
210
+ const diagnostic = normalizeDiagnostic(compilerCtx, diagnostics[i]);
211
+ const key = (diagnostic.absFilePath ?? "") + (diagnostic.code ?? "") + diagnostic.messageText + diagnostic.type;
212
+ if (dups.has(key)) continue;
213
+ dups.add(key);
214
+ const total = normalizedErrors.length + normalizedOthers.length;
215
+ if (diagnostic.level === "error") normalizedErrors.push(diagnostic);
216
+ else if (total < maxErrorsToNormalize) normalizedOthers.push(diagnostic);
217
+ }
218
+ return [...normalizedErrors, ...normalizedOthers];
219
+ };
220
+ /**
221
+ * Perform post-processing on a `Diagnostic` to handle a few message edge cases, massaging error message text and
222
+ * updating build failure contexts
223
+ * @param compilerCtx the current compiler
224
+ * @param diagnostic the diagnostic to normalize
225
+ * @returns the altered diagnostic
226
+ */
227
+ const normalizeDiagnostic = (compilerCtx, diagnostic) => {
228
+ if (diagnostic.messageText) {
229
+ if (typeof diagnostic.messageText.message === "string") diagnostic.messageText = diagnostic.messageText.message;
230
+ else if (typeof diagnostic.messageText === "string" && diagnostic.messageText.indexOf("Error: ") === 0) diagnostic.messageText = diagnostic.messageText.slice(7);
231
+ }
232
+ if (diagnostic.messageText) {
233
+ if (diagnostic.messageText.includes(`Cannot find name 'h'`)) {
234
+ diagnostic.header = `Missing "h" import for JSX types`;
235
+ diagnostic.messageText = `In order to load accurate JSX types for components, the "h" function must be imported from "@stencil/core" by each component using JSX. For example: import { Component, h } from '@stencil/core';`;
236
+ if (diagnostic.absFilePath) try {
237
+ const sourceText = compilerCtx.fs.readFileSync(diagnostic.absFilePath);
238
+ const srcLines = splitLineBreaks(sourceText);
239
+ for (let i = 0; i < srcLines.length; i++) {
240
+ const srcLine = srcLines[i];
241
+ if (srcLine.includes("@stencil/core")) {
242
+ const msgLines = [];
243
+ const beforeLineIndex = i - 1;
244
+ if (beforeLineIndex > -1) {
245
+ const beforeLine = {
246
+ lineIndex: beforeLineIndex,
247
+ lineNumber: beforeLineIndex + 1,
248
+ text: srcLines[beforeLineIndex],
249
+ errorCharStart: -1,
250
+ errorLength: -1
251
+ };
252
+ msgLines.push(beforeLine);
253
+ }
254
+ const errorLine = {
255
+ lineIndex: i,
256
+ lineNumber: i + 1,
257
+ text: srcLine,
258
+ errorCharStart: 0,
259
+ errorLength: -1
260
+ };
261
+ msgLines.push(errorLine);
262
+ diagnostic.lineNumber = errorLine.lineNumber;
263
+ diagnostic.columnNumber = srcLine.indexOf("}");
264
+ const afterLineIndex = i + 1;
265
+ if (afterLineIndex < srcLines.length) {
266
+ const afterLine = {
267
+ lineIndex: afterLineIndex,
268
+ lineNumber: afterLineIndex + 1,
269
+ text: srcLines[afterLineIndex],
270
+ errorCharStart: -1,
271
+ errorLength: -1
272
+ };
273
+ msgLines.push(afterLine);
274
+ }
275
+ diagnostic.lines = msgLines;
276
+ break;
277
+ }
278
+ }
279
+ } catch {}
280
+ }
281
+ }
282
+ return diagnostic;
283
+ };
284
+ /**
285
+ * Split a corpus by newlines. Carriage returns are treated a newlines.
286
+ * @param sourceText the corpus to split
287
+ * @returns the split text
288
+ */
289
+ const splitLineBreaks = (sourceText) => {
290
+ if (typeof sourceText !== "string") return [];
291
+ sourceText = sourceText.replace(/\\r/g, "\n");
292
+ return sourceText.split("\n");
293
+ };
294
+ const escapeHtml = (unsafe) => {
295
+ if (unsafe === void 0) return "undefined";
296
+ if (unsafe === null) return "null";
297
+ if (typeof unsafe !== "string") unsafe = unsafe.toString();
298
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
299
+ };
300
+ //#endregion
301
+ //#region src/utils/logger/logger-rolldown.ts
302
+ const isRolldownError = (e) => typeof e === "object" && e !== null && "message" in e;
303
+ const loadRolldownDiagnostics = (config, compilerCtx, buildCtx, rolldownError) => {
304
+ const formattedCode = formatErrorCode(rolldownError.code);
305
+ const diagnostic = {
306
+ level: "error",
307
+ type: "bundling",
308
+ language: "javascript",
309
+ code: rolldownError.code,
310
+ header: `Rolldown${formattedCode.length > 0 ? ": " + formattedCode : ""}`,
311
+ messageText: formattedCode,
312
+ relFilePath: void 0,
313
+ absFilePath: void 0,
314
+ lines: []
315
+ };
316
+ if (config.logLevel === "debug" && rolldownError.stack) diagnostic.messageText = rolldownError.stack;
317
+ else if (rolldownError.message) diagnostic.messageText = rolldownError.message;
318
+ if (rolldownError.plugin) diagnostic.messageText += ` (plugin: ${rolldownError.plugin}${rolldownError.hook ? `, ${rolldownError.hook}` : ""})`;
319
+ const loc = rolldownError.loc;
320
+ if (loc != null) {
321
+ const srcFile = loc.file || rolldownError.id;
322
+ if (isString(srcFile)) try {
323
+ const sourceText = compilerCtx.fs.readFileSync(srcFile);
324
+ if (sourceText) {
325
+ diagnostic.absFilePath = srcFile;
326
+ try {
327
+ const srcLines = splitLineBreaks(sourceText);
328
+ const errorLine = {
329
+ lineIndex: loc.line - 1,
330
+ lineNumber: loc.line,
331
+ text: srcLines[loc.line - 1],
332
+ errorCharStart: loc.column,
333
+ errorLength: 0
334
+ };
335
+ diagnostic.lineNumber = errorLine.lineNumber;
336
+ diagnostic.columnNumber = errorLine.errorCharStart;
337
+ const highlightLine = errorLine.text?.slice(loc.column) ?? "";
338
+ for (let i = 0; i < highlightLine.length; i++) {
339
+ if (charBreak.has(highlightLine.charAt(i))) break;
340
+ errorLine.errorLength++;
341
+ }
342
+ diagnostic.lines.push(errorLine);
343
+ if (errorLine.errorLength === 0 && errorLine.errorCharStart > 0) {
344
+ errorLine.errorLength = 1;
345
+ errorLine.errorCharStart--;
346
+ }
347
+ if (errorLine.lineIndex > 0) {
348
+ const previousLine = {
349
+ lineIndex: errorLine.lineIndex - 1,
350
+ lineNumber: errorLine.lineNumber - 1,
351
+ text: srcLines[errorLine.lineIndex - 1],
352
+ errorCharStart: -1,
353
+ errorLength: -1
354
+ };
355
+ diagnostic.lines.unshift(previousLine);
356
+ }
357
+ if (errorLine.lineIndex + 1 < srcLines.length) {
358
+ const nextLine = {
359
+ lineIndex: errorLine.lineIndex + 1,
360
+ lineNumber: errorLine.lineNumber + 1,
361
+ text: srcLines[errorLine.lineIndex + 1],
362
+ errorCharStart: -1,
363
+ errorLength: -1
364
+ };
365
+ diagnostic.lines.push(nextLine);
366
+ }
367
+ } catch {
368
+ diagnostic.messageText += `\nError parsing: ${diagnostic.absFilePath}, line: ${loc.line}, column: ${loc.column}`;
369
+ diagnostic.debugText = sourceText;
370
+ }
371
+ } else if (typeof rolldownError.frame === "string") diagnostic.messageText += "\n" + rolldownError.frame;
372
+ } catch {}
373
+ }
374
+ buildCtx.diagnostics.push(diagnostic);
375
+ };
376
+ const createOnWarnFn = (diagnostics, bundleModulesFiles) => {
377
+ const previousWarns = /* @__PURE__ */ new Set();
378
+ return function onWarningMessage(warning) {
379
+ if (warning == null || warning.code && ignoreWarnCodes.has(warning.code) || warning.message && previousWarns.has(warning.message)) return;
380
+ if (warning.message) previousWarns.add(warning.message);
381
+ let label = "";
382
+ if (bundleModulesFiles) {
383
+ label = bundleModulesFiles.reduce((cmps, m) => {
384
+ cmps.push(...m.cmps);
385
+ return cmps;
386
+ }, []).join(", ").trim();
387
+ if (label.length) label += ": ";
388
+ }
389
+ const diagnostic = buildWarn(diagnostics);
390
+ diagnostic.header = `Bundling Warning ${warning.code}`;
391
+ diagnostic.messageText = label + (warning.message || warning);
392
+ };
393
+ };
394
+ const ignoreWarnCodes = /* @__PURE__ */ new Set([
395
+ "THIS_IS_UNDEFINED",
396
+ "NON_EXISTENT_EXPORT",
397
+ "CIRCULAR_DEPENDENCY",
398
+ "EMPTY_BUNDLE",
399
+ "UNUSED_EXTERNAL_IMPORT",
400
+ "EMPTY_IMPORT_META"
401
+ ]);
402
+ const charBreak = /* @__PURE__ */ new Set([
403
+ " ",
404
+ "=",
405
+ ".",
406
+ ",",
407
+ "?",
408
+ ":",
409
+ ";",
410
+ "(",
411
+ ")",
412
+ "{",
413
+ "}",
414
+ "[",
415
+ "]",
416
+ "|",
417
+ `'`,
418
+ `"`,
419
+ "`"
420
+ ]);
421
+ const formatErrorCode = (errorCode) => {
422
+ if (typeof errorCode === "string") return errorCode.split("_").map((c) => {
423
+ return toTitleCase(c.toLowerCase());
424
+ }).join(" ");
425
+ return (errorCode || "").trim();
426
+ };
427
+ //#endregion
428
+ //#region src/utils/logger/logger-typescript.ts
429
+ /**
430
+ * Augment a `Diagnostic` with information from a `Node` in the AST to provide richer error information
431
+ * @param d the diagnostic to augment
432
+ * @param node the node to augment with additional information
433
+ * @returns the augmented diagnostic
434
+ */
435
+ const augmentDiagnosticWithNode = (d, node) => {
436
+ if (!node) return d;
437
+ const sourceFile = node.getSourceFile();
438
+ if (!sourceFile) return d;
439
+ d.absFilePath = normalizePath(sourceFile.fileName);
440
+ const sourceText = sourceFile.text;
441
+ const srcLines = splitLineBreaks(sourceText);
442
+ const start = node.getStart();
443
+ const end = node.getEnd();
444
+ const posStart = sourceFile.getLineAndCharacterOfPosition(start);
445
+ const errorLine = {
446
+ lineIndex: posStart.line,
447
+ lineNumber: posStart.line + 1,
448
+ text: srcLines[posStart.line],
449
+ errorCharStart: posStart.character,
450
+ errorLength: Math.max(end - start, 1)
451
+ };
452
+ d.lineNumber = errorLine.lineNumber;
453
+ d.columnNumber = errorLine.errorCharStart + 1;
454
+ d.lines.push(errorLine);
455
+ if (errorLine.errorLength === 0 && errorLine.errorCharStart > 0) {
456
+ errorLine.errorLength = 1;
457
+ errorLine.errorCharStart--;
458
+ }
459
+ if (errorLine.lineIndex > 0) {
460
+ const previousLine = {
461
+ lineIndex: errorLine.lineIndex - 1,
462
+ lineNumber: errorLine.lineNumber - 1,
463
+ text: srcLines[errorLine.lineIndex - 1],
464
+ errorCharStart: -1,
465
+ errorLength: -1
466
+ };
467
+ d.lines.unshift(previousLine);
468
+ }
469
+ if (errorLine.lineIndex + 1 < srcLines.length) {
470
+ const nextLine = {
471
+ lineIndex: errorLine.lineIndex + 1,
472
+ lineNumber: errorLine.lineNumber + 1,
473
+ text: srcLines[errorLine.lineIndex + 1],
474
+ errorCharStart: -1,
475
+ errorLength: -1
476
+ };
477
+ d.lines.push(nextLine);
478
+ }
479
+ return d;
480
+ };
481
+ /**
482
+ * Ok, so formatting overkill, we know. But whatever, it makes for great
483
+ * error reporting within a terminal. So, yeah, let's code it up, shall we?
484
+ */
485
+ /**
486
+ * Convert an array of TypeScript diagnostics to Stencil diagnostic format.
487
+ *
488
+ * @param tsDiagnostics - array of TypeScript diagnostic objects
489
+ * @returns array of Stencil diagnostic objects
490
+ */
491
+ const loadTypeScriptDiagnostics = (tsDiagnostics) => {
492
+ const diagnostics = [];
493
+ const maxErrors = Math.min(tsDiagnostics.length, 50);
494
+ for (let i = 0; i < maxErrors; i++) diagnostics.push(loadTypeScriptDiagnostic(tsDiagnostics[i]));
495
+ return diagnostics;
496
+ };
497
+ /**
498
+ * Convert a TypeScript diagnostic object into our internal, Stencil-specific
499
+ * diagnostic format
500
+ *
501
+ * @param tsDiagnostic a TypeScript diagnostic message record
502
+ * @returns a Stencil diagnostic, suitable for showing an error to the user
503
+ */
504
+ const loadTypeScriptDiagnostic = (tsDiagnostic) => {
505
+ const d = {
506
+ absFilePath: void 0,
507
+ code: tsDiagnostic.code.toString(),
508
+ columnNumber: void 0,
509
+ header: "TypeScript",
510
+ language: "typescript",
511
+ level: "warn",
512
+ lineNumber: void 0,
513
+ lines: [],
514
+ messageText: flattenDiagnosticMessageText(tsDiagnostic, tsDiagnostic.messageText),
515
+ relFilePath: void 0,
516
+ type: "typescript"
517
+ };
518
+ if (tsDiagnostic.category === 1) d.level = "error";
519
+ if (tsDiagnostic.file && typeof tsDiagnostic.start === "number") {
520
+ d.absFilePath = tsDiagnostic.file.fileName;
521
+ const sourceText = tsDiagnostic.file.text;
522
+ const srcLines = splitLineBreaks(sourceText);
523
+ const posData = tsDiagnostic.file.getLineAndCharacterOfPosition(tsDiagnostic.start);
524
+ const errorLine = {
525
+ lineIndex: posData.line,
526
+ lineNumber: posData.line + 1,
527
+ text: srcLines[posData.line],
528
+ errorCharStart: posData.character,
529
+ errorLength: Math.max(tsDiagnostic.length ?? 0, 1)
530
+ };
531
+ d.lineNumber = errorLine.lineNumber;
532
+ d.columnNumber = errorLine.errorCharStart + 1;
533
+ d.lines.push(errorLine);
534
+ if (errorLine.errorLength === 0 && errorLine.errorCharStart > 0) {
535
+ errorLine.errorLength = 1;
536
+ errorLine.errorCharStart--;
537
+ }
538
+ if (errorLine.lineIndex > 0) {
539
+ const previousLine = {
540
+ lineIndex: errorLine.lineIndex - 1,
541
+ lineNumber: errorLine.lineNumber - 1,
542
+ text: srcLines[errorLine.lineIndex - 1],
543
+ errorCharStart: -1,
544
+ errorLength: -1
545
+ };
546
+ d.lines.unshift(previousLine);
547
+ }
548
+ if (errorLine.lineIndex + 1 < srcLines.length) {
549
+ const nextLine = {
550
+ lineIndex: errorLine.lineIndex + 1,
551
+ lineNumber: errorLine.lineNumber + 1,
552
+ text: srcLines[errorLine.lineIndex + 1],
553
+ errorCharStart: -1,
554
+ errorLength: -1
555
+ };
556
+ d.lines.push(nextLine);
557
+ }
558
+ }
559
+ return d;
560
+ };
561
+ /**
562
+ * Flatten a TypeScript diagnostic object into a string which can be easily
563
+ * included in a Stencil diagnostic record.
564
+ *
565
+ * @param tsDiagnostic a TypeScript diagnostic record
566
+ * @param diag a {@link DiagnosticMessageChain} or a string with further info
567
+ * @returns a string with the relevant error message
568
+ */
569
+ const flattenDiagnosticMessageText = (tsDiagnostic, diag) => {
570
+ if (typeof diag === "string") return diag;
571
+ else if (diag === void 0) return "";
572
+ const ignoreCodes = [];
573
+ const isStencilConfig = (tsDiagnostic.file?.fileName ?? "").includes("stencil.config");
574
+ if (isStencilConfig) ignoreCodes.push(2322);
575
+ let result = "";
576
+ if (!ignoreCodes.includes(diag.code)) {
577
+ result = diag.messageText;
578
+ if (isIterable(diag.next)) for (const kid of diag.next) result += flattenDiagnosticMessageText(tsDiagnostic, kid);
579
+ }
580
+ if (isStencilConfig) {
581
+ result = result.replace(`type 'StencilConfig'`, `Stencil Config`);
582
+ result = result.replace(`Object literal may only specify known properties, but `, ``);
583
+ result = result.replace(`Object literal may only specify known properties, and `, ``);
584
+ }
585
+ return result.trim();
586
+ };
587
+ //#endregion
588
+ //#region src/utils/result.ts
589
+ var result_exports = /* @__PURE__ */ __exportAll({
590
+ err: () => err,
591
+ map: () => map,
592
+ ok: () => ok,
593
+ unwrap: () => unwrap,
594
+ unwrapErr: () => unwrapErr
595
+ });
596
+ /**
597
+ * Create an `Ok` given a value. This doesn't do any checking that the value is
598
+ * 'ok-ish' since doing so would make an undue assumption about what is 'ok'.
599
+ * Instead, this trusts the user to determine, at the call site, whether
600
+ * something is `ok()` or `err()`.
601
+ *
602
+ * @param value the value to wrap up in an `Ok`
603
+ * @returns an Ok wrapping the value
604
+ */
605
+ const ok = (value) => ({
606
+ isOk: true,
607
+ isErr: false,
608
+ value
609
+ });
610
+ /**
611
+ * Create an `Err` given a value.
612
+ *
613
+ * @param value the value to wrap up in an `Err`
614
+ * @returns an Ok wrapping the value
615
+ */
616
+ const err = (value) => ({
617
+ isOk: false,
618
+ isErr: true,
619
+ value
620
+ });
621
+ function map(result, fn) {
622
+ if (result.isOk) {
623
+ const val = fn(result.value);
624
+ if (val instanceof Promise) return val.then((newVal) => ok(newVal));
625
+ else return ok(val);
626
+ }
627
+ if (result.isErr) {
628
+ const value = result.value;
629
+ return err(value);
630
+ }
631
+ throw "should never get here";
632
+ }
633
+ /**
634
+ * Unwrap a {@link Result}, return the value inside if it is an `Ok` and
635
+ * throw with the wrapped value if it is an `Err`.
636
+ *
637
+ * @throws with the wrapped value if it is an `Err`.
638
+ * @param result a result to peer inside of
639
+ * @returns the wrapped value, if `Ok`
640
+ */
641
+ const unwrap = (result) => {
642
+ if (result.isOk) return result.value;
643
+ else throw result.value;
644
+ };
645
+ /**
646
+ * Unwrap a {@link Result}, return the value inside if it is an `Err` and
647
+ * throw with the wrapped value if it is an `Ok`.
648
+ *
649
+ * @throws with the wrapped value if it is an `Ok`.
650
+ * @param result a result to peer inside of
651
+ * @returns the wrapped value, if `Err`
652
+ */
653
+ const unwrapErr = (result) => {
654
+ if (result.isErr) return result.value;
655
+ else throw result.value;
656
+ };
657
+ //#endregion
658
+ //#region src/utils/sourcemaps.ts
659
+ function rolldownToStencilSourceMap(rolldownSourceMap) {
660
+ if (!rolldownSourceMap || !rolldownSourceMap.file) return null;
661
+ return {
662
+ file: rolldownSourceMap.file,
663
+ mappings: rolldownSourceMap.mappings,
664
+ names: rolldownSourceMap.names,
665
+ sources: rolldownSourceMap.sources,
666
+ sourcesContent: rolldownSourceMap.sourcesContent,
667
+ version: rolldownSourceMap.version
668
+ };
669
+ }
670
+ /**
671
+ * A JavaScript formatted string used to link generated code back to the original. This string follows the guidelines
672
+ * found in the [Linking generated code to source maps](https://sourcemaps.info/spec.html#h.lmz475t4mvbx) section of
673
+ * the Sourcemaps V3 specification proposal.
674
+ */
675
+ const JS_SOURCE_MAPPING_URL_LINKER = "//# sourceMappingURL=";
676
+ /**
677
+ * Generates an RFC-3986 compliant string for the given input.
678
+ * More information about RFC-3986 can be found [here](https://datatracker.ietf.org/doc/html/rfc3986)
679
+ * This function's original source is derived from
680
+ * [MDN's encodeURIComponent documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent#description)
681
+ * @param filename the filename to encode
682
+ * @returns the encoded URI
683
+ */
684
+ const encodeToRfc3986 = (filename) => {
685
+ return encodeURIComponent(filename).replace(/[!'()*]/g, (matchedCharacter) => {
686
+ return "%" + matchedCharacter.charCodeAt(0).toString(16);
687
+ });
688
+ };
689
+ /**
690
+ * Generates a string used to link generated code with the original source, to be placed at the end of the generated
691
+ * code.
692
+ * @param url the url of the source map
693
+ * @returns a linker string, of the format {@link JS_SOURCE_MAPPING_URL_LINKER}=<url>
694
+ */
695
+ const getSourceMappingUrlLinker = (url) => {
696
+ return `${JS_SOURCE_MAPPING_URL_LINKER}${encodeToRfc3986(url)}`;
697
+ };
698
+ /**
699
+ * Generates a string used to link generated code with the original source, to be placed at the end of the generated
700
+ * code as an inline source map.
701
+ * @param sourceMapContents the sourceMapContents of the source map
702
+ * @returns a linker string, of the format {@link JS_SOURCE_MAPPING_URL_LINKER}<dataUriPrefixAndMime><sourceMapContents>
703
+ */
704
+ const getInlineSourceMappingUrlLinker = (sourceMapContents) => {
705
+ const mapBase64 = Buffer.from(sourceMapContents, "utf8").toString("base64");
706
+ return `${JS_SOURCE_MAPPING_URL_LINKER}data:application/json;charset=utf-8;base64,${mapBase64}`;
707
+ };
708
+ /**
709
+ * Generates a string used to link generated code with the original source, to be placed at the end of the generated
710
+ * code. This function prepends a newline to the string.
711
+ * @param url the url of the source map
712
+ * @returns a linker string, of the format {@link JS_SOURCE_MAPPING_URL_LINKER}=<url>.map, prepended with a newline
713
+ */
714
+ const getSourceMappingUrlForEndOfFile = (url) => {
715
+ return `\n${getSourceMappingUrlLinker(url)}.map`;
716
+ };
717
+ /**
718
+ * Rolldown source map output options. Stencil appends its own `sourceMappingURL` comment, so the map
719
+ * is `hidden`. A chunk can be written to several directories, so `sources` are made absolute here
720
+ * (query strings stripped) and relative to each destination by {@link relativizeSourceMap}.
721
+ * Virtual modules have no file and keep their id.
722
+ *
723
+ * @param config the validated Stencil configuration
724
+ * @returns the source map options to spread into Rolldown's output options
725
+ */
726
+ const getRolldownSourceMapOptions = (config) => ({
727
+ sourcemap: config.sourceMap ? "hidden" : false,
728
+ sourcemapPathTransform: (relativeSourcePath, sourcemapPath) => {
729
+ const absPath = resolve$1(nodePath.dirname(sourcemapPath), relativeSourcePath.split("?")[0]);
730
+ return config.sys.accessSync(absPath) ? absPath : relative$1(process.cwd(), absPath);
731
+ }
732
+ });
733
+ /**
734
+ * Makes a source map's absolute `sources` relative to where the map is written, and names the
735
+ * file it maps.
736
+ *
737
+ * @param sourceMap the source map, with absolute `sources` from {@link getRolldownSourceMapOptions}
738
+ * @param filePath the path the mapped `.js` file is written to
739
+ * @returns the source map to write next to `filePath`
740
+ */
741
+ const relativizeSourceMap = (sourceMap, filePath) => {
742
+ const dir = nodePath.dirname(filePath);
743
+ return {
744
+ ...sourceMap,
745
+ file: nodePath.basename(filePath),
746
+ sources: sourceMap.sources.map((source) => nodePath.isAbsolute(source) ? relative$1(dir, source) : normalizePath(source, false))
747
+ };
748
+ };
749
+ //#endregion
750
+ //#region src/utils/url-paths.ts
751
+ /**
752
+ * Determines whether a string should be considered a remote url or not.
753
+ *
754
+ * This helper only checks the provided string to evaluate is one of a few pre-defined schemes, and should not be
755
+ * considered all-encompassing
756
+ *
757
+ * @param p the string to evaluate
758
+ * @returns `true` if the provided string is a remote url, `false` otherwise
759
+ */
760
+ const isRemoteUrl = (p) => {
761
+ if (isString(p)) {
762
+ p = p.toLowerCase();
763
+ return p.startsWith("https://") || p.startsWith("http://");
764
+ }
765
+ return false;
766
+ };
767
+ //#endregion
768
+ //#region src/utils/validation.ts
769
+ const getModeKeys = (value) => {
770
+ if (value == null || typeof value !== "object" || Array.isArray(value) || value.__identifier) return [];
771
+ return Object.keys(value);
772
+ };
773
+ /**
774
+ * Validates the mode keys used in a component's `styleUrls`/`styles` against a
775
+ * `config.modes` allowlist, if one is declared.
776
+ * @param configModes the `config.modes` allowlist (mixed string/{@link d.ModeConfig} entries)
777
+ * @param componentOptions the `@Component()` decorator options for a single component
778
+ * @returns a validation error if a used mode is unknown or a required mode is missing, undefined otherwise
779
+ */
780
+ const validateComponentModes = (configModes, componentOptions) => {
781
+ if (!configModes || configModes.length === 0) return;
782
+ const allowedModes = /* @__PURE__ */ new Map();
783
+ for (const entry of configModes) if (typeof entry === "string") allowedModes.set(entry, false);
784
+ else allowedModes.set(entry.mode, !!entry.required);
785
+ const fields = [{
786
+ propName: "styleUrls",
787
+ keys: getModeKeys(componentOptions.styleUrls)
788
+ }, {
789
+ propName: "styles",
790
+ keys: getModeKeys(componentOptions.styles)
791
+ }];
792
+ for (const field of fields) for (const key of field.keys) if (!allowedModes.has(key)) return {
793
+ propName: field.propName,
794
+ message: `Invalid mode "${key}" in "${field.propName}". Valid modes are: ${[...allowedModes.keys()].join(", ")}.`
795
+ };
796
+ const usedModes = /* @__PURE__ */ new Set([...fields[0].keys, ...fields[1].keys]);
797
+ if (usedModes.size > 0) {
798
+ const missingRequired = [...allowedModes.entries()].filter(([mode, required]) => required && !usedModes.has(mode)).map(([mode]) => mode);
799
+ if (missingRequired.length > 0) return {
800
+ propName: fields[0].keys.length > 0 ? "styleUrls" : "styles",
801
+ message: `Missing required mode${missingRequired.length > 1 ? "s" : ""}: ${missingRequired.join(", ")}.`
802
+ };
803
+ }
804
+ };
805
+ /**
806
+ * Validates that a component tag meets required naming conventions to be used for a web component
807
+ * @param tag the tag to validate
808
+ * @returns an error message if the tag has an invalid name, undefined if the tag name passes all checks
809
+ */
810
+ const validateComponentTag = (tag) => {
811
+ if (typeof tag !== "string") return `Tag "${tag}" must be a string type`;
812
+ if (tag !== tag.trim()) return `Tag can not contain white spaces`;
813
+ if (tag !== tag.toLowerCase()) return `Tag can not contain upper case characters`;
814
+ if (tag.length === 0) return `Received empty tag value`;
815
+ if (tag.indexOf(" ") > -1) return `"${tag}" tag cannot contain a space`;
816
+ if (tag.indexOf(",") > -1) return `"${tag}" tag cannot be used for multiple tags`;
817
+ const invalidChars = tag.replace(/\w|-/g, "");
818
+ if (invalidChars !== "") return `"${tag}" tag contains invalid characters: ${invalidChars}`;
819
+ if (tag.indexOf("-") === -1) return `"${tag}" tag must contain a dash (-) to work as a valid web component`;
820
+ if (tag.indexOf("--") > -1) return `"${tag}" tag cannot contain multiple dashes (--) next to each other`;
821
+ if (tag.indexOf("-") === 0) return `"${tag}" tag cannot start with a dash (-)`;
822
+ if (tag.lastIndexOf("-") === tag.length - 1) return `"${tag}" tag cannot end with a dash (-)`;
823
+ };
824
+ //#endregion
825
+ export { isRootPath as C, byteSize as D, stringifyRuntimeData as E, escapeRegExpSpecialCharacters as O, splitLineBreaks as S, formatLazyBundleRuntimeMeta as T, createOnWarnFn as _, getRolldownSourceMapOptions as a, escapeHtml as b, relativizeSourceMap as c, map as d, ok as f, loadTypeScriptDiagnostics as g, loadTypeScriptDiagnostic as h, getInlineSourceMappingUrlLinker as i, rolldownToStencilSourceMap as l, augmentDiagnosticWithNode as m, validateComponentTag as n, getSourceMappingUrlForEndOfFile as o, result_exports as p, isRemoteUrl as r, getSourceMappingUrlLinker as s, validateComponentModes as t, err as u, isRolldownError as v, formatComponentRuntimeMeta as w, normalizeDiagnostics as x, loadRolldownDiagnostics as y };