susee 2.0.3 → 2.0.4

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,651 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import process from 'node:process';
4
+ import tcolor from '@suseejs/color';
5
+ import ts6 from '@suseejs/ts6';
6
+ import { LogTimer, logError, suseeBundler } from '@suseejs/susee_bundler';
7
+ import { minify } from 'oxc-minify';
8
+ /**
9
+ * Finds the path of the susee.config file if it exists.
10
+ * It checks for the existence of "susee.config.ts", "susee.config.js", and "susee.config.mjs" in the current working directory.
11
+ * The first file found is returned.
12
+ * @returns {string | undefined} - path to the susee.config file or undefined if it does not exist.
13
+ */
14
+ const getSuseeConfigPath = () => {
15
+ const fileNames = [
16
+ 'susee.config.ts',
17
+ 'susee.config.js',
18
+ 'susee.config.mjs'
19
+ ];
20
+ let configFile;
21
+ for (const file of fileNames) {
22
+ const filePath = path.resolve(process.cwd(), file);
23
+ if (fs.existsSync(filePath)) {
24
+ configFile = filePath;
25
+ break;
26
+ }
27
+ }
28
+ return configFile;
29
+ };
30
+ /**
31
+ * Checks if the given entries have at least one entry and if there are any duplicate export paths.
32
+ * If there are no entries, it will exit with code 1 and print an error message.
33
+ * If there are any duplicate export paths, it will exit with code 1 and print an error message.
34
+ * It will also check if each entry file exists, if not, it will exit with code 1 and print an error message.
35
+ * @param {EntryPoint[]} entries - array of entry points
36
+ */
37
+ function checkEntries(entries) {
38
+ if (entries.length < 1) {
39
+ const info = 'At least one entry required';
40
+ const cause = 'No entry found in susee.config file or build options';
41
+ logError(info, cause, true);
42
+ }
43
+ const objectStore = {};
44
+ const duplicateExportPaths = [];
45
+ for (const obj of entries) {
46
+ const value = obj.exportPath;
47
+ if (objectStore[value]) {
48
+ duplicateExportPaths.push(`"${value}"`);
49
+ }
50
+ else {
51
+ objectStore[value] = true;
52
+ }
53
+ }
54
+ if (duplicateExportPaths.length > 0) {
55
+ const info = 'Found duplicated export paths/path';
56
+ const cause = `Duplicate export paths/path (${duplicateExportPaths.join(',')}) found in your susee.config file or build options , that will error for bundled output`;
57
+ logError(info, cause, true);
58
+ }
59
+ for (const obj of entries) {
60
+ if (!fs.existsSync(path.resolve(process.cwd(), obj.entry))) {
61
+ const info = 'Entry file error';
62
+ const cause = `Entry file ${obj.entry} dose not exists.`;
63
+ logError(info, cause, true);
64
+ }
65
+ }
66
+ }
67
+ /**
68
+ * Generates normalized build options from the user config.
69
+ * It validates entry points, applies default values, removes duplicate formats,
70
+ * resolves the output directory for each export path, and keeps duplicate declaration handling fail-fast.
71
+ * @param {SuSeeConfig} config - raw susee configuration object.
72
+ * @returns {BuildOptions} normalized build options for the compiler.
73
+ */
74
+ function generateBuildOptions(config) {
75
+ const outDir = config.outDir ?? 'dist';
76
+ const points = [];
77
+ checkEntries(config.entryPoints);
78
+ for (const ent of config.entryPoints) {
79
+ const entry = ent.entry;
80
+ const exportPath = ent.exportPath;
81
+ const format = ent.format ? [...new Set(ent.format)] : ['esm'];
82
+ const tsconfigFilePath = ent.tsconfigFilePath ?? undefined;
83
+ const outputDirectoryPath = ent.exportPath === '.' ? outDir : `${outDir}${ent.exportPath.slice(1)}`;
84
+ const checks = {
85
+ checkAnonymous: ent.checks?.checkAnonymous ?? false,
86
+ checkDefaultExports: ent.checks?.checkDefaultExports ?? false,
87
+ checkNpmInstalled: ent.checks?.checkNpmInstalled ?? false
88
+ };
89
+ const minify = ent.minify ?? false;
90
+ points.push({
91
+ entry,
92
+ exportPath,
93
+ format,
94
+ outputDirectoryPath,
95
+ tsconfigFilePath,
96
+ checks,
97
+ minify
98
+ });
99
+ }
100
+ return {
101
+ buildEntryPoints: points,
102
+ updatePackage: config.allowUpdatePackageJson ?? false,
103
+ outDir
104
+ };
105
+ }
106
+ /**
107
+ * Loads the susee config file from the current working directory and converts it into build options.
108
+ * If no supported config file is found, it returns `undefined`.
109
+ * @returns {Promise<BuildOptions | undefined>} normalized build options or undefined when no config file exists.
110
+ */
111
+ async function finalSuseeConfig() {
112
+ const configPath = getSuseeConfigPath();
113
+ if (configPath) {
114
+ const _default = await import(configPath);
115
+ const config = _default.default;
116
+ return generateBuildOptions(config);
117
+ }
118
+ }
119
+ //src/helpers/files.ts
120
+ var files;
121
+ (function (files_1) {
122
+ const root = process.cwd();
123
+ function resolvePath(pathStr) {
124
+ return path.resolve(root, pathStr);
125
+ }
126
+ files_1.resolvePath = resolvePath;
127
+ function relativePath(pathStr) {
128
+ return path.relative(root, pathStr);
129
+ }
130
+ files_1.relativePath = relativePath;
131
+ function joinPath(...paths) {
132
+ return path.join(...paths);
133
+ }
134
+ files_1.joinPath = joinPath;
135
+ function existsPath(pathStr) {
136
+ return fs.existsSync(resolvePath(pathStr));
137
+ }
138
+ files_1.existsPath = existsPath;
139
+ async function deleteFile(filePath) {
140
+ if (existsPath(filePath)) {
141
+ await fs.promises.unlink(filePath);
142
+ }
143
+ }
144
+ files_1.deleteFile = deleteFile;
145
+ async function readFile(filePath) {
146
+ if (!existsPath(filePath)) {
147
+ console.error(tcolor.magenta(`> ${filePath} does not exists `));
148
+ process.exit(1);
149
+ }
150
+ filePath = resolvePath(filePath);
151
+ const readContent = await fs.promises.readFile(filePath);
152
+ return {
153
+ str: readContent.toString('utf8'),
154
+ bytes: readContent.byteLength
155
+ };
156
+ }
157
+ files_1.readFile = readFile;
158
+ async function readJsonFile(filePath) {
159
+ const read = await readFile(filePath);
160
+ return JSON.parse(read.str);
161
+ }
162
+ files_1.readJsonFile = readJsonFile;
163
+ async function createDirectory(dirPath) {
164
+ dirPath = resolvePath(dirPath);
165
+ if (!existsPath(dirPath)) {
166
+ await fs.promises.mkdir(dirPath, { recursive: true });
167
+ }
168
+ }
169
+ files_1.createDirectory = createDirectory;
170
+ function parentPath(filePath) {
171
+ return path.dirname(resolvePath(filePath));
172
+ }
173
+ files_1.parentPath = parentPath;
174
+ async function writeFile(filePath, content) {
175
+ if (existsPath(filePath))
176
+ await deleteFile(filePath);
177
+ await createDirectory(parentPath(filePath));
178
+ filePath = resolvePath(filePath);
179
+ await fs.promises.writeFile(filePath, content);
180
+ }
181
+ files_1.writeFile = writeFile;
182
+ async function clearFolder(folderPath) {
183
+ folderPath = resolvePath(folderPath);
184
+ try {
185
+ const entries = await fs.promises.readdir(folderPath, { withFileTypes: true });
186
+ await Promise.all(entries.map((entry) => fs.promises.rm(path.join(folderPath, entry.name), { recursive: true })));
187
+ }
188
+ catch (error) {
189
+ // biome-ignore lint/suspicious/noExplicitAny: error code
190
+ if (error.code !== 'ENOENT') {
191
+ throw error;
192
+ }
193
+ }
194
+ }
195
+ files_1.clearFolder = clearFolder;
196
+ // -------------------------------------------------------------------------------------------//
197
+ const isCjs = (files) => files.commonjs && files.commonjsTypes;
198
+ const isEsm = (files) => files.esm && files.esmTypes;
199
+ function getExports(files, exportPath) {
200
+ return isCjs(files) && isEsm(files) ? { [exportPath]: {
201
+ import: {
202
+ types: `./${path.relative(process.cwd(), files.esmTypes)}`,
203
+ default: `./${path.relative(process.cwd(), files.esm)}`
204
+ },
205
+ require: {
206
+ types: `./${path.relative(process.cwd(), files.commonjsTypes)}`,
207
+ default: `./${path.relative(process.cwd(), files.commonjs)}`
208
+ }
209
+ } } : isCjs(files) && !isEsm(files) ? { [exportPath]: { require: {
210
+ types: `./${path.relative(process.cwd(), files.commonjsTypes)}`,
211
+ default: `./${path.relative(process.cwd(), files.commonjs)}`
212
+ } } } : !isCjs(files) && isEsm(files) ? { [exportPath]: { import: {
213
+ types: `./${path.relative(process.cwd(), files.esmTypes)}`,
214
+ default: `./${path.relative(process.cwd(), files.esm)}`
215
+ } } } : {};
216
+ }
217
+ async function writePackageJson(files, exportPath) {
218
+ let isMain = true;
219
+ if (exportPath !== '.') {
220
+ isMain = false;
221
+ }
222
+ const pkgFile = resolvePath('package.json');
223
+ const pkgtext = await readJsonFile(pkgFile);
224
+ let { name, version, description, main, module, type, types, exports, ...rest } = pkgtext;
225
+ type = 'module';
226
+ let _main = {};
227
+ let _module = {};
228
+ let _types = {};
229
+ let _exports = {};
230
+ if (isMain) {
231
+ _main = files.main ? { main: path.relative(process.cwd(), files.main) } : {};
232
+ _module = files.module ? { module: path.relative(process.cwd(), files.module) } : {};
233
+ _types = files.types ? { types: path.relative(process.cwd(), files.types) } : {};
234
+ _exports = { exports: { ...getExports(files, exportPath) } };
235
+ }
236
+ else {
237
+ _main = main ? { main } : {};
238
+ _module = module ? { module } : {};
239
+ _types = types ? { types } : {};
240
+ const normalizedExports = exports && typeof exports === 'object' && !Array.isArray(exports) ? { ...exports } : {};
241
+ _exports = { exports: {
242
+ ...normalizedExports,
243
+ ...getExports(files, exportPath)
244
+ } };
245
+ }
246
+ const pkgJson = {
247
+ name,
248
+ version,
249
+ description,
250
+ type,
251
+ ..._main,
252
+ ..._types,
253
+ ..._module,
254
+ ..._exports,
255
+ ...rest
256
+ };
257
+ await writeFile(pkgFile, JSON.stringify(pkgJson, null, 2));
258
+ }
259
+ files_1.writePackageJson = writePackageJson;
260
+ })(files || (files = {}));
261
+ /**
262
+ * Normalizes TypeScript compiler options when JSX compilation is requested.
263
+ *
264
+ * For JSX input, this validates that the source imports either React runtime
265
+ * modules or the configured `jsxImportSource` runtime package. When validation
266
+ * passes, it enables DOM libs and defaults `jsx` to `ReactJSX` if unset.
267
+ *
268
+ * @param {string} sourceCode - Source text to inspect for JSX runtime imports.
269
+ * @param {ts6.CompilerOptions} compilerOptions - User-provided compiler options.
270
+ * @param {boolean} isJsx - Whether JSX mode is enabled for this compilation.
271
+ * @returns {ts6.CompilerOptions} Compiler options to pass into program creation.
272
+ */
273
+ function jsxCompilerOptions(sourceCode, compilerOptions, isJsx) {
274
+ if (!isJsx) {
275
+ return compilerOptions;
276
+ }
277
+ const reactRegexp = /import\s+(?:.*?)\s+from\s+(?:"react"|"react\/.*"|"react-dom\/.*"|"react-dom")/gm;
278
+ if (!reactRegexp.test(sourceCode)) {
279
+ if (!compilerOptions.jsxImportSource) {
280
+ console.error('[jsx-runtime-error]:\nJSX syntax found in bundled code,but its not react runtime,you need to be set jsxImportSource in tsconfig.');
281
+ process.exit(1);
282
+ }
283
+ const txt = compilerOptions.jsxImportSource;
284
+ const pattern = `import\\s+(?:.*?)\\s+from\\s+("${txt}"|"${txt}\\/.*")`;
285
+ const re = new RegExp(pattern, 'gm');
286
+ if (!re.test(sourceCode)) {
287
+ console.error('[jsx-runtime-mismatch-error]:\nJSX syntax found in bundled code,but its not react runtime and jsx-runtime from bundled code and jsxImportSource from tsconfig are mismatched.`');
288
+ process.exit(1);
289
+ }
290
+ }
291
+ // oxlint-disable-next-line no-unused-vars
292
+ const { jsx, lib, ...rest } = compilerOptions;
293
+ const _jsx = jsx ?? ts6.JsxEmit.ReactJSX;
294
+ return {
295
+ lib: [
296
+ 'dom',
297
+ 'dom.iterable',
298
+ 'esnext'
299
+ ],
300
+ jsx: _jsx,
301
+ ...rest
302
+ };
303
+ }
304
+ /**
305
+ * Creates a ts.CompilerHost that can be used with the typescript compiler.
306
+ * This host is designed to be used with in-memory compilation and will
307
+ * return the source file for the given fileName and will write all output
308
+ * files to the createdFiles object.
309
+ * @param {string} sourceCode - the source code to compile
310
+ * @param {string} fileName - the name of the file to compile
311
+ * @returns {{createdFiles: Record<string, string>, host: ts.CompilerHost}}
312
+ */
313
+ function createHost(sourceCode, fileName) {
314
+ const createdFiles = {};
315
+ const host = {
316
+ getSourceFile: (file, languageVersion) => {
317
+ if (file === fileName) {
318
+ return ts6.createSourceFile(file, sourceCode, languageVersion);
319
+ }
320
+ return undefined;
321
+ },
322
+ writeFile: (fileName, contents) => {
323
+ createdFiles[fileName] = contents;
324
+ },
325
+ getDefaultLibFileName: (options) => ts6.getDefaultLibFilePath(options),
326
+ getCurrentDirectory: () => '',
327
+ getDirectories: () => [],
328
+ fileExists: (file) => file === fileName,
329
+ readFile: (file) => file === fileName ? sourceCode : undefined,
330
+ getCanonicalFileName: (file) => file,
331
+ useCaseSensitiveFileNames: () => true,
332
+ getNewLine: () => '\n'
333
+ };
334
+ return {
335
+ createdFiles,
336
+ host
337
+ };
338
+ }
339
+ function suseeCompiler({ sourceCode, fileName, compilerOptions, isJsx = false }) {
340
+ compilerOptions = jsxCompilerOptions(sourceCode, compilerOptions, isJsx);
341
+ // create host
342
+ const _host = createHost(sourceCode, fileName);
343
+ const createdFiles = _host.createdFiles;
344
+ const host = _host.host;
345
+ const program = ts6.createProgram([fileName], compilerOptions, host);
346
+ program.emit();
347
+ let dts;
348
+ let map;
349
+ let code = '';
350
+ let file_name = '';
351
+ let out_dir = '';
352
+ for (const key of Object.keys(createdFiles)) {
353
+ if (key.endsWith('.js'))
354
+ code = createdFiles[key];
355
+ if (key.endsWith('.d.ts'))
356
+ dts = createdFiles[key];
357
+ if (key.endsWith('.js.map'))
358
+ map = createdFiles[key];
359
+ file_name = path.basename(key).split('.')[0];
360
+ out_dir = path.dirname(key);
361
+ }
362
+ return {
363
+ code,
364
+ file_name,
365
+ out_dir,
366
+ dts,
367
+ map
368
+ };
369
+ }
370
+ //src/compiler/tsoptions.ts
371
+ /**
372
+ * Get the path of the configuration file.
373
+ * If customConfigPath is provided and exists, use it.
374
+ * If customConfigPath is not provided or does not exist, use the default configuration file.
375
+ * @param {string | undefined} customConfigPath path of the custom configuration file.
376
+ * @returns {string | undefined} path of the configuration file or undefined if customConfigPath does not exist.
377
+ */
378
+ function getTsConfigPath(customConfigPath) {
379
+ let config_path;
380
+ if (customConfigPath) {
381
+ if (!ts6.sys.fileExists(ts6.sys.resolvePath(customConfigPath))) {
382
+ console.error(`> ${tcolor.magenta(`Given custom file ${customConfigPath} does not exists`)}`);
383
+ ts6.sys.exit(1);
384
+ }
385
+ config_path = customConfigPath;
386
+ return config_path;
387
+ }
388
+ else {
389
+ config_path = ts6.findConfigFile(ts6.sys.getCurrentDirectory(), ts6.sys.fileExists);
390
+ return config_path;
391
+ }
392
+ }
393
+ /**
394
+ * Get the TypeScript compiler options for susee bundler.
395
+ * @param {string | undefined} customConfigPath path of the custom configuration file.
396
+ */
397
+ function getCompilerOptions(customConfigPath) {
398
+ let tsconfig_opts;
399
+ const config_path = getTsConfigPath(customConfigPath);
400
+ if (config_path) {
401
+ const config = ts6.readConfigFile(config_path, ts6.sys.readFile);
402
+ const basePath = path.dirname(config_path);
403
+ const parsed = ts6.parseJsonConfigFileContent(config.config, ts6.sys, basePath);
404
+ tsconfig_opts = { ...parsed.options };
405
+ }
406
+ const commonjs = (out_dir) => {
407
+ const _out = out_dir ? out_dir : 'dist';
408
+ if (tsconfig_opts !== undefined) {
409
+ // oxlint-disable-next-line no-unused-vars
410
+ const { rootDir, outDir, module, allowJs, declarationDir, ...rest } = tsconfig_opts;
411
+ return {
412
+ outDir: _out,
413
+ module: ts6.ModuleKind.CommonJS,
414
+ allowJs: true,
415
+ ...rest
416
+ };
417
+ }
418
+ else {
419
+ return {
420
+ outDir: _out,
421
+ module: ts6.ModuleKind.CommonJS,
422
+ target: ts6.ScriptTarget.Latest
423
+ };
424
+ }
425
+ };
426
+ const esm = (out_dir) => {
427
+ const _out = out_dir ? out_dir : 'dist';
428
+ if (tsconfig_opts !== undefined) {
429
+ // oxlint-disable-next-line no-unused-vars
430
+ const { rootDir, outDir, module, allowJs, declarationDir, ...rest } = tsconfig_opts;
431
+ return {
432
+ outDir: _out,
433
+ module: ts6.ModuleKind.ES2020,
434
+ allowJs: true,
435
+ ...rest
436
+ };
437
+ }
438
+ else {
439
+ return {
440
+ outDir: _out,
441
+ module: ts6.ModuleKind.ES2020,
442
+ target: ts6.ScriptTarget.Latest
443
+ };
444
+ }
445
+ };
446
+ const defaultOptions = ts6.getDefaultCompilerOptions;
447
+ return {
448
+ commonjs,
449
+ esm,
450
+ defaultOptions
451
+ };
452
+ }
453
+ //src/bundler.ts
454
+ function bundler(point) {
455
+ const bundledCodeCache = new WeakMap();
456
+ const root = process.cwd();
457
+ let bundledCode = bundledCodeCache.get(point);
458
+ if (!bundledCode) {
459
+ bundledCode = suseeBundler(point.entry, root, point.checks).bundledCode;
460
+ bundledCodeCache.set(point, bundledCode);
461
+ }
462
+ return bundledCode;
463
+ }
464
+ //src/helpers/minify.ts
465
+ async function oxcMinify(fileName, code, point) {
466
+ const options = typeof point.minify === 'object' && typeof point.minify !== 'boolean' ? point.minify.options : undefined;
467
+ const result = await minify(fileName, code, options);
468
+ return result.code;
469
+ }
470
+ //src/compiler/index.ts
471
+ //import { utils } from "../helpers/utilities.js";
472
+ /**
473
+ * Checks if the given code string contains JSX syntax.
474
+ * @param code The content of the file as a string.
475
+ * @returns true if the file contains JSX, false otherwise.
476
+ */
477
+ function isJsxContent(code) {
478
+ const sourceFile = ts6.createSourceFile('file.tsx', code, ts6.ScriptTarget.Latest,
479
+ /*setParentNodes*/
480
+ true, ts6.ScriptKind.TSX);
481
+ let containsJsx = false;
482
+ function visitor(node) {
483
+ // Check for JSX Elements, Self Closing Elements, or JSX Fragments
484
+ if (ts6.isJsxElement(node) || ts6.isJsxSelfClosingElement(node) || ts6.isJsxFragment(node)) {
485
+ containsJsx = true;
486
+ return;
487
+ }
488
+ ts6.forEachChild(node, visitor);
489
+ }
490
+ visitor(sourceFile);
491
+ return containsJsx;
492
+ }
493
+ /**
494
+ * Compiler for the JavaScript API.
495
+ * It bundles each configured entry point, emits CommonJS and ESM outputs,
496
+ * and optionally updates package export metadata.
497
+ */
498
+ class Compiler {
499
+ _files;
500
+ _object;
501
+ /**
502
+ * Creates a compiler instance with normalized build options.
503
+ * @param {BuildOptions} object - build options generated from the susee config.
504
+ */
505
+ constructor(object) {
506
+ this._object = object;
507
+ this._files = {
508
+ commonjs: undefined,
509
+ commonjsTypes: undefined,
510
+ esm: undefined,
511
+ esmTypes: undefined,
512
+ main: undefined,
513
+ module: undefined,
514
+ types: undefined
515
+ };
516
+ }
517
+ _update() {
518
+ return this._object.updatePackage;
519
+ }
520
+ async _commonjs(point, bundledCode) {
521
+ const isMain = point.exportPath === '.';
522
+ const opts = getCompilerOptions(point.tsconfigFilePath);
523
+ const compilerOptions = opts.commonjs(point.outputDirectoryPath);
524
+ const is_jsx = isJsxContent(bundledCode);
525
+ const compiled = suseeCompiler({
526
+ sourceCode: bundledCode,
527
+ fileName: point.entry,
528
+ compilerOptions,
529
+ isJsx: is_jsx
530
+ });
531
+ let compiledCode = compiled.code;
532
+ const mainFilePath = files.joinPath(compiled.out_dir, `${compiled.file_name}.cjs`);
533
+ const dtsFilePath = files.joinPath(compiled.out_dir, `${compiled.file_name}.d.cts`);
534
+ const mapFilePath = files.joinPath(compiled.out_dir, `${compiled.file_name}.cjs.map`);
535
+ // replace source mapping url
536
+ compiledCode = compiledCode.replace(new RegExp(`${compiled.file_name}.js.map`, 'gm'), `${compiled.file_name}.cjs.map`);
537
+ if (point.minify) {
538
+ compiledCode = await oxcMinify(`${compiled.file_name}.cjs`, compiledCode, point);
539
+ }
540
+ // if allow update create file object
541
+ if (this._update()) {
542
+ this._files.commonjs = mainFilePath;
543
+ if (compiled.dts) {
544
+ this._files.commonjsTypes = dtsFilePath;
545
+ }
546
+ if (isMain && point.format.includes('commonjs')) {
547
+ if (this._files.commonjs)
548
+ this._files.main = this._files.commonjs;
549
+ if (this._files.commonjsTypes)
550
+ this._files.types = this._files.commonjsTypes;
551
+ }
552
+ }
553
+ await files.writeFile(mainFilePath, compiledCode);
554
+ if (compiled.dts)
555
+ await files.writeFile(dtsFilePath, compiled.dts);
556
+ if (compiled.map)
557
+ await files.writeFile(mapFilePath, compiled.map);
558
+ }
559
+ async _esm(point, bundledCode) {
560
+ const isMain = point.exportPath === '.';
561
+ const opts = getCompilerOptions(point.tsconfigFilePath);
562
+ const compilerOptions = opts.esm(point.outputDirectoryPath);
563
+ const is_jsx = isJsxContent(bundledCode);
564
+ const compiled = suseeCompiler({
565
+ sourceCode: bundledCode,
566
+ fileName: point.entry,
567
+ compilerOptions,
568
+ isJsx: is_jsx
569
+ });
570
+ let compiledCode = compiled.code;
571
+ const mainFilePath = files.joinPath(compiled.out_dir, `${compiled.file_name}.mjs`);
572
+ const dtsFilePath = files.joinPath(compiled.out_dir, `${compiled.file_name}.d.mts`);
573
+ const mapFilePath = files.joinPath(compiled.out_dir, `${compiled.file_name}.mjs.map`);
574
+ compiledCode = compiledCode.replace(new RegExp(`${compiled.file_name}.js.map`, 'gm'), `${compiled.file_name}.mjs.map`);
575
+ if (point.minify) {
576
+ compiledCode = await oxcMinify(`${compiled.file_name}.mjs`, compiledCode, point);
577
+ }
578
+ if (this._update()) {
579
+ this._files.esm = mainFilePath;
580
+ if (compiled.dts) {
581
+ this._files.esmTypes = dtsFilePath;
582
+ }
583
+ if (isMain && this._files.esm) {
584
+ this._files.module = this._files.esm;
585
+ }
586
+ }
587
+ await files.writeFile(mainFilePath, compiledCode);
588
+ if (compiled.dts)
589
+ await files.writeFile(dtsFilePath, compiled.dts);
590
+ if (compiled.map)
591
+ await files.writeFile(mapFilePath, compiled.map);
592
+ }
593
+ /**
594
+ * Clears the output directory and compiles all configured entry points.
595
+ * It also updates package.json export fields when package updates are enabled.
596
+ * @returns {Promise<void>}
597
+ */
598
+ async compile() {
599
+ await files.clearFolder(this._object.outDir);
600
+ for (const point of this._object.buildEntryPoints) {
601
+ const bundleCode = bundler(point);
602
+ for (const format of point.format) {
603
+ switch (format) {
604
+ case 'commonjs':
605
+ await this._commonjs(point, bundleCode);
606
+ if (this._update()) {
607
+ await files.writePackageJson(this._files, point.exportPath);
608
+ }
609
+ break;
610
+ case 'esm':
611
+ await this._esm(point, bundleCode);
612
+ if (this._update()) {
613
+ await files.writePackageJson(this._files, point.exportPath);
614
+ }
615
+ break;
616
+ }
617
+ }
618
+ }
619
+ }
620
+ }
621
+ //src/build.ts
622
+ /**
623
+ * Run a Susee build.
624
+ *
625
+ * Resolution order:
626
+ * 1. Use `options` when provided.
627
+ * 2. Otherwise try loading root config via `finalSuseeConfig()`.
628
+ *
629
+ * If neither source is available, this logs an error and exits with code 1.
630
+ */
631
+ async function build(options) {
632
+ const buildTime = new LogTimer();
633
+ let buildOptions = {};
634
+ const _buildOptions = await finalSuseeConfig();
635
+ if (!options && !_buildOptions) {
636
+ const info = 'Required build options or susee config file at root.You can use `npx susee init` to create susee config file at root';
637
+ const cause = 'No build options or susee config file at root.';
638
+ logError(info, cause, true);
639
+ }
640
+ if (options) {
641
+ buildOptions = generateBuildOptions(options);
642
+ }
643
+ else if (_buildOptions) {
644
+ buildOptions = _buildOptions;
645
+ }
646
+ const compiler = new Compiler(buildOptions);
647
+ await compiler.compile();
648
+ buildTime.buildTime();
649
+ }
650
+ export { build };
651
+ //# sourceMappingURL=index.mjs.map