@remotex-labs/xbuild 1.3.4 → 1.3.6
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/README.md +153 -1
- package/dist/cli.d.ts +5 -0
- package/dist/cli.js +13 -0
- package/dist/cli.js.map +8 -0
- package/dist/index.d.ts +56 -1
- package/dist/index.js +20 -31
- package/dist/index.js.map +5 -5
- package/dist/providers/configuration.provider.d.ts +54 -4
- package/dist/services/build.service.d.ts +27 -17
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -69,7 +69,8 @@ Options:
|
|
|
69
69
|
|
|
70
70
|
## Configuration
|
|
71
71
|
|
|
72
|
-
The `xBuild` configuration file allows you to customize various settings for the build and development process.
|
|
72
|
+
The `xBuild` configuration file allows you to customize various settings for the build and development process.
|
|
73
|
+
By default, xbuild uses `xbuild.config.ts` (`--config` change it). Here’s how you can configure it:
|
|
73
74
|
|
|
74
75
|
### Example Configuration
|
|
75
76
|
```typescript
|
|
@@ -94,3 +95,154 @@ const config: ConfigurationInterface = {
|
|
|
94
95
|
}
|
|
95
96
|
};
|
|
96
97
|
```
|
|
98
|
+
|
|
99
|
+
You can also define multiple configurations as an array:
|
|
100
|
+
```typescript
|
|
101
|
+
/**
|
|
102
|
+
* Import will remove at compile time
|
|
103
|
+
*/
|
|
104
|
+
|
|
105
|
+
import type { xBuildConfig } from '@remotex-labs/xbuild';
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Imports
|
|
109
|
+
*/
|
|
110
|
+
|
|
111
|
+
import { version } from 'process';
|
|
112
|
+
import pkg from './package.json' with { type: 'json' };
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Config build
|
|
116
|
+
*/
|
|
117
|
+
|
|
118
|
+
const config: Array<xBuildConfig> = [
|
|
119
|
+
{
|
|
120
|
+
declaration: true,
|
|
121
|
+
esbuild: {
|
|
122
|
+
bundle: true,
|
|
123
|
+
minify: true,
|
|
124
|
+
format: 'esm',
|
|
125
|
+
outdir: 'dist/esm',
|
|
126
|
+
target: [ `node${ version.slice(1) }` ],
|
|
127
|
+
platform: 'node',
|
|
128
|
+
packages: 'external',
|
|
129
|
+
sourcemap: true,
|
|
130
|
+
sourceRoot: `https://github.com/remotex-lab/xmap/tree/v${ pkg.version }/`,
|
|
131
|
+
entryPoints: [ 'src/index.ts' ]
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
declaration: false,
|
|
136
|
+
noTypeChecker: true,
|
|
137
|
+
esbuild: {
|
|
138
|
+
bundle: true,
|
|
139
|
+
format: 'cjs',
|
|
140
|
+
outdir: 'dist/cjs'
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
export default config;
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## Using the ifdef Plugin
|
|
149
|
+
The `ifdef` plugin in `xBuild` helps conditionally include or exclude code based on defined variables. Here’s an example:
|
|
150
|
+
```typescript
|
|
151
|
+
// main.ts
|
|
152
|
+
|
|
153
|
+
console.log("This code always runs");
|
|
154
|
+
|
|
155
|
+
// If the `DEBUG` flag is set in your build config, this block will be included
|
|
156
|
+
// ifdef DEBUG
|
|
157
|
+
console.log("Debug mode is enabled");
|
|
158
|
+
// endif
|
|
159
|
+
|
|
160
|
+
// ifdef FEATURE_X
|
|
161
|
+
console.log("Feature X is active");
|
|
162
|
+
// endif
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### Setting Conditions in Configuration
|
|
166
|
+
To enable these blocks during the build, define your conditions in the `xBuild` configuration file:
|
|
167
|
+
```typescript
|
|
168
|
+
export default {
|
|
169
|
+
esbuild: {
|
|
170
|
+
entryPoints: ['./src/main.ts'],
|
|
171
|
+
outdir: 'dist',
|
|
172
|
+
minify: false,
|
|
173
|
+
format: 'esm',
|
|
174
|
+
bundle: true,
|
|
175
|
+
},
|
|
176
|
+
ifdef: {
|
|
177
|
+
DEBUG: true, // Enables the DEBUG section
|
|
178
|
+
FEATURE_X: false, // Excludes the FEATURE_X section
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
```
|
|
182
|
+
In this example:
|
|
183
|
+
* When `DEBUG` is set to `true`, the `Debug mode is enabled` message is included.
|
|
184
|
+
* When `FEATURE_X` is `false`, the `console.log("Feature X is active");` line is excluded.
|
|
185
|
+
|
|
186
|
+
This approach helps manage feature toggles and debug code efficiently, making it possible to build different versions of your code based on configuration.
|
|
187
|
+
|
|
188
|
+
## Hooks
|
|
189
|
+
The `hooks` interface provides a structure for lifecycle hooks to customize the build process.
|
|
190
|
+
```typescript
|
|
191
|
+
export interface hooks {
|
|
192
|
+
onEnd: OnEndType;
|
|
193
|
+
onLoad: OnLoadType;
|
|
194
|
+
onStart: OnStartType;
|
|
195
|
+
onResolve: OnResolveType;
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
```typescript
|
|
200
|
+
/**
|
|
201
|
+
* Import will remove at compile time
|
|
202
|
+
*/
|
|
203
|
+
|
|
204
|
+
import type { xBuildConfig } from '@remotex-labs/xbuild';
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Imports
|
|
208
|
+
*/
|
|
209
|
+
|
|
210
|
+
import { version } from 'process';
|
|
211
|
+
import pkg from './package.json' with { type: 'json' };
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Config build
|
|
215
|
+
*/
|
|
216
|
+
|
|
217
|
+
const config: xBuildConfig = {
|
|
218
|
+
dev: true,
|
|
219
|
+
watch: true,
|
|
220
|
+
declaration: true,
|
|
221
|
+
buildOnError: false,
|
|
222
|
+
noTypeChecker: false,
|
|
223
|
+
esbuild: {
|
|
224
|
+
entryPoints: ['./src/index.ts'],
|
|
225
|
+
bundle: true,
|
|
226
|
+
minify: true,
|
|
227
|
+
target: 'es2020'
|
|
228
|
+
},
|
|
229
|
+
serve: {
|
|
230
|
+
port: 8080,
|
|
231
|
+
host: 'localhost',
|
|
232
|
+
active: true // can be activeate using -s insted
|
|
233
|
+
},
|
|
234
|
+
hooks: {
|
|
235
|
+
onStart: async (build) => {
|
|
236
|
+
console.log('Build started');
|
|
237
|
+
},
|
|
238
|
+
onEnd: async (result) => {
|
|
239
|
+
console.log('Build finished:', result);
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
define: {
|
|
243
|
+
'__ENV__': 'development',
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
export default config;
|
|
248
|
+
```
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{buildWithArgv as u}from"./index.js";function e(r,n,_=__ACTIVE_COLOR){return _?`${r}${n}\x1B[0m`:n}var i=`
|
|
3
|
+
______ _ _ _
|
|
4
|
+
| ___ \\ (_) | | |
|
|
5
|
+
__ _| |_/ /_ _ _| | __| |
|
|
6
|
+
\\ \\/ / ___ \\ | | | | |/ _\` |
|
|
7
|
+
> <| |_/ / |_| | | | (_| |
|
|
8
|
+
/_/\\_\\____/ \\__,_|_|_|\\__,_|
|
|
9
|
+
`;function t(r=!0){return`
|
|
10
|
+
\r${e("\x1B[38;5;208m",i,r)}
|
|
11
|
+
\rVersion: ${e("\x1B[38;5;197m","1.3.6",r)}
|
|
12
|
+
\r`}console.log(t());u(process.argv).catch(r=>{console.error(r.stack)});
|
|
13
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/cli.ts", "../src/components/colors.component.ts", "../src/components/banner.component.ts"],
|
|
4
|
+
"sourceRoot": "https://github.com/remotex-lab/xBuild/tree/v1.3.6/",
|
|
5
|
+
"sourcesContent": ["#!/usr/bin/env node\n\n/**\n * Import will remove at compile time\n */\n\nimport type { xBuildError } from '@errors/xbuild.error';\nimport type { VMRuntimeError } from '@errors/vm-runtime.error';\n\n/**\n * Imports\n */\n\nimport { buildWithArgv } from './index.js';\nimport { bannerComponent } from '@components/banner.component';\n\n/**\n * Banner\n */\n\nconsole.log(bannerComponent());\n\n/**\n * Run entrypoint of xBuild\n */\n\nbuildWithArgv(process.argv).catch((error: VMRuntimeError & xBuildError) => {\n console.error(error.stack);\n});\n", "/**\n * An enumeration of ANSI color codes used for text formatting in the terminal.\n *\n * These colors can be used to format terminal output with various text colors,\n * including different shades of gray, yellow, and orange, among others.\n *\n * Each color code starts with an ANSI escape sequence (`\\u001B`), followed by the color code.\n * The `Reset` option can be used to reset the terminal's text formatting back to the default.\n *\n * @example\n * ```typescript\n * console.log(Color.BrightPink, 'This is bright pink text', Color.Reset);\n * ```\n *\n * @enum {string}\n */\n\nexport const enum Colors {\n Reset = '\\u001B[0m',\n Red = '\\u001B[38;5;9m',\n Gray = '\\u001B[38;5;243m',\n Cyan = '\\u001B[38;5;81m',\n DarkGray = '\\u001B[38;5;238m',\n LightCoral = '\\u001B[38;5;203m',\n LightOrange = '\\u001B[38;5;215m',\n OliveGreen = '\\u001B[38;5;149m',\n BurntOrange = '\\u001B[38;5;208m',\n LightGoldenrodYellow = '\\u001B[38;5;221m',\n LightYellow = '\\u001B[38;5;230m',\n CanaryYellow = '\\u001B[38;5;227m',\n DeepOrange = '\\u001B[38;5;166m',\n LightGray = '\\u001B[38;5;252m',\n BrightPink = '\\u001B[38;5;197m'\n}\n\n/**\n * Formats a message string with the specified ANSI color and optionally resets it after the message.\n *\n * This function applies an ANSI color code to the provided message,\n * and then appends the reset code to ensure that the color formatting doesn't extend beyond the message.\n * It's useful for outputting colored text in a terminal. If color formatting is not desired,\n * the function can return the message unformatted.\n *\n * @param color - The ANSI color code to apply. This is used only if `activeColor` is true.\n * @param msg - The message to be formatted with the specified color.\n * @param activeColor - A boolean flag indicating whether color formatting should be applied. Default is `__ACTIVE_COLOR`.\n *\n * @returns {string} A string with the specified color applied to the message,\n * followed by a reset sequence if `activeColor` is true.\n *\n * @example\n * ```typescript\n * const coloredMessage = setColor(Colors.LightOrange, 'This is a light orange message');\n * console.log(coloredMessage);\n * ```\n *\n * @example\n * ```typescript\n * const plainMessage = setColor(Colors.LightOrange, 'This is a light orange message', false);\n * console.log(plainMessage); // Output will be without color formatting\n * ```\n */\n\n\nexport function setColor(color: Colors, msg: string, activeColor: boolean = __ACTIVE_COLOR): string {\n if (!activeColor)\n return msg;\n\n return `${color}${msg}${Colors.Reset}`;\n}\n\n", "/**\n * Imports\n */\n\nimport { Colors, setColor } from '@components/colors.component';\n\n/**\n * ASCII Logo and Version Information\n *\n * @remarks\n * The `asciiLogo` constant stores an ASCII representation of the project logo\n * that will be displayed in the banner. This banner is rendered in a formatted\n * string in the `bannerComponent` function.\n *\n * The `cleanScreen` constant contains an ANSI escape code to clear the terminal screen.\n */\n\nexport const asciiLogo = `\n ______ _ _ _\n | ___ \\\\ (_) | | |\n__ _| |_/ /_ _ _| | __| |\n\\\\ \\\\/ / ___ \\\\ | | | | |/ _\\` |\n > <| |_/ / |_| | | | (_| |\n/_/\\\\_\\\\____/ \\\\__,_|_|_|\\\\__,_|\n`;\n\n// ANSI escape codes for colors\nexport const cleanScreen = '\\x1Bc';\n\n/**\n * Renders the banner with the ASCII logo and version information.\n *\n * This function constructs and returns a formatted banner string that includes an ASCII logo and the version number.\n * The colors used for the ASCII logo and version number can be enabled or disabled based on the `activeColor` parameter.\n * If color formatting is enabled, the ASCII logo will be rendered in burnt orange, and the version number will be in bright pink.\n *\n * @param activeColor - A boolean flag indicating whether ANSI color formatting should be applied. Default is `__ACTIVE_COLOR`.\n *\n * @returns A formatted string containing the ASCII logo, version number, and ANSI color codes if `activeColor` is `true`.\n *\n * @remarks\n * The `bannerComponent` function clears the terminal screen, applies color formatting if enabled, and displays\n * the ASCII logo and version number. The version number is retrieved from the global `__VERSION` variable, and\n * the colors are reset after the text is rendered.\n *\n * @example\n * ```typescript\n * console.log(bannerComponent());\n * ```\n *\n * This will output the banner to the console with the ASCII logo, version, and colors.\n *\n * @example\n * ```typescript\n * console.log(bannerComponent(false));\n * ```\n *\n * This will output the banner to the console with the ASCII logo and version number without color formatting.\n *\n * Todo \\r${ activeColor ? cleanScreen : '' }\n *\n * @public\n */\n\nexport function bannerComponent(activeColor: boolean = true): string {\n return `\n \\r${ setColor(Colors.BurntOrange, asciiLogo, activeColor) }\n \\rVersion: ${ setColor(Colors.BrightPink, __VERSION, activeColor) }\n \\r`;\n}\n\n/**\n * A formatted string prefix used for logging build-related messages.\n * // todo optimize this\n */\n\nexport function prefix() {\n return setColor(Colors.LightCoral, '[xBuild]');\n}\n"],
|
|
6
|
+
"mappings": ";AAaA,OAAS,iBAAAA,MAAqB,aCmDvB,SAASC,EAASC,EAAeC,EAAaC,EAAuB,eAAwB,CAChG,OAAKA,EAGE,GAAGF,CAAK,GAAGC,CAAG,UAFVA,CAGf,CCpDO,IAAME,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;EA+ClB,SAASC,EAAgBC,EAAuB,GAAc,CACjE,MAAO;AAAA,YACEC,mBAA6BC,EAAWF,CAAW,CAAE;AAAA,qBAC5CC,mBAA4B,QAAWD,CAAW,CAAE;AAAA,OAE1E,CFjDA,QAAQ,IAAIG,EAAgB,CAAC,EAM7BC,EAAc,QAAQ,IAAI,EAAE,MAAOC,GAAwC,CACvE,QAAQ,MAAMA,EAAM,KAAK,CAC7B,CAAC",
|
|
7
|
+
"names": ["buildWithArgv", "setColor", "color", "msg", "activeColor", "asciiLogo", "bannerComponent", "activeColor", "setColor", "asciiLogo", "bannerComponent", "buildWithArgv", "error"]
|
|
8
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,66 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
1
|
/**
|
|
3
2
|
* Exports
|
|
4
3
|
*/
|
|
5
4
|
export type * from "./configuration/interfaces/configuration.interface";
|
|
6
5
|
export type { BuildResult, OnLoadArgs, OnLoadResult, OnResolveArgs, OnResolveResult, PluginBuild } from 'esbuild';
|
|
6
|
+
/**
|
|
7
|
+
* Import will remove at compile time
|
|
8
|
+
*/
|
|
9
|
+
import type { BuildResult } from 'esbuild';
|
|
7
10
|
/**
|
|
8
11
|
* Imports
|
|
9
12
|
*/
|
|
10
13
|
import "./errors/stack.error";
|
|
11
14
|
import "./errors/uncaught.error";
|
|
15
|
+
import type { PartialDeepConfigurationsType } from "./configuration/interfaces/configuration.interface";
|
|
16
|
+
/**
|
|
17
|
+
* Main run function that initiates the build process based on CLI arguments.
|
|
18
|
+
*
|
|
19
|
+
* This function parses the CLI arguments, configures the build settings, and executes
|
|
20
|
+
* the appropriate build tasks, including type checking, serving, or running in debug mode.
|
|
21
|
+
*
|
|
22
|
+
* @param argv - An array of strings representing the CLI arguments.
|
|
23
|
+
*
|
|
24
|
+
* @returns A promise that resolves when all build tasks are completed.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* await buildWithArgv(process.argv);
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export declare function buildWithArgv(argv: Array<string>): Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* Builds the project using a configuration file specified by its path.
|
|
34
|
+
*
|
|
35
|
+
* This function reads the configuration from the provided file path, processes it,
|
|
36
|
+
* and initiates the build tasks.
|
|
37
|
+
*
|
|
38
|
+
* @param configFilePath - The path to the configuration file to be used for the build.
|
|
39
|
+
*
|
|
40
|
+
* @returns A promise that resolves to an array of `BuildResult` objects once all build tasks are completed.
|
|
41
|
+
*
|
|
42
|
+
* @throws {Error} Throws an error if the configuration file does not exist or is invalid.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* const results = await buildWithPath('./config.ts');
|
|
47
|
+
* console.log('Build results:', results);
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export declare function buildWithConfigPath(configFilePath: string): Promise<BuildResult[]>;
|
|
51
|
+
/**
|
|
52
|
+
* Builds the project based on the provided configuration object.
|
|
53
|
+
*
|
|
54
|
+
* This function processes the given configuration and executes the build tasks accordingly.
|
|
55
|
+
*
|
|
56
|
+
* @param config - A partial configuration object used to define the build settings.
|
|
57
|
+
*
|
|
58
|
+
* @returns A promise that resolves to an array of `BuildResult` objects once all build tasks are completed.
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```typescript
|
|
62
|
+
* const results = await build({ entryPoints: ['./src/index.ts'] });
|
|
63
|
+
* console.log('Build results:', results);
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
export declare function build(config: PartialDeepConfigurationsType): Promise<BuildResult[]>;
|
package/dist/index.js
CHANGED
|
@@ -1,35 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
${
|
|
4
|
-
${c("\x1B[38;5;203m",o.message)}
|
|
1
|
+
import{cwd as me}from"process";import{readFileSync as ge}from"fs";import{fileURLToPath as he}from"url";import{dirname as M,join as ye,resolve as _}from"path";function c(i,e,t=__ACTIVE_COLOR){return t?`${i}${e}\x1B[0m`:e}import{SourceService as ve,formatErrorCode as Se,highlightCode as be}from"@remotex-labs/xmap";var I=me(),A=M(he(import.meta.url)),Ce=M(A),$=(()=>{let i;return{get service(){if(!i){let e=ge(ye(A,"index.js.map"));i=new ve(e.toString(),import.meta.url)}return i}}})();global.__ACTIVE_COLOR||(global.__ACTIVE_COLOR=!0);function xe(i,e,t,r){return`${i.replace(`${r}\\`,e).replace(/\\/g,"/")}#L${t}`}function D(i,e,t,r,o){if(o.isPromiseAll())return`at async Promise.all (index: ${o.getPromiseIndex()})`;let n=o.isAsync()?"async":"",s=i?`${n} ${i}`:n,a=t>=0&&r>=0?c("\x1B[38;5;243m",`[${t}:${r}]`):"";return`at ${s} ${c("\x1B[38;5;238m",e)} ${a}`.replace(/\s{2,}/g," ").trim()}function we(i){let e=i.getLineNumber()||-1,t=i.getColumnNumber()||-1,r=i.getFileName()||"<anonymous>",o=i.getTypeName()||"",n=i.getFunctionName()||"",s=i.isNative()?"<native>":n;return o&&(s=`${o}.${s}`),{functionName:s,source:r,line:e,column:t}}function Pe(i,e){let t=__ACTIVE_COLOR?be(i.code):i.code;return i.name&&e.name=="TypeError"&&(e.message=e.message.replace(/^\S+/,i.name)),Se({...i,code:t},{color:__ACTIVE_COLOR?"\x1B[38;5;197m":"",reset:__ACTIVE_COLOR?"\x1B[0m":""})}function ke(i,e){let{functionName:t,source:r,line:o,column:n}=we(i);if(i.isPromiseAll()||i.isEval()||i.isNative())return D(t,r,o,n,i);let s=null,a=r===$.service.file;if(a?s=$.service.getPositionWithCode(o,n):e.error.sourceMap&&(s=e.error.sourceMap.getPositionWithCode(o,n)),s){let l=a?A:I,{line:h,column:y,name:R}=s,L=_(l,s.source);return e.blockCode||(e.blockCode=Pe(s,e.error)),s.sourceRoot&&(L=xe(_(l,s.source),s.sourceRoot,s.line,a?Ce:I)),D(R||t,L,h,y,i)}return r==="evalmachine.<anonymous>"?"":D(t,r,o,n,i)}function Ee(i,e){return e.map(t=>ke(t,i)).filter(Boolean)}function F(i,e){let t={error:i,blockCode:null,formattedError:global.__ACTIVE_COLOR?"\x1B[0m":""},r=Ee(t,e);return t.formattedError+=`
|
|
2
|
+
${i.name}:
|
|
3
|
+
${c("\x1B[38;5;203m",i.message)}
|
|
5
4
|
|
|
6
|
-
`,
|
|
5
|
+
`,t.blockCode&&(t.formattedError+=`${t.blockCode}
|
|
7
6
|
|
|
8
|
-
`),
|
|
9
|
-
${
|
|
7
|
+
`),r.length>0&&(t.formattedError+=`Enhanced Stack Trace:
|
|
8
|
+
${r.join(`
|
|
10
9
|
`)}
|
|
11
|
-
`),
|
|
10
|
+
`),t.formattedError}var N=Error.prepareStackTrace;Error.prepareStackTrace=(i,e)=>(i.callStacks=e,N?N(i,e):"");process.on("uncaughtException",i=>{console.error(i.stack)});process.on("unhandledRejection",i=>{console.error(i.stack)});import{existsSync as vt}from"fs";import Te from"yargs";import{hideBin as Oe}from"yargs/helpers";function j(i){let e=Te(Oe(i)).command("$0 [file]","A versatile JavaScript and TypeScript toolchain build system.",t=>{t.positional("entryPoints",{describe:"The file entryPoints to build",type:"string"}).option("typeCheck",{describe:"Perform type checking",alias:"tc",type:"boolean"}).option("node",{alias:"n",describe:"Build for node platform",type:"boolean"}).option("dev",{alias:"d",describe:"Array entryPoints to run as development in Node.js",type:"array"}).option("debug",{alias:"db",describe:"Array entryPoints to run in Node.js with debug state",type:"array"}).option("serve",{alias:"s",describe:"Serve the build folder over HTTP",type:"boolean"}).option("outdir",{alias:"o",describe:"Output directory",type:"string"}).option("declaration",{alias:"de",describe:"Add TypeScript declarations",type:"boolean"}).option("watch",{alias:"w",describe:"Watch for file changes",type:"boolean"}).option("config",{alias:"c",describe:"Build configuration file (js/ts)",type:"string",default:"xbuild.config.ts"}).option("tsconfig",{alias:"tsc",describe:"Set TypeScript configuration file to use",type:"string",default:"tsconfig.json"}).option("minify",{alias:"m",describe:"Minify the code",type:"boolean"}).option("bundle",{alias:"b",describe:"Bundle the code",type:"boolean"}).option("noTypeChecker",{alias:"ntc",describe:"Skip TypeScript type checking",type:"boolean"}).option("buildOnError",{alias:"boe",describe:"Continue building even if there are TypeScript type errors",type:"boolean"}).option("format",{alias:"f",describe:"Defines the format for the build output ('cjs' | 'esm' | 'iif').",type:"string"}).option("version",{alias:"v",describe:"Show version number",type:"boolean",default:!1,conflicts:"help"})}).help().alias("help","h").version(!1).middleware(t=>{t.version&&process.exit(0)});return e.showHelp(t=>{(process.argv.includes("--help")||process.argv.includes("-h"))&&(console.log(t+`
|
|
12
11
|
|
|
13
|
-
`),process.exit(0))}),e}import{dirname as
|
|
14
|
-
${this.name}: ${this.applyColor("\x1B[38;5;243m",
|
|
15
|
-
`);if(n+=this.applyColor("\x1B[38;5;203m",`${
|
|
12
|
+
`),process.exit(0))}),e}import{dirname as gt,resolve as S}from"path";import{build as ht,context as yt}from"esbuild";import{spawn as Re}from"child_process";function H(i,e=!1){let t=["--enable-source-maps",i];e&&t.unshift("--inspect-brk=0.0.0.0:0");let r=Re("node",t);return r.stdout.on("data",o=>{console.log(o.toString())}),r.stderr.on("data",o=>{console.error(o.toString())}),r}import{join as De}from"path";import{cwd as Ae}from"process";import{existsSync as Be,readFileSync as Le}from"fs";var d=class i extends Error{constructor(t,r){super(t);this.sourceMap=r;Error.captureStackTrace&&Error.captureStackTrace(this,i),this.name="xBuildBaseError"}callStacks=[];reformatStack(t){return t.callStacks?F(this,t.callStacks):t.stack??""}};import{formatErrorCode as _e,highlightCode as Ie}from"@remotex-labs/xmap";var b=class i extends d{originalErrorStack;constructor(e){super(e.text),this.name="esBuildError",Error.captureStackTrace&&Error.captureStackTrace(this,i),e.location?this.stack=this.generateFormattedError(e):(this.originalErrorStack=this.stack,this.stack=this.reformatStack(this))}generateFormattedError(e){let{text:t,location:r,notes:o}=e,n=this.applyColor("\x1B[0m",`
|
|
13
|
+
${this.name}: ${this.applyColor("\x1B[38;5;243m",r?.file??"")}
|
|
14
|
+
`);if(n+=this.applyColor("\x1B[38;5;203m",`${t}
|
|
16
15
|
|
|
17
|
-
`),
|
|
16
|
+
`),o.forEach(s=>{n+=this.applyColor("\x1B[38;5;243m",`${s.text}
|
|
18
17
|
|
|
19
|
-
`)}),
|
|
20
|
-
`)}return n}readCode(e){try{return
|
|
21
|
-
`):null}catch{return null}}formatCodeSnippet(e,
|
|
22
|
-
`));return
|
|
23
|
-
______ _ _ _
|
|
24
|
-
| ___ \\ (_) | | |
|
|
25
|
-
__ _| |_/ /_ _ _| | __| |
|
|
26
|
-
\\ \\/ / ___ \\ | | | | |/ _\` |
|
|
27
|
-
> <| |_/ / |_| | | | (_| |
|
|
28
|
-
/_/\\_\\____/ \\__,_|_|_|\\__,_|
|
|
29
|
-
`;function j(o=!0){return`
|
|
30
|
-
\r${c("\x1B[38;5;208m",$e,o)}
|
|
31
|
-
\rVersion: ${c("\x1B[38;5;197m","1.3.4",o)}
|
|
32
|
-
\r`}function f(){return c("\x1B[38;5;203m","[xBuild]")}var m=class o extends d{originalError;originalErrorStack;constructor(e,r){super(e.message,r),Error.captureStackTrace&&Error.captureStackTrace(this,o),this.originalError=e,this.originalErrorStack=e.stack,this.name="VMRuntimeError",this.stack=this.reformatStack(e)}};import*as q from"http";import*as z from"https";var H=`<!DOCTYPE html>
|
|
18
|
+
`)}),r){let s=this.readCode(r.file);s&&(n+=`${this.formatCodeSnippet(s,r)}
|
|
19
|
+
`)}return n}readCode(e){try{return Be(e)?Le(De(Ae(),e),"utf-8").split(`
|
|
20
|
+
`):null}catch{return null}}formatCodeSnippet(e,t){let{line:r=1,column:o=0,file:n}=t,s=Math.max(r-3,0),a=Math.min(r+3,e.length),l=Ie(e.slice(s,a).join(`
|
|
21
|
+
`));return _e({line:r,name:null,code:l,source:n,endLine:a,startLine:s,column:o+1,sourceRoot:null,sourceIndex:-1,generatedLine:-1,generatedColumn:-1},{color:global.__ACTIVE_COLOR?"\x1B[38;5;197m":"",reset:global.__ACTIVE_COLOR?"\x1B[0m":""})}applyColor(e,t){return global.__ACTIVE_COLOR?c(e,t):t}};function u(){return c("\x1B[38;5;203m","[xBuild]")}var m=class i extends d{originalError;originalErrorStack;constructor(e,t){super(e.message,t),Error.captureStackTrace&&Error.captureStackTrace(this,i),this.originalError=e,this.originalErrorStack=e.stack,this.name="VMRuntimeError",this.stack=this.reformatStack(e)}};import*as z from"http";import*as Y from"https";var W=`<!DOCTYPE html>
|
|
33
22
|
<html>
|
|
34
23
|
<head>
|
|
35
24
|
<meta charset="UTF-8">
|
|
@@ -86,10 +75,10 @@ __ _| |_/ /_ _ _| | __| |
|
|
|
86
75
|
<ul>\${ fileList }</ul>
|
|
87
76
|
</body>
|
|
88
77
|
</html>
|
|
89
|
-
`;import{extname as
|
|
90
|
-
`),a=c("\x1B[38;5;81m",
|
|
78
|
+
`;import{extname as V,join as J,resolve as Ne}from"path";import{existsSync as U,readdir as Me,readFile as Fe,readFileSync as G,stat as je}from"fs";var q={html:{icon:"fa-file-code",color:"#d1a65f"},css:{icon:"fa-file-css",color:"#264de4"},js:{icon:"fa-file-code",color:"#f7df1e"},json:{icon:"fa-file-json",color:"#b41717"},png:{icon:"fa-file-image",color:"#53a8e4"},jpg:{icon:"fa-file-image",color:"#53a8e4"},jpeg:{icon:"fa-file-image",color:"#53a8e4"},gif:{icon:"fa-file-image",color:"#53a8e4"},txt:{icon:"fa-file-alt",color:"#8e8e8e"},folder:{icon:"fa-folder",color:"#ffb800"}},C=class{rootDir;isHttps;config;constructor(e,t){this.rootDir=Ne(t),this.config=e,this.isHttps=this.config.keyfile&&this.config.certfile?U(this.config.keyfile)&&U(this.config.certfile):!1}start(){if(this.isHttps)return this.startHttpsServer();this.startHttpServer()}startHttpServer(){z.createServer((t,r)=>{this.handleRequest(t,r,()=>this.defaultResponse(t,r))}).listen(this.config.port,this.config.host,()=>{console.log(`${u()} HTTP/S server is running at http://${this.config.host}:${this.config.port}`)})}startHttpsServer(){let e={key:G(this.config.keyfile),cert:G(this.config.certfile)};Y.createServer(e,(r,o)=>{this.handleRequest(r,o,()=>this.defaultResponse(r,o))}).listen(this.config.port,this.config.host,()=>{let r=c("\x1B[38;5;227m",`https://${this.config.host}:${this.config.port}`);console.log(`${u()} HTTPS server is running at ${r}`)})}handleRequest(e,t,r){try{this.config.onRequest?this.config.onRequest(e,t,r):r()}catch(o){this.sendError(t,o)}}getContentType(e){return{html:"text/html",css:"text/css",js:"application/javascript",ts:"text/plain",map:"application/json",json:"application/json",png:"image/png",jpg:"image/jpeg",gif:"image/gif",txt:"text/plain"}[e]||"application/octet-stream"}async defaultResponse(e,t){let r=e.url==="/"?"":e.url?.replace(/^\/+/,"")||"",o=J(this.rootDir,r);if(!o.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let n=await this.promisifyStat(o);n.isDirectory()?this.handleDirectory(o,r,t):n.isFile()&&this.handleFile(o,t)}catch(n){let s=n.message;s.includes("favicon")||console.log(u(),s),this.sendNotFound(t)}}promisifyStat(e){return new Promise((t,r)=>{je(e,(o,n)=>o?r(o):t(n))})}handleDirectory(e,t,r){Me(e,(o,n)=>{if(o)return this.sendError(r,o);let s=n.map(a=>{if(a.match(/[^A-Za-z0-9_\/\\.-]/))return;let l=J(t,a);if(l.match(/[^A-Za-z0-9_\/\\.-]/))return;let h=V(a).slice(1)||"folder",{icon:y,color:R}=q[h]||q.folder;return`<li><i class="fas ${y}" style="color: ${R};"></i> <a href="/${l}">${a}</a></li>`}).join("");r.writeHead(200,{"Content-Type":"text/html"}),r.end(W.replace("${ fileList }",s))})}handleFile(e,t){let r=V(e).slice(1)||"txt",o=this.getContentType(r);Fe(e,(n,s)=>{if(n)return this.sendError(t,n);t.writeHead(200,{"Content-Type":o}),t.end(s)})}sendNotFound(e){e.writeHead(404,{"Content-Type":"text/plain"}),e.end("Not Found")}sendError(e,t){console.error(`${u()}`,t.toString()),e.writeHead(500,{"Content-Type":"text/plain"}),e.end("Internal Server Error")}};import{promises as He}from"fs";import{resolve as We}from"path";var x=class{buildState={};onEndHooks=[];onLoadHooks=[];onStartHooks=[];onResolveHooks=[];registerOnStart(e){e&&this.onStartHooks.push(e)}registerOnEnd(e){e&&this.onEndHooks.push(e)}registerOnResolve(e){e&&this.onResolveHooks.push(e)}registerOnLoad(e){e&&this.onLoadHooks.push(e)}setup(){return{name:"middleware-plugin",setup:e=>{e.initialOptions.metafile=!0,e.onEnd(this.handleOnEnd.bind(this)),e.onStart(this.handleOnStart.bind(this,e)),e.onLoad({filter:/.*/},this.handleOnLoad.bind(this)),e.onResolve({filter:/.*/},this.handleOnResolve.bind(this))}}}async handleOnStart(e){this.buildState={};let t={errors:[],warnings:[]};for(let r of this.onStartHooks){let o=await r(e,this.buildState);o&&(o.errors?.length&&t.errors.push(...o.errors),o.warnings?.length&&t.warnings.push(...o.warnings))}return t}async handleOnEnd(e){let t={errors:e.errors??[],warnings:e.warnings??[]};for(let r of this.onEndHooks){e.errors=t.errors,e.warnings=t.warnings;let o=await r(e,this.buildState);o&&(o.errors?.length&&t.errors.push(...o.errors),o.warnings?.length&&t.warnings.push(...o.warnings))}return t}async handleOnResolve(e){let t={};for(let r of this.onResolveHooks){let o=await r(e,this.buildState);o&&(t={...t,...o,path:o.path||t.path})}return t.path?t:null}async handleOnLoad(e){let t={contents:void 0,loader:"default"},r=We(e.path);t.contents||(t.contents=await He.readFile(r,"utf8"));for(let o of this.onLoadHooks){let n=await o(t.contents??"",t.loader,e,this.buildState);n&&(t={...t,...n,contents:n.contents||t.contents,loader:n.loader||t.loader})}return t.contents?t:null}};function Z(i,e){return i.replace(/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,(t,r,o)=>e[r]?o:"")}import{relative as Ve}from"path";function K(i,e,t,r){let o=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let n in t){let s=Ve(e,t[n]).replace(/\\/g,"/");s.startsWith("..")||(s=`./${s}`),i=i.replaceAll(n,`${s}/`),r&&(i=i.replace(o,(a,l)=>(l.startsWith("../")||l.startsWith("./"))&&!l.endsWith(".js")?a.replace(l,`${l}.js`):a))}return i}import{cwd as Je}from"process";import{build as X}from"esbuild";var f=class i extends d{originalErrorStack;constructor(e,t){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,i),t&&Object.assign(this,t),this.name="xBuildError",this.originalErrorStack=this.stack,this.stack=this.reformatStack(this)}};var Ue={write:!1,bundle:!0,minify:!0,format:"cjs",target:"esnext",platform:"node",sourcemap:!0,sourcesContent:!0,preserveSymlinks:!0};function Ge(i){let e=/\/\/# sourceMappingURL=data:application\/json;base64,([^'"\s]+)/,t=i.match(e);if(!t||!t[1])throw new f("Source map URL not found in the output.");let r=t[1];return{code:i.replace(e,""),sourceMap:r}}async function Q(i,e={}){let t={absWorkingDir:Je(),...Ue,...e,entryPoints:[i]},o=(await X(t)).outputFiles?.pop()?.text??"";return Ge(o)}async function ee(i,e="browser"){return(await X({entryPoints:i,bundle:!0,write:!1,metafile:!0,platform:e,packages:"external",logLevel:"silent",outdir:"dist"})).metafile}var w=class i extends Error{constructor(e,t){super(e),this.name="TypesError",Object.setPrototypeOf(this,i.prototype),t?.cause&&(this.cause=t.cause)}};import{resolve as P,relative as qe,dirname as ze,parse as Ye}from"path";import{sys as Ze,factory as B,createProgram as te,visitEachChild as re,isStringLiteral as Ke,resolveModuleName as Xe,DiagnosticCategory as Qe,isImportDeclaration as ie,isExportDeclaration as oe,getPreEmitDiagnostics as ne,flattenDiagnosticMessageText as se}from"typescript";var k=class{constructor(e,t,r=!0){this.tsConfig=e;this.outDir=t;this.activeColor=r;this.options={...this.tsConfig.options,outDir:this.outDir}}options;typeCheck(e=!1){let t=te(this.tsConfig.fileNames,{...this.options,noEmit:!0,skipLibCheck:!0});this.handleDiagnostics(ne(t),e)}generateDeclarations(e=!1,t=!1){let r=te(this.tsConfig.fileNames,{...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0}),o=ne(r);!e&&o.some(n=>n.category===Qe.Error)&&this.handleDiagnostics(o,t),r.emit(void 0,void 0,void 0,!0,{afterDeclarations:[this.createTransformerFactory()]})}isImportOrExportDeclaration(e){return ie(e)||oe(e)}hasStringLiteralModuleSpecifier(e){return e.moduleSpecifier&&Ke(e.moduleSpecifier)}resolveModuleFileName(e,t){let r,o=Xe(e,t.baseUrl,t,Ze);if(o.resolvedModule&&t.baseUrl){if(o.resolvedModule.resolvedFileName.includes("node_modules"))return r;r=P(o.resolvedModule.resolvedFileName).replace(P(t.baseUrl),".")}return r}getRelativePathToOutDir(e,t){e=P(e).replace(P(this.options.baseUrl??""),".");let r=qe(ze(e),t).replace(/\\/g,"/"),o=Ye(r);return o.dir.startsWith("..")||(o.dir=`./${o.dir}`),`${o.dir}/${o.name}`}updateModuleSpecifier(e,t){let r=B.createStringLiteral(t);return ie(e)?B.updateImportDeclaration(e,e.modifiers,e.importClause,r,void 0):oe(e)?B.updateExportDeclaration(e,e.modifiers,e.isTypeOnly,e.exportClause,r,void 0):e}createVisitor(e,t){let r=o=>{if(this.isImportOrExportDeclaration(o)&&this.hasStringLiteralModuleSpecifier(o)){let n=o.moduleSpecifier.text,s=this.resolveModuleFileName(n,this.options);if(s){let a=this.getRelativePathToOutDir(e.fileName,s);return this.updateModuleSpecifier(o,a)}}return re(o,r,t)};return r}createTransformerFactory(){return e=>({transformSourceFile:t=>re(t,this.createVisitor(t,e),e),transformBundle:t=>t})}handleDiagnostics(e,t=!1){if(e.length!==0&&(e.forEach(r=>{if(r.file&&r.start!==void 0){let{line:o,character:n}=r.file.getLineAndCharacterOfPosition(r.start),s=se(r.messageText,`
|
|
79
|
+
`),a=c("\x1B[38;5;81m",r.file.fileName,this.activeColor),l=c("\x1B[38;5;230m",`${o+1}:${n+1}`,this.activeColor),h=c("\x1B[38;5;9m","error",this.activeColor),y=c("\x1B[38;5;243m",`TS${r.code}`,this.activeColor);console.error(`${u()} ${a}:${l} - ${h} ${y}:${s}`)}else console.error(se(r.messageText,`
|
|
91
80
|
`))}),console.log(`
|
|
92
|
-
`),!
|
|
93
|
-
${
|
|
94
|
-
`),this.config.dev&&this.spawnDev(e.metafile,this.config.dev)}async processEntryPoints(){let e=this.config.esbuild,
|
|
81
|
+
`),!t))throw new w("Type checking failed due to errors.")}};import p from"typescript";import{dirname as at}from"path";import{existsSync as le,readFileSync as ct}from"fs";import{cwd as et}from"process";var E={dev:!1,watch:!1,declaration:!1,buildOnError:!1,noTypeChecker:!1,define:{},esbuild:{write:!0,bundle:!0,minify:!0,format:"cjs",outdir:"dist",platform:"browser",absWorkingDir:et(),loader:{".js":"ts"}},serve:{port:3e3,host:"localhost",active:!1}};import{createRequire as it}from"module";import{SourceService as ot}from"@remotex-labs/xmap";import{Script as tt,createContext as rt}from"vm";function ae(i,e={}){e.console=console;let t=new tt(i),r=rt(e);return t.runInContext(r,{breakOnSigint:!0})}function ce(i,e){for(let t in i)if(Object.prototype.hasOwnProperty.call(i,t)){let r=i[t];typeof r=="function"?i[t]=nt(r,e):typeof r=="object"&&r!==null&&ce(r,e)}return i}function nt(i,e){return(...t)=>{try{return i(...t)}catch(r){throw new m(r,e)}}}function st(i,e){return ce(i,e)}async function T(i){let{code:e,sourceMap:t}=await Q(i,{packages:"external",banner:{js:"(function(module, exports) {"},footer:{js:"})(module, module.exports);"}}),r={exports:{}},o=it(import.meta.url),n=new ot(JSON.parse(atob(t)));try{await ae(e,{require:o,module:r})}catch(s){throw new m(s,n)}return st(r.exports.default,n)}var lt=JSON.stringify({compilerOptions:{strict:!0,target:"ESNext",module:"ESNext",outDir:"dist",skipLibCheck:!0,isolatedModules:!1,esModuleInterop:!1,moduleDetection:"force",moduleResolution:"node",resolveJsonModule:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0}});function ut(i){let e=i.argv,t=o=>Object.fromEntries(Object.entries(o).filter(([,n])=>n!==void 0)),r=t({bundle:e.bundle,minify:e.minify,outdir:e.outdir,tsconfig:e.tsconfig,entryPoints:e.file?[e.file]:void 0,target:e.node?[`node${process.version.slice(1)}`]:void 0,platform:e.node?"node":void 0,format:e.format});return{...t({dev:e.dev,watch:e.watch,declaration:e.declaration,serve:e.serve?{active:e.serve}:{undefined:void 0}}),esbuild:r}}function ue(i){let e=i.tsconfig??"tsconfig.json",t=le(e)?ct(e,"utf8"):JSON.stringify(lt),r=p.parseConfigFileTextToJson(e,t);if(r.error)throw new f(p.formatDiagnosticsWithColorAndContext([r.error],{getCurrentDirectory:p.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>p.sys.newLine}));let o=p.parseJsonConfigFileContent(r.config,p.sys,at(e));if(o.errors.length>0)throw new f(p.formatDiagnosticsWithColorAndContext(o.errors,{getCurrentDirectory:p.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>p.sys.newLine}));return o}async function O(i,e={}){let t=Array.isArray(i)?i:[i],r=t[0];return t.flatMap(o=>{let n={...E,...r,...o,...e,esbuild:{...E.esbuild,...r?.esbuild,...o?.esbuild,...e.esbuild},serve:{...E.serve,...r.serve,...o.serve,...e.serve}};if(!n.esbuild.entryPoints)throw new f("entryPoints cannot be undefined.");return n})}async function fe(i,e){let t=ut(e),r=le(i)?await T(i):{};return O(r,t)}function ft(i){let e={};return i.forEach(t=>{let r=t.substring(0,t.lastIndexOf("."));e[r]=t}),e}function pe(i){if(Array.isArray(i)){let e={};return i.length>0&&typeof i[0]=="object"?i.forEach(t=>{e[t.out]=t.in}):typeof i[0]=="string"&&(e=ft(i)),e}else if(i&&typeof i=="object")return i;throw new f("Unsupported entry points format")}import{join as pt}from"path";import{mkdirSync as dt,writeFileSync as mt}from"fs";function de(i){let e=i.moduleTypeOutDir??i.esbuild.outdir??"dist",t=i.esbuild.format==="esm"?"module":"commonjs";dt(e,{recursive:!0}),mt(pt(e,"package.json"),`{"type": "${t}"}`)}var g=class{constructor(e){this.config=e;let t=ue(this.config.esbuild);this.config.esbuild.logLevel="silent",this.pluginsProvider=new x,this.typeScriptProvider=new k(t,this.config.declarationOutDir??t.options.outDir??this.config.esbuild.outdir),this.configureDevelopmentMode(),this.setupPlugins()}typeScriptProvider;activePossess=[];pluginsProvider;async run(){return await this.execute(async()=>{let e=await this.build();return(this.config.watch||this.config.dev)&&await e.watch(),e})}async runDebug(e){return await this.execute(async()=>{this.config.dev=!1,this.config.watch=!1;let t=await this.build();this.spawnDev(t.metafile,e,!0)})}async serve(){let e=new C(this.config.serve,this.config.esbuild.outdir??"");return await this.execute(async()=>{e.start(),await(await this.build()).watch()})}async execute(e){try{return await e()}catch(t){let r=t;Array.isArray(r.errors)&&(!this.config.watch||!this.config.dev||!this.config.serve.active)?this.handleErrors(r):console.error(new m(t).stack)}}configureDevelopmentMode(){this.config.dev!==!1&&(!Array.isArray(this.config.dev)||this.config.dev.length<1)&&(this.config.dev=["index"])}setupPlugins(){let e=S(this.typeScriptProvider.options.baseUrl??""),t=this.generatePathAlias(e);this.registerPluginHooks(t,e)}registerPluginHooks(e,t){this.pluginsProvider.registerOnEnd(this.end.bind(this)),this.pluginsProvider.registerOnStart(this.start.bind(this)),this.pluginsProvider.registerOnLoad((r,o,n)=>{if(n.path.endsWith(".ts")){if(!this.config.esbuild.bundle){let s=gt(S(n.path).replace(t,"."));r=K(r.toString(),s,e,this.config.esbuild.format==="esm")}return{loader:"ts",contents:Z(r.toString(),this.config.define)}}})}generatePathAlias(e){let t=this.typeScriptProvider.options.paths,r={};for(let o in t){let n=t[o];if(n.length>0){let s=o.replace(/\*/g,"");r[s]=S(n[0].replace(/\*/g,"")).replace(e,".")}}return r}handleErrors(e){let t=e.errors??[];for(let r of t){if(!r.detail){console.error(new b(r).stack);continue}if(r.detail.name!=="TypesError"){if(r.detail.name){if(r.detail.name==="VMRuntimeError"){console.error(r.detail.stack);continue}if(r.detail instanceof Error){console.error(new m(r.detail).stack);continue}}return console.error(r.text)}}}async build(){de(this.config);let e=this.config.esbuild;this.config.hooks&&(this.pluginsProvider.registerOnEnd(this.config.hooks.onEnd),this.pluginsProvider.registerOnLoad(this.config.hooks.onLoad),this.pluginsProvider.registerOnStart(this.config.hooks.onStart),this.pluginsProvider.registerOnResolve(this.config.hooks.onResolve)),e.define||(e.define={});for(let t in this.config.define)e.define[t]=JSON.stringify(this.config.define[t]);return this.config.esbuild.bundle||await this.processEntryPoints(),e.plugins=[this.pluginsProvider.setup()],this.config.watch||this.config.dev||this.config.serve.active?await yt(e):await ht(e)}spawnDev(e,t,r=!1){if(Array.isArray(t))for(let o in e.outputs)o.includes("map")||!t.some(n=>o.includes(`/${n}.`))||this.activePossess.push(H(o,r))}async start(e,t){try{t.startTime=Date.now(),console.log(`${u()} StartBuild ${e.initialOptions.outdir}`),this.config.declaration?this.typeScriptProvider.generateDeclarations(this.config.noTypeChecker,this.config.buildOnError):this.config.noTypeChecker||this.typeScriptProvider.typeCheck(this.config.buildOnError)}finally{for(;this.activePossess.length>0;){let r=this.activePossess.pop();r&&r.kill("SIGTERM")}}}async end(e,t){if(e.errors.length>0)return this.handleErrors(e);let r=Date.now()-t.startTime;console.log(`
|
|
82
|
+
${u()} ${c("\x1B[38;5;166m",`Build completed! in ${r} ms`)}`),console.log(`${u()} ${Object.keys(e.metafile.outputs).length} Modules:`),Object.keys(e.metafile.outputs).forEach(o=>{let n=e.metafile.outputs[o].bytes;console.log(`${u()} ${c("\x1B[38;5;227m",o)}: ${c("\x1B[38;5;208m",n.toString())} bytes`)}),console.log(`
|
|
83
|
+
`),this.config.dev&&this.spawnDev(e.metafile,this.config.dev)}async processEntryPoints(){let e=this.config.esbuild,t=await ee(e.entryPoints,e.platform),r=S(this.typeScriptProvider.options.baseUrl??""),o=pe(e.entryPoints),n=Object.values(o);Array.isArray(e.entryPoints)&&typeof e.entryPoints[0]=="string"&&(o={},n=[]);for(let s in t.inputs){if(n.includes(s))continue;let a=S(s).replace(r,"."),l=a.substring(0,a.lastIndexOf("."));o[l]=s}e.entryPoints=o}};global.__ACTIVE_COLOR=!0;async function li(i){let e=j(i),t=e.argv,o=(await fe(t.config,e)).map(async n=>{let s=new g(n);if(t.typeCheck)return s.typeScriptProvider.typeCheck(!0);if(t.serve||n.serve.active)return await s.serve();if(Array.isArray(t.debug))return t.debug.length<1&&(t.debug=["index"]),await s.runDebug(t.debug);await s.run()});await Promise.all(o)}async function ui(i){let e=vt(i)?await T(i):{},r=(await O(e)).map(async o=>await new g(o).run());return await Promise.all(r)}async function fi(i){let t=(await O(i)).map(async r=>await new g(r).run());return await Promise.all(t)}export{fi as build,li as buildWithArgv,ui as buildWithConfigPath};
|
|
95
84
|
//# sourceMappingURL=index.js.map
|