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