@storybook/web-components 11.0.0-alpha.6 → 11.0.0-alpha.8

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.
@@ -1,35 +1,110 @@
1
- import CJS_COMPAT_NODE_URL_3ov4ld79bt3 from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_3ov4ld79bt3 from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_3ov4ld79bt3 from "node:module";
1
+ import CJS_COMPAT_NODE_URL_f6rwsm0jxpo from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_f6rwsm0jxpo from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_f6rwsm0jxpo from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_3ov4ld79bt3.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_3ov4ld79bt3.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_3ov4ld79bt3.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_f6rwsm0jxpo.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_f6rwsm0jxpo.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_f6rwsm0jxpo.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
11
  // ------------------------------------------------------------
12
12
  import {
13
- deprecationMessage,
14
- errorMessage,
15
- firstValue,
16
- isRecord,
17
- namedItems,
18
13
  parseStoryFile,
19
- readCssPropertySyntax,
20
- readTypeText,
21
- resolveStoryComponent,
22
- trimmedOrUndefined
23
- } from "./chunk-GDY64HEP.js";
14
+ resolveStoryComponent
15
+ } from "./chunk-A2ZEEPU6.js";
24
16
 
25
17
  // src/docgen/docgen-worker.ts
26
18
  import { createLazyDocgenMiddleware } from "storybook/internal/common";
27
- import { logger as logger2 } from "storybook/internal/node-logger";
19
+ import { logger as logger5 } from "storybook/internal/node-logger";
28
20
 
29
21
  // src/docgen/component-docgen/build-docgen.ts
30
22
  import { getComponentIdFromEntry, getStoryImportPathFromEntry } from "storybook/internal/common";
31
- import { extractComponentDescription, extractDescription } from "storybook/internal/csf-tools";
32
- import { resolve } from "node:path";
23
+ import {
24
+ extractComponentDescription,
25
+ extractDescription
26
+ } from "storybook/internal/csf-tools";
27
+
28
+ // node_modules/pathe/dist/shared/pathe.ff20891b.mjs
29
+ var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
30
+ function normalizeWindowsPath(input = "") {
31
+ return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
32
+ }
33
+ var _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/, _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
34
+ var normalize = function(path2) {
35
+ if (path2.length === 0)
36
+ return ".";
37
+ path2 = normalizeWindowsPath(path2);
38
+ let isUNCPath = path2.match(_UNC_REGEX), isPathAbsolute = isAbsolute(path2), trailingSeparator = path2[path2.length - 1] === "/";
39
+ return path2 = normalizeString(path2, !isPathAbsolute), path2.length === 0 ? isPathAbsolute ? "/" : trailingSeparator ? "./" : "." : (trailingSeparator && (path2 += "/"), _DRIVE_LETTER_RE.test(path2) && (path2 += "/"), isUNCPath ? isPathAbsolute ? `//${path2}` : `//./${path2}` : isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2);
40
+ }, join = function(...arguments_) {
41
+ if (arguments_.length === 0)
42
+ return ".";
43
+ let joined;
44
+ for (let argument of arguments_)
45
+ argument && argument.length > 0 && (joined === void 0 ? joined = argument : joined += `/${argument}`);
46
+ return joined === void 0 ? "." : normalize(joined.replace(/\/\/+/g, "/"));
47
+ };
48
+ function cwd() {
49
+ return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
50
+ }
51
+ var resolve = function(...arguments_) {
52
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
53
+ let resolvedPath = "", resolvedAbsolute = !1;
54
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
55
+ let path2 = index >= 0 ? arguments_[index] : cwd();
56
+ !path2 || path2.length === 0 || (resolvedPath = `${path2}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path2));
57
+ }
58
+ return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
59
+ };
60
+ function normalizeString(path2, allowAboveRoot) {
61
+ let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
62
+ for (let index = 0; index <= path2.length; ++index) {
63
+ if (index < path2.length)
64
+ char = path2[index];
65
+ else {
66
+ if (char === "/")
67
+ break;
68
+ char = "/";
69
+ }
70
+ if (char === "/") {
71
+ if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
72
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
73
+ if (res.length > 2) {
74
+ let lastSlashIndex = res.lastIndexOf("/");
75
+ lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
76
+ continue;
77
+ } else if (res.length > 0) {
78
+ res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
79
+ continue;
80
+ }
81
+ }
82
+ allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
83
+ } else
84
+ res.length > 0 ? res += `/${path2.slice(lastSlash + 1, index)}` : res = path2.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
85
+ lastSlash = index, dots = 0;
86
+ } else char === "." && dots !== -1 ? ++dots : dots = -1;
87
+ }
88
+ return res;
89
+ }
90
+ var isAbsolute = function(p) {
91
+ return _IS_ABSOLUTE_RE.test(p);
92
+ };
93
+ var relative = function(from, to) {
94
+ let _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"), _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
95
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0])
96
+ return _to.join("/");
97
+ let _fromCopy = [..._from];
98
+ for (let segment of _fromCopy) {
99
+ if (_to[0] !== segment)
100
+ break;
101
+ _from.shift(), _to.shift();
102
+ }
103
+ return [..._from.map(() => ".."), ..._to].join("/");
104
+ }, dirname = function(p) {
105
+ let segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
106
+ return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
107
+ };
33
108
 
34
109
  // src/arg-keys.ts
35
110
  var DEFAULT_SLOT_NAME = "default";
@@ -37,6 +112,7 @@ function toArgKey(category, name) {
37
112
  return category === "cssProperties" ? name : `${name}${ARG_KEY_SUFFIXES[category]}`;
38
113
  }
39
114
  var ARG_KEY_SUFFIXES = {
115
+ attributes: "-attr",
40
116
  events: "-event",
41
117
  methods: "-method",
42
118
  slots: "-slot",
@@ -44,6 +120,37 @@ var ARG_KEY_SUFFIXES = {
44
120
  cssStates: "-state"
45
121
  };
46
122
 
123
+ // src/docgen/component-docgen/utils.ts
124
+ function isRecord(value) {
125
+ return value !== null && typeof value == "object";
126
+ }
127
+ function namedItems(value) {
128
+ return Array.isArray(value) ? value.filter((item) => isRecord(item) && typeof item.name == "string") : [];
129
+ }
130
+ function errorMessage(error) {
131
+ return error instanceof Error ? error.message : String(error);
132
+ }
133
+ var trimmedOrUndefined = (text) => typeof text == "string" && text.trim() || void 0;
134
+ function deprecationMessage(deprecated) {
135
+ if (deprecated)
136
+ return typeof deprecated == "string" ? trimmedOrUndefined(deprecated) : "deprecated";
137
+ }
138
+ function firstValue(sources, read) {
139
+ for (let source of sources) {
140
+ let value = read(source);
141
+ if (value !== void 0)
142
+ return value;
143
+ }
144
+ }
145
+
146
+ // src/docgen/component-docgen/manifest/type-text.ts
147
+ function readTypeText({ type, parsedType }) {
148
+ return isRecord(parsedType) && typeof parsedType.text == "string" && parsedType.text.trim() ? parsedType.text : typeof type?.text == "string" ? type.text : void 0;
149
+ }
150
+ function readCssPropertySyntax(property) {
151
+ return property.syntax ?? readTypeText(property);
152
+ }
153
+
47
154
  // src/docgen/component-docgen/manifest/members.ts
48
155
  function isPublicField(member) {
49
156
  return isField(member) && isPublicMember(member);
@@ -86,34 +193,37 @@ function classifyDeclaration(declaration) {
86
193
  };
87
194
  }
88
195
  function isBackedByAttribute(field, attributes) {
196
+ return attributes.some((attribute) => isAttributeField(attribute, field));
197
+ }
198
+ function foldsIntoAttributeRow(field, attributes) {
89
199
  return attributes.some(
90
- (attribute) => attribute.field === field || attribute.attribute.name === field.name
200
+ (attribute) => attribute.attribute.name === field.name && isAttributeField(attribute, field)
91
201
  );
92
202
  }
203
+ function isAttributeField({ attribute, field: backingField2 }, field) {
204
+ return backingField2 === field || attribute.fieldName === void 0 && attribute.name === field.name;
205
+ }
93
206
  function backingField(attribute, fields) {
94
207
  return attribute.fieldName === void 0 ? void 0 : fields.find((field) => field.name === attribute.fieldName);
95
208
  }
96
209
 
97
210
  // src/docgen/component-docgen/api-description.ts
98
211
  var IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
99
- function buildApiDescription(declaration, typeProperty) {
100
- let api = classifyDeclaration(declaration), attributes = api.attributes.map((attribute) => attributeDoc(attribute, typeProperty)), properties = api.fields.filter((field) => !isBackedByAttribute(field, api.attributes));
212
+ function buildApiDescription(declaration) {
213
+ let api = classifyDeclaration(declaration), attributes = api.attributes.map(attributeDoc), properties = api.fields.filter((field) => !isBackedByAttribute(field, api.attributes));
101
214
  if (attributes.length === 0 && properties.length === 0 && api.events.length === 0 && api.methods.length === 0 && api.slots.length === 0 && api.cssProperties.length === 0 && api.cssParts.length === 0 && api.cssStates.length === 0)
102
215
  return;
103
216
  let typePrefix = declaration.name.replace(/\W+/g, "");
104
217
  return [
105
218
  attributesSection(typePrefix, attributes),
106
- propertiesSection(typePrefix, properties, typeProperty),
107
- eventsSection(typePrefix, api.events, typeProperty),
108
- methodsSection(typePrefix, api.methods, typeProperty),
219
+ propertiesSection(typePrefix, properties),
220
+ eventsSection(typePrefix, api.events),
221
+ methodsSection(typePrefix, api.methods),
109
222
  listSection(
110
223
  "Slots",
111
224
  api.slots.map((slot) => listItem(slot.name || DEFAULT_SLOT_NAME, memberDoc(slot)))
112
225
  ),
113
- listSection(
114
- "CSS Custom Properties",
115
- api.cssProperties.map((property) => cssPropertyListItem(property, typeProperty))
116
- ),
226
+ listSection("CSS Custom Properties", api.cssProperties.map(cssPropertyListItem)),
117
227
  listSection(
118
228
  "CSS Parts",
119
229
  api.cssParts.map((part) => listItem(part.name, memberDoc(part)))
@@ -140,13 +250,13 @@ function attributesSection(typePrefix, attributes) {
140
250
  })
141
251
  );
142
252
  }
143
- function propertiesSection(typePrefix, properties, typeProperty) {
253
+ function propertiesSection(typePrefix, properties) {
144
254
  if (properties.length !== 0)
145
255
  return typeSection(
146
256
  "Properties",
147
257
  `${typePrefix}Properties`,
148
258
  properties.flatMap((property) => {
149
- let doc = memberDoc(property), type = fieldType(property, typeProperty);
259
+ let doc = memberDoc(property), type = fieldType(property);
150
260
  return [
151
261
  ...docComment(doc),
152
262
  property.readonly === !0 ? ` readonly ${memberName(property.name)}: ${type}${memberDefault(doc)};` : ` ${memberName(property.name)}?: ${type}${memberDefault(doc)};`
@@ -154,28 +264,25 @@ function propertiesSection(typePrefix, properties, typeProperty) {
154
264
  })
155
265
  );
156
266
  }
157
- function eventsSection(typePrefix, events, typeProperty) {
267
+ function eventsSection(typePrefix, events) {
158
268
  if (events.length !== 0)
159
269
  return typeSection(
160
270
  "Events",
161
271
  `${typePrefix}Events`,
162
272
  events.flatMap((event) => [
163
273
  ...docComment(memberDoc(event)),
164
- ` ${memberName(event.name)}: ${readTypeText(event, typeProperty) ?? "Event"};`
274
+ ` ${memberName(event.name)}: ${readTypeText(event) ?? "Event"};`
165
275
  ])
166
276
  );
167
277
  }
168
- function methodsSection(typePrefix, methods, typeProperty) {
278
+ function methodsSection(typePrefix, methods) {
169
279
  if (methods.length !== 0)
170
280
  return typeSection(
171
281
  "Methods",
172
282
  `${typePrefix}Methods`,
173
283
  methods.flatMap((method) => [
174
284
  ...docComment(memberDoc(method)),
175
- ` ${memberName(method.name)}(${formatParameters(method)}): ${methodReturnType(
176
- method,
177
- typeProperty
178
- )};`
285
+ ` ${memberName(method.name)}(${formatParameters(method)}): ${methodReturnType(method)};`
179
286
  ])
180
287
  );
181
288
  }
@@ -190,8 +297,8 @@ function listSection(heading, items) {
190
297
  return [`## ${heading}`, "", ...items].join(`
191
298
  `);
192
299
  }
193
- function cssPropertyListItem(property, typeProperty) {
194
- let syntax = readCssPropertySyntax(property, typeProperty), name = property.name, syntaxText = syntax ? ` \`${syntax}\`` : "";
300
+ function cssPropertyListItem(property) {
301
+ let syntax = readCssPropertySyntax(property), name = property.name, syntaxText = syntax ? ` \`${syntax}\`` : "";
195
302
  return listItemPrefix(`${name}${syntaxText}`, memberDoc(property));
196
303
  }
197
304
  function listItem(name, doc) {
@@ -201,25 +308,25 @@ function listItemPrefix(prefix, doc) {
201
308
  let text = doc.text ? `: ${doc.text}` : "", defaultText = doc.defaultValue === void 0 ? "" : ` Default: ${doc.defaultValue}.`, deprecatedText = doc.deprecated === void 0 ? "" : doc.deprecated === "deprecated" ? " Deprecated." : ` Deprecated: ${doc.deprecated}.`;
202
309
  return `- ${prefix}${text}${defaultText}${deprecatedText}`;
203
310
  }
204
- function attributeDoc(attribute, typeProperty) {
311
+ function attributeDoc(attribute) {
205
312
  let { field } = attribute;
206
313
  return {
207
314
  ...attribute,
208
- type: attributeType(attribute, typeProperty),
315
+ type: attributeType(attribute),
209
316
  doc: memberDoc(field, attribute.attribute)
210
317
  };
211
318
  }
212
- function attributeType({ attribute, field }, typeProperty) {
319
+ function attributeType({ attribute, field }) {
213
320
  return firstValue(
214
321
  [field, attribute],
215
- (source) => source ? trimmedOrUndefined(readTypeText(source, typeProperty)) : void 0
322
+ (source) => source ? trimmedOrUndefined(readTypeText(source)) : void 0
216
323
  ) ?? "string";
217
324
  }
218
- function fieldType(field, typeProperty) {
219
- return trimmedOrUndefined(readTypeText(field, typeProperty)) ?? "unknown";
325
+ function fieldType(field) {
326
+ return trimmedOrUndefined(readTypeText(field)) ?? "unknown";
220
327
  }
221
- function methodReturnType(method, typeProperty) {
222
- return method.return ? readTypeText(method.return, typeProperty) ?? "void" : "void";
328
+ function methodReturnType(method) {
329
+ return method.return ? readTypeText(method.return) ?? "void" : "void";
223
330
  }
224
331
  function memberDoc(...sources) {
225
332
  return {
@@ -263,9 +370,9 @@ var ARRAY_RE = /^(?:Array<(.+)>|(.+)\[\])$/, DROPPED_MEMBERS = /* @__PURE__ */ n
263
370
  "never",
264
371
  "string & {}",
265
372
  "(string & {})"
266
- ]), FUNCTION_RE = /^(new\s+)?(<.*>\s*)?\(.*\)\s*=>/, UNKNOWN_ARRAY_ELEMENT_TYPE = { name: "other", value: "" }, MAX_ARRAY_DEPTH = 8;
373
+ ]), FUNCTION_RE = /^(new\s+)?(<.*>\s*)?\(.*\)\s*=>/, QUOTED_OR_WHITESPACE_RE = /(['"])(?:\\.|(?!\1)[^\\])*\1|\s+/g, UNKNOWN_ARRAY_ELEMENT_TYPE = { name: "other", value: "" }, MAX_ARRAY_DEPTH = 8;
267
374
  function parseTypeText(text, depth = 0) {
268
- let trimmed = text?.trim() ?? "", members = normalizeMembers(trimmed);
375
+ let members = normalizeMembers(collapseWhitespace(text ?? ""));
269
376
  if (members.length === 0)
270
377
  return;
271
378
  let literalValues = members.map(parseLiteral).filter((literal) => literal !== void 0);
@@ -310,6 +417,9 @@ function parseTypeText(text, depth = 0) {
310
417
  function normalizeMembers(text) {
311
418
  return text ? flattenMembers(text).filter((member) => member && !DROPPED_MEMBERS.has(member)) : [];
312
419
  }
420
+ function collapseWhitespace(text) {
421
+ return text.replace(QUOTED_OR_WHITESPACE_RE, (match) => /^\s/.test(match) ? " " : match).trim();
422
+ }
313
423
  function flattenMembers(text) {
314
424
  return splitTopLevel(text).flatMap((part) => {
315
425
  let member = stripWrappingParens(part);
@@ -389,50 +499,45 @@ var NAMED_ENTRY_CATEGORIES = {
389
499
  cssParts: "css shadow parts",
390
500
  cssStates: "css states"
391
501
  };
392
- function mapArgTypes(declaration, typeProperty) {
502
+ function mapArgTypes(declaration) {
393
503
  let api = classifyDeclaration(declaration);
394
504
  return {
395
505
  ...Object.fromEntries([
396
- ...api.events.flatMap((event) => eventEntries(event, typeProperty)),
506
+ ...api.events.flatMap(eventEntries),
397
507
  ...api.methods.map(methodEntry),
398
508
  ...api.slots.map((slot) => namedEntry(slot, "slots")),
399
509
  ...api.cssParts.map((part) => namedEntry(part, "cssParts")),
400
510
  ...api.cssStates.map((state) => namedEntry(state, "cssStates")),
401
- ...api.cssProperties.map((property) => cssPropertyEntry(property, typeProperty))
511
+ ...api.cssProperties.map(cssPropertyEntry)
402
512
  ]),
403
- ...mapAttributesAndProperties(api, typeProperty)
513
+ ...mapAttributesAndProperties(api)
404
514
  };
405
515
  }
406
- function mapAttributesAndProperties(api, typeProperty) {
407
- let argTypes = {}, properties = api.fields.filter(
408
- (field) => !api.attributes.some(({ attribute }) => attribute.name === field.name)
409
- );
516
+ function mapAttributesAndProperties(api) {
517
+ let argTypes = {}, properties = api.fields.filter((field) => !foldsIntoAttributeRow(field, api.attributes));
410
518
  for (let field of properties) {
411
519
  let attribute = api.attributes.find(({ field: backingField2 }) => backingField2 === field);
412
520
  argTypes[field.name] = toArgType({
413
521
  key: field.name,
414
522
  category: "properties",
415
- sources: attribute ? [field, attribute.attribute] : [field],
416
- typeProperty
523
+ sources: attribute ? [field, attribute.attribute] : [field]
417
524
  });
418
525
  }
419
- for (let { attribute, field } of api.attributes)
420
- argTypes[attribute.name] = toArgType({
526
+ for (let { attribute, field } of api.attributes) {
527
+ let key = Object.hasOwn(argTypes, attribute.name) ? toArgKey("attributes", attribute.name) : attribute.name;
528
+ argTypes[key] = toArgType({
421
529
  key: attribute.name,
422
530
  category: "attributes",
423
- sources: field ? [field, attribute] : [attribute],
424
- typeProperty
531
+ sources: field ? [field, attribute] : [attribute]
425
532
  });
533
+ }
426
534
  return argTypes;
427
535
  }
428
- function toArgType({ key, category, sources, typeProperty }) {
536
+ function toArgType({ key, category, sources }) {
429
537
  let rawTypeText = firstValue(
430
538
  sources,
431
539
  (source) => typeof source.type?.text == "string" ? source.type.text : void 0
432
- ), text = firstValue(
433
- sources,
434
- (source) => trimmedOrUndefined(readTypeText(source, typeProperty))
435
- ), parsed = parseTypeText(text) ?? (category === "attributes" ? { type: { name: "string" } } : { type: { name: "other", value: text ?? "" }, control: !1 }), readonly = firstValue(
540
+ ), text = firstValue(sources, (source) => trimmedOrUndefined(readTypeText(source))), parsed = parseTypeText(text) ?? (category === "attributes" ? { type: { name: "string" } } : { type: { name: "other", value: text ?? "" }, control: !1 }), readonly = firstValue(
436
541
  sources,
437
542
  (source) => "readonly" in source && source.readonly === !0 ? !0 : void 0
438
543
  );
@@ -445,8 +550,8 @@ function toArgType({ key, category, sources, typeProperty }) {
445
550
  }
446
551
  });
447
552
  }
448
- function eventEntries(event, typeProperty) {
449
- let text = readTypeText(event, typeProperty) ?? "CustomEvent";
553
+ function eventEntries(event) {
554
+ let text = readTypeText(event) ?? "CustomEvent";
450
555
  return [
451
556
  [
452
557
  toArgKey("events", event.name),
@@ -474,8 +579,8 @@ function namedEntry(item, category) {
474
579
  memberArgType(name, [item], NAMED_ENTRY_CATEGORIES[category], { type: { name: "string" } })
475
580
  ];
476
581
  }
477
- function cssPropertyEntry(property, typeProperty) {
478
- let syntax = readCssPropertySyntax(property, typeProperty);
582
+ function cssPropertyEntry(property) {
583
+ let syntax = readCssPropertySyntax(property);
479
584
  return [
480
585
  toArgKey("cssProperties", property.name),
481
586
  memberArgType(property.name, [property], "css custom properties", {
@@ -519,14 +624,14 @@ function cssCustomPropertyControl(syntax) {
519
624
  }
520
625
 
521
626
  // src/docgen/component-docgen/build-docgen.ts
522
- function buildDocgenPayload(input, context) {
627
+ async function buildDocgenPayload(input, context) {
523
628
  let storyImportPath = getStoryImportPathFromEntry(input.entry);
524
629
  if (!storyImportPath)
525
630
  return;
526
- let id = getComponentIdFromEntry(input.entry), path = storyImportPath, fail = (name, error) => ({
631
+ let id = getComponentIdFromEntry(input.entry), path2 = storyImportPath, fail = (name, error) => ({
527
632
  id,
528
633
  name,
529
- path,
634
+ path: path2,
530
635
  jsDocTags: {},
531
636
  error
532
637
  }), storyFilePath = resolve(process.cwd(), storyImportPath), csf = parseStoryFile(storyFilePath, input.entry.title);
@@ -537,34 +642,31 @@ function buildDocgenPayload(input, context) {
537
642
  if (resolved.reason === "no-meta-component")
538
643
  return;
539
644
  let componentName = input.entry.title.slice(input.entry.title.lastIndexOf("/") + 1);
540
- return fail(componentName, {
645
+ return resolved.reason === "unresolvable-meta-spread" ? fail(componentName, {
646
+ name: "unresolvable-meta-spread",
647
+ message: `\`meta.component\` could not be read because \`${resolved.spread}\` is not a local object literal. Set \`component: '<tag-name>'\` on the default export.`
648
+ }) : fail(componentName, {
541
649
  name: "component-not-a-tag",
542
650
  message: `\`meta.component\` must be the element's tag name as a string, got \`${resolved.expression}\``
543
651
  });
544
652
  }
545
- let { tag } = resolved, found = context.cem.tags.get(tag);
546
- if (!found)
547
- return fail(
548
- tag,
549
- context.cem.errors[0] ?? {
550
- name: "tag-not-found",
551
- message: `No declaration for "${tag}" was found in ${context.cem.paths.join(", ")}. If the element is new, rerun the custom elements manifest analyzer.`
552
- }
553
- );
653
+ let { tag } = resolved, found = await context.resolver.find(tag, { storyFilePath });
654
+ if (!("declaration" in found))
655
+ return fail(tag, found);
554
656
  let { description, summary, jsDocTags } = extractComponentDescription(
555
- extractDescription(csf._metaStatement) || void 0,
657
+ extractDescription(csf._metaStatement, csf.editor) || void 0,
556
658
  found.declaration.description,
557
659
  declarationTags(found.declaration)
558
660
  );
559
661
  return {
560
662
  id,
561
663
  name: tag,
562
- path,
664
+ path: path2,
563
665
  description,
564
666
  summary,
565
667
  jsDocTags,
566
- argTypes: mapArgTypes(found.declaration, context.typeProperty),
567
- apiDescription: buildApiDescription(found.declaration, context.typeProperty),
668
+ argTypes: mapArgTypes(found.declaration),
669
+ apiDescription: buildApiDescription(found.declaration),
568
670
  renderer: "web-components",
569
671
  ...found.warning ? { warning: found.warning } : {},
570
672
  customElementsManifest: {
@@ -583,7 +685,7 @@ function declarationTags(declaration) {
583
685
  // src/docgen/component-docgen/manifest/cem-manager.ts
584
686
  import { logger } from "storybook/internal/node-logger";
585
687
  import { stat } from "node:fs/promises";
586
- import { relative as relative2 } from "node:path";
688
+ import { relative as relative3 } from "node:path";
587
689
 
588
690
  // src/docgen/component-docgen/manifest/build-tag-index.ts
589
691
  function buildTagIndex(manifest) {
@@ -748,21 +850,21 @@ function modulePathOf(module) {
748
850
 
749
851
  // src/docgen/component-docgen/manifest/load-manifest.ts
750
852
  import { readFile } from "node:fs/promises";
751
- import { relative } from "node:path";
752
- var isFailedManifest = (result) => "error" in result, isCustomElementsManifest = (value) => isRecord(value) && Array.isArray(value.modules), unsupportedMessage = (path) => `${path} uses the web-component-analyzer manifest shape. The Storybook docgen server reads Custom Elements Manifests only; generate one with @custom-elements-manifest/analyzer.`, invalidMessage = (path, detail) => detail ? `Invalid Custom Elements Manifest at ${path}: ${detail}` : `Invalid Custom Elements Manifest at ${path}: expected a top-level modules array.`;
753
- function classifyManifest(path, parsed) {
754
- return isRecord(parsed) ? isCustomElementsManifest(parsed) ? { path, manifest: parsed } : parsed.version === "experimental" || Array.isArray(parsed.tags) ? { path, error: { name: "manifest-unsupported", message: unsupportedMessage(path) } } : { path, error: { name: "manifest-invalid", message: invalidMessage(path) } } : { path, error: { name: "manifest-invalid", message: invalidMessage(path) } };
853
+ import { relative as relative2 } from "node:path";
854
+ var isFailedManifest = (result) => "error" in result, isCustomElementsManifest = (value) => isRecord(value) && Array.isArray(value.modules), unsupportedMessage = (path2) => `${path2} uses the web-component-analyzer manifest shape. The Storybook docgen server reads Custom Elements Manifests only; generate one with @custom-elements-manifest/analyzer.`, invalidMessage = (path2, detail) => detail ? `Invalid Custom Elements Manifest at ${path2}: ${detail}` : `Invalid Custom Elements Manifest at ${path2}: expected a top-level modules array.`;
855
+ function classifyManifest(path2, parsed) {
856
+ return isRecord(parsed) ? isCustomElementsManifest(parsed) ? { path: path2, manifest: parsed } : parsed.version === "experimental" || Array.isArray(parsed.tags) ? { path: path2, error: { name: "manifest-unsupported", message: unsupportedMessage(path2) } } : { path: path2, error: { name: "manifest-invalid", message: invalidMessage(path2) } } : { path: path2, error: { name: "manifest-invalid", message: invalidMessage(path2) } };
755
857
  }
756
858
  async function loadManifest(absolutePath) {
757
- let path = relative(process.cwd(), absolutePath);
859
+ let path2 = relative2(process.cwd(), absolutePath);
758
860
  try {
759
- return classifyManifest(path, JSON.parse(await readFile(absolutePath, "utf8")));
861
+ return classifyManifest(path2, JSON.parse(await readFile(absolutePath, "utf8")));
760
862
  } catch (error) {
761
863
  return {
762
- path,
864
+ path: path2,
763
865
  error: {
764
866
  name: "manifest-invalid",
765
- message: invalidMessage(path, errorMessage(error))
867
+ message: invalidMessage(path2, errorMessage(error))
766
868
  }
767
869
  };
768
870
  }
@@ -773,9 +875,12 @@ var CemManager = class {
773
875
  constructor(absolutePaths) {
774
876
  this.states = absolutePaths.map((absolutePath) => ({
775
877
  absolutePath,
776
- path: relative2(process.cwd(), absolutePath)
878
+ path: relative3(process.cwd(), absolutePath)
777
879
  }));
778
880
  }
881
+ async find(tag) {
882
+ return findInSnapshot(await this.refresh(), tag);
883
+ }
779
884
  refresh() {
780
885
  return this.current ? (this.next ??= this.current.then(
781
886
  () => (this.next = void 0, this.refresh()),
@@ -832,8 +937,14 @@ var CemManager = class {
832
937
  state.lastWarning !== message && (state.lastWarning = message, logger.warn(message));
833
938
  }
834
939
  };
940
+ function findInSnapshot(snapshot, tag) {
941
+ return snapshot.tags.get(tag) ?? snapshot.errors[0] ?? {
942
+ name: "tag-not-found",
943
+ message: `No declaration for "${tag}" was found in ${snapshot.paths.join(", ")}. If the element is new, rerun the custom elements manifest analyzer.`
944
+ };
945
+ }
835
946
  function buildSnapshot(states) {
836
- let tags = /* @__PURE__ */ new Map(), errors = [], paths = states.map(({ path }) => path);
947
+ let tags = /* @__PURE__ */ new Map(), errors = [], paths = states.map(({ path: path2 }) => path2);
837
948
  for (let state of states) {
838
949
  if (state.entry) {
839
950
  let warning = state.error ? staleWarning(state.error) : void 0;
@@ -853,44 +964,343 @@ function buildSnapshot(states) {
853
964
  paths
854
965
  };
855
966
  }
856
- function failureFromError(path, error) {
967
+ function failureFromError(path2, error) {
857
968
  return {
858
969
  name: "manifest-invalid",
859
- message: `Invalid Custom Elements Manifest at ${path}: ${errorMessage(error)}`
970
+ message: `Invalid Custom Elements Manifest at ${path2}: ${errorMessage(error)}`
860
971
  };
861
972
  }
862
973
  function isNotFound(error) {
863
974
  return error instanceof Error && "code" in error && error.code === "ENOENT";
864
975
  }
865
- function missingManifestError(path) {
976
+ function missingManifestError(path2) {
866
977
  return {
867
978
  name: "manifest-not-found",
868
- message: `Custom Elements Manifest ${path} not found yet; docs load once the analyzer writes it`
979
+ message: `Custom Elements Manifest ${path2} not found yet; docs load once the analyzer writes it`
869
980
  };
870
981
  }
871
982
  function staleWarning(error) {
872
983
  return `${error.message}; using the last valid version`;
873
984
  }
874
985
 
986
+ // src/docgen/component-docgen/source/generator.ts
987
+ import { logger as logger2 } from "storybook/internal/node-logger";
988
+ var loadPromise;
989
+ async function loadGenerator() {
990
+ return loadPromise ??= loadGeneratorModule(), loadPromise;
991
+ }
992
+ async function loadGeneratorModule() {
993
+ let [generator, lit] = await Promise.all([
994
+ import("@wc-toolkit/cem-generator"),
995
+ import("@wc-toolkit/cem-generator-lit")
996
+ ]);
997
+ return {
998
+ generate: (tsConfigPath, files) => generator.generateCem({
999
+ tsConfigPath,
1000
+ include: files,
1001
+ plugins: [lit.litPlugin()],
1002
+ validation: {
1003
+ invariants: "warning",
1004
+ onWarning: (message) => logger2.debug(message)
1005
+ },
1006
+ modulePathResolver: { skip: !0 }
1007
+ })
1008
+ };
1009
+ }
1010
+
1011
+ // src/docgen/component-docgen/source/source-manager.ts
1012
+ import { logger as logger4 } from "storybook/internal/node-logger";
1013
+
1014
+ // src/docgen/component-docgen/source/generator-manager.ts
1015
+ import {
1016
+ ComponentMetaManager,
1017
+ parseTsconfigCommandLine
1018
+ } from "storybook/internal/component-meta";
1019
+
1020
+ // src/docgen/component-docgen/source/generator-project.ts
1021
+ import { isInNodeModules } from "storybook/internal/common";
1022
+ import {
1023
+ filterSourceFilePaths
1024
+ } from "storybook/internal/component-meta";
1025
+ import { logger as logger3 } from "storybook/internal/node-logger";
1026
+ var GeneratorProject = class {
1027
+ constructor(typescript, generator, commandLine, configFileName, getCommandLineFn) {
1028
+ this.typescript = typescript;
1029
+ this.generator = generator;
1030
+ this.commandLine = commandLine;
1031
+ this.configFileName = configFileName;
1032
+ this.getCommandLineFn = getCommandLineFn;
1033
+ this.importsByFile = /* @__PURE__ */ new Map();
1034
+ this.rootsStale = !1;
1035
+ this.revisionCount = 0;
1036
+ }
1037
+ /** Moves on every file event or new root, so callers can tell whether a cached miss is still valid. */
1038
+ get revision() {
1039
+ return this.revisionCount;
1040
+ }
1041
+ getCommandLine() {
1042
+ return this.rootsStale && this.getCommandLineFn && (this.commandLine = this.getCommandLineFn()), this.rootsStale = !1, this.commandLine;
1043
+ }
1044
+ rootFileNames() {
1045
+ return this.getCommandLine().fileNames;
1046
+ }
1047
+ hasSourceFile(fileName) {
1048
+ let normalized = normalize(fileName);
1049
+ return this.importsByFile.has(normalized) || this.rootFileNames().includes(normalized);
1050
+ }
1051
+ ensureFiles(fileNames) {
1052
+ for (let fileName of fileNames.map(normalize))
1053
+ this.commandLine.fileNames.includes(fileName) || (this.commandLine.fileNames.push(fileName), this.revisionCount++);
1054
+ }
1055
+ getSourceFilePaths() {
1056
+ return filterSourceFilePaths([
1057
+ .../* @__PURE__ */ new Set([...this.rootFileNames(), ...this.importsByFile.keys()])
1058
+ ]);
1059
+ }
1060
+ onFilesChanged(changes) {
1061
+ for (let { filePath, type } of changes) {
1062
+ if (type === "changed") {
1063
+ this.importsByFile.delete(normalize(filePath));
1064
+ continue;
1065
+ }
1066
+ this.importsByFile.clear(), this.rootsStale = !0;
1067
+ }
1068
+ this.revisionCount++;
1069
+ }
1070
+ dispose() {
1071
+ this.importsByFile.clear();
1072
+ }
1073
+ createManifestForRoots(rootPaths) {
1074
+ let roots = rootPaths.map(normalize), closure = this.importClosure(roots);
1075
+ if (closure.length === 0) {
1076
+ this.debug(`none of ${rootPaths.join(", ")} could be read`);
1077
+ return;
1078
+ }
1079
+ let tsConfigPath = this.configFileName ?? join(commonDirectory(roots), "tsconfig.json");
1080
+ return this.generator.generate(tsConfigPath, closure);
1081
+ }
1082
+ importClosure(roots) {
1083
+ let closure = /* @__PURE__ */ new Set(), queue = [...roots];
1084
+ for (; queue.length > 0; ) {
1085
+ let fileName = queue.pop();
1086
+ if (closure.has(fileName) || isInNodeModules(fileName))
1087
+ continue;
1088
+ let imports = this.importsOf(fileName);
1089
+ imports && (closure.add(fileName), queue.push(...imports));
1090
+ }
1091
+ return [...closure];
1092
+ }
1093
+ importsOf(fileName) {
1094
+ let { sys } = this.typescript, mtime = sys.getModifiedTime?.(fileName)?.valueOf(), cached = this.importsByFile.get(fileName);
1095
+ if (cached && cached.mtime === mtime)
1096
+ return cached.imports;
1097
+ let text = sys.readFile(fileName);
1098
+ if (text === void 0) {
1099
+ this.importsByFile.delete(fileName);
1100
+ return;
1101
+ }
1102
+ let { options } = this.getCommandLine(), imports = this.typescript.preProcessFile(text, !0, !0).importedFiles.flatMap(
1103
+ ({ fileName: specifier }) => this.typescript.resolveModuleName(specifier, fileName, options, sys).resolvedModule?.resolvedFileName ?? []
1104
+ ).map(normalize);
1105
+ return this.importsByFile.set(fileName, { mtime, imports }), imports;
1106
+ }
1107
+ debug(message) {
1108
+ logger3.debug(
1109
+ `[web-components-cem] ${message}${this.configFileName ? ` (${this.configFileName})` : ""}`
1110
+ );
1111
+ }
1112
+ };
1113
+ function commonDirectory(fileNames) {
1114
+ let [first, ...rest] = fileNames.map((fileName) => dirname(fileName).split("/")), length = first.length;
1115
+ for (let segments of rest) {
1116
+ let mismatch = first.slice(0, length).findIndex((segment, index) => segment !== segments[index]);
1117
+ mismatch !== -1 && (length = mismatch);
1118
+ }
1119
+ return first.slice(0, length).join("/") || "/";
1120
+ }
1121
+
1122
+ // src/docgen/component-docgen/source/generator-manager.ts
1123
+ var GeneratorManager = class extends ComponentMetaManager {
1124
+ constructor(typescript, generator) {
1125
+ super(typescript, createGeneratorProjectFactory(typescript, generator));
1126
+ }
1127
+ };
1128
+ function createGeneratorProjectFactory(typescript, generator) {
1129
+ return {
1130
+ // A JS story outside a tsconfig's files falls to the inferred project, whose generator run
1131
+ // scans the story's folder with `allowJs`; matching it to the tsconfig would hide it instead.
1132
+ parseCommandLine: (tsconfig) => parseTsconfigCommandLine(typescript, tsconfig),
1133
+ createConfiguredProject: (commandLine, tsconfig, getCommandLine) => new GeneratorProject(typescript, generator, commandLine, tsconfig, getCommandLine),
1134
+ createInferredProject: () => new GeneratorProject(
1135
+ typescript,
1136
+ generator,
1137
+ {
1138
+ options: {
1139
+ allowJs: !0,
1140
+ target: typescript.ScriptTarget.Latest,
1141
+ module: typescript.ModuleKind.ESNext,
1142
+ moduleResolution: typescript.ModuleResolutionKind.Bundler
1143
+ },
1144
+ fileNames: [],
1145
+ errors: []
1146
+ },
1147
+ void 0
1148
+ )
1149
+ };
1150
+ }
1151
+
1152
+ // src/docgen/component-docgen/source/source-manager.ts
1153
+ var SourceManager = class {
1154
+ constructor(typescript, generator, previewFilePath) {
1155
+ this.typescript = typescript;
1156
+ this.generator = generator;
1157
+ this.previewFilePath = previewFilePath;
1158
+ this.rootsByTag = /* @__PURE__ */ new WeakMap();
1159
+ this.literalMisses = /* @__PURE__ */ new WeakMap();
1160
+ /** Keyed by story file, then tag; valid until a searched project sees a file event. */
1161
+ this.misses = /* @__PURE__ */ new Map();
1162
+ this.warnedAnalysisFailures = /* @__PURE__ */ new Set();
1163
+ }
1164
+ async find(tag, lookup) {
1165
+ try {
1166
+ let manager = this.getManager(), story = normalize(lookup.storyFilePath), preview = this.previewFilePath ? normalize(this.previewFilePath) : void 0, storyProject = manager.getProjectForFile(story), previewProject = preview ? manager.getProjectForFile(preview) : void 0, projects = [.../* @__PURE__ */ new Set([storyProject, previewProject ?? storyProject])], tried = [story, ...preview ? [preview] : []], miss = this.misses.get(story)?.get(tag);
1167
+ if (miss && projects.every((project) => miss.revisions.get(project) === project.revision))
1168
+ return miss.error;
1169
+ let probes = [
1170
+ () => this.findFromRememberedRoot(tag, storyProject),
1171
+ () => this.findFromRoots(tag, [story], storyProject),
1172
+ () => preview && previewProject ? this.findFromRoots(tag, [preview], previewProject) : void 0,
1173
+ ...projects.map((project) => () => this.findFromTagLiteral(tag, project, tried))
1174
+ ];
1175
+ for (let probe of probes) {
1176
+ let found = probe();
1177
+ if (found)
1178
+ return found;
1179
+ }
1180
+ let error = tagNotFound(tag, story, preview, projects), storyMisses = this.misses.get(story) ?? /* @__PURE__ */ new Map();
1181
+ return storyMisses.set(tag, {
1182
+ error,
1183
+ revisions: new Map(projects.map((project) => [project, project.revision]))
1184
+ }), this.misses.set(story, storyMisses), error;
1185
+ } catch (error) {
1186
+ let message = `Failed to analyze sources for "${tag}": ${errorMessage(error)}`;
1187
+ return this.warnOnce(message), { name: "source-analysis-failed", message };
1188
+ }
1189
+ }
1190
+ dispose() {
1191
+ this.manager?.dispose(), this.manager = void 0;
1192
+ }
1193
+ getManager() {
1194
+ return this.manager || (this.manager = new GeneratorManager(this.typescript, this.generator), this.manager.startWatching()), this.manager;
1195
+ }
1196
+ findFromRememberedRoot(tag, project) {
1197
+ let root = this.rootsByTag.get(project)?.get(tag);
1198
+ if (!root)
1199
+ return;
1200
+ let found = this.findFromRoots(tag, [root], project);
1201
+ return found || this.rootsByTag.get(project)?.delete(tag), found;
1202
+ }
1203
+ findFromTagLiteral(tag, project, tried) {
1204
+ let misses = this.literalMisses.get(project) ?? /* @__PURE__ */ new Map();
1205
+ if (this.literalMisses.set(project, misses), misses.get(tag) === project.revision)
1206
+ return;
1207
+ let pattern = tagLiteralPattern(tag), candidates = project.rootFileNames().filter(
1208
+ (fileName) => !tried.includes(fileName) && pattern.test(this.typescript.sys.readFile(fileName) ?? "")
1209
+ ), found = candidates.length > 0 ? this.findFromRoots(tag, candidates, project) : void 0;
1210
+ return found || misses.set(tag, project.revision), found;
1211
+ }
1212
+ findFromRoots(tag, roots, project) {
1213
+ let manifest = project.createManifestForRoots(roots), found = manifest ? cemTagFromManifest(tag, manifest) : void 0;
1214
+ if (!found)
1215
+ return;
1216
+ let projectRoots = this.rootsByTag.get(project) ?? /* @__PURE__ */ new Map();
1217
+ return projectRoots.set(tag, found.rootPath), this.rootsByTag.set(project, projectRoots), { declaration: found.declaration, manifestPath: found.manifestPath };
1218
+ }
1219
+ warnOnce(message) {
1220
+ this.warnedAnalysisFailures.has(message) || (this.warnedAnalysisFailures.add(message), logger4.warn(message));
1221
+ }
1222
+ };
1223
+ function cemTagFromManifest(tag, manifest) {
1224
+ let flattened = flattenInheritance(manifest), declaration = buildTagIndex(flattened).get(tag);
1225
+ if (!declaration)
1226
+ return;
1227
+ let modulePath = declarationModulePath(flattened, declaration), rootPath = definitionModulePath(flattened, tag) ?? modulePath;
1228
+ if (rootPath)
1229
+ return {
1230
+ declaration,
1231
+ manifestPath: modulePath ? cwdRelative(modulePath) : "",
1232
+ rootPath
1233
+ };
1234
+ }
1235
+ function definitionModulePath(manifest, tag) {
1236
+ for (let module of manifest.modules)
1237
+ if (module.exports?.some(
1238
+ (candidate) => candidate.kind === "custom-element-definition" && candidate.name === tag
1239
+ ) && typeof module.path == "string")
1240
+ return normalize(module.path);
1241
+ }
1242
+ function declarationModulePath(manifest, declaration) {
1243
+ for (let module of manifest.modules)
1244
+ if (Array.isArray(module.declarations) && module.declarations.includes(declaration))
1245
+ return typeof module.path == "string" ? normalize(module.path) : void 0;
1246
+ }
1247
+ function cwdRelative(path2) {
1248
+ return isAbsolute(path2) ? relative(process.cwd(), path2) : normalize(path2);
1249
+ }
1250
+ function tagLiteralPattern(tag) {
1251
+ let escaped = tag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1252
+ return new RegExp(`(['"\`])${escaped}\\1`);
1253
+ }
1254
+ function tagNotFound(tag, storyFilePath, previewFilePath, projects) {
1255
+ let searched = projects.map(
1256
+ (project) => project.configFileName ? cwdRelative(project.configFileName) : "the inferred TypeScript project"
1257
+ ), preview = previewFilePath ? ` and preview file ${cwdRelative(previewFilePath)}` : "";
1258
+ return {
1259
+ name: "tag-not-found",
1260
+ message: `No declaration for "${tag}" was found from story file ${cwdRelative(storyFilePath)}${preview}. Searched the tsconfig files covering those files: ${searched.join(", ") || "none"}. Import the element module in the story or configure customElementsManifest.`
1261
+ };
1262
+ }
1263
+
1264
+ // src/docgen/component-docgen/tag-resolver.ts
1265
+ function firstMatch([first, ...rest]) {
1266
+ return {
1267
+ async find(tag, lookup) {
1268
+ let result = await first.find(tag, lookup);
1269
+ for (let resolver of rest) {
1270
+ if ("declaration" in result)
1271
+ break;
1272
+ result = await resolver.find(tag, lookup);
1273
+ }
1274
+ return result;
1275
+ }
1276
+ };
1277
+ }
1278
+
875
1279
  // src/docgen/docgen-worker.ts
876
1280
  var createDocgenProvider = ({
877
1281
  manifestPaths,
878
- typeProperty
1282
+ previewFilePath
879
1283
  }) => createLazyDocgenMiddleware({
880
1284
  createManager: async () => {
881
- if (manifestPaths.length === 0) {
882
- logger2.warn(
883
- "No Custom Elements Manifest was configured; web-components server docgen is skipped. Set the `customElementsManifest` framework option or `customElements` in package.json."
884
- );
885
- return;
886
- }
887
- return new CemManager(manifestPaths);
1285
+ let sources = await loadSourceManager(previewFilePath), [first, ...rest] = [
1286
+ ...manifestPaths.length > 0 ? [new CemManager(manifestPaths)] : [],
1287
+ ...sources ? [sources] : []
1288
+ ];
1289
+ return first ? firstMatch([first, ...rest]) : void 0;
888
1290
  },
889
- extract: async (manager, input) => buildDocgenPayload(input, {
890
- cem: await manager.refresh(),
891
- typeProperty
892
- })
1291
+ extract: async (resolver, input) => buildDocgenPayload(input, { resolver })
893
1292
  });
1293
+ async function loadSourceManager(previewFilePath) {
1294
+ try {
1295
+ let [typescript, generator] = await Promise.all([import("typescript"), loadGenerator()]);
1296
+ return new SourceManager(typescript.default ?? typescript, generator, previewFilePath);
1297
+ } catch (error) {
1298
+ logger5.warn(
1299
+ `Web components docgen cannot generate declarations from sources: ${errorMessage(error)}`
1300
+ );
1301
+ return;
1302
+ }
1303
+ }
894
1304
 
895
1305
  export {
896
1306
  buildDocgenPayload,