@vx-oss/docs-story 1.0.6 → 1.0.7

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,7 +1,7 @@
1
1
  "use client";
2
2
  import { cn } from "../utils/cn.js";
3
3
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./components/select.js";
4
- import { ErrorBoundary as m } from "../node_modules/.pnpm/react-error-boundary@6.1.3_@types_react@19.2.18_react@19.2.8/node_modules/react-error-boundary/dist/react-error-boundary.js";
4
+ import { ErrorBoundary as m } from "../node_modules/.pnpm/react-error-boundary@6.1.4_@types_react@19.2.18_react@19.2.8/node_modules/react-error-boundary/dist/react-error-boundary.js";
5
5
  import { FieldSet } from "./arg-form.js";
6
6
  import { jsx, jsxs } from "react/jsx-runtime";
7
7
  import { Suspense, createElement, useDeferredValue, useRef, useState } from "react";
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.pnpm/@ungap+structured-clone@1.3.4/node_modules/@ungap/structured-clone/esm/deserialize.js
1
+ //#region ../../node_modules/.pnpm/@ungap+structured-clone@1.4.0/node_modules/@ungap/structured-clone/esm/deserialize.js
2
2
  const { defineProperty } = Object;
3
3
  const env = typeof self === "object" ? self : globalThis;
4
4
  const guard = (name, init) => {
@@ -68,6 +68,7 @@ const deserializer = ($, _) => {
68
68
  const { buffer } = new Uint8Array(value);
69
69
  return as(new DataView(buffer), value);
70
70
  }
71
+ case "-0": return -0;
71
72
  }
72
73
  return as(guard(type, value), index);
73
74
  };
@@ -1,6 +1,6 @@
1
1
  import { deserialize } from "./deserialize.js";
2
2
  import { serialize } from "./serialize.js";
3
- //#region ../../node_modules/.pnpm/@ungap+structured-clone@1.3.4/node_modules/@ungap/structured-clone/esm/json.js
3
+ //#region ../../node_modules/.pnpm/@ungap+structured-clone@1.4.0/node_modules/@ungap/structured-clone/esm/json.js
4
4
  /*! (c) Andrea Giammarchi - ISC */
5
5
  const { parse: $parse, stringify: $stringify } = JSON;
6
6
  const options = {
@@ -1,7 +1,7 @@
1
- //#region ../../node_modules/.pnpm/@ungap+structured-clone@1.3.4/node_modules/@ungap/structured-clone/esm/serialize.js
1
+ //#region ../../node_modules/.pnpm/@ungap+structured-clone@1.4.0/node_modules/@ungap/structured-clone/esm/serialize.js
2
2
  const EMPTY = "";
3
3
  const { toString } = {};
4
- const { keys } = Object;
4
+ const { keys, is } = Object;
5
5
  const typeOf = (value) => {
6
6
  const type = typeof value;
7
7
  if (type !== "object" || !value) return [0, type];
@@ -37,6 +37,9 @@ const serializer = (strict, json, $, _) => {
37
37
  TYPE = 8;
38
38
  entry = value.toString();
39
39
  break;
40
+ case "number":
41
+ if (!value && is(value, -0)) return _.push(["-0"]) - 1;
42
+ break;
40
43
  case "function":
41
44
  case "symbol":
42
45
  if (strict) throw new TypeError("unable to serialize " + type);
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { Component, createContext, createElement } from "react";
3
- //#region ../../node_modules/.pnpm/react-error-boundary@6.1.3_@types+react@19.2.18_react@19.2.8/node_modules/react-error-boundary/dist/react-error-boundary.js
3
+ //#region ../../node_modules/.pnpm/react-error-boundary@6.1.4_@types+react@19.2.18_react@19.2.8/node_modules/react-error-boundary/dist/react-error-boundary.js
4
4
  const h = createContext(null);
5
5
  const c = {
6
6
  didCatch: !1,
@@ -17,8 +17,8 @@ var m = class extends Component {
17
17
  };
18
18
  }
19
19
  resetErrorBoundary(...e) {
20
- const { error: t } = this.state;
21
- t !== null && (this.props.onReset?.({
20
+ const { didCatch: t } = this.state;
21
+ t && (this.props.onReset?.({
22
22
  args: e,
23
23
  reason: "imperative-api"
24
24
  }), this.setState(c));
@@ -28,7 +28,7 @@ var m = class extends Component {
28
28
  }
29
29
  componentDidUpdate(e, t) {
30
30
  const { didCatch: o } = this.state, { resetKeys: s } = this.props;
31
- o && t.error !== null && C(e.resetKeys, s) && (this.props.onReset?.({
31
+ o && t.didCatch && C(e.resetKeys, s) && (this.props.onReset?.({
32
32
  next: s,
33
33
  prev: e.resetKeys,
34
34
  reason: "keys"
@@ -1,5 +1,6 @@
1
1
  import { TypeNode, UnionNode } from "./types.js";
2
- import { Node, Project, Type } from "ts-morph";
2
+ import { Project, Type } from "typescript/unstable/sync";
3
+ import { Node } from "typescript/unstable/ast";
3
4
  //#region src/type-tree/builder.d.ts
4
5
  declare enum TypeToNodeFlag {
5
6
  None = 0,
@@ -13,6 +14,9 @@ type Handler = (options: {
13
14
  location: Node;
14
15
  flag: TypeToNodeFlag;
15
16
  builder: TypeTreeBuilder;
17
+ /**
18
+ * The TypeScript project (from `typescript/unstable/sync`) of the type, use `project.checker` for type checking.
19
+ */
16
20
  project: Project;
17
21
  cache: Map<TypeToNodeFlag, WeakMap<Type, TypeNode>>;
18
22
  getCache: () => TypeNode | undefined;
@@ -1,34 +1,56 @@
1
1
  import { validate } from "./validator.js";
2
- import { Node, ts } from "ts-morph";
2
+ import { NodeBuilderFlags, SignatureKind, SymbolFlags, TypeFlags, isBigIntLiteralType, isBooleanLiteralType, isIntersectionType, isLiteralType, isObjectType, isTypeReference, isUnionType } from "typescript/unstable/sync";
3
+ import { SyntaxKind, isEnumDeclaration, isNumericLiteral, isStringLiteral } from "typescript/unstable/ast";
3
4
  //#region src/type-tree/builder.ts
4
5
  let TypeToNodeFlag = /* @__PURE__ */ function(TypeToNodeFlag) {
5
6
  TypeToNodeFlag[TypeToNodeFlag["None"] = 0] = "None";
6
7
  TypeToNodeFlag[TypeToNodeFlag["NoIntersection"] = 1] = "NoIntersection";
7
8
  return TypeToNodeFlag;
8
9
  }({});
9
- const baseHandler = ({ type, flag, location, setCache, root }) => {
10
- if (type.isString()) return { type: "string" };
11
- if (type.isNumber()) return { type: "number" };
12
- if (type.isBoolean()) return { type: "boolean" };
13
- if (type.isBigInt()) return { type: "bigint" };
10
+ /**
11
+ * Private class members (`#name`) are exposed with their escaped name (`__#1@#name`) by TypeScript.
12
+ */
13
+ function isPrivateName(name) {
14
+ return name.startsWith("#") || name.startsWith("__#");
15
+ }
16
+ function getLiteralValue(checker, type) {
17
+ if (isBooleanLiteralType(type)) return typeof type.value === "boolean" ? type.value : checker.typeToString(type) === "true";
18
+ if (isBigIntLiteralType(type)) {
19
+ const value = type.value;
20
+ if (typeof value === "bigint") return value;
21
+ if (typeof value === "object" && value !== null && "base10Value" in value) {
22
+ const { negative, base10Value } = value;
23
+ return BigInt(`${negative ? "-" : ""}${base10Value}`);
24
+ }
25
+ return BigInt(value);
26
+ }
27
+ return type.value ?? checker.typeToString(type);
28
+ }
29
+ const baseHandler = ({ type, flag, location, project, setCache, root }) => {
30
+ const { checker } = project;
31
+ const { flags } = type;
32
+ if (flags & TypeFlags.String) return { type: "string" };
33
+ if (flags & TypeFlags.Number) return { type: "number" };
34
+ if (flags & TypeFlags.Boolean) return { type: "boolean" };
35
+ if (flags & TypeFlags.BigInt) return { type: "bigint" };
14
36
  const symbol = type.getSymbol();
15
- if (symbol && symbol.getName() === "Date") return { type: "date" };
16
- if (type.isUndefined()) return { type: "undefined" };
17
- if (type.isUnknown()) return { type: "unknown" };
18
- if (type.isNull()) return { type: "null" };
19
- if (type.isNever() || type.getCallSignatures().length > 0) return { type: "never" };
20
- if (type.isUnion()) {
37
+ if (symbol && symbol.name === "Date") return { type: "date" };
38
+ if (flags & TypeFlags.Undefined) return { type: "undefined" };
39
+ if (flags & TypeFlags.Unknown) return { type: "unknown" };
40
+ if (flags & TypeFlags.Null) return { type: "null" };
41
+ if (flags & TypeFlags.Never || checker.getSignaturesOfType(type, SignatureKind.Call).length > 0) return { type: "never" };
42
+ if (isUnionType(type)) {
21
43
  const result = {
22
44
  type: "union",
23
45
  types: []
24
46
  };
25
47
  setCache(result);
26
- for (const t of type.getUnionTypes()) result.types.push(root(t, flag));
48
+ for (const t of type.getTypes()) result.types.push(root(t, flag));
27
49
  Object.assign(result, unwrapUnion(result));
28
50
  return result;
29
51
  }
30
- if (type.isIntersection() && (flag & 1) === 0) {
31
- const intersectionTypes = type.getIntersectionTypes();
52
+ if (isIntersectionType(type) && (flag & 1) === 0) {
53
+ const intersectionTypes = type.getTypes();
32
54
  const result = {
33
55
  type: "intersection",
34
56
  members: [],
@@ -42,18 +64,12 @@ const baseHandler = ({ type, flag, location, setCache, root }) => {
42
64
  }
43
65
  return result;
44
66
  }
45
- if (type.isLiteral()) {
46
- let value;
47
- if (type.isBooleanLiteral()) value = type.getText() === "true";
48
- else if (type.isBigIntLiteral()) value = BigInt(type.getLiteralValue().base10Value);
49
- else value = type.getLiteralValue();
50
- return {
51
- type: "literal",
52
- value
53
- };
54
- }
55
- if (type.isArray() || type.isReadonlyArray()) {
56
- const elementType = type.getArrayElementType();
67
+ if (isLiteralType(type)) return {
68
+ type: "literal",
69
+ value: getLiteralValue(checker, type)
70
+ };
71
+ if (checker.isArrayType(type)) {
72
+ const elementType = isTypeReference(type) ? checker.getTypeArguments(type)[0] : void 0;
57
73
  const result = {
58
74
  type: "array",
59
75
  elementType: { type: "never" }
@@ -62,8 +78,8 @@ const baseHandler = ({ type, flag, location, setCache, root }) => {
62
78
  result.elementType = elementType ? root(elementType, flag) : { type: "unknown" };
63
79
  return result;
64
80
  }
65
- if (type.isTuple()) {
66
- const elements = type.getTupleElements();
81
+ if (checker.isTupleType(type)) {
82
+ const elements = isTypeReference(type) ? checker.getTypeArguments(type) : [];
67
83
  if (elements.length === 0) return {
68
84
  type: "array",
69
85
  elementType: { type: "unknown" }
@@ -79,20 +95,19 @@ const baseHandler = ({ type, flag, location, setCache, root }) => {
79
95
  });
80
96
  return result;
81
97
  }
82
- const enumSymbol = type.getSymbol();
83
- if (enumSymbol && enumSymbol.getFlags() & ts.SymbolFlags.Enum) {
84
- const enumDeclaration = enumSymbol.getValueDeclaration();
85
- if (enumDeclaration && Node.isEnumDeclaration(enumDeclaration)) return {
98
+ if (symbol && symbol.flags & SymbolFlags.Enum) {
99
+ const enumDeclaration = symbol.valueDeclaration?.resolve(project);
100
+ if (enumDeclaration && isEnumDeclaration(enumDeclaration)) return {
86
101
  type: "enum",
87
- members: enumDeclaration.getMembers().map((member) => {
88
- const name = member.getName();
89
- const initializer = member.getInitializer();
102
+ members: enumDeclaration.members.map((member) => {
103
+ const name = member.name.getText();
104
+ const initializer = member.initializer;
90
105
  let value = name;
91
106
  if (initializer) {
92
- if (Node.isStringLiteral(initializer)) value = initializer.getText().slice(1, -1);
93
- else if (Node.isNumericLiteral(initializer)) value = Number.parseFloat(initializer.getText());
94
- else if (Node.isTrueLiteral(initializer)) value = true;
95
- else if (Node.isFalseLiteral(initializer)) value = false;
107
+ if (isStringLiteral(initializer)) value = initializer.getText().slice(1, -1);
108
+ else if (isNumericLiteral(initializer)) value = Number.parseFloat(initializer.getText());
109
+ else if (initializer.kind === SyntaxKind.TrueKeyword) value = true;
110
+ else if (initializer.kind === SyntaxKind.FalseKeyword) value = false;
96
111
  }
97
112
  return {
98
113
  label: name,
@@ -101,35 +116,35 @@ const baseHandler = ({ type, flag, location, setCache, root }) => {
101
116
  })
102
117
  };
103
118
  }
104
- if (type.isObject() || type.isClassOrInterface() || type.getProperties().length > 0) {
105
- const properties = type.getProperties();
119
+ const properties = checker.getPropertiesOfType(type);
120
+ if (isObjectType(type) || properties.length > 0) {
106
121
  const alias = type.getAliasSymbol();
107
122
  const aliasTypeArguments = type.getAliasTypeArguments();
108
123
  const result = {
109
124
  type: "object",
110
- displayName: alias && aliasTypeArguments.length === 0 ? alias.getName() : void 0,
125
+ displayName: alias && aliasTypeArguments.length === 0 ? alias.name : void 0,
111
126
  properties: []
112
127
  };
113
128
  setCache(result);
114
129
  for (const prop of properties) {
115
- if (prop.getName().startsWith("#")) continue;
116
- let child = root(prop.getTypeAtLocation(location), flag, prop.getValueDeclaration());
130
+ if (isPrivateName(prop.name)) continue;
131
+ let child = root(checker.getTypeOfSymbolAtLocation(prop, location), flag, prop.valueDeclaration?.resolve(project));
117
132
  if (child.type === "union") child = unwrapUnion({
118
133
  ...child,
119
134
  types: child.types.filter((t) => t.type !== "undefined")
120
135
  });
121
136
  else if (child.type === "undefined") continue;
122
137
  if (child.type !== "never") result.properties.push({
123
- name: prop.getName(),
138
+ name: prop.name,
124
139
  type: child,
125
- required: !prop.isOptional()
140
+ required: (prop.flags & SymbolFlags.Optional) === 0
126
141
  });
127
142
  }
128
143
  return result;
129
144
  }
130
145
  return {
131
146
  type: "never",
132
- displayName: type.getText(location, ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope)
147
+ displayName: checker.typeToString(type, location, NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope)
133
148
  };
134
149
  };
135
150
  const literalEnumHandler = ({ type, flag, next }) => {
package/dist/utils/cn.js CHANGED
@@ -1,2 +1,2 @@
1
- import { cn } from "cnfast";
1
+ import { cn } from "cn";
2
2
  export { cn };
@@ -1,24 +1,37 @@
1
1
  import { createTypeTreeBuilder, literalEnumHandler } from "../type-tree/builder.js";
2
+ import { createProject } from "./project.js";
2
3
  //#region src/utils/generate.ts
3
4
  async function createControlsProject(tsconfigPath) {
4
- const { Project } = await import("ts-morph");
5
- return new Project({
6
- tsConfigFilePath: tsconfigPath,
7
- skipAddingFilesFromTsConfig: true
8
- });
5
+ return createProject(tsconfigPath);
9
6
  }
7
+ /**
8
+ * The type alias declaration to append to story files, for resolving the props of a story.
9
+ */
10
+ function getControlsAlias(mode, exportName) {
11
+ const name = `_StoryProps_${exportName}_`;
12
+ return {
13
+ name,
14
+ code: `export type ${name} = import('${mode}').GetProps<typeof ${exportName}>;`
15
+ };
16
+ }
17
+ /**
18
+ * Generate controls for an exported story.
19
+ *
20
+ * @param content - content of the story file, the alias declaration of `getControlsAlias()` is appended when missing.
21
+ */
10
22
  function generateControls(mode, project, filePath, exportName, content) {
11
- const aliasName = `_StoryProps_${exportName}_`;
12
- const sourceFile = project.getSourceFile(filePath) ?? project.createSourceFile(filePath, content, { overwrite: true });
13
- if (!sourceFile.getTypeAlias(aliasName)) sourceFile.addTypeAlias({
14
- isExported: true,
15
- name: aliasName,
16
- type: `import('${mode}').GetProps<typeof ${exportName}>`
17
- });
18
- const declarations = sourceFile.getExportedDeclarations();
19
- const declaration = declarations.get(aliasName)?.[0];
20
- if (!declaration || !declarations.get(exportName)) throw new Error(`Export "${exportName}" not found in file "${filePath}"`);
21
- return createTypeTreeBuilder(project, [literalEnumHandler]).typeToNode(declaration.getType(), declaration);
23
+ const alias = getControlsAlias(mode, exportName);
24
+ if (!content.includes(alias.code)) content = `${content}\n${alias.code}`;
25
+ const loaded = project.getSourceFile(filePath, content);
26
+ if (!loaded) throw new Error(`Failed to load "${filePath}" into TypeScript project`);
27
+ const { project: tsProject, sourceFile } = loaded;
28
+ const { checker } = tsProject;
29
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
30
+ const exports = moduleSymbol ? checker.getExportsOfModule(moduleSymbol) : [];
31
+ const declaration = exports.find((symbol) => symbol.name === alias.name)?.declarations[0]?.resolve(tsProject);
32
+ const type = declaration ? checker.getTypeAtLocation(declaration) : void 0;
33
+ if (!declaration || !type || !exports.some((symbol) => symbol.name === exportName)) throw new Error(`Export "${exportName}" not found in file "${filePath}"`);
34
+ return createTypeTreeBuilder(tsProject, [literalEnumHandler]).typeToNode(type, declaration);
22
35
  }
23
36
  //#endregion
24
- export { createControlsProject, generateControls };
37
+ export { createControlsProject, generateControls, getControlsAlias };
@@ -1,18 +1,29 @@
1
- import { Node, SyntaxKind } from "ts-morph";
1
+ import { SymbolFlags } from "typescript/unstable/sync";
2
+ import { isCallExpression, isVariableDeclaration } from "typescript/unstable/ast";
2
3
  //#region src/utils/parse.ts
3
4
  function isDefineStoryCall(text) {
4
5
  return text === "defineStory" || text.endsWith(".defineStory");
5
6
  }
6
- function findDefineStoryCalls(sourceFile) {
7
+ /**
8
+ * Find `defineStory()` calls exported from the source file.
9
+ */
10
+ function findDefineStoryCalls(project, sourceFile) {
11
+ const { checker } = project;
7
12
  const stories = [];
8
- for (const [exportName, declarations] of sourceFile.getExportedDeclarations()) for (const decl of declarations) {
9
- if (!Node.isVariableDeclaration(decl)) continue;
10
- const call = decl.getInitializer();
11
- if (!call || !call.isKind(SyntaxKind.CallExpression) || !isDefineStoryCall(call.getExpression().getText())) continue;
12
- stories.push({
13
- call,
14
- exportName
15
- });
13
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
14
+ if (!moduleSymbol) return stories;
15
+ for (const exported of checker.getExportsOfModule(moduleSymbol)) {
16
+ const symbol = (exported.flags & SymbolFlags.Alias) !== 0 ? checker.getAliasedSymbol(exported) : exported;
17
+ for (const handle of symbol.declarations) {
18
+ const decl = handle.resolve(project);
19
+ if (!decl || !isVariableDeclaration(decl) || decl.getSourceFile() !== sourceFile) continue;
20
+ const call = decl.initializer;
21
+ if (!call || !isCallExpression(call) || !isDefineStoryCall(call.expression.getText())) continue;
22
+ stories.push({
23
+ call,
24
+ exportName: exported.name
25
+ });
26
+ }
16
27
  }
17
28
  return stories;
18
29
  }
@@ -0,0 +1,85 @@
1
+ import { API } from "typescript/unstable/sync";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ //#region src/utils/project.ts
5
+ function normalizePath(p) {
6
+ let out = path.resolve(p).replaceAll("\\", "/");
7
+ if (process.platform === "win32" && /^[A-Z]:/.test(out)) out = out[0].toLowerCase() + out.slice(1);
8
+ return out;
9
+ }
10
+ function readDiskFile(filePath) {
11
+ try {
12
+ return fs.readFileSync(filePath, "utf-8");
13
+ } catch {
14
+ return;
15
+ }
16
+ }
17
+ function createProject(tsconfigPath) {
18
+ tsconfigPath = normalizePath(tsconfigPath);
19
+ if (!fs.existsSync(tsconfigPath)) throw new Error(`tsconfig file not found: ${tsconfigPath}`);
20
+ const dir = path.posix.dirname(tsconfigPath);
21
+ /** in-memory files, overriding the file system */
22
+ const virtualFiles = /* @__PURE__ */ new Map();
23
+ /** root files of the generated tsconfig */
24
+ const rootFiles = /* @__PURE__ */ new Set();
25
+ let snapshot;
26
+ let configPath = `${dir}/tsconfig.fumadocs-story.json`;
27
+ for (let i = 0; fs.existsSync(configPath); i++) configPath = `${dir}/tsconfig.fumadocs-story.${i}.json`;
28
+ function writeConfig() {
29
+ virtualFiles.set(configPath, JSON.stringify({
30
+ extends: `./${path.posix.basename(tsconfigPath)}`,
31
+ include: [],
32
+ files: Array.from(rootFiles)
33
+ }));
34
+ }
35
+ const api = new API({
36
+ cwd: dir,
37
+ fs: { readFile: (fileName) => virtualFiles.get(normalizePath(fileName)) }
38
+ });
39
+ return {
40
+ api,
41
+ tsconfigPath,
42
+ getSourceFile(filePath, content) {
43
+ const key = normalizePath(filePath);
44
+ const changed = [];
45
+ const created = [];
46
+ if (content !== void 0) {
47
+ const current = virtualFiles.has(key) ? virtualFiles.get(key) : readDiskFile(key);
48
+ if (current !== content) {
49
+ virtualFiles.set(key, content);
50
+ if (current !== void 0) changed.push(key);
51
+ else created.push(key);
52
+ }
53
+ }
54
+ if (!rootFiles.has(key)) {
55
+ rootFiles.add(key);
56
+ writeConfig();
57
+ changed.push(configPath);
58
+ }
59
+ if (!snapshot) snapshot = api.updateSnapshot({ openProjects: [configPath] });
60
+ else if (changed.length > 0 || created.length > 0) {
61
+ const prev = snapshot;
62
+ snapshot = api.updateSnapshot({ fileChanges: {
63
+ changed: changed.length > 0 ? changed : void 0,
64
+ created: created.length > 0 ? created : void 0
65
+ } });
66
+ prev.dispose();
67
+ }
68
+ const project = snapshot.getProject(configPath);
69
+ if (!project) return;
70
+ const sourceFile = project.program.getSourceFile(key);
71
+ if (!sourceFile) return;
72
+ return {
73
+ project,
74
+ sourceFile
75
+ };
76
+ },
77
+ close() {
78
+ snapshot?.dispose();
79
+ snapshot = void 0;
80
+ api.close();
81
+ }
82
+ };
83
+ }
84
+ //#endregion
85
+ export { createProject };
@@ -1,4 +1,4 @@
1
- import { parse, stringify } from "../node_modules/.pnpm/@ungap_structured-clone@1.3.4/node_modules/@ungap/structured-clone/esm/json.js";
1
+ import { parse, stringify } from "../node_modules/.pnpm/@ungap_structured-clone@1.4.0/node_modules/@ungap/structured-clone/esm/json.js";
2
2
  //#region src/utils/serialization.ts
3
3
  function serialize(value) {
4
4
  return stringify(value);
@@ -1,27 +1,60 @@
1
1
  import { serialize } from "./serialization.js";
2
- import { generateControls } from "./generate.js";
2
+ import { generateControls, getControlsAlias } from "./generate.js";
3
3
  import { findDefineStoryCalls } from "./parse.js";
4
- import { SyntaxKind } from "ts-morph";
4
+ import { isObjectLiteralExpression, isPropertyAssignment } from "typescript/unstable/ast";
5
5
  //#region src/utils/transform.ts
6
- function injectControls(parsed, controls) {
7
- const [optionsArg] = parsed.call.getArguments();
8
- if (optionsArg.getKind() !== SyntaxKind.ObjectLiteralExpression) throw new Error("defineStory() options must be an object literal to inject controls from @vx-oss/docs-story.");
9
- const object = optionsArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
10
- object.getProperty("_generated")?.remove();
11
- object.addPropertyAssignment({
12
- name: "_generated",
13
- initializer: `{ exportName: ${JSON.stringify(parsed.exportName)}, controls: ${JSON.stringify(serialize(controls))} }`
14
- });
6
+ function getPropertyName(name) {
7
+ return /^['"`]/.test(name) ? name.slice(1, -1) : name;
8
+ }
9
+ /**
10
+ * Create the edits to inject `_generated` into the options object literal
11
+ */
12
+ function injectControls(sourceFile, object, exportName, controls) {
13
+ const initializer = `{ exportName: ${JSON.stringify(exportName)}, controls: ${JSON.stringify(serialize(controls))} }`;
14
+ const existing = object.properties.find((prop) => isPropertyAssignment(prop) && getPropertyName(prop.name.getText(sourceFile)) === "_generated");
15
+ if (existing) return {
16
+ start: existing.getStart(sourceFile),
17
+ end: existing.getEnd(),
18
+ text: `_generated: ${initializer}`
19
+ };
20
+ const last = object.properties.at(-1);
21
+ if (!last) {
22
+ const start = object.getStart(sourceFile) + 1;
23
+ return {
24
+ start,
25
+ end: start,
26
+ text: ` _generated: ${initializer} `
27
+ };
28
+ }
29
+ const lastStart = last.getStart(sourceFile);
30
+ const lineStart = sourceFile.text.lastIndexOf("\n", lastStart) + 1;
31
+ const indent = /^\s*/.exec(sourceFile.text.slice(lineStart, lastStart))?.[0] ?? "";
32
+ return {
33
+ start: last.getEnd(),
34
+ end: last.getEnd(),
35
+ text: `,\n${indent}_generated: ${initializer}`
36
+ };
37
+ }
38
+ function applyEdits(code, edits) {
39
+ let out = code;
40
+ for (const edit of edits.toSorted((a, b) => b.start - a.start)) out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
41
+ return out;
15
42
  }
16
43
  function transformStoryFile(mode, code, id, project) {
17
- const sourceFile = project.createSourceFile(id, code, { overwrite: true });
18
- const calls = findDefineStoryCalls(sourceFile);
44
+ const loaded = project.getSourceFile(id, code);
45
+ if (!loaded) throw new Error(`Failed to load "${id}" into TypeScript project`);
46
+ const calls = findDefineStoryCalls(loaded.project, loaded.sourceFile).filter((parsed) => parsed.call.arguments.length === 1);
19
47
  if (calls.length === 0) return;
48
+ const aliases = calls.map((parsed) => getControlsAlias(mode, parsed.exportName)).filter((alias) => !code.includes(alias.code));
49
+ const content = [code, ...aliases.map((alias) => alias.code)].join("\n");
50
+ const edits = [];
20
51
  for (const parsed of calls) {
21
- if (parsed.call.getArguments().length !== 1) continue;
22
- injectControls(parsed, generateControls(mode, project, id, parsed.exportName, code));
52
+ const [optionsArg] = parsed.call.arguments;
53
+ if (!isObjectLiteralExpression(optionsArg)) throw new Error("defineStory() options must be an object literal to inject controls from @vx-oss/docs-story.");
54
+ const controls = generateControls(mode, project, id, parsed.exportName, content);
55
+ edits.push(injectControls(loaded.sourceFile, optionsArg, parsed.exportName, controls));
23
56
  }
24
- return sourceFile.getFullText();
57
+ return [applyEdits(code, edits), ...aliases.map((alias) => alias.code)].join("\n");
25
58
  }
26
59
  //#endregion
27
60
  export { transformStoryFile };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vx-oss/docs-story",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "Story integration to Fumadocs.",
5
5
  "keywords": [],
6
6
  "license": "MIT",
@@ -34,38 +34,39 @@
34
34
  "@base-ui/react": "^1.7.0",
35
35
  "@fuma-translate/react": "^1.0.2",
36
36
  "class-variance-authority": "^0.7.1",
37
- "cnfast": "^0.1.0",
38
- "lucide-react": "^1.34.0",
37
+ "cn": "^0.2.4",
38
+ "lucide-react": "^1.39.0",
39
+ "typescript": "~7.0.2",
39
40
  "ts-morph": "^28.0.0",
40
- "@vx-oss/docs-stf": "1.0.6"
41
+ "@vx-oss/docs-stf": "1.0.7"
41
42
  },
42
43
  "devDependencies": {
43
44
  "@fastify/deepmerge": "^3.2.1",
44
- "@types/node": "26.3.0",
45
+ "@types/node": "26.4.1",
45
46
  "@types/react": "^19.2.18",
46
47
  "@types/ungap__structured-clone": "^1.2.0",
47
- "@ungap/structured-clone": "^1.3.4",
48
- "next": "^16.3.3",
48
+ "@ungap/structured-clone": "^1.4.0",
49
+ "next": "^16.3.4",
49
50
  "react": "^19.2.8",
50
51
  "react-dom": "^19.2.8",
51
- "react-error-boundary": "^6.1.3",
52
+ "react-error-boundary": "^6.1.4",
52
53
  "tailwindcss": "^4.3.3",
53
54
  "tsdown": "0.22.14",
54
55
  "vite": "^8.2.2",
55
- "webpack": "^5.109.2",
56
- "@vx-oss/docs-core": "1.0.6",
57
- "tsconfig": "0.0.1",
58
- "@vx-oss/docs-react": "1.0.6"
56
+ "webpack": "^5.110.3",
57
+ "@vx-oss/docs-react": "1.0.7",
58
+ "@vx-oss/docs-core": "1.0.7",
59
+ "tsconfig": "0.0.1"
59
60
  },
60
61
  "peerDependencies": {
61
62
  "@types/react": "*",
63
+ "@vx-oss/docs-core": "*",
64
+ "@vx-oss/docs-react": "*",
62
65
  "next": "^15.3.0 || ^16.0.0",
63
66
  "react": "^19.2.0",
64
67
  "react-dom": "^19.2.0",
65
68
  "vite": "^8",
66
- "webpack": "^5",
67
- "@vx-oss/docs-core": "^1.0.4",
68
- "@vx-oss/docs-react": "^1.0.4"
69
+ "webpack": "^5"
69
70
  },
70
71
  "peerDependenciesMeta": {
71
72
  "next": {
@@ -83,8 +84,8 @@
83
84
  },
84
85
  "inlinedDependencies": {
85
86
  "@fastify/deepmerge": "3.2.1",
86
- "@ungap/structured-clone": "1.3.4",
87
- "react-error-boundary": "6.1.3"
87
+ "@ungap/structured-clone": "1.4.0",
88
+ "react-error-boundary": "6.1.4"
88
89
  },
89
90
  "scripts": {
90
91
  "build": "tsdown",