@pie-element/cli 0.1.1

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 (255) hide show
  1. package/.compatibility/report.json +2491 -0
  2. package/.turbo/turbo-build.log +1 -0
  3. package/CHANGELOG.md +8 -0
  4. package/README.md +240 -0
  5. package/REFACTORING.md +131 -0
  6. package/bin/dev.js +5 -0
  7. package/bin/run.js +5 -0
  8. package/dist/commands/dev/demo/index.d.ts +33 -0
  9. package/dist/commands/dev/demo/index.d.ts.map +1 -0
  10. package/dist/commands/dev/demo/index.js +274 -0
  11. package/dist/commands/dev/demo/index.js.map +1 -0
  12. package/dist/commands/dev/test-bundler.d.ts +18 -0
  13. package/dist/commands/dev/test-bundler.d.ts.map +1 -0
  14. package/dist/commands/dev/test-bundler.js +284 -0
  15. package/dist/commands/dev/test-bundler.js.map +1 -0
  16. package/dist/commands/mathquill/migrate.d.ts +20 -0
  17. package/dist/commands/mathquill/migrate.d.ts.map +1 -0
  18. package/dist/commands/mathquill/migrate.js +240 -0
  19. package/dist/commands/mathquill/migrate.js.map +1 -0
  20. package/dist/commands/mathquill/status.d.ts +20 -0
  21. package/dist/commands/mathquill/status.d.ts.map +1 -0
  22. package/dist/commands/mathquill/status.js +231 -0
  23. package/dist/commands/mathquill/status.js.map +1 -0
  24. package/dist/commands/packages/create-controllers.d.ts +13 -0
  25. package/dist/commands/packages/create-controllers.d.ts.map +1 -0
  26. package/dist/commands/packages/create-controllers.js +103 -0
  27. package/dist/commands/packages/create-controllers.js.map +1 -0
  28. package/dist/commands/packages/create-lib-react.d.ts +17 -0
  29. package/dist/commands/packages/create-lib-react.d.ts.map +1 -0
  30. package/dist/commands/packages/create-lib-react.js +228 -0
  31. package/dist/commands/packages/create-lib-react.js.map +1 -0
  32. package/dist/commands/packages/create-react-elements.d.ts +16 -0
  33. package/dist/commands/packages/create-react-elements.d.ts.map +1 -0
  34. package/dist/commands/packages/create-react-elements.js +259 -0
  35. package/dist/commands/packages/create-react-elements.js.map +1 -0
  36. package/dist/commands/packages/enable-publishing.d.ts +11 -0
  37. package/dist/commands/packages/enable-publishing.d.ts.map +1 -0
  38. package/dist/commands/packages/enable-publishing.js +117 -0
  39. package/dist/commands/packages/enable-publishing.js.map +1 -0
  40. package/dist/commands/packages/init-synced-elements.d.ts +16 -0
  41. package/dist/commands/packages/init-synced-elements.d.ts.map +1 -0
  42. package/dist/commands/packages/init-synced-elements.js +204 -0
  43. package/dist/commands/packages/init-synced-elements.js.map +1 -0
  44. package/dist/commands/upstream/analyze-esm.d.ts +59 -0
  45. package/dist/commands/upstream/analyze-esm.d.ts.map +1 -0
  46. package/dist/commands/upstream/analyze-esm.js +1481 -0
  47. package/dist/commands/upstream/analyze-esm.js.map +1 -0
  48. package/dist/commands/upstream/check.d.ts +15 -0
  49. package/dist/commands/upstream/check.d.ts.map +1 -0
  50. package/dist/commands/upstream/check.js +165 -0
  51. package/dist/commands/upstream/check.js.map +1 -0
  52. package/dist/commands/upstream/deps.d.ts +15 -0
  53. package/dist/commands/upstream/deps.d.ts.map +1 -0
  54. package/dist/commands/upstream/deps.js +174 -0
  55. package/dist/commands/upstream/deps.js.map +1 -0
  56. package/dist/commands/upstream/sync-mathquill.d.ts +12 -0
  57. package/dist/commands/upstream/sync-mathquill.d.ts.map +1 -0
  58. package/dist/commands/upstream/sync-mathquill.js +97 -0
  59. package/dist/commands/upstream/sync-mathquill.js.map +1 -0
  60. package/dist/commands/upstream/sync.d.ts +25 -0
  61. package/dist/commands/upstream/sync.d.ts.map +1 -0
  62. package/dist/commands/upstream/sync.js +552 -0
  63. package/dist/commands/upstream/sync.js.map +1 -0
  64. package/dist/commands/upstream/track.d.ts +15 -0
  65. package/dist/commands/upstream/track.d.ts.map +1 -0
  66. package/dist/commands/upstream/track.js +115 -0
  67. package/dist/commands/upstream/track.js.map +1 -0
  68. package/dist/commands/upstream/update.d.ts +15 -0
  69. package/dist/commands/upstream/update.d.ts.map +1 -0
  70. package/dist/commands/upstream/update.js +98 -0
  71. package/dist/commands/upstream/update.js.map +1 -0
  72. package/dist/commands/verify/controllers.d.ts +12 -0
  73. package/dist/commands/verify/controllers.d.ts.map +1 -0
  74. package/dist/commands/verify/controllers.js +138 -0
  75. package/dist/commands/verify/controllers.js.map +1 -0
  76. package/dist/commands/verify/react-build.d.ts +13 -0
  77. package/dist/commands/verify/react-build.d.ts.map +1 -0
  78. package/dist/commands/verify/react-build.js +135 -0
  79. package/dist/commands/verify/react-build.js.map +1 -0
  80. package/dist/index.d.ts +2 -0
  81. package/dist/index.d.ts.map +1 -0
  82. package/dist/index.js +2 -0
  83. package/dist/index.js.map +1 -0
  84. package/dist/lib/mathquill/extension-generator.d.ts +9 -0
  85. package/dist/lib/mathquill/extension-generator.d.ts.map +1 -0
  86. package/dist/lib/mathquill/extension-generator.js +107 -0
  87. package/dist/lib/mathquill/extension-generator.js.map +1 -0
  88. package/dist/lib/mathquill/khan-extractor.d.ts +16 -0
  89. package/dist/lib/mathquill/khan-extractor.d.ts.map +1 -0
  90. package/dist/lib/mathquill/khan-extractor.js +148 -0
  91. package/dist/lib/mathquill/khan-extractor.js.map +1 -0
  92. package/dist/lib/mathquill/learnosity-extractor.d.ts +15 -0
  93. package/dist/lib/mathquill/learnosity-extractor.d.ts.map +1 -0
  94. package/dist/lib/mathquill/learnosity-extractor.js +170 -0
  95. package/dist/lib/mathquill/learnosity-extractor.js.map +1 -0
  96. package/dist/lib/mathquill/migration-orchestrator.d.ts +77 -0
  97. package/dist/lib/mathquill/migration-orchestrator.d.ts.map +1 -0
  98. package/dist/lib/mathquill/migration-orchestrator.js +391 -0
  99. package/dist/lib/mathquill/migration-orchestrator.js.map +1 -0
  100. package/dist/lib/mathquill/package-updater.d.ts +9 -0
  101. package/dist/lib/mathquill/package-updater.d.ts.map +1 -0
  102. package/dist/lib/mathquill/package-updater.js +103 -0
  103. package/dist/lib/mathquill/package-updater.js.map +1 -0
  104. package/dist/lib/mathquill/pie-extractor.d.ts +14 -0
  105. package/dist/lib/mathquill/pie-extractor.d.ts.map +1 -0
  106. package/dist/lib/mathquill/pie-extractor.js +167 -0
  107. package/dist/lib/mathquill/pie-extractor.js.map +1 -0
  108. package/dist/lib/upstream/repo-utils.d.ts +9 -0
  109. package/dist/lib/upstream/repo-utils.d.ts.map +1 -0
  110. package/dist/lib/upstream/repo-utils.js +10 -0
  111. package/dist/lib/upstream/repo-utils.js.map +1 -0
  112. package/dist/lib/upstream/sync-compatibility.d.ts +29 -0
  113. package/dist/lib/upstream/sync-compatibility.d.ts.map +1 -0
  114. package/dist/lib/upstream/sync-compatibility.js +70 -0
  115. package/dist/lib/upstream/sync-compatibility.js.map +1 -0
  116. package/dist/lib/upstream/sync-constants.d.ts +50 -0
  117. package/dist/lib/upstream/sync-constants.d.ts.map +1 -0
  118. package/dist/lib/upstream/sync-constants.js +66 -0
  119. package/dist/lib/upstream/sync-constants.js.map +1 -0
  120. package/dist/lib/upstream/sync-controllers-strategy.d.ts +18 -0
  121. package/dist/lib/upstream/sync-controllers-strategy.d.ts.map +1 -0
  122. package/dist/lib/upstream/sync-controllers-strategy.js +243 -0
  123. package/dist/lib/upstream/sync-controllers-strategy.js.map +1 -0
  124. package/dist/lib/upstream/sync-demo-metadata.d.ts +15 -0
  125. package/dist/lib/upstream/sync-demo-metadata.d.ts.map +1 -0
  126. package/dist/lib/upstream/sync-demo-metadata.js +165 -0
  127. package/dist/lib/upstream/sync-demo-metadata.js.map +1 -0
  128. package/dist/lib/upstream/sync-dev-exports.d.ts +13 -0
  129. package/dist/lib/upstream/sync-dev-exports.d.ts.map +1 -0
  130. package/dist/lib/upstream/sync-dev-exports.js +115 -0
  131. package/dist/lib/upstream/sync-dev-exports.js.map +1 -0
  132. package/dist/lib/upstream/sync-externals.d.ts +29 -0
  133. package/dist/lib/upstream/sync-externals.d.ts.map +1 -0
  134. package/dist/lib/upstream/sync-externals.js +164 -0
  135. package/dist/lib/upstream/sync-externals.js.map +1 -0
  136. package/dist/lib/upstream/sync-filesystem.d.ts +21 -0
  137. package/dist/lib/upstream/sync-filesystem.d.ts.map +1 -0
  138. package/dist/lib/upstream/sync-filesystem.js +64 -0
  139. package/dist/lib/upstream/sync-filesystem.js.map +1 -0
  140. package/dist/lib/upstream/sync-imports.d.ts +284 -0
  141. package/dist/lib/upstream/sync-imports.d.ts.map +1 -0
  142. package/dist/lib/upstream/sync-imports.js +816 -0
  143. package/dist/lib/upstream/sync-imports.js.map +1 -0
  144. package/dist/lib/upstream/sync-mathquill.d.ts +19 -0
  145. package/dist/lib/upstream/sync-mathquill.d.ts.map +1 -0
  146. package/dist/lib/upstream/sync-mathquill.js +160 -0
  147. package/dist/lib/upstream/sync-mathquill.js.map +1 -0
  148. package/dist/lib/upstream/sync-package-json.d.ts +28 -0
  149. package/dist/lib/upstream/sync-package-json.d.ts.map +1 -0
  150. package/dist/lib/upstream/sync-package-json.js +66 -0
  151. package/dist/lib/upstream/sync-package-json.js.map +1 -0
  152. package/dist/lib/upstream/sync-package-manager.d.ts +50 -0
  153. package/dist/lib/upstream/sync-package-manager.d.ts.map +1 -0
  154. package/dist/lib/upstream/sync-package-manager.js +570 -0
  155. package/dist/lib/upstream/sync-package-manager.js.map +1 -0
  156. package/dist/lib/upstream/sync-pielib-strategy.d.ts +26 -0
  157. package/dist/lib/upstream/sync-pielib-strategy.d.ts.map +1 -0
  158. package/dist/lib/upstream/sync-pielib-strategy.js +345 -0
  159. package/dist/lib/upstream/sync-pielib-strategy.js.map +1 -0
  160. package/dist/lib/upstream/sync-react-strategy.d.ts +54 -0
  161. package/dist/lib/upstream/sync-react-strategy.d.ts.map +1 -0
  162. package/dist/lib/upstream/sync-react-strategy.js +733 -0
  163. package/dist/lib/upstream/sync-react-strategy.js.map +1 -0
  164. package/dist/lib/upstream/sync-strategy.d.ts +49 -0
  165. package/dist/lib/upstream/sync-strategy.d.ts.map +1 -0
  166. package/dist/lib/upstream/sync-strategy.js +2 -0
  167. package/dist/lib/upstream/sync-strategy.js.map +1 -0
  168. package/dist/lib/upstream/sync-summary.d.ts +20 -0
  169. package/dist/lib/upstream/sync-summary.d.ts.map +1 -0
  170. package/dist/lib/upstream/sync-summary.js +157 -0
  171. package/dist/lib/upstream/sync-summary.js.map +1 -0
  172. package/dist/lib/upstream/sync-transforms.d.ts +60 -0
  173. package/dist/lib/upstream/sync-transforms.d.ts.map +1 -0
  174. package/dist/lib/upstream/sync-transforms.js +97 -0
  175. package/dist/lib/upstream/sync-transforms.js.map +1 -0
  176. package/dist/lib/upstream/sync-vite-config.d.ts +13 -0
  177. package/dist/lib/upstream/sync-vite-config.d.ts.map +1 -0
  178. package/dist/lib/upstream/sync-vite-config.js +231 -0
  179. package/dist/lib/upstream/sync-vite-config.js.map +1 -0
  180. package/dist/utils/compatibility.d.ts +129 -0
  181. package/dist/utils/compatibility.d.ts.map +1 -0
  182. package/dist/utils/compatibility.js +44 -0
  183. package/dist/utils/compatibility.js.map +1 -0
  184. package/dist/utils/conversion.d.ts +25 -0
  185. package/dist/utils/conversion.d.ts.map +1 -0
  186. package/dist/utils/conversion.js +123 -0
  187. package/dist/utils/conversion.js.map +1 -0
  188. package/dist/utils/git.d.ts +7 -0
  189. package/dist/utils/git.d.ts.map +1 -0
  190. package/dist/utils/git.js +63 -0
  191. package/dist/utils/git.js.map +1 -0
  192. package/dist/utils/logger.d.ts +29 -0
  193. package/dist/utils/logger.d.ts.map +1 -0
  194. package/dist/utils/logger.js +63 -0
  195. package/dist/utils/logger.js.map +1 -0
  196. package/dist/utils/package-json.d.ts +12 -0
  197. package/dist/utils/package-json.d.ts.map +1 -0
  198. package/dist/utils/package-json.js +29 -0
  199. package/dist/utils/package-json.js.map +1 -0
  200. package/package.json +59 -0
  201. package/packages/cli/bin/dev.js +5 -0
  202. package/packages/cli/bin/run.js +5 -0
  203. package/src/commands/dev/demo/index.ts +313 -0
  204. package/src/commands/dev/test-bundler.ts +345 -0
  205. package/src/commands/mathquill/migrate.ts +269 -0
  206. package/src/commands/mathquill/status.ts +267 -0
  207. package/src/commands/packages/create-controllers.ts +127 -0
  208. package/src/commands/packages/create-lib-react.ts +279 -0
  209. package/src/commands/packages/create-react-elements.ts +306 -0
  210. package/src/commands/packages/enable-publishing.ts +161 -0
  211. package/src/commands/packages/init-synced-elements.ts +259 -0
  212. package/src/commands/upstream/README.md +444 -0
  213. package/src/commands/upstream/analyze-esm.ts +1973 -0
  214. package/src/commands/upstream/check.ts +228 -0
  215. package/src/commands/upstream/deps.ts +222 -0
  216. package/src/commands/upstream/sync-mathquill.ts +108 -0
  217. package/src/commands/upstream/sync.ts +687 -0
  218. package/src/commands/upstream/track.ts +145 -0
  219. package/src/commands/upstream/update.ts +110 -0
  220. package/src/commands/verify/controllers.ts +166 -0
  221. package/src/commands/verify/react-build.ts +171 -0
  222. package/src/index.ts +1 -0
  223. package/src/lib/mathquill/extension-generator.ts +111 -0
  224. package/src/lib/mathquill/khan-extractor.ts +175 -0
  225. package/src/lib/mathquill/learnosity-extractor.ts +198 -0
  226. package/src/lib/mathquill/migration-orchestrator.ts +513 -0
  227. package/src/lib/mathquill/package-updater.ts +120 -0
  228. package/src/lib/mathquill/pie-extractor.ts +194 -0
  229. package/src/lib/upstream/repo-utils.ts +18 -0
  230. package/src/lib/upstream/sync-compatibility.ts +89 -0
  231. package/src/lib/upstream/sync-constants.ts +77 -0
  232. package/src/lib/upstream/sync-controllers-strategy.ts +291 -0
  233. package/src/lib/upstream/sync-demo-metadata.ts +199 -0
  234. package/src/lib/upstream/sync-dev-exports.ts +151 -0
  235. package/src/lib/upstream/sync-externals.ts +159 -0
  236. package/src/lib/upstream/sync-filesystem.ts +87 -0
  237. package/src/lib/upstream/sync-imports.ts +992 -0
  238. package/src/lib/upstream/sync-mathquill.ts +194 -0
  239. package/src/lib/upstream/sync-package-json.ts +86 -0
  240. package/src/lib/upstream/sync-package-manager.ts +694 -0
  241. package/src/lib/upstream/sync-pielib-strategy.ts +441 -0
  242. package/src/lib/upstream/sync-react-strategy.ts +945 -0
  243. package/src/lib/upstream/sync-strategy.ts +61 -0
  244. package/src/lib/upstream/sync-summary.ts +194 -0
  245. package/src/lib/upstream/sync-transforms.ts +154 -0
  246. package/src/lib/upstream/sync-vite-config.ts +243 -0
  247. package/src/types/es-module-lexer.d.ts +4 -0
  248. package/src/utils/compatibility.ts +182 -0
  249. package/src/utils/conversion.ts +153 -0
  250. package/src/utils/git.ts +63 -0
  251. package/src/utils/logger.ts +69 -0
  252. package/src/utils/package-json.ts +43 -0
  253. package/tests/sync-package-manager.test.ts +112 -0
  254. package/tests/transform-assign-props.test.ts +101 -0
  255. package/tsconfig.json +15 -0
@@ -0,0 +1,992 @@
1
+ /**
2
+ * Import rewriting utilities for sync operations
3
+ *
4
+ * This module contains transforms that rewrite imports during the sync process
5
+ * to handle differences between the upstream CommonJS/Webpack code and the
6
+ * ESM-only target environment.
7
+ *
8
+ * ## Why These Rewrites Are Needed:
9
+ *
10
+ * 1. **Lodash → Lodash-ES**:
11
+ * - Upstream uses CommonJS `lodash` package
12
+ * - ESM requires `lodash-es` for proper tree-shaking
13
+ *
14
+ * 2. **Recharts 2.x → 3.x**:
15
+ * - Upstream uses recharts 2.x which has lodash dependency
16
+ * - Recharts 3.x is fully ESM-compatible with no lodash dependency
17
+ *
18
+ * 3. **@pie-framework Events → Internal Packages**:
19
+ * - Upstream references external @pie-framework packages
20
+ * - Monorepo uses internal @pie-element/shared-* packages
21
+ *
22
+ * 4. **Editable-HTML Constants Inlining**:
23
+ * - `editable-html` package is not ESM-compatible (Slate v0.x dependencies)
24
+ * - We only need constants, so inline them to avoid the dependency
25
+ *
26
+ * 5. **TokenTypes Re-export**:
27
+ * - Upstream code works in CommonJS/Webpack (looser module resolution)
28
+ * - ESM requires explicit re-exports for proper module graph
29
+ *
30
+ * 6. **Configure Defaults Inlining**:
31
+ * - Configure package is not ESM-compatible (Slate v0.x dependencies)
32
+ * - Student-facing UI only needs minimal fallback configuration
33
+ * - Inline empty defaults object to avoid the dependency
34
+ */
35
+ import { readFile, writeFile } from 'node:fs/promises';
36
+
37
+ /**
38
+ * Fix import statements in a file to handle default export conversions
39
+ *
40
+ * When converting JS files with default exports to TS, we need to update
41
+ * imports in consuming files to use named imports instead.
42
+ */
43
+ export async function fixImportsInFile(
44
+ filePath: string,
45
+ defaultExportFiles: Set<string>
46
+ ): Promise<boolean> {
47
+ let content = await readFile(filePath, 'utf-8');
48
+ let modified = false;
49
+
50
+ // Match import statements: import Something from './file'
51
+ const importRegex = /import\s+(\w+)\s+from\s+['"](\.[^'"]+)['"]/g;
52
+ const matches = Array.from(content.matchAll(importRegex));
53
+
54
+ for (const match of matches) {
55
+ const [fullMatch, importName, importPath] = match;
56
+ // Normalize the import path (remove extensions, resolve relative paths)
57
+ const normalizedPath = importPath.replace(/\.(tsx?|jsx?)$/, '');
58
+
59
+ // Check if this file had a default export
60
+ if (defaultExportFiles.has(normalizedPath)) {
61
+ // Replace default import with named import
62
+ const replacement = `import { ${importName} } from '${importPath}'`;
63
+ content = content.replace(fullMatch, replacement);
64
+ modified = true;
65
+ }
66
+ }
67
+
68
+ if (modified) {
69
+ await writeFile(filePath, content, 'utf-8');
70
+ }
71
+
72
+ return modified;
73
+ }
74
+
75
+ /**
76
+ * Check if code contains JSX syntax
77
+ */
78
+ export function containsJsx(code: string): boolean {
79
+ return /<[A-Za-z][\w-]*[\s/>]/.test(code);
80
+ }
81
+
82
+ /**
83
+ * Replace editable-html imports with inlined constants
84
+ *
85
+ * editable-html is not ESM-compatible (depends on Slate v0.x), but some packages
86
+ * only import constants from it. We inline these constants to avoid the dependency.
87
+ */
88
+ export function inlineEditableHtmlConstants(code: string): string {
89
+ // Check if file imports from editable-html
90
+ const editableHtmlImportRegex =
91
+ /import\s+(\w+)\s+from\s+['"]\.\.\/\.\.\/\.\.\/editable-html\/src\/constants['"]/;
92
+ const match = code.match(editableHtmlImportRegex);
93
+
94
+ if (!match) {
95
+ return code; // No editable-html import, return unchanged
96
+ }
97
+
98
+ const importName = match[1];
99
+
100
+ // Replace the import with inlined constants
101
+ const inlinedConstants = `// Inlined from editable-html/src/constants (not ESM-compatible)
102
+ const ${importName} = {
103
+ MAIN_CONTAINER_CLASS: 'main-container',
104
+ PIE_TOOLBAR__CLASS: 'pie-toolbar',
105
+ };`;
106
+
107
+ return code.replace(editableHtmlImportRegex, inlinedConstants);
108
+ }
109
+
110
+ /**
111
+ * Fix missing re-export of TokenTypes in text-select token-select/index.jsx
112
+ * The upstream imports TokenTypes from ./token but doesn't re-export it,
113
+ * causing build failures when parent index.js tries to import it.
114
+ */
115
+ export function reexportTokenTypes(code: string, filePath: string): string {
116
+ // Only apply to text-select token-select/index file
117
+ if (!filePath.includes('text-select') || !filePath.includes('token-select/index')) {
118
+ return code;
119
+ }
120
+
121
+ // Check if file imports TokenTypes from ./token
122
+ if (!code.includes("import Token, { TokenTypes } from './token'")) {
123
+ return code;
124
+ }
125
+
126
+ // Check if already exports TokenTypes
127
+ if (code.includes('export { TokenTypes }')) {
128
+ return code;
129
+ }
130
+
131
+ // Add export after the default export
132
+ return code.replace(
133
+ /^export default TokenSelect;$/m,
134
+ 'export default TokenSelect;\nexport { TokenTypes };'
135
+ );
136
+ }
137
+
138
+ /**
139
+ * Replace configure/lib/defaults import with an empty defaults object
140
+ * when configure directory is not synced (ESM-incompatible due to Slate v0.x)
141
+ */
142
+ export function inlineConfigureDefaults(code: string): string {
143
+ // Only apply to files that import from ../configure/lib/defaults
144
+ const configureImportRegex =
145
+ /import\s+(\w+)\s+from\s+['"](\.\.\/configure\/lib\/defaults|\.\.\/\.\.\/configure\/lib\/defaults)['"]/;
146
+ const match = code.match(configureImportRegex);
147
+
148
+ if (!match) return code;
149
+
150
+ const importName = match[1];
151
+
152
+ // Replace with minimal defaults object
153
+ // The configuration property is what's typically used in student-facing code
154
+ const inlinedDefaults = `// Inlined from configure/lib/defaults (configure/ not synced - ESM-incompatible)
155
+ const ${importName} = {
156
+ configuration: {
157
+ // Minimal configuration for student-facing UI
158
+ // Full authoring configuration is only needed in the configure package
159
+ } as any
160
+ };`;
161
+
162
+ return code.replace(configureImportRegex, inlinedDefaults);
163
+ }
164
+
165
+ /**
166
+ * Determine if a file should have .tsx extension based on content
167
+ */
168
+ export function shouldUseTsxExtension(content: string, originalPath: string): boolean {
169
+ // If original file was .jsx, use .tsx
170
+ if (originalPath.endsWith('.jsx')) {
171
+ return true;
172
+ }
173
+
174
+ // If content contains JSX, use .tsx
175
+ if (containsJsx(content)) {
176
+ return true;
177
+ }
178
+
179
+ // Otherwise use .ts
180
+ return false;
181
+ }
182
+
183
+ /**
184
+ * Convert CommonJS module.exports to ES module exports
185
+ *
186
+ * Handles patterns like:
187
+ * module.exports = { foo: ..., bar: ... }
188
+ *
189
+ * Converts to:
190
+ * export const foo = ...;
191
+ * export const bar = ...;
192
+ */
193
+ export function convertModuleExportsToEsm(content: string): string {
194
+ // Match: module.exports = { key: value, key2: value2, ... };
195
+ const moduleExportsPattern = /module\.exports\s*=\s*\{([\s\S]*?)\};?/;
196
+ const match = content.match(moduleExportsPattern);
197
+
198
+ if (!match) {
199
+ return content;
200
+ }
201
+
202
+ const [fullMatch, objectContent] = match;
203
+
204
+ // Parse the object content into key-value pairs
205
+ // Match patterns like: key: value, (with value possibly spanning multiple lines)
206
+ const exports: string[] = [];
207
+ const lines = objectContent.split('\n');
208
+
209
+ let currentKey: string | null = null;
210
+ let currentValue: string[] = [];
211
+
212
+ for (const line of lines) {
213
+ const trimmed = line.trim();
214
+ if (!trimmed || trimmed === '{' || trimmed === '}') continue;
215
+
216
+ // Check if this line starts a new key
217
+ const keyMatch = trimmed.match(/^(\w+):\s*(.*)/);
218
+ if (keyMatch) {
219
+ // Save previous export if any
220
+ if (currentKey) {
221
+ const value = currentValue.join('\n').replace(/,\s*$/, ''); // Remove trailing comma
222
+ exports.push(`export const ${currentKey} =\n${value};`);
223
+ }
224
+
225
+ // Start new export
226
+ currentKey = keyMatch[1];
227
+ currentValue = [keyMatch[2]];
228
+ } else {
229
+ // Continuation of current value
230
+ currentValue.push(line);
231
+ }
232
+ }
233
+
234
+ // Save last export
235
+ if (currentKey) {
236
+ const value = currentValue.join('\n').replace(/,\s*$/, '');
237
+ exports.push(`export const ${currentKey} =\n${value};`);
238
+ }
239
+
240
+ // Replace the module.exports block with ES module exports
241
+ const esmExports = exports.join('\n\n');
242
+ return content.replace(fullMatch, esmExports);
243
+ }
244
+
245
+ /**
246
+ * Transform lodash imports to lodash-es for ESM compatibility
247
+ *
248
+ * Handles all lodash import patterns:
249
+ * - Individual module imports: import isEmpty from 'lodash/isEmpty'
250
+ * - Named imports: import { isEmpty, isEqual } from 'lodash'
251
+ * - Default import: import _ from 'lodash'
252
+ * - Namespace import: import * as _ from 'lodash'
253
+ *
254
+ * Converts them to use lodash-es which is a pure ESM package.
255
+ */
256
+ export function transformLodashToLodashEs(content: string): string {
257
+ let transformed = content;
258
+
259
+ // Pattern 1: Individual module imports
260
+ // import isEmpty from 'lodash/isEmpty' → import { isEmpty } from 'lodash-es'
261
+ // import cloneDeep from 'lodash/cloneDeep' → import { cloneDeep } from 'lodash-es'
262
+ transformed = transformed.replace(
263
+ /import\s+(\w+)\s+from\s+['"]lodash\/(\w+)['"]/g,
264
+ "import { $1 } from 'lodash-es'"
265
+ );
266
+
267
+ // Pattern 2: Named imports, default imports, and namespace imports from main module
268
+ // import { isEmpty, isEqual } from 'lodash' → import { isEmpty, isEqual } from 'lodash-es'
269
+ // import _ from 'lodash' → import _ from 'lodash-es'
270
+ // import * as _ from 'lodash' → import * as _ from 'lodash-es'
271
+ transformed = transformed.replace(/from\s+['"]lodash['"]/g, "from 'lodash-es'");
272
+
273
+ return transformed;
274
+ }
275
+
276
+ /**
277
+ * Transform package.json dependencies from lodash to lodash-es
278
+ *
279
+ * Replaces lodash with lodash-es version 4.17.22 (latest ESM version)
280
+ * Also removes @types/lodash as lodash-es includes built-in TypeScript types
281
+ */
282
+ export function transformPackageJsonLodash<T extends Record<string, any>>(packageJson: T): T {
283
+ const transformed = { ...packageJson };
284
+
285
+ // Replace lodash with lodash-es in dependencies
286
+ if (transformed.dependencies?.lodash) {
287
+ transformed.dependencies['lodash-es'] = '^4.17.22';
288
+ delete transformed.dependencies.lodash;
289
+ }
290
+
291
+ // Replace lodash with lodash-es in devDependencies
292
+ if (transformed.devDependencies?.lodash) {
293
+ transformed.devDependencies['lodash-es'] = '^4.17.22';
294
+ delete transformed.devDependencies.lodash;
295
+ }
296
+
297
+ // Remove @types/lodash if present (lodash-es has built-in types)
298
+ if (transformed.dependencies?.['@types/lodash']) {
299
+ delete transformed.dependencies['@types/lodash'];
300
+ }
301
+ if (transformed.devDependencies?.['@types/lodash']) {
302
+ delete transformed.devDependencies['@types/lodash'];
303
+ }
304
+
305
+ return transformed;
306
+ }
307
+
308
+ /**
309
+ * Transform recharts version in package.json
310
+ *
311
+ * Upgrades recharts from 2.x to 3.x for ESM compatibility.
312
+ * Recharts 3.x removes the lodash dependency and is fully ESM-compatible.
313
+ */
314
+ export function transformPackageJsonRecharts<T extends Record<string, any>>(packageJson: T): T {
315
+ const transformed = { ...packageJson };
316
+
317
+ // Upgrade recharts to 3.x in dependencies
318
+ if (transformed.dependencies?.recharts) {
319
+ // Only upgrade if it's 2.x
320
+ const version = transformed.dependencies.recharts;
321
+ if (version.includes('2.')) {
322
+ transformed.dependencies.recharts = '^3.7.0';
323
+ }
324
+ }
325
+
326
+ return transformed;
327
+ }
328
+
329
+ /**
330
+ * Transform @pie-framework event package imports to internal packages
331
+ *
332
+ * Handles:
333
+ * - @pie-framework/pie-player-events → @pie-element/shared-player-events
334
+ * - @pie-framework/pie-configure-events → @pie-element/shared-configure-events
335
+ */
336
+ export function transformPieFrameworkEventImports(content: string): string {
337
+ let transformed = content;
338
+
339
+ // Transform pie-player-events imports
340
+ transformed = transformed.replace(
341
+ /from\s+['"]@pie-framework\/pie-player-events['"]/g,
342
+ "from '@pie-element/shared-player-events'"
343
+ );
344
+
345
+ // Transform pie-configure-events imports
346
+ transformed = transformed.replace(
347
+ /from\s+['"]@pie-framework\/pie-configure-events['"]/g,
348
+ "from '@pie-element/shared-configure-events'"
349
+ );
350
+
351
+ return transformed;
352
+ }
353
+
354
+ /**
355
+ * Transform @pie-lib/controller-utils imports to internal @pie-element/shared-controller-utils
356
+ *
357
+ * Handles:
358
+ * - @pie-lib/controller-utils → @pie-element/shared-controller-utils
359
+ *
360
+ * Our internal controller-utils package has the same API but with modernized TypeScript
361
+ * and no lodash/debug dependencies.
362
+ */
363
+ export function transformControllerUtilsImports(content: string): string {
364
+ return content.replace(
365
+ /from\s+['"]@pie-lib\/controller-utils['"]/g,
366
+ "from '@pie-element/shared-controller-utils'"
367
+ );
368
+ }
369
+
370
+ /**
371
+ * Transform @pie-lib shared package imports to internal @pie-element/shared-* packages
372
+ *
373
+ * Handles:
374
+ * - @pie-lib/math-rendering → @pie-element/shared-math-rendering-mathjax
375
+ *
376
+ * These packages have been moved to shared/ for better version control and consistency.
377
+ */
378
+ export function transformSharedPackageImports(content: string): string {
379
+ let transformed = content;
380
+
381
+ // Transform math-rendering
382
+ transformed = transformed.replace(
383
+ /from\s+['"]@pie-lib\/math-rendering['"]/g,
384
+ "from '@pie-element/shared-math-rendering-mathjax'"
385
+ );
386
+
387
+ // Transform feedback
388
+ transformed = transformed.replace(
389
+ /from\s+['"]@pie-lib\/feedback['"]/g,
390
+ "from '@pie-element/shared-feedback'"
391
+ );
392
+
393
+ return transformed;
394
+ }
395
+
396
+ /**
397
+ * Transform @pie-framework/mathquill imports to internal @pie-element/shared-mathquill
398
+ *
399
+ * Handles:
400
+ * - @pie-framework/mathquill → @pie-element/shared-mathquill
401
+ *
402
+ * Our internal mathquill package is a fork from the PIE org with matrix support,
403
+ * accessibility features, and modernized ESM code.
404
+ */
405
+ export function transformMathquillImports(content: string): string {
406
+ return content.replace(
407
+ /from\s+['"]@pie-framework\/mathquill['"]/g,
408
+ "from '@pie-element/shared-mathquill'"
409
+ );
410
+ }
411
+
412
+ /**
413
+ * Transform package.json dependencies for PIE Framework event packages
414
+ *
415
+ * Replaces external @pie-framework event packages with internal workspace packages
416
+ */
417
+ export function transformPackageJsonPieEvents<T extends Record<string, any>>(packageJson: T): T {
418
+ const transformed = { ...packageJson };
419
+
420
+ // Replace @pie-framework/pie-player-events with internal package
421
+ if (transformed.dependencies?.['@pie-framework/pie-player-events']) {
422
+ transformed.dependencies['@pie-element/shared-player-events'] = 'workspace:*';
423
+ delete transformed.dependencies['@pie-framework/pie-player-events'];
424
+ }
425
+ if (transformed.devDependencies?.['@pie-framework/pie-player-events']) {
426
+ transformed.devDependencies['@pie-element/shared-player-events'] = 'workspace:*';
427
+ delete transformed.devDependencies['@pie-framework/pie-player-events'];
428
+ }
429
+
430
+ // Replace @pie-framework/pie-configure-events with internal package
431
+ if (transformed.dependencies?.['@pie-framework/pie-configure-events']) {
432
+ transformed.dependencies['@pie-element/shared-configure-events'] = 'workspace:*';
433
+ delete transformed.dependencies['@pie-framework/pie-configure-events'];
434
+ }
435
+ if (transformed.devDependencies?.['@pie-framework/pie-configure-events']) {
436
+ transformed.devDependencies['@pie-element/shared-configure-events'] = 'workspace:*';
437
+ delete transformed.devDependencies['@pie-framework/pie-configure-events'];
438
+ }
439
+
440
+ return transformed;
441
+ }
442
+
443
+ /**
444
+ * Transform package.json dependencies for @pie-lib/controller-utils
445
+ *
446
+ * Replaces @pie-lib/controller-utils with internal @pie-element/shared-controller-utils
447
+ */
448
+ export function transformPackageJsonControllerUtils<T extends Record<string, any>>(
449
+ packageJson: T
450
+ ): T {
451
+ const transformed = { ...packageJson };
452
+
453
+ // Replace @pie-lib/controller-utils with internal package
454
+ if (transformed.dependencies?.['@pie-lib/controller-utils']) {
455
+ transformed.dependencies['@pie-element/shared-controller-utils'] = 'workspace:*';
456
+ delete transformed.dependencies['@pie-lib/controller-utils'];
457
+ }
458
+ if (transformed.devDependencies?.['@pie-lib/controller-utils']) {
459
+ transformed.devDependencies['@pie-element/shared-controller-utils'] = 'workspace:*';
460
+ delete transformed.devDependencies['@pie-lib/controller-utils'];
461
+ }
462
+
463
+ return transformed;
464
+ }
465
+
466
+ /**
467
+ * Transform package.json dependencies for shared packages
468
+ *
469
+ * Replaces @pie-lib shared packages with internal @pie-element/shared-* packages
470
+ */
471
+ export function transformPackageJsonSharedPackages<T extends Record<string, any>>(
472
+ packageJson: T
473
+ ): T {
474
+ const transformed = { ...packageJson };
475
+
476
+ const sharedPackages = {
477
+ '@pie-lib/math-rendering': '@pie-element/shared-math-rendering-mathjax',
478
+ '@pie-lib/feedback': '@pie-element/shared-feedback',
479
+ };
480
+
481
+ for (const [oldPkg, newPkg] of Object.entries(sharedPackages)) {
482
+ // Replace in dependencies
483
+ if (transformed.dependencies?.[oldPkg]) {
484
+ transformed.dependencies[newPkg] = 'workspace:*';
485
+ delete transformed.dependencies[oldPkg];
486
+ }
487
+ // Replace in devDependencies
488
+ if (transformed.devDependencies?.[oldPkg]) {
489
+ transformed.devDependencies[newPkg] = 'workspace:*';
490
+ delete transformed.devDependencies[oldPkg];
491
+ }
492
+ }
493
+
494
+ return transformed;
495
+ }
496
+
497
+ /**
498
+ * Transform package.json dependencies for @pie-framework/mathquill
499
+ *
500
+ * Replaces @pie-framework/mathquill with internal @pie-element/shared-mathquill
501
+ */
502
+ export function transformPackageJsonMathquill<T extends Record<string, any>>(packageJson: T): T {
503
+ const transformed = { ...packageJson };
504
+
505
+ // Replace @pie-framework/mathquill with internal package
506
+ if (transformed.dependencies?.['@pie-framework/mathquill']) {
507
+ transformed.dependencies['@pie-element/shared-mathquill'] = 'workspace:*';
508
+ delete transformed.dependencies['@pie-framework/mathquill'];
509
+ }
510
+ if (transformed.devDependencies?.['@pie-framework/mathquill']) {
511
+ transformed.devDependencies['@pie-element/shared-mathquill'] = 'workspace:*';
512
+ delete transformed.devDependencies['@pie-framework/mathquill'];
513
+ }
514
+
515
+ return transformed;
516
+ }
517
+
518
+ /**
519
+ * Transform direct property assignment patterns to use assignProps utility
520
+ *
521
+ * Replaces patterns like:
522
+ * Object.entries(props).forEach(([key, value]) => { element[key] = value; });
523
+ * With:
524
+ * assignProps(element, props);
525
+ *
526
+ * And adds the import if not present.
527
+ *
528
+ * NOTE: This transform is available but NOT enabled in the sync pipeline by default.
529
+ * Only enable it if this pattern appears frequently in upstream code and needs
530
+ * to be refactored automatically. For one-off cases, manual refactoring is preferred.
531
+ *
532
+ * To enable: Import and call this in sync-pielib-strategy.ts after other transforms.
533
+ */
534
+ export function transformToAssignProps(content: string): string {
535
+ let transformed = content;
536
+ let needsImport = false;
537
+
538
+ // Pattern 1: Object.entries(props).forEach with element[key] = value
539
+ // Matches: Object.entries(props).forEach(([key, value]) => { element[key] = value; });
540
+ const pattern1 =
541
+ /Object\.entries\((\w+)\)\.forEach\(\(\[(\w+),\s*(\w+)\]\)\s*=>\s*\{\s*(\w+)\[\2\]\s*=\s*\3;\s*\}\);?/g;
542
+ const matches1 = Array.from(transformed.matchAll(pattern1));
543
+
544
+ for (const match of matches1) {
545
+ const [fullMatch, propsVar, _keyVar, _valueVar, elementVar] = match;
546
+ const replacement = `assignProps(${elementVar}, ${propsVar});`;
547
+ transformed = transformed.replace(fullMatch, replacement);
548
+ needsImport = true;
549
+ }
550
+
551
+ // Pattern 2: for...of loop with Object.entries
552
+ // Matches: for (const [key, value] of Object.entries(props)) { element[key] = value; }
553
+ const pattern2 =
554
+ /for\s*\(const\s*\[(\w+),\s*(\w+)\]\s*of\s*Object\.entries\((\w+)\)\)\s*\{\s*(\w+)\[\1\]\s*=\s*\2;\s*\}/g;
555
+ const matches2 = Array.from(transformed.matchAll(pattern2));
556
+
557
+ for (const match of matches2) {
558
+ const [fullMatch, _keyVar, _valueVar, propsVar, elementVar] = match;
559
+ const replacement = `assignProps(${elementVar}, ${propsVar});`;
560
+ transformed = transformed.replace(fullMatch, replacement);
561
+ needsImport = true;
562
+ }
563
+
564
+ // Add import if needed and not already present
565
+ if (needsImport && !transformed.includes("from '@pie-element/shared-utils'")) {
566
+ // Find where to insert the import (after other imports)
567
+ const importMatch = transformed.match(/(import\s+.*?from\s+['"].*?['"];?\s*\n)+/);
568
+ if (importMatch && importMatch.index !== undefined) {
569
+ const lastImportEnd = importMatch.index + importMatch[0].length;
570
+ transformed =
571
+ transformed.slice(0, lastImportEnd) +
572
+ "import { assignProps } from '@pie-element/shared-utils';\n" +
573
+ transformed.slice(lastImportEnd);
574
+ } else {
575
+ // No imports found, add at the beginning (after any leading comments)
576
+ const firstNonCommentLine = transformed.search(/^(?!\/\/|\/\*|\*|$)/m);
577
+ if (firstNonCommentLine !== -1) {
578
+ transformed =
579
+ transformed.slice(0, firstNonCommentLine) +
580
+ "import { assignProps } from '@pie-element/shared-utils';\n\n" +
581
+ transformed.slice(firstNonCommentLine);
582
+ }
583
+ }
584
+ }
585
+
586
+ return transformed;
587
+ }
588
+
589
+ /**
590
+ * Transform configure utility imports for flattened directory structure
591
+ *
592
+ * In upstream pie-elements, configure utility files live at configure/utils.js
593
+ * and are imported from configure/src/ files using '../utils'.
594
+ *
595
+ * In the synced structure, both configure/src/ files and configure/utils.js
596
+ * are synced to src/configure/, so the import path needs to change from
597
+ * '../utils' to './utils'.
598
+ *
599
+ * This transform handles:
600
+ * - import { x } from '../utils' → import { x } from './utils'
601
+ * - Only applies to files directly in configure/src/, not subdirectories
602
+ * - Only when the import is '../utils' (not '../utils/something')
603
+ */
604
+ export function transformConfigureUtilsImports(content: string, relativePath: string): string {
605
+ // Only apply to files directly in configure/src/ (not in subdirectories)
606
+ // Note: In the target, these files end up in author/ directory
607
+ // Match patterns like:
608
+ // - "configure/src/something.js" (yes)
609
+ // - "configure/src/design/something.js" (no - has subdirectory)
610
+ const configureRootFilePattern = /^configure\/src\/[^/]+\.(jsx?|tsx?)$/;
611
+ if (!configureRootFilePattern.test(relativePath)) {
612
+ return content;
613
+ }
614
+
615
+ // Transform '../utils' to './utils' (only exact match, not '../utils/something')
616
+ let transformed = content;
617
+ transformed = transformed.replace(/from\s+['"]\.\.\/utils['"]/g, "from './utils'");
618
+
619
+ return transformed;
620
+ }
621
+
622
+ /**
623
+ * Transform SSR-unsafe require() calls to standard ESM imports
624
+ *
625
+ * Upstream pie-lib code uses this pattern for SSR compatibility with MathQuill:
626
+ *
627
+ * ```js
628
+ * // - mathquill error window not defined
629
+ * let EditableHtml;
630
+ * let StyledEditableHTML;
631
+ * if (typeof window !== 'undefined') {
632
+ * EditableHtml = require('@pie-lib/editable-html-tip-tap')['default'];
633
+ * StyledEditableHTML = styled(EditableHtml)(({ theme }) => ({
634
+ * fontFamily: theme.typography.fontFamily,
635
+ * }));
636
+ * }
637
+ * ```
638
+ *
639
+ * This doesn't work in browser ESM (require is not defined). Transform to:
640
+ *
641
+ * ```tsx
642
+ * import EditableHtmlImport from '@pie-lib/editable-html-tip-tap';
643
+ *
644
+ * const EditableHtml = EditableHtmlImport;
645
+ * const StyledEditableHTML = styled(EditableHtml)(({ theme }) => ({
646
+ * fontFamily: theme.typography.fontFamily,
647
+ * }));
648
+ * ```
649
+ *
650
+ * We use direct imports instead of React.lazy because:
651
+ * - Simpler code (no Suspense wrapper needed)
652
+ * - No loading flicker
653
+ * - Modern bundlers handle ESM imports correctly for SSR
654
+ * - The component is always needed (no code-splitting benefit)
655
+ */
656
+ export function transformSsrRequireToReactLazy(content: string): string {
657
+ let transformed = content;
658
+
659
+ // Pattern 1: SSR check with require() for editable-html-tip-tap with styled wrapper
660
+ // Matches:
661
+ // // - mathquill error window not defined
662
+ // let EditableHtml;
663
+ // let StyledEditableHTML;
664
+ // if (typeof window !== 'undefined') {
665
+ // EditableHtml = require('@pie-lib/editable-html-tip-tap')['default'];
666
+ // StyledEditableHTML = styled(EditableHtml)(...);
667
+ // }
668
+ //
669
+ // Note: styled() call may span multiple lines
670
+
671
+ const ssrRequirePattern =
672
+ /(?:\/\/import\s+\w+\s+from\s+['"]@pie-lib\/[^'"]+['"]\s*;\s*\n)?let\s+(\w+);\s*\nlet\s+(\w+);\s*\n(?:\/\/\s*-\s*mathquill\s+error\s+window\s+not\s+defined\s*\n)?if\s*\(\s*typeof\s+window\s*!==\s*['"]undefined['"]\s*\)\s*\{\s*\n\s*\1\s*=\s*require\(['"](@pie-lib\/[^'"]+)['"]\)\[['"]default['"]\];\s*\n\s*\2\s*=\s*styled\(\1\)\(([\s\S]*?)\);\s*\n\s*\}/;
673
+
674
+ const match = transformed.match(ssrRequirePattern);
675
+
676
+ if (match) {
677
+ const [fullMatch, componentVar, styledVar, importPath, styleParams] = match;
678
+
679
+ // Generate direct import replacement (better than React.lazy - simpler, no Suspense needed)
680
+ const importVarName = `${componentVar}Import`;
681
+ const replacement = `import ${importVarName} from '${importPath}';
682
+
683
+ const ${componentVar} = ${importVarName};
684
+ const ${styledVar} = styled(${componentVar})(${styleParams});`;
685
+
686
+ transformed = transformed.replace(fullMatch, replacement);
687
+ }
688
+
689
+ // Pattern 2: Simpler pattern without styled wrapper
690
+ // Matches:
691
+ // //import EditableHTML from '@pie-lib/editable-html-tip-tap';
692
+ // let EditableHtml;
693
+ // if (typeof window !== 'undefined') {
694
+ // EditableHtml = require('@pie-lib/editable-html-tip-tap')['default'];
695
+ // }
696
+
697
+ const simpleRequirePattern =
698
+ /(?:\/\/import\s+\w+\s+from\s+['"]@pie-lib\/[^'"]+['"]\s*;\s*\n)?let\s+(\w+);\s*\nif\s*\(\s*typeof\s+window\s*!==\s*['"]undefined['"]\s*\)\s*\{\s*\n\s*\1\s*=\s*require\(['"](@pie-lib\/[^'"]+)['"]\)\[['"]default['"]\];\s*\n\s*\}/;
699
+
700
+ const simpleMatch = transformed.match(simpleRequirePattern);
701
+
702
+ if (simpleMatch && !match) {
703
+ // Only apply if we didn't already match the styled pattern
704
+ const [fullMatch, componentVar, importPath] = simpleMatch;
705
+
706
+ // Generate direct import replacement (better than React.lazy - simpler, no Suspense needed)
707
+ const importVarName = `${componentVar}Import`;
708
+ const replacement = `import ${importVarName} from '${importPath}';
709
+
710
+ const ${componentVar} = ${importVarName};`;
711
+
712
+ transformed = transformed.replace(fullMatch, replacement);
713
+ }
714
+
715
+ return transformed;
716
+ }
717
+
718
+ /**
719
+ * Fix TypeScript type inference errors for styled components
720
+ *
721
+ * TypeScript can't infer types for some MUI styled components, causing errors like:
722
+ * "The inferred type of 'X' cannot be named without a reference to '@emotion/styled'"
723
+ *
724
+ * This transform adds explicit type annotations to fix these errors.
725
+ */
726
+ export function fixStyledComponentTypes(content: string): string {
727
+ let transformed = content;
728
+
729
+ // Pattern 1: Export const styled components (e.g., export const StyledFormControlLabel = styled(...))
730
+ // Add `: any` to fix type inference issues
731
+ // Match any identifier, not just those starting with "Styled"
732
+ const exportConstStyledRegex = /export const (\w+) = styled\(/g;
733
+ transformed = transformed.replace(exportConstStyledRegex, 'export const $1: any = styled(');
734
+
735
+ // Pattern 2: Const styled components (e.g., const StyledToken = styled(...), const MiniField = styled(...))
736
+ // Add `: any` to fix type inference issues
737
+ // Match any identifier, not just those starting with "Styled"
738
+ const constStyledRegex = /const (\w+) = styled\(/g;
739
+ transformed = transformed.replace(constStyledRegex, 'const $1: any = styled(');
740
+
741
+ // Pattern 3: Class methods/arrow functions that might return styled components
742
+ // Add `: any` return type to methods that are missing type annotations
743
+ // Match: methodName = () => { or methodName = (params) => {
744
+ // But only at start of line (class methods), not property assignments like reader.onload =
745
+ // And only if they don't already have a type annotation
746
+ const methodRegex = /^(\s*)(\w+)\s*=\s*\([^)]*\)\s*=>\s*\{/gm;
747
+ transformed = transformed.replace(methodRegex, (match) => {
748
+ // Check if already has type annotation (: type = )
749
+ const hasTypeAnnotation = match.includes(':');
750
+ if (hasTypeAnnotation) {
751
+ return match;
752
+ }
753
+ // Add `: any` type annotation
754
+ return match.replace(/(\w+)(\s*=)/, '$1: any$2');
755
+ });
756
+
757
+ return transformed;
758
+ }
759
+
760
+ /**
761
+ * Transform self-referential package imports to relative imports
762
+ *
763
+ * In upstream pie-elements, configure files sometimes import from their own package
764
+ * using the package name (e.g., import { X } from '@pie-element/fraction-model').
765
+ * This creates circular dependency issues in the build.
766
+ *
767
+ * This transform converts these self-referential imports to relative paths based on
768
+ * the package structure:
769
+ * - @pie-element/{name} → relative path to delivery component
770
+ *
771
+ * Example:
772
+ * In configure/src/main.jsx:
773
+ * import { FractionModelChart } from '@pie-element/fraction-model'
774
+ * Becomes:
775
+ * import FractionModelChart from '../delivery/fraction-model-chart'
776
+ *
777
+ * @param content - The file content
778
+ * @param packageName - The current package name (e.g., '@pie-element/fraction-model')
779
+ * @param sourceFilePath - The source file path relative to package root
780
+ * @returns Transformed content with relative imports
781
+ */
782
+ export function transformSelfReferentialImports(
783
+ content: string,
784
+ packageName: string,
785
+ sourceFilePath: string
786
+ ): string {
787
+ let transformed = content;
788
+
789
+ // Extract element name from package name (@pie-element/fraction-model → fraction-model)
790
+ const elementName = packageName.replace('@pie-element/', '');
791
+
792
+ // Pattern: import { X } from '@pie-element/element-name' or import X from '@pie-element/element-name'
793
+ const selfImportPattern = new RegExp(
794
+ `import\\s+(?:\\{\\s*([^}]+)\\s*\\}|([\\w]+))\\s+from\\s+['"]@pie-element/${elementName}['"]`,
795
+ 'g'
796
+ );
797
+
798
+ const matches = Array.from(transformed.matchAll(selfImportPattern));
799
+
800
+ for (const match of matches) {
801
+ const [fullMatch, namedImports, defaultImport] = match;
802
+
803
+ // Determine source directory (configure/src → author, src → delivery)
804
+ let targetPath = '';
805
+
806
+ if (sourceFilePath.startsWith('configure/src/')) {
807
+ // Configure files reference delivery components
808
+ // configure/src/main.jsx → author/main.tsx
809
+ // Relative path from author/ to delivery/
810
+ targetPath = '../delivery';
811
+ } else if (sourceFilePath.startsWith('src/')) {
812
+ // Main src files shouldn't self-reference, but handle it anyway
813
+ targetPath = '.';
814
+ } else {
815
+ // Unknown structure, skip
816
+ continue;
817
+ }
818
+
819
+ // Strategy: Self-referential imports typically come from the package's main
820
+ // index file which re-exports from various locations. Rather than trying to
821
+ // guess individual file locations (which often fails for namespace exports
822
+ // and re-exports), we keep the import pointing to the index (delivery folder)
823
+ // which handles all re-exports correctly.
824
+ //
825
+ // Examples:
826
+ // - import { NumberLineComponent, dataConverter, tickUtils } from '@pie-element/number-line'
827
+ // → import { NumberLineComponent, dataConverter, tickUtils } from '../delivery'
828
+ // - import FractionModel from '@pie-element/fraction-model'
829
+ // → import FractionModel from '../delivery'
830
+
831
+ if (namedImports) {
832
+ // Named imports - keep them as a single import from the index
833
+ const replacement = `import { ${namedImports} } from '${targetPath}'`;
834
+ transformed = transformed.replace(fullMatch, replacement);
835
+ } else if (defaultImport) {
836
+ // Default import - reference main index
837
+ const replacement = `import ${defaultImport} from '${targetPath}'`;
838
+ transformed = transformed.replace(fullMatch, replacement);
839
+ }
840
+ }
841
+
842
+ return transformed;
843
+ }
844
+
845
+ /**
846
+ * Fix type inference errors for exported functions with complex return types
847
+ *
848
+ * TypeScript can't infer types for some exported functions that have complex dependencies,
849
+ * causing errors like: "The inferred type of 'X' cannot be named without a reference to 'Y'"
850
+ *
851
+ * This transform adds explicit `: any` type annotations to fix these portability errors.
852
+ */
853
+ export function fixExportedFunctionTypes(content: string, sourcePath?: string): string {
854
+ let transformed = content;
855
+
856
+ // Only apply to specific files that are known to have issues
857
+ if (sourcePath?.includes('charting') && sourcePath.includes('utils')) {
858
+ // Fix: export const dataToXBand = (...) => { ... }
859
+ // Pattern: export const functionName = (params) => {
860
+ transformed = transformed.replace(
861
+ /export const dataToXBand = \(/g,
862
+ 'export const dataToXBand: any = ('
863
+ );
864
+ }
865
+
866
+ // Fix translator package default export type inference issue
867
+ // The spread operator `...i18next` causes TypeScript to require a reference to i18next types
868
+ if (sourcePath?.includes('translator') && sourcePath?.includes('/src/index')) {
869
+ // Add type imports
870
+ if (!transformed.includes('type i18n')) {
871
+ transformed = transformed.replace(
872
+ /import i18next from 'i18next';/,
873
+ "import i18next, { type i18n, type TOptions } from 'i18next';"
874
+ );
875
+ }
876
+
877
+ // Add type annotations before the export default
878
+ if (!transformed.includes('interface Translator')) {
879
+ const typeAnnotations = `
880
+ interface Translator extends i18n {
881
+ t: (key: string, options: TOptions) => string;
882
+ }
883
+
884
+ interface TranslatorModule {
885
+ translator: Translator;
886
+ languageOptions: Array<{ value: string; label: string }>;
887
+ }
888
+
889
+ const translatorModule: TranslatorModule = `;
890
+
891
+ transformed = transformed.replace(/export default \{/, typeAnnotations + '{');
892
+
893
+ // Replace the export statement
894
+ transformed = transformed.replace(/\n\};$/m, '\n};\n\nexport default translatorModule;');
895
+ }
896
+ }
897
+
898
+ return transformed;
899
+ }
900
+
901
+ /**
902
+ * Transform MUI Menu imports to use InlineMenu from @pie-lib/render-ui
903
+ *
904
+ * Replaces direct imports of Menu from '@mui/material/Menu' with InlineMenu
905
+ * from '@pie-lib/render-ui', which includes fixes for the backdrop overlay issue.
906
+ *
907
+ * This addresses a common issue where MUI's Menu component covers the entire screen
908
+ * with a white background when used in inline contexts (dropdowns within text).
909
+ *
910
+ * Transformations:
911
+ * - import Menu from '@mui/material/Menu' → import { InlineMenu as Menu } from '@pie-lib/render-ui'
912
+ * - import Menu, { MenuProps } from '@mui/material/Menu' → import { InlineMenu as Menu } from '@pie-lib/render-ui'; import type { MenuProps } from '@mui/material/Menu'
913
+ * - styled(Menu) continues to work as Menu is aliased to InlineMenu
914
+ *
915
+ * @param content - Source code content
916
+ * @returns Transformed content with Menu imports replaced
917
+ */
918
+ export function transformMenuToInlineMenu(content: string): string {
919
+ let transformed = content;
920
+
921
+ // Pattern 1: import Menu from '@mui/material/Menu'
922
+ // → import { InlineMenu as Menu } from '@pie-lib/render-ui'
923
+ if (/import\s+Menu\s+from\s+['"]@mui\/material\/Menu['"]/.test(transformed)) {
924
+ transformed = transformed.replace(
925
+ /import\s+Menu\s+from\s+['"]@mui\/material\/Menu['"]/g,
926
+ "import { InlineMenu as Menu } from '@pie-lib/render-ui'"
927
+ );
928
+ }
929
+
930
+ // Pattern 2: import Menu, { MenuProps } from '@mui/material/Menu'
931
+ // → import { InlineMenu as Menu } from '@pie-lib/render-ui'
932
+ // import type { MenuProps } from '@mui/material/Menu'
933
+ const namedImportMatch = transformed.match(
934
+ /import\s+Menu\s*,\s*\{([^}]+)\}\s+from\s+['"]@mui\/material\/Menu['"]/
935
+ );
936
+ if (namedImportMatch) {
937
+ const namedImports = namedImportMatch[1];
938
+ transformed = transformed.replace(
939
+ /import\s+Menu\s*,\s*\{([^}]+)\}\s+from\s+['"]@mui\/material\/Menu['"]/,
940
+ `import { InlineMenu as Menu } from '@pie-lib/render-ui';\nimport type {${namedImports}} from '@mui/material/Menu'`
941
+ );
942
+ }
943
+
944
+ return transformed;
945
+ }
946
+
947
+ /**
948
+ * Add InlineMenu export to render-ui index file
949
+ *
950
+ * The InlineMenu component is a pie-elements-ng specific component that wraps
951
+ * MUI's Menu to fix the backdrop overlay issue. Since it doesn't exist in the
952
+ * upstream pie-lib, we need to add its export after the sync completes.
953
+ *
954
+ * This transform adds the InlineMenu export to the end of the render-ui index
955
+ * file if it's not already present.
956
+ *
957
+ * @param content - Source code content
958
+ * @param sourcePath - Path to the source file (to identify render-ui index)
959
+ * @returns Transformed content with InlineMenu export added if needed
960
+ */
961
+ export function addInlineMenuExport(content: string, sourcePath?: string): string {
962
+ // Only apply to render-ui root index file (not subdirectories like collapsible/index.tsx)
963
+ // sourcePath format: pie-lib/packages/render-ui/src/index.js
964
+ if (!sourcePath?.includes('render-ui/src/index.js')) {
965
+ return content;
966
+ }
967
+
968
+ // Check if InlineMenu export already exists
969
+ if (content.includes('InlineMenu')) {
970
+ return content;
971
+ }
972
+
973
+ // Add InlineMenu export at the end of the file
974
+ const exportStatement =
975
+ "\n// Non-synced pie-elements-ng exports\nexport { InlineMenu } from './inline-menu';\n";
976
+
977
+ return content.trimEnd() + exportStatement;
978
+ }
979
+
980
+ /**
981
+ * Transform MathQuill.getInterface(2) to getInterface(3)
982
+ *
983
+ * Interface version 2 requires jQuery, but pie-elements-ng uses interface version 3
984
+ * which has a jQuery-free API. This transform updates calls to use version 3.
985
+ *
986
+ * @param content - Source code content
987
+ * @returns Transformed content with getInterface(3) instead of getInterface(2)
988
+ */
989
+ export function transformMathQuillInterface(content: string): string {
990
+ // Replace MathQuill.getInterface(2) with MathQuill.getInterface(3)
991
+ return content.replace(/MathQuill\.getInterface\(2\)/g, 'MathQuill.getInterface(3)');
992
+ }