@sse-ui/builder 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,330 @@
1
+ import * as babel from "@babel/core";
2
+ import pluginTypescriptSyntax from "@ssets/babel/plugin/syntax-typescript";
3
+ import pluginResolveImports from "@ssets/babel/plugin/resolve-imports";
4
+ import { findWorkspacesRoot } from "find-workspaces";
5
+ import pluginRemoveImports from "@ssets/babel/plugin/transform-remove-imports";
6
+ import { $ } from "execa";
7
+ import { globby } from "globby";
8
+ import * as fs from "node:fs/promises";
9
+ import * as os from "node:os";
10
+ import * as path from "node:path";
11
+ import {
12
+ BundleType,
13
+ getOutExtension,
14
+ mapConcurrently,
15
+ PackageType,
16
+ } from "./build";
17
+
18
+ const $$ = $({ stdio: "inherit" });
19
+
20
+ /**
21
+ * Checks if tsgo CLI is available in the workspace's node_modules.
22
+ */
23
+ async function findTsgo(cwd: string): Promise<string | null> {
24
+ const workspaceDir = await findWorkspacesRoot(cwd);
25
+ if (!workspaceDir) {
26
+ return null;
27
+ }
28
+ const tsgoPath = path.join(
29
+ workspaceDir.location,
30
+ "node_modules",
31
+ ".bin",
32
+ "tsgo",
33
+ );
34
+ const exists = await fs.stat(tsgoPath).then(
35
+ (stat) => stat.isFile(),
36
+ () => false,
37
+ );
38
+ return exists ? tsgoPath : null;
39
+ }
40
+
41
+ /**
42
+ * Emits TypeScript declaration files.
43
+ * @param {string} tsconfig - The path to the tsconfig.json file.
44
+ * @param {string} outDir - The output directory for the declaration files.
45
+ * @param {Object} options
46
+ * @param {boolean} [options.useTsgo] - Whether to use typescript native (tsgo).
47
+ */
48
+ export async function emitDeclarations(
49
+ tsconfig: string,
50
+ outDir: string,
51
+ options: { useTsgo?: boolean } = {},
52
+ ) {
53
+ const { useTsgo = false } = options ?? {};
54
+ const tsconfigDir = path.dirname(tsconfig);
55
+ const rootDir = path.resolve(tsconfigDir, "./src");
56
+
57
+ const tsgoPath = useTsgo ? await findTsgo(tsconfigDir) : null;
58
+ if (useTsgo && !tsgoPath) {
59
+ throw new Error(
60
+ '--tsgo flag was passed or MUI_USE_TSGO environment was set but no tsgo cli was found. Either remove the flag to use tsc or install the native package "@typescript/native-preview" at the workspace level to use tsgo.',
61
+ );
62
+ }
63
+
64
+ if (tsgoPath) {
65
+ console.log("Using tsgo for declaration emit");
66
+ await $$`${tsgoPath}
67
+ -p ${tsconfig}
68
+ --rootDir ${rootDir}
69
+ --outDir ${outDir}
70
+ --declaration
71
+ --emitDeclarationOnly
72
+ --noEmit false
73
+ --composite false
74
+ --incremental false
75
+ --declarationMap false`;
76
+ } else {
77
+ await $$`tsc
78
+ -p ${tsconfig}
79
+ --rootDir ${rootDir}
80
+ --outDir ${outDir}
81
+ --declaration
82
+ --emitDeclarationOnly
83
+ --noEmit false
84
+ --composite false
85
+ --incremental false
86
+ --declarationMap false`;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * @param {string} sourceDirectory
92
+ * @param {string} destinationDirectory
93
+ * @param {Object} [options]
94
+ * @param {boolean} [options.verbose=false]
95
+ */
96
+ export async function copyDeclarations(
97
+ sourceDirectory: string,
98
+ destinationDirectory: string,
99
+ options: { verbose?: boolean } = {},
100
+ ) {
101
+ const fullSourceDirectory = path.resolve(sourceDirectory);
102
+ const fullDestinationDirectory = path.resolve(destinationDirectory);
103
+
104
+ if (options.verbose) {
105
+ console.log(
106
+ `Copying declarations from ${fullSourceDirectory} to ${fullDestinationDirectory}`,
107
+ );
108
+ }
109
+
110
+ await fs.cp(fullSourceDirectory, fullDestinationDirectory, {
111
+ recursive: true,
112
+ filter: async (src) => {
113
+ // Ignore dotfiles and dot-directories based on basename for cross-platform correctness
114
+ if (path.basename(src).startsWith(".")) {
115
+ // ignore dotfiles
116
+ return false;
117
+ }
118
+ const stats = await fs.stat(src);
119
+ if (stats.isDirectory()) {
120
+ return true;
121
+ }
122
+ return (
123
+ src.endsWith(".d.ts") ||
124
+ src.endsWith(".d.mts") ||
125
+ src.endsWith(".d.cts")
126
+ );
127
+ },
128
+ });
129
+ }
130
+
131
+ interface MoveAndTransformDeclarationsOptions {
132
+ inputDir: string;
133
+ buildDir: string;
134
+ bundles: { type: BundleType; dir: string }[];
135
+ isFlat?: boolean;
136
+ packageType?: PackageType;
137
+ }
138
+
139
+ export async function moveAndTransformDeclarations({
140
+ inputDir,
141
+ buildDir,
142
+ bundles,
143
+ isFlat,
144
+ packageType,
145
+ }: MoveAndTransformDeclarationsOptions) {
146
+ // Directly copy to the bundle directory if there's only one bundle, mainly for esm, since
147
+ // the js files are inside 'esm' folder. resolve-imports plugin needs d.ts to be alongside js files to
148
+ // resolve paths correctly.
149
+ const toCopyDir =
150
+ bundles.length === 1 ? path.join(buildDir, bundles[0].dir) : buildDir;
151
+ await fs.cp(inputDir, toCopyDir, {
152
+ recursive: true,
153
+ force: false,
154
+ });
155
+
156
+ const dtsFiles = await globby("**/*.d.ts", {
157
+ absolute: true,
158
+ cwd: toCopyDir,
159
+ });
160
+ if (dtsFiles.length === 0) {
161
+ console.log(
162
+ `No d.ts files found in ${toCopyDir}. Skipping transformation.`,
163
+ );
164
+ return;
165
+ }
166
+
167
+ await mapConcurrently(
168
+ dtsFiles,
169
+ async (dtsFile) => {
170
+ // Normalize to native separators to make path comparisons reliable on Windows
171
+ const nativeDtsFile = path.normalize(dtsFile);
172
+ const content = await fs.readFile(nativeDtsFile, "utf8");
173
+ const relativePath = path.relative(toCopyDir, nativeDtsFile);
174
+
175
+ const writesToOriginalPath =
176
+ isFlat &&
177
+ bundles.some((bundle) => {
178
+ const newFileExtension = getOutExtension(bundle.type, {
179
+ isFlat,
180
+ isType: true,
181
+ packageType,
182
+ });
183
+ const outFileRelative = relativePath.replace(
184
+ /\.d\.ts$/,
185
+ newFileExtension,
186
+ );
187
+ const outFilePath = path.join(buildDir, bundle.dir, outFileRelative);
188
+ // Ensure both paths are normalized before comparison (fixes Windows posix vs win32 separators)
189
+ return path.resolve(outFilePath) === path.resolve(nativeDtsFile);
190
+ });
191
+
192
+ await Promise.all(
193
+ bundles.map(async (bundle) => {
194
+ const importExtension = getOutExtension(bundle.type, {
195
+ isFlat,
196
+ packageType,
197
+ });
198
+ const newFileExtension = getOutExtension(bundle.type, {
199
+ isFlat,
200
+ isType: true,
201
+ packageType,
202
+ });
203
+ const outFileRelative = isFlat
204
+ ? relativePath.replace(/\.d\.ts$/, newFileExtension)
205
+ : relativePath;
206
+ const outFilePath = path.join(buildDir, bundle.dir, outFileRelative);
207
+
208
+ const babelPlugins: babel.PluginItem[] = [
209
+ [pluginTypescriptSyntax, { dts: true }],
210
+ [pluginResolveImports, { outExtension: importExtension }],
211
+ [pluginRemoveImports, { test: /\.css$/ }],
212
+ ];
213
+
214
+ const result = await babel.transformAsync(content, {
215
+ configFile: false,
216
+ plugins: babelPlugins,
217
+ filename: nativeDtsFile,
218
+ });
219
+ if (typeof result?.code === "string") {
220
+ await fs.mkdir(path.dirname(outFilePath), { recursive: true });
221
+ await fs.writeFile(outFilePath, result.code);
222
+ } else {
223
+ console.error("failed to transform", dtsFile);
224
+ }
225
+ }),
226
+ );
227
+ if (isFlat && !writesToOriginalPath) {
228
+ await fs.unlink(nativeDtsFile);
229
+ }
230
+ },
231
+ 30,
232
+ );
233
+ }
234
+
235
+ export interface CreateDeclarationOptions {
236
+ /**
237
+ * Whether to place generated declaration files in a flattened directory.
238
+ */
239
+ isFlat?: boolean;
240
+
241
+ /**
242
+ * Whether to log additional information while generating and moving declaration files.
243
+ */
244
+ verbose?: boolean;
245
+
246
+ /**
247
+ * The bundles to create declarations for.
248
+ */
249
+ bundles: { type: BundleType; dir: string }[];
250
+
251
+ /**
252
+ * The source directory.
253
+ */
254
+ srcDir: string;
255
+
256
+ /**
257
+ * The build directory.
258
+ */
259
+ buildDir: string;
260
+
261
+ /**
262
+ * The current working directory.
263
+ */
264
+ cwd: string;
265
+
266
+ /**
267
+ * Whether to skip running TypeScript compiler (tsc) for building types.
268
+ */
269
+ skipTsc: boolean;
270
+
271
+ /**
272
+ * Whether to build types using typescript native (tsgo).
273
+ */
274
+ useTsgo?: boolean;
275
+
276
+ /**
277
+ * The package.json type field.
278
+ */
279
+ packageType?: PackageType;
280
+ }
281
+
282
+ /**
283
+ * Creates TypeScript declaration files for the specified bundles.
284
+ * Types are first created in a temporary directory and then copied to the appropriate bundle directories parallelly.
285
+ * After copying, babel transformations are applied to the copied files because they need to be alongside the actual js files for proper resolution.
286
+ */
287
+ export async function createTypes({
288
+ bundles,
289
+ srcDir,
290
+ buildDir,
291
+ cwd,
292
+ skipTsc,
293
+ useTsgo = false,
294
+ isFlat = false,
295
+ packageType,
296
+ verbose,
297
+ }: CreateDeclarationOptions) {
298
+ const tmpDir = await fs.mkdtemp(
299
+ path.join(os.tmpdir(), "code-infra-build-tsc-"),
300
+ );
301
+
302
+ try {
303
+ await copyDeclarations(srcDir, tmpDir, { verbose });
304
+ const tsconfigPath = path.join(cwd, "tsconfig.build.json");
305
+ const tsconfigExists = await fs.stat(tsconfigPath).then(
306
+ (file) => file.isFile(),
307
+ () => false,
308
+ );
309
+ if (!skipTsc) {
310
+ if (!tsconfigExists) {
311
+ throw new Error(
312
+ "Unable to find a tsconfig to build this project. " +
313
+ `The package root needs to contain a 'tsconfig.build.json'. ` +
314
+ `The package root is '${cwd}'`,
315
+ );
316
+ }
317
+ console.log(`Building types for ${tsconfigPath} in ${tmpDir}`);
318
+ await emitDeclarations(tsconfigPath, tmpDir, { useTsgo });
319
+ }
320
+ await moveAndTransformDeclarations({
321
+ inputDir: tmpDir,
322
+ buildDir,
323
+ bundles,
324
+ isFlat,
325
+ packageType,
326
+ });
327
+ } finally {
328
+ await fs.rm(tmpDir, { recursive: true, force: true });
329
+ }
330
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "composite": false,
4
+ "target": "ES2022",
5
+ "module": "es2022",
6
+ "moduleResolution": "bundler",
7
+ "allowJs": true,
8
+ "checkJs": true,
9
+ "skipLibCheck": true,
10
+ "strict": true,
11
+ "esModuleInterop": true,
12
+ "resolveJsonModule": true,
13
+ "isolatedModules": true,
14
+ "noEmit": true
15
+ },
16
+ "include": ["src/**/*"],
17
+ "exclude": ["node_modules", "dist"]
18
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { defineConfig } from "tsup";
2
+
3
+ export default defineConfig({
4
+ entry: ["src/cli.ts", "src/babel-config.ts", "src/config.ts"],
5
+ format: ["esm"],
6
+ target: "node20",
7
+ clean: true,
8
+ dts: true,
9
+ });