@remotex-labs/xbuild 1.5.2 → 1.5.3

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 CHANGED
@@ -73,7 +73,7 @@ The `xBuild` configuration file allows you to customize various settings for the
73
73
  By default, xbuild uses `xbuild.config.ts` (`--config` change it). Here’s how you can configure it:
74
74
 
75
75
  ### Example Configuration
76
- ```typescript
76
+ ```ts
77
77
  const config: ConfigurationInterface = {
78
78
  declaration: true,
79
79
  buildOnError: false,
@@ -97,7 +97,7 @@ const config: ConfigurationInterface = {
97
97
  ```
98
98
 
99
99
  You can also define multiple configurations as an array:
100
- ```typescript
100
+ ```ts
101
101
  /**
102
102
  * Import will remove at compile time
103
103
  */
@@ -147,7 +147,7 @@ export default config;
147
147
 
148
148
  ## Using the ifdef Plugin
149
149
  The `ifdef` plugin in `xBuild` allows to conditionally include or exclude code based on defined variables. Here’s an example:
150
- ```typescript
150
+ ```ts
151
151
  // main.ts
152
152
 
153
153
  console.log("This code always runs");
@@ -164,7 +164,7 @@ console.log("Feature X is active");
164
164
 
165
165
  ### Setting Conditions in Configuration
166
166
  To enable these blocks during the build, define your conditions in the `xBuild` configuration file:
167
- ```typescript
167
+ ```ts
168
168
  export default {
169
169
  esbuild: {
170
170
  entryPoints: ['./src/main.ts'],
@@ -187,7 +187,7 @@ This approach helps to manage feature toggles and debug code efficiently, making
187
187
 
188
188
  ## Hooks
189
189
  The `hooks` interface provides a structure for lifecycle hooks to customize the build process.
190
- ```typescript
190
+ ```ts
191
191
  export interface hooks {
192
192
  onEnd: OnEndType;
193
193
  onLoad: OnLoadType;
@@ -196,7 +196,7 @@ export interface hooks {
196
196
  }
197
197
  ```
198
198
 
199
- ```typescript
199
+ ```ts
200
200
  /**
201
201
  * Imports will be remove at compile time
202
202
  */
@@ -248,7 +248,7 @@ export default config;
248
248
  ```
249
249
 
250
250
  ## Using the ifdef and macros
251
- ```typescript
251
+ ```ts
252
252
  // main.ts
253
253
 
254
254
  console.log("This code always runs");
package/dist/cli.js CHANGED
@@ -8,6 +8,6 @@ __ _| |_/ /_ _ _| | __| |
8
8
  /_/\\_\\____/ \\__,_|_|_|\\__,_|
9
9
  `;function t(r=!0){return`
10
10
  \r${e("\x1B[38;5;208m",i,r)}
11
- \rVersion: ${e("\x1B[38;5;197m","1.5.2",r)}
11
+ \rVersion: ${e("\x1B[38;5;197m","1.5.3",r)}
12
12
  \r`}console.log(t());o(process.argv).catch(r=>{console.error(r.stack),process.exit(1)});
13
13
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "version": 3,
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.5.2/",
5
- "sourcesContent": ["#!/usr/bin/env node\n/**\n * Import will remove at compile time\n */\nimport type { xBuildError } from '@errors/xbuild.error';\nimport type { VMRuntimeError } from '@errors/vm-runtime.error';\n/**\n * Imports\n */\nimport { buildWithArgv } from './index.js';\nimport { bannerComponent } from '@components/banner.component';\n/**\n * Banner\n */\nconsole.log(bannerComponent());\n/**\n * Run entrypoint of xBuild\n */\nbuildWithArgv(process.argv).catch((error: VMRuntimeError & xBuildError) => {\n console.error(error.stack);\n process.exit(1);\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 */\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 * 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 */\nexport function setColor(color: Colors, msg: string, activeColor: boolean = __ACTIVE_COLOR): string {\n if (!activeColor)\n return msg;\n return `${color}${msg}${Colors.Reset}`;\n}\n", "/**\n * Imports\n */\nimport { Colors, setColor } from '@components/colors.component';\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 */\nexport const asciiLogo = `\n ______ _ _ _\n | ___ \\\\ (_) | | |\n__ _| |_/ /_ _ _| | __| |\n\\\\ \\\\/ / ___ \\\\ | | | | |/ _\\` |\n > <| |_/ / |_| | | | (_| |\n/_/\\\\_\\\\____/ \\\\__,_|_|_|\\\\__,_|\n`;\n// ANSI escape codes for colors\nexport const cleanScreen = '\\x1Bc';\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 */\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 * A formatted string prefix used for logging build-related messages.\n * // todo optimize this\n */\nexport function prefix() {\n return setColor(Colors.LightCoral, '[xBuild]');\n}\n"],
6
- "mappings": ";AASA,OAAS,iBAAAA,MAAqB,aCmDvB,SAASC,EAASC,EAAeC,EAAaC,EAAuB,eAAwB,CAChG,OAAKA,EAEE,GAAGF,CAAK,GAAGC,CAAG,UADVA,CAEf,CClDO,IAAME,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;EA4ClB,SAASC,EAAgBC,EAAuB,GAAc,CACjE,MAAO;AAAA,YACCC,mBAA6BC,EAAWF,CAAW,CAAC;AAAA,qBAC3CC,mBAA4B,QAAWD,CAAW,CAAC;AAAA,OAExE,CFjDA,QAAQ,IAAIG,EAAgB,CAAC,EAI7BC,EAAc,QAAQ,IAAI,EAAE,MAAOC,GAAwC,CACvE,QAAQ,MAAMA,EAAM,KAAK,EACzB,QAAQ,KAAK,CAAC,CAClB,CAAC",
4
+ "sourceRoot": "https://github.com/remotex-lab/xBuild/tree/v1.5.3/",
5
+ "sourcesContent": ["#!/usr/bin/env node\n/**\n * Import will remove at compile time\n */\nimport type { xBuildError } from '@errors/xbuild.error';\nimport type { VMRuntimeError } from '@errors/vm-runtime.error';\n/**\n * Imports\n */\nimport { buildWithArgv } from './index.js';\nimport { bannerComponent } from '@components/banner.component';\n/**\n * Banner\n */\nconsole.log(bannerComponent());\n/**\n * Run entrypoint of xBuild\n */\nbuildWithArgv(process.argv).catch((error: VMRuntimeError & xBuildError) => {\n console.error(error.stack);\n process.exit(1);\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 * ```ts\n * console.log(Color.BrightPink, 'This is bright pink text', Color.Reset);\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 * 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 A string with the specified color applied to the message,\n * followed by a reset sequence if `activeColor` is true.\n *\n * @example\n * ```ts\n * const coloredMessage = setColor(Colors.LightOrange, 'This is a light orange message');\n * console.log(coloredMessage);\n * ```\n *\n * @example\n * ```ts\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 */\nexport function setColor(color: Colors, msg: string, activeColor: boolean = __ACTIVE_COLOR): string {\n if (!activeColor)\n return msg;\n return `${color}${msg}${Colors.Reset}`;\n}\n", "/**\n * Imports\n */\nimport { Colors, setColor } from '@components/colors.component';\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 */\nexport const asciiLogo = `\n ______ _ _ _\n | ___ \\\\ (_) | | |\n__ _| |_/ /_ _ _| | __| |\n\\\\ \\\\/ / ___ \\\\ | | | | |/ _\\` |\n > <| |_/ / |_| | | | (_| |\n/_/\\\\_\\\\____/ \\\\__,_|_|_|\\\\__,_|\n`;\n// ANSI escape codes for colors\nexport const cleanScreen = '\\x1Bc';\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 * ```ts\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 * ```ts\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 * @public\n */\n// Todo \\r${ activeColor ? cleanScreen : '' }\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 * A formatted string prefix used for logging build-related messages.\n * // todo optimize this\n */\nexport function prefix() {\n return setColor(Colors.LightCoral, '[xBuild]');\n}\n"],
6
+ "mappings": ";AASA,OAAS,iBAAAA,MAAqB,aCiDvB,SAASC,EAASC,EAAeC,EAAaC,EAAuB,eAAwB,CAChG,OAAKA,EAEE,GAAGF,CAAK,GAAGC,CAAG,UADVA,CAEf,CChDO,IAAME,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;EA2ClB,SAASC,EAAgBC,EAAuB,GAAc,CACjE,MAAO;AAAA,YACCC,mBAA6BC,EAAWF,CAAW,CAAC;AAAA,qBAC3CC,mBAA4B,QAAWD,CAAW,CAAC;AAAA,OAExE,CFhDA,QAAQ,IAAIG,EAAgB,CAAC,EAI7BC,EAAc,QAAQ,IAAI,EAAE,MAAOC,GAAwC,CACvE,QAAQ,MAAMA,EAAM,KAAK,EACzB,QAAQ,KAAK,CAAC,CAClB,CAAC",
7
7
  "names": ["buildWithArgv", "setColor", "color", "msg", "activeColor", "asciiLogo", "bannerComponent", "activeColor", "setColor", "asciiLogo", "bannerComponent", "buildWithArgv", "error"]
8
8
  }
@@ -30,21 +30,19 @@ export declare const cleanScreen = "\u001Bc";
30
30
  * the colors are reset after the text is rendered.
31
31
  *
32
32
  * @example
33
- * ```typescript
33
+ * ```ts
34
34
  * console.log(bannerComponent());
35
35
  * ```
36
36
  *
37
37
  * This will output the banner to the console with the ASCII logo, version, and colors.
38
38
  *
39
39
  * @example
40
- * ```typescript
40
+ * ```ts
41
41
  * console.log(bannerComponent(false));
42
42
  * ```
43
43
  *
44
44
  * This will output the banner to the console with the ASCII logo and version number without color formatting.
45
45
  *
46
- * Todo \r${ activeColor ? cleanScreen : '' }
47
- *
48
46
  * @public
49
47
  */
50
48
  export declare function bannerComponent(activeColor?: boolean): string;
@@ -8,11 +8,9 @@
8
8
  * The `Reset` option can be used to reset the terminal's text formatting back to the default.
9
9
  *
10
10
  * @example
11
- * ```typescript
11
+ * ```ts
12
12
  * console.log(Color.BrightPink, 'This is bright pink text', Color.Reset);
13
13
  * ```
14
- *
15
- * @enum {string}
16
14
  */
17
15
  export declare const enum Colors {
18
16
  Reset = "\u001B[0m",
@@ -43,17 +41,17 @@ export declare const enum Colors {
43
41
  * @param msg - The message to be formatted with the specified color.
44
42
  * @param activeColor - A boolean flag indicating whether color formatting should be applied. Default is `__ACTIVE_COLOR`.
45
43
  *
46
- * @returns {string} A string with the specified color applied to the message,
44
+ * @returns A string with the specified color applied to the message,
47
45
  * followed by a reset sequence if `activeColor` is true.
48
46
  *
49
47
  * @example
50
- * ```typescript
48
+ * ```ts
51
49
  * const coloredMessage = setColor(Colors.LightOrange, 'This is a light orange message');
52
50
  * console.log(coloredMessage);
53
51
  * ```
54
52
  *
55
53
  * @example
56
- * ```typescript
54
+ * ```ts
57
55
  * const plainMessage = setColor(Colors.LightOrange, 'This is a light orange message', false);
58
56
  * console.log(plainMessage); // Output will be without color formatting
59
57
  * ```
@@ -13,7 +13,7 @@ import type { EntryPoints } from "../configuration/interfaces/configuration.inte
13
13
  * @returns An object where the keys are filenames (without extensions) and the values are the corresponding file paths.
14
14
  *
15
15
  * @example
16
- * ```typescript
16
+ * ```ts
17
17
  * const filePaths = ['src/index.ts', 'src/utils.ts'];
18
18
  * const result = mapFilePathsToNames(filePaths);
19
19
  * console.log(result);
@@ -45,19 +45,19 @@ export declare function mapFilePathsToNames(filePaths: Array<string>): Record<st
45
45
  * @throws Will throw an `Error` if the entry points format is unsupported.
46
46
  *
47
47
  * @example
48
- * ```typescript
48
+ * ```ts
49
49
  * const entryPoints = extractEntryPoints(['src/index.ts', 'src/utils.ts']);
50
50
  * console.log(entryPoints); // { 'index': 'src/index.ts', 'utils': 'src/utils.ts' }
51
51
  * ```
52
52
  *
53
53
  * @example
54
- * ```typescript
54
+ * ```ts
55
55
  * const entryPoints = extractEntryPoints([{ in: 'src/index.ts', out: 'dist/index.js' }]);
56
56
  * console.log(entryPoints); // { 'dist/index.js': 'src/index.ts' }
57
57
  * ```
58
58
  *
59
59
  * @example
60
- * ```typescript
60
+ * ```ts
61
61
  * const entryPoints = extractEntryPoints({ index: 'src/index.ts', index2: 'dist/index2.js' });
62
62
  * console.log(entryPoints); // { index: 'src/index.ts', index2: 'dist/index2.js' }
63
63
  * ```
@@ -6,7 +6,7 @@ import type { ConfigurationInterface } from "./interfaces/configuration.interfac
6
6
  * The default configuration options for the build.
7
7
  *
8
8
  * @example
9
- * ```typescript
9
+ * ```ts
10
10
  * import { defaultConfiguration } from '@configuration/default-configuration';
11
11
  *
12
12
  * console.log(defaultConfiguration);
@@ -19,7 +19,7 @@ import type { OnEndType, OnLoadType, OnResolveType, OnStartType } from "../../pr
19
19
  *
20
20
  * Example usage:
21
21
  *
22
- * ```typescript
22
+ * ```ts
23
23
  * const entryPoints1: EntryPoints = ['src/index.ts', 'src/utils.ts'];
24
24
  * const entryPoints2: EntryPoints = { main: 'src/index.ts', utils: 'src/utils.ts' };
25
25
  * const entryPoints3: EntryPoints = [{ in: 'src/index.ts', out: 'dist/index.d.ts' }, { in: 'src/utils.ts', out: 'dist/utils.d.ts' }];
@@ -37,7 +37,7 @@ export type EntryPoints = Array<string> | Record<string, string> | Array<{
37
37
  *
38
38
  * **Example Usage:**
39
39
  *
40
- * ```typescript
40
+ * ```ts
41
41
  * interface User {
42
42
  * name: string;
43
43
  * address: {
@@ -99,7 +99,7 @@ export interface ModuleInterface {
99
99
  * An object representing the exports of the module.
100
100
  * The keys are strings representing export names, and the values can be of any type.
101
101
  *
102
- * @property {ConfigurationInterface} [default] - An optional default export of type `ConfigurationInterface`.
102
+ * @property default - An optional default export of type `ConfigurationInterface`.
103
103
  */
104
104
  exports: {
105
105
  [key: string]: unknown;
@@ -113,7 +113,7 @@ export interface ModuleInterface {
113
113
  * such as the port, host, SSL/TLS certificates, and request handling functions.
114
114
  *
115
115
  * @example
116
- * ```typescript
116
+ * ```ts
117
117
  * const serverConfig = {
118
118
  * serve: {
119
119
  * active: true,
@@ -152,17 +152,17 @@ export interface Serve {
152
152
  *
153
153
  * @interface hooks
154
154
  *
155
- * @property {OnEndType} onEnd - A hook function that is called after the build process completes.
155
+ * @property onEnd - A hook function that is called after the build process completes.
156
156
  * This allows for post-processing or cleanup tasks.
157
- * @property {OnLoadType} onLoad - A hook function that is called when esbuild attempts to load a module.
157
+ * @property onLoad - A hook function that is called when esbuild attempts to load a module.
158
158
  * It can be used to modify the contents of the loaded module.
159
- * @property {OnStartType} onStart - A hook function that is called before the build process starts.
159
+ * @property onStart - A hook function that is called before the build process starts.
160
160
  * This is useful for initialization tasks or logging.
161
- * @property {OnResolveType} onResolve - A hook function that is called when esbuild attempts to resolve a module path.
161
+ * @property onResolve - A hook function that is called when esbuild attempts to resolve a module path.
162
162
  * It can be used to customize module resolution behavior.
163
163
  *
164
164
  * @example
165
- * ```typescript
165
+ * ```ts
166
166
  * const myHooks: hooks = {
167
167
  * onEnd: async (result) => {
168
168
  * console.log('Build finished:', result);
@@ -182,6 +182,11 @@ export interface Serve {
182
182
  * }
183
183
  * };
184
184
  * ```
185
+ *
186
+ * @see OnEndType
187
+ * @see OnLoadType
188
+ * @see OnStartType
189
+ * @see OnResolveType
185
190
  */
186
191
  export interface hooks {
187
192
  onEnd: OnEndType;
@@ -197,7 +202,7 @@ export interface hooks {
197
202
  * file watching, TypeScript declaration generation, error handling, TypeScript type checking, and esbuild bundler options.
198
203
  *
199
204
  * @example
200
- * ```typescript
205
+ * ```ts
201
206
  * const config: ConfigurationInterface = {
202
207
  * dev: true,
203
208
  * watch: true,
@@ -319,7 +324,7 @@ export interface ConfigurationInterface {
319
324
  * environment-specific configurations, or any other value that you may want to define at compile time.
320
325
  *
321
326
  * @example
322
- * ```typescript
327
+ * ```ts
323
328
  * const config: ConfigurationInterface = {
324
329
  * dev: true,
325
330
  * define: {
@@ -376,6 +381,7 @@ export type PartialDeepConfigurationsType = PartialDeep<ConfigurationInterface>;
376
381
  * support for various build setups.
377
382
  *
378
383
  * @example
384
+ * ```ts
379
385
  * // A single configuration object
380
386
  * const config: ConfigurationsType = {
381
387
  * esbuild: {
@@ -383,6 +389,7 @@ export type PartialDeepConfigurationsType = PartialDeep<ConfigurationInterface>;
383
389
  * outdir: 'dist'
384
390
  * }
385
391
  * };
392
+ * ```
386
393
  *
387
394
  * @example
388
395
  * ```ts
@@ -18,11 +18,9 @@ import type { ConfigurationInterface } from "./interfaces/configuration.interfac
18
18
  *
19
19
  * @throws Will throw an error if the transpilation or execution of the configuration file fails.
20
20
  * The thrown error will have sourcemap information attached if available.
21
- *
22
- * @async
23
- *
21
+
24
22
  * @example
25
- * ```typescript
23
+ * ```ts
26
24
  * const config = await parseConfigurationFile('./config.jet.ts');
27
25
  * console.log(config);
28
26
  * ```
@@ -9,7 +9,7 @@ import type { BaseError } from "../base.error";
9
9
  *
10
10
  * @type ErrorType
11
11
  *
12
- * @extends {Error}
12
+ * @extends Error
13
13
  *
14
14
  * @property callStacks - An optional array of call sites
15
15
  * captured when the error was created. This can provide additional context
@@ -7,7 +7,7 @@
7
7
  * in your application.
8
8
  *
9
9
  * @example
10
- * ```typescript
10
+ * ```ts
11
11
  * throw new TypesError('Invalid type encountered.');
12
12
  * ```
13
13
  *
@@ -19,7 +19,6 @@ export declare class TypesError extends Error {
19
19
  *
20
20
  * @param message - A human-readable message providing details about the error.
21
21
  * @param options - Optional configuration for the error, such as a `cause` (ECMAScript 2022+).
22
- * @param options.cause
23
22
  */
24
23
  constructor(message?: string, options?: {
25
24
  cause?: Error;
@@ -19,7 +19,7 @@ import { BaseError } from ".//base.error";
19
19
  * @param sourceMap - The `SourceService` providing source map data to link the error to its original source.
20
20
  *
21
21
  * @example
22
- * ```typescript
22
+ * ```ts
23
23
  * try {
24
24
  * vm.run(someCode);
25
25
  * } catch (error) {
@@ -49,7 +49,7 @@ export declare class VMRuntimeError extends BaseError {
49
49
  * source code locations. If not provided, this will be `null`.
50
50
  *
51
51
  * @example
52
- * ```typescript
52
+ * ```ts
53
53
  * try {
54
54
  * vm.run(code);
55
55
  * } catch (error) {
package/dist/index.d.ts CHANGED
@@ -39,10 +39,10 @@ export declare function buildWithArgv(argv: Array<string>): Promise<void>;
39
39
  *
40
40
  * @returns A promise that resolves to an array of `BuildResult` objects once all build tasks are completed.
41
41
  *
42
- * @throws {Error} Throws an error if the configuration file does not exist or is invalid.
42
+ * @throws Error Throws an error if the configuration file does not exist or is invalid.
43
43
  *
44
44
  * @example
45
- * ```typescript
45
+ * ```ts
46
46
  * const results = await buildWithPath('./config.ts');
47
47
  * console.log('Build results:', results);
48
48
  * ```
@@ -58,7 +58,7 @@ export declare function buildWithConfigPath(configFilePath: string): Promise<Bui
58
58
  * @returns A promise that resolves to an array of `BuildResult` objects once all build tasks are completed.
59
59
  *
60
60
  * @example
61
- * ```typescript
61
+ * ```ts
62
62
  * const results = await build({ entryPoints: ['./src/index.ts'] });
63
63
  * console.log('Build results:', results);
64
64
  * ```
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ ${r.join(`
9
9
  `)}
10
10
  `),t.formattedError}var M=Error.prepareStackTrace;Error.prepareStackTrace=(o,e)=>(o.callStacks=e,M?M(o,e):"");process.on("uncaughtException",o=>{console.error(o.stack),process.exit(1)});process.on("unhandledRejection",o=>{console.error(o.stack),process.exit(1)});import{existsSync as Tt}from"fs";import Be from"yargs";import{hideBin as Ae}from"yargs/helpers";function H(o){let e=Be(Ae(o)).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+`
11
11
 
12
- `),process.exit(0))}),e}import*as he from"node:process";import{dirname as xt,resolve as b}from"path";import{build as wt,context as Et}from"esbuild";import{spawn as Le}from"child_process";function V(o,e=!1){let t=["--enable-source-maps",o];e&&t.unshift("--inspect-brk=0.0.0.0:0");let r=Le("node",t);return r.stdout.on("data",i=>{console.log(i.toString())}),r.stderr.on("data",i=>{console.error(i.toString())}),r}import l from"typescript";import{promises as _e}from"fs";import{cwd as De}from"process";import{build as J}from"esbuild";var h=class o extends Error{constructor(t,r){super(t);this.sourceMap=r;Error.captureStackTrace&&Error.captureStackTrace(this,o),this.name="xBuildBaseError"}callStacks=[];reformatStack(t){return t.callStacks?W(this,t.callStacks):t.stack??""}};var d=class o extends h{originalErrorStack;constructor(e,t){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,o),t&&Object.assign(this,t),this.name="xBuildError",this.originalErrorStack=this.stack,this.stack=this.reformatStack(this)}};var Ie={write:!1,bundle:!0,minify:!0,format:"cjs",target:"esnext",platform:"node",sourcemap:!0,sourcesContent:!0,preserveSymlinks:!0};function $e(o){let e=/\/\/# sourceMappingURL=data:application\/json;base64,([^'"\s]+)/,t=o.match(e);if(!t||!t[1])throw new d("Source map URL not found in the output.");let r=t[1];return{code:o.replace(e,""),sourceMap:r}}async function U(o,e={}){let t={absWorkingDir:De(),...Ie,...e,entryPoints:[o]},i=(await J(t)).outputFiles?.pop()?.text??"";return $e(i)}async function x(o,e="browser"){return await J({outdir:"tmp",write:!1,bundle:!0,metafile:!0,platform:e,packages:"external",logLevel:"silent",entryPoints:o,loader:{".html":"text"}})}function Ne(o,e){let t=l.createSourceFile("temp.ts",o,l.ScriptTarget.Latest,!0),r=i=>{if(l.isFunctionDeclaration(i)&&i.name&&i.name.text.startsWith("$$")){e.removeFunctions.add(i.name.text);return}if(l.isVariableStatement(i)&&i.declarationList.declarations.length>0){i.declarationList.declarations.forEach(n=>{l.isIdentifier(n.name)&&n.name.text.startsWith("$$")&&n.initializer&&(l.isArrowFunction(n.initializer)||l.isFunctionExpression(n.initializer))&&e.removeFunctions.add(n.name.text)});return}if(l.isIdentifier(i)&&l.isExpression(i)&&i.escapedText&&i.escapedText.startsWith("$$")){e.removeFunctions.add(i.escapedText);return}l.forEachChild(i,r)};r(t)}async function Fe(o,e,t){let r=Object.keys(o.inputs);for(let i of r){let n=await _e.readFile(i,"utf8"),s=/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,a;for(;(a=s.exec(n))!==null;){let[,c,p]=a;e.define[c]||Ne(p,t)}}}function Me(o,e){function t(n){let s=a=>{if(l.isCallExpression(a)){let c=a.expression.getText(),p=c.endsWith("!")?c.slice(0,-1):c;if(p.startsWith("$$")&&e.removeFunctions.has(p))return l.factory.createIdentifier("undefined");let g=a.expression;if(l.isPropertyAccessExpression(g)){let v=g.name;if(l.isIdentifier(v)&&v.text.startsWith("$$"))return l.factory.createIdentifier("undefined")}}return l.visitEachChild(a,s,n)};return a=>l.visitNode(a,s)}let r=l.transform(o,[t]);return l.createPrinter().printFile(r.transformed[0])}async function z(o,e,t,r,i){if(!t.path.endsWith(".ts")&&!t.path.endsWith(".js"))return{loader:e,contents:o};if(!r.macros){r.macros={removeFunctions:new Set};let a=await x([t.path]);await Fe(a.metafile,i,r.macros)}let n=o.toString(),s=l.createSourceFile(t.path,n,l.ScriptTarget.Latest,!0);return{loader:e??"ts",contents:Me(s,r.macros)}}import{join as je}from"path";import{cwd as We}from"process";import{existsSync as He,readFileSync as Ve}from"fs";import{formatErrorCode as Je,highlightCode as Ue}from"@remotex-labs/xmap";var w=class o extends h{originalErrorStack;constructor(e){super(e.text),this.name="esBuildError",Error.captureStackTrace&&Error.captureStackTrace(this,o),e.location?this.stack=this.generateFormattedError(e):(this.originalErrorStack=this.stack,this.stack=this.reformatStack(this))}generateFormattedError(e){let{text:t,location:r,notes:i}=e,n=this.applyColor("\x1B[0m",`
12
+ `),process.exit(0))}),e}import*as he from"node:process";import{dirname as xt,resolve as b}from"path";import{build as wt,context as Et}from"esbuild";import{spawn as Le}from"child_process";function V(o,e=!1){let t=["--enable-source-maps",o];e&&t.unshift("--inspect-brk=0.0.0.0:0");let r=Le("node",t);return r.stdout.on("data",i=>{console.log(i.toString())}),r.stderr.on("data",i=>{console.error(i.toString())}),r}import l from"typescript";import{promises as _e}from"fs";import{cwd as De}from"process";import{build as J}from"esbuild";var h=class o extends Error{constructor(t,r){super(t);this.sourceMap=r;Error.captureStackTrace&&Error.captureStackTrace(this,o),this.name="xBuildBaseError"}callStacks=[];reformatStack(t){return t.callStacks?W(this,t.callStacks):t.stack??""}};var d=class o extends h{originalErrorStack;constructor(e,t){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,o),t&&Object.assign(this,t),this.name="xBuildError",this.originalErrorStack=this.stack,this.stack=this.reformatStack(this)}};var Ie={write:!1,bundle:!0,minify:!0,format:"cjs",target:"esnext",platform:"node",sourcemap:!0,sourcesContent:!0,preserveSymlinks:!0};function $e(o){let e=/\/\/# sourceMappingURL=data:application\/json;base64,([^'"\s]+)/,t=o.match(e);if(!t||!t[1])throw new d("Source map URL not found in the output.");let r=t[1];return{code:o.replace(e,""),sourceMap:r}}async function U(o,e={}){let t={absWorkingDir:De(),...Ie,...e,entryPoints:[o]},i=(await J(t)).outputFiles?.pop()?.text??"";return $e(i)}async function x(o,e="browser"){return await J({outdir:"tmp",write:!1,bundle:!0,metafile:!0,platform:e,packages:"external",logLevel:"silent",entryPoints:o,loader:{".html":"text"}})}function Ne(o,e){let t=l.createSourceFile("temp.ts",o,l.ScriptTarget.Latest,!0),r=i=>{if(l.isFunctionDeclaration(i)&&i.name&&i.name.text.startsWith("$$")){e.removeFunctions.add(i.name.text);return}if(l.isVariableStatement(i)&&i.declarationList.declarations.length>0){i.declarationList.declarations.forEach(n=>{l.isIdentifier(n.name)&&n.name.text.startsWith("$$")&&n.initializer&&(l.isArrowFunction(n.initializer)||l.isFunctionExpression(n.initializer))&&e.removeFunctions.add(n.name.text)});return}if(l.isIdentifier(i)&&l.isExpression(i)&&i.escapedText&&i.escapedText.startsWith("$$")){e.removeFunctions.add(i.escapedText);return}l.forEachChild(i,r)};r(t)}async function Fe(o,e,t){let r=Object.keys(o.inputs);for(let i of r){let n=await _e.readFile(i,"utf8"),s=/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,a;for(;(a=s.exec(n))!==null;){let[,c,p]=a;e.define[c]||Ne(p,t)}}}function Me(o,e){function t(n){let s=a=>{if(l.isCallExpression(a)){let c=a.expression.getText(),p=c.endsWith("!")?c.slice(0,-1):c;if(p.startsWith("$$")&&e.removeFunctions.has(p))return l.factory.createIdentifier("undefined");let g=a.expression;if(l.isPropertyAccessExpression(g)){let v=g.name;if(l.isIdentifier(v)&&v.text.startsWith("$$"))return l.factory.createIdentifier("undefined")}}return l.visitEachChild(a,s,n)};return a=>l.visitNode(a,s)}let r=l.transform(o,[t]);return l.createPrinter().printFile(r.transformed[0])}async function z(o,e,t,r,i){if(!t.path.endsWith(".ts")&&!t.path.endsWith(".js"))return{loader:e,contents:o};if(!r.macros){let a={removeFunctions:new Set},c=await x([t.path]);await Fe(c.metafile,i,a),r.macros=a}let n=o.toString(),s=l.createSourceFile(t.path,n,l.ScriptTarget.Latest,!0);return{loader:e??"ts",contents:Me(s,r.macros)}}import{join as je}from"path";import{cwd as We}from"process";import{existsSync as He,readFileSync as Ve}from"fs";import{formatErrorCode as Je,highlightCode as Ue}from"@remotex-labs/xmap";var w=class o extends h{originalErrorStack;constructor(e){super(e.text),this.name="esBuildError",Error.captureStackTrace&&Error.captureStackTrace(this,o),e.location?this.stack=this.generateFormattedError(e):(this.originalErrorStack=this.stack,this.stack=this.reformatStack(this))}generateFormattedError(e){let{text:t,location:r,notes:i}=e,n=this.applyColor("\x1B[0m",`
13
13
  ${this.name}: ${this.applyColor("\x1B[38;5;243m",r?.file??"")}
14
14
  `);if(n+=this.applyColor("\x1B[38;5;203m",`${t}
15
15
 
@@ -75,7 +75,7 @@ ${this.name}: ${this.applyColor("\x1B[38;5;243m",r?.file??"")}
75
75
  <ul>\${ fileList }</ul>
76
76
  </body>
77
77
  </html>
78
- `;import{extname as q,join as Y,resolve as Ge}from"path";import{existsSync as K,readdir as qe,readFile as Ye,readFileSync as Z,stat as Ke}from"fs";var X={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"}},E=class{rootDir;isHttps;config;constructor(e,t){this.rootDir=Ge(t),this.config=e,this.isHttps=this.config.keyfile&&this.config.certfile?K(this.config.keyfile)&&K(this.config.certfile):!1}start(){if(this.config.onStart&&this.config.onStart(),this.isHttps)return this.startHttpsServer();this.startHttpServer()}startHttpServer(){Q.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:Z(this.config.keyfile),cert:Z(this.config.certfile)};ee.createServer(e,(r,i)=>{this.handleRequest(r,i,()=>this.defaultResponse(r,i))}).listen(this.config.port,this.config.host,()=>{let r=f("\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(i){this.sendError(t,i)}}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(/^\/+/,"")||"",i=Y(this.rootDir,r);if(!i.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let n=await this.promisifyStat(i);n.isDirectory()?this.handleDirectory(i,r,t):n.isFile()&&this.handleFile(i,t)}catch(n){let s=n.message;s.includes("favicon")||console.log(u(),s),this.sendNotFound(t)}}promisifyStat(e){return new Promise((t,r)=>{Ke(e,(i,n)=>i?r(i):t(n))})}handleDirectory(e,t,r){qe(e,(i,n)=>{if(i)return this.sendError(r,i);let s=n.map(a=>{if(a.match(/[^A-Za-z0-9_\/\\.-]/))return;let c=Y(t,a);if(c.match(/[^A-Za-z0-9_\/\\.-]/))return;let p=q(a).slice(1)||"folder",{icon:g,color:v}=X[p]||X.folder;return`<li><i class="fas ${g}" style="color: ${v};"></i> <a href="/${c}">${a}</a></li>`}).join("");r.writeHead(200,{"Content-Type":"text/html"}),r.end(G.replace("${ fileList }",s))})}handleFile(e,t){let r=q(e).slice(1)||"txt",i=this.getContentType(r);Ye(e,(n,s)=>{if(n)return this.sendError(t,n);t.writeHead(200,{"Content-Type":i}),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 Ze}from"fs";import{resolve as Xe}from"path";var T=class{buildState={};onEndHooks=[];onSuccess=[];onLoadHooks=[];onStartHooks=[];onResolveHooks=[];registerOnStart(e){e&&this.onStartHooks.push(e)}registerOnEnd(e){e&&this.onEndHooks.push(e)}registerOnSuccess(e){e&&this.onSuccess.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 i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.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 i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.warnings))}if(t.errors.length<1)for(let r of this.onSuccess)await r(e,this.buildState);return t}async handleOnResolve(e){let t={};for(let r of this.onResolveHooks){let i=await r(e,this.buildState);i&&(t={...t,...i,path:i.path||t.path})}return t.path?t:null}async handleOnLoad(e){let t={contents:void 0,loader:"default"},r=Xe(e.path);t.contents||(t.contents=await Ze.readFile(r,"utf8"));for(let i of this.onLoadHooks){let n=await i(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 te(o,e){return o.replace(/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,(t,r,i)=>e[r]?i:"")}import{relative as Qe}from"path";function re(o,e,t,r){let i=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let n in t){let s=Qe(e,t[n]).replace(/\\/g,"/");s.startsWith("..")||(s=`./${s}`),o=o.replaceAll(n,`${s}/`),r&&(o=o.replace(i,(a,c)=>(c.startsWith("../")||c.startsWith("./"))&&!c.endsWith(".js")?a.replace(c,`${c}.js`):a))}return o}var P=class o extends Error{constructor(e,t){super(e),this.name="TypesError",Object.setPrototypeOf(this,o.prototype),t?.cause&&(this.cause=t.cause)}};import{resolve as k,relative as et,dirname as tt,parse as rt}from"path";import{sys as it,factory as I,createProgram as ie,visitEachChild as oe,isStringLiteral as ot,resolveModuleName as nt,DiagnosticCategory as st,isImportDeclaration as ne,isExportDeclaration as se,getPreEmitDiagnostics as ae,flattenDiagnosticMessageText as ce}from"typescript";var O=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=ie(this.tsConfig.fileNames,{...this.options,noEmit:!0,skipLibCheck:!0});this.handleDiagnostics(ae(t),e)}generateDeclarations(e=!1,t=!1){let r=ie(this.tsConfig.fileNames,{...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0}),i=ae(r);!e&&i.some(n=>n.category===st.Error)&&this.handleDiagnostics(i,t),r.emit(void 0,void 0,void 0,!0,{afterDeclarations:[this.createTransformerFactory()]})}isImportOrExportDeclaration(e){return ne(e)||se(e)}hasStringLiteralModuleSpecifier(e){return e.moduleSpecifier&&ot(e.moduleSpecifier)}resolveModuleFileName(e,t){let r,i=nt(e,t.baseUrl,t,it);if(i.resolvedModule&&t.baseUrl){if(i.resolvedModule.resolvedFileName.includes("node_modules"))return r;r=k(i.resolvedModule.resolvedFileName).replace(k(t.baseUrl),".")}return r}getRelativePathToOutDir(e,t){e=k(e).replace(k(this.options.baseUrl??""),".");let r=et(tt(e),t).replace(/\\/g,"/"),i=rt(r);return i.dir.startsWith("..")||(i.dir=`./${i.dir}`),`${i.dir}/${i.name}`}updateModuleSpecifier(e,t){let r=I.createStringLiteral(t);return ne(e)?I.updateImportDeclaration(e,e.modifiers,e.importClause,r,void 0):se(e)?I.updateExportDeclaration(e,e.modifiers,e.isTypeOnly,e.exportClause,r,void 0):e}createVisitor(e,t){let r=i=>{if(this.isImportOrExportDeclaration(i)&&this.hasStringLiteralModuleSpecifier(i)){let n=i.moduleSpecifier.text,s=this.resolveModuleFileName(n,this.options);if(s){let a=this.getRelativePathToOutDir(e.fileName,s);return this.updateModuleSpecifier(i,a)}}return oe(i,r,t)};return r}createTransformerFactory(){return e=>({transformSourceFile:t=>oe(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:i,character:n}=r.file.getLineAndCharacterOfPosition(r.start),s=ce(r.messageText,`
78
+ `;import{extname as q,join as Y,resolve as Ge}from"path";import{existsSync as K,readdir as qe,readFile as Ye,readFileSync as Z,stat as Ke}from"fs";var X={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"}},E=class{rootDir;isHttps;config;constructor(e,t){this.rootDir=Ge(t),this.config=e,this.isHttps=this.config.keyfile&&this.config.certfile?K(this.config.keyfile)&&K(this.config.certfile):!1}start(){if(this.config.onStart&&this.config.onStart(),this.isHttps)return this.startHttpsServer();this.startHttpServer()}startHttpServer(){Q.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:Z(this.config.keyfile),cert:Z(this.config.certfile)};ee.createServer(e,(r,i)=>{this.handleRequest(r,i,()=>this.defaultResponse(r,i))}).listen(this.config.port,this.config.host,()=>{let r=f("\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(i){this.sendError(t,i)}}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(/^\/+/,"")||"",i=Y(this.rootDir,r);if(!i.startsWith(this.rootDir)){t.statusCode=403,t.end();return}try{let n=await this.promisifyStat(i);n.isDirectory()?this.handleDirectory(i,r,t):n.isFile()&&this.handleFile(i,t)}catch(n){let s=n.message;s.includes("favicon")||console.log(u(),s),this.sendNotFound(t)}}promisifyStat(e){return new Promise((t,r)=>{Ke(e,(i,n)=>i?r(i):t(n))})}handleDirectory(e,t,r){qe(e,(i,n)=>{if(i)return this.sendError(r,i);let s=n.map(a=>{if(a.match(/[^A-Za-z0-9_\/\\.-]/))return;let c=Y(t,a);if(c.match(/[^A-Za-z0-9_\/\\.-]/))return;let p=q(a).slice(1)||"folder",{icon:g,color:v}=X[p]||X.folder;return`<li><i class="fas ${g}" style="color: ${v};"></i> <a href="/${c}">${a}</a></li>`}).join("");r.writeHead(200,{"Content-Type":"text/html"}),r.end(G.replace("${ fileList }",s))})}handleFile(e,t){let r=q(e).slice(1)||"txt",i=this.getContentType(r);Ye(e,(n,s)=>{if(n)return this.sendError(t,n);t.writeHead(200,{"Content-Type":i}),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 Ze}from"fs";import{resolve as Xe}from"path";var T=class{buildState={};onEndHooks=[];onSuccess=[];onLoadHooks=[];onStartHooks=[];onResolveHooks=[];registerOnStart(e){e&&this.onStartHooks.push(e)}registerOnEnd(e){e&&this.onEndHooks.push(e)}registerOnSuccess(e){e&&this.onSuccess.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 i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.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 i=await r(e,this.buildState);i&&(i.errors?.length&&t.errors.push(...i.errors),i.warnings?.length&&t.warnings.push(...i.warnings))}if(t.errors.length<1)for(let r of this.onSuccess)await r(e,this.buildState);return t}async handleOnResolve(e){let t={};for(let r of this.onResolveHooks){let i=await r(e,this.buildState);i&&(t={...t,...i,path:i.path||t.path})}return t.path?t:null}async handleOnLoad(e){let t={contents:void 0,loader:"default"},r=Xe(e.path);t.contents||(t.contents=await Ze.readFile(r,"utf8"));for(let i of this.onLoadHooks){let n=await i(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 te(o,e){return o.replace(/\/\/\s?ifdef\s?(\w+)([\s\S]*?)\/\/\s?endif/g,(t,r,i)=>e[r]?i:"")}import{relative as Qe}from"path";function re(o,e,t,r){let i=/(?:import|export)\s.*?\sfrom\s+['"]([^'"]+)['"]/g;for(let n in t){let s=Qe(e,t[n]).replace(/\\/g,"/");s.startsWith("..")||(s=`./${s}`),o=o.replaceAll(n,`${s}/`),r&&(o=o.replace(i,(a,c)=>(c.startsWith("../")||c.startsWith("./"))&&!c.endsWith(".js")?a.replace(c,`${c}.js`):a))}return o}var P=class o extends Error{constructor(e,t){super(e),this.name="TypesError",Object.setPrototypeOf(this,o.prototype),t?.cause&&(this.cause=t.cause)}};import{resolve as k,relative as et,dirname as tt,parse as rt}from"path";import{sys as it,factory as I,createProgram as ie,visitEachChild as oe,isStringLiteral as ot,resolveModuleName as nt,DiagnosticCategory as st,isImportDeclaration as ne,isExportDeclaration as se,getPreEmitDiagnostics as ae,flattenDiagnosticMessageText as ce}from"typescript";var O=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=ie(this.tsConfig.fileNames,{...this.options,noEmit:!0,skipLibCheck:!0,emitDeclarationOnly:!0});this.handleDiagnostics(ae(t),e)}generateDeclarations(e=!1,t=!1){let r=ie(this.tsConfig.fileNames,{...this.options,rootDir:this.options.baseUrl,declaration:!0,skipLibCheck:!0,emitDeclarationOnly:!0}),i=ae(r);!e&&i.some(n=>n.category===st.Error)&&this.handleDiagnostics(i,t),r.emit(void 0,void 0,void 0,!0,{afterDeclarations:[this.createTransformerFactory()]})}isImportOrExportDeclaration(e){return ne(e)||se(e)}hasStringLiteralModuleSpecifier(e){return e.moduleSpecifier&&ot(e.moduleSpecifier)}resolveModuleFileName(e,t){let r,i=nt(e,t.baseUrl,t,it);if(i.resolvedModule&&t.baseUrl){if(i.resolvedModule.resolvedFileName.includes("node_modules"))return r;r=k(i.resolvedModule.resolvedFileName).replace(k(t.baseUrl),".")}return r}getRelativePathToOutDir(e,t){e=k(e).replace(k(this.options.baseUrl??""),".");let r=et(tt(e),t).replace(/\\/g,"/"),i=rt(r);return i.dir.startsWith("..")||(i.dir=`./${i.dir}`),`${i.dir}/${i.name}`}updateModuleSpecifier(e,t){let r=I.createStringLiteral(t);return ne(e)?I.updateImportDeclaration(e,e.modifiers,e.importClause,r,void 0):se(e)?I.updateExportDeclaration(e,e.modifiers,e.isTypeOnly,e.exportClause,r,void 0):e}createVisitor(e,t){let r=i=>{if(this.isImportOrExportDeclaration(i)&&this.hasStringLiteralModuleSpecifier(i)){let n=i.moduleSpecifier.text,s=this.resolveModuleFileName(n,this.options);if(s){let a=this.getRelativePathToOutDir(e.fileName,s);return this.updateModuleSpecifier(i,a)}}return oe(i,r,t)};return r}createTransformerFactory(){return e=>({transformSourceFile:t=>oe(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:i,character:n}=r.file.getLineAndCharacterOfPosition(r.start),s=ce(r.messageText,`
79
79
  `),a=f("\x1B[38;5;81m",r.file.fileName,this.activeColor),c=f("\x1B[38;5;230m",`${i+1}:${n+1}`,this.activeColor),p=f("\x1B[38;5;9m","error",this.activeColor),g=f("\x1B[38;5;243m",`TS${r.code}`,this.activeColor);console.error(`${u()} ${a}:${c} - ${p} ${g}:${s}`)}else console.error(ce(r.messageText,`
80
80
  `))}),console.log(`
81
81
  `),!t))throw new P("Type checking failed due to errors.")}};import m from"typescript";import{dirname as mt}from"path";import{existsSync as ue,readFileSync as gt}from"fs";import{cwd as at}from"process";var R={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:at(),loader:{".js":"ts"}},serve:{port:3e3,host:"localhost",active:!1}};import{createRequire as ft}from"module";import{SourceService as ut}from"@remotex-labs/xmap";import{Script as ct,createContext as lt}from"vm";function le(o,e={}){e.RegExp=RegExp,e.console=console;let t=new ct(o),r=lt(e);return t.runInContext(r,{breakOnSigint:!0})}function fe(o,e){for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let r=o[t];typeof r=="function"?o[t]=pt(r,e):typeof r=="object"&&r!==null&&fe(r,e)}return o}function pt(o,e){return(...t)=>{try{return o(...t)}catch(r){throw new y(r,e)}}}function dt(o,e){return fe(o,e)}async function B(o){let{code:e,sourceMap:t}=await U(o,{banner:{js:"(function(module, exports) {"},footer:{js:"})(module, module.exports);"}}),r={exports:{}},i=ft(import.meta.url),n=new ut(JSON.parse(atob(t)));try{await le(e,{require:i,module:r})}catch(s){throw new y(s,n)}return dt(r.exports.default,n)}var ht=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 yt(o){let e=o.argv,t=i=>Object.fromEntries(Object.entries(i).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 pe(o){let e=o.tsconfig??"tsconfig.json",t=ue(e)?gt(e,"utf8"):JSON.stringify(ht),r=m.parseConfigFileTextToJson(e,t);if(r.error)throw new d(m.formatDiagnosticsWithColorAndContext([r.error],{getCurrentDirectory:m.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>m.sys.newLine}));let i=m.parseJsonConfigFileContent(r.config,m.sys,mt(e));if(i.errors.length>0)throw new d(m.formatDiagnosticsWithColorAndContext(i.errors,{getCurrentDirectory:m.sys.getCurrentDirectory,getCanonicalFileName:n=>n,getNewLine:()=>m.sys.newLine}));return i}async function A(o,e={}){let t=Array.isArray(o)?o:[o],r=t[0];return t.flatMap(i=>{let n={...R,...r,...i,...e,esbuild:{...R.esbuild,...r?.esbuild,...i?.esbuild,...e.esbuild},serve:{...R.serve,...r.serve,...i.serve,...e.serve}};if(!n.esbuild.entryPoints)throw new d("entryPoints cannot be undefined.");return n})}async function de(o,e){let t=yt(e),r=ue(o)?await B(o):{};return A(r,t)}function vt(o){let e={};return o.forEach(t=>{let r=t.substring(0,t.lastIndexOf("."));e[r]=t}),e}function me(o){if(Array.isArray(o)){let e={};return o.length>0&&typeof o[0]=="object"?o.forEach(t=>{e[t.out]=t.in}):typeof o[0]=="string"&&(e=vt(o)),e}else if(o&&typeof o=="object")return o;throw new d("Unsupported entry points format")}import{join as St}from"path";import{mkdirSync as Ct,writeFileSync as bt}from"fs";function ge(o){let e=o.moduleTypeOutDir??o.esbuild.outdir??"dist",t=o.esbuild.format==="esm"?"module":"commonjs";Ct(e,{recursive:!0}),bt(St(e,"package.json"),`{"type": "${t}"}`)}var S=class{constructor(e){this.config=e;let t=pe(this.config.esbuild);this.config.esbuild.logLevel="silent",this.pluginsProvider=new T,this.typeScriptProvider=new O(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 E(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 y(t).stack)}}configureDevelopmentMode(){this.config.dev!==!1&&(!Array.isArray(this.config.dev)||this.config.dev.length<1)&&(this.config.dev=["index"])}setupPlugins(){let e=b(this.typeScriptProvider.options.baseUrl??""),t=this.generatePathAlias(e);this.registerPluginHooks(t,e),this.pluginsProvider.registerOnLoad(async(r,i,n,s)=>await z(r,i,n,s,this.config))}registerPluginHooks(e,t){this.pluginsProvider.registerOnEnd(this.end.bind(this)),this.pluginsProvider.registerOnStart(this.start.bind(this)),this.pluginsProvider.registerOnLoad((r,i,n)=>{if(n.path.endsWith(".ts")){if(!this.config.esbuild.bundle){let s=xt(b(n.path).replace(t,"."));r=re(r.toString(),s,e,this.config.esbuild.format==="esm")}return{loader:"ts",contents:te(r.toString(),this.config.define)}}})}generatePathAlias(e){let t=this.typeScriptProvider.options.paths,r={};for(let i in t){let n=t[i];if(n.length>0){let s=i.replace(/\*/g,"");r[s]=b(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 w(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 y(r.detail).stack);continue}}return console.error(r.text)}}}injects(e,t,r){if(!t)return;e[r]||(e[r]={});let i=e[r];for(let n in t)if(t.hasOwnProperty(n)){let s=t[n];if(typeof s=="function"){console.log(`${u()} trigger ${r} function`),i[n]=s();continue}i[n]=s}}async build(){ge(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.registerOnEnd(this.config.hooks.onSuccess),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.injects(this.config.esbuild,this.config.banner,"banner"),this.injects(this.config.esbuild,this.config.footer,"footer"),this.config.watch||this.config.dev||this.config.serve.active?await Et(e):await wt(e)}spawnDev(e,t,r=!1){if(Array.isArray(t))for(let i in e.outputs)i.includes("map")||!t.some(n=>i.includes(`/${n}.`))||this.activePossess.push(V(i,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){this.handleErrors(e),!this.config.serve.active&&!this.config.dev&&!this.config.watch&&he.exit(1);return}let r=Date.now()-t.startTime;console.log(`