vivth 1.3.1 → 1.3.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.
Files changed (56) hide show
  1. package/README.md +2160 -1772
  2. package/README.src.md +5 -0
  3. package/bun.lock +6 -0
  4. package/index.mjs +12 -3
  5. package/package.json +4 -2
  6. package/src/bundler/CompileJS.mjs +60 -28
  7. package/src/bundler/EsBundler.mjs +2 -1
  8. package/src/bundler/FSInline.mjs +8 -1
  9. package/src/bundler/FSInlineAnalyzer.mjs +47 -38
  10. package/src/bundler/adds/ToBundledJSPlugin.mjs +38 -26
  11. package/src/bundler/adds/pluginVivthBundle.mjs +3 -1
  12. package/src/class/EventSignal.mjs +15 -9
  13. package/src/class/ListSignal.mjs +1 -1
  14. package/src/class/LitExp.mjs +3 -2
  15. package/src/class/Paths.mjs +0 -4
  16. package/src/class/QChannel.mjs +4 -5
  17. package/src/class/SafeExit.mjs +27 -8
  18. package/src/class/Signal.mjs +4 -1
  19. package/src/common/Base64URL.mjs +6 -4
  20. package/src/common/Dev.mjs +134 -0
  21. package/src/common/DevBundled.mjs +5 -0
  22. package/src/common/Trace.mjs +24 -0
  23. package/src/doc/JSautoDOC.mjs +15 -11
  24. package/src/doc/parsedFile.mjs +1 -1
  25. package/src/function/GetNamedImportAlias.mjs +37 -0
  26. package/src/function/LazyFactory.mjs +1 -1
  27. package/src/function/TsToMjs.mjs +3 -3
  28. package/src/types/DevTestCB.mjs +11 -0
  29. package/src/types/Runtime.mjs +0 -1
  30. package/src/types/VivthDevCodeBlockStringType.mjs +6 -0
  31. package/tsconfig.json +6 -1
  32. package/types/index.d.mts +8 -3
  33. package/types/src/bundler/CompileJS.d.mts +55 -27
  34. package/types/src/bundler/EsBundler.d.mts +2 -2
  35. package/types/src/bundler/FSInline.d.mts +8 -1
  36. package/types/src/bundler/FSInlineAnalyzer.d.mts +1 -0
  37. package/types/src/bundler/adds/ToBundledJSPlugin.d.mts +6 -3
  38. package/types/src/class/EventSignal.d.mts +8 -8
  39. package/types/src/class/ListSignal.d.mts +2 -2
  40. package/types/src/class/LitExp.d.mts +1 -0
  41. package/types/src/class/Paths.d.mts +0 -4
  42. package/types/src/class/QChannel.d.mts +4 -4
  43. package/types/src/class/SafeExit.d.mts +25 -8
  44. package/types/src/common/Base64URL.d.mts +5 -3
  45. package/types/src/common/Dev.d.mts +68 -0
  46. package/types/src/common/DevBundled.d.mts +3 -0
  47. package/types/src/common/Trace.d.mts +14 -0
  48. package/types/src/doc/JSautoDOC.d.mts +8 -7
  49. package/types/src/function/GetNamedImportAlias.d.mts +22 -0
  50. package/types/src/function/LazyFactory.d.mts +1 -1
  51. package/types/src/function/TsToMjs.d.mts +3 -3
  52. package/types/src/function/WithDefer.d.mts +10 -0
  53. package/types/src/types/DevTestCB.d.mts +3 -0
  54. package/types/src/types/IsDevCBStringType.d.mts +4 -0
  55. package/types/src/types/Runtime.d.mts +3 -0
  56. package/types/src/types/VivthDevCodeBlockStringType.d.mts +4 -0
@@ -2,7 +2,6 @@
2
2
 
3
3
  import { LazyFactory } from '../function/LazyFactory.mjs';
4
4
  import { TryAsync } from '../function/TryAsync.mjs';
5
- import { TrySync } from '../function/TrySync.mjs';
6
5
  import { Console } from './Console.mjs';
7
6
 
8
7
  /**
@@ -34,9 +33,9 @@ export class QChannel {
34
33
  * import { QChannel } from 'vivth';
35
34
  *
36
35
  * const myMappedQref = (window['myMappedQref'] = new Map());
37
- * export const MyQClass = QChannel.makeQClass(myMappedQref);
36
+ * export const MyQClass = QChannel.setup(myMappedQref);
38
37
  */
39
- static makeQClass = (uniqueMap) => {
38
+ static setup = (uniqueMap) => {
40
39
  QChannel.#uniquePromiser = uniqueMap;
41
40
  return QChannel;
42
41
  };
@@ -215,7 +214,7 @@ export class QChannel {
215
214
  * - `callbackBlock` with error as value:
216
215
  * - caveat:
217
216
  * >- no need to manually call resume();
218
- * >- slightly less performant than `callback`;
217
+ * >- slightly less performant than `key`;
219
218
  * @template RESULT
220
219
  * @param {DEFINEDANY} keyID
221
220
  * @param {(options:Omit<QCBReturn,
@@ -224,7 +223,7 @@ export class QChannel {
224
223
  * @returns {ReturnType<typeof TryAsync<RESULT>>}
225
224
  * @example
226
225
  * const q = new QChannel('channel name');
227
- * const [result, error] = await q.callback(keyID, async ({ isLastOnQ }) = > {
226
+ * const [result, error] = await q.callback(keyID, async ({ isLastOnQ }) => {
228
227
  * // if (!isLastOnQ()) { // imperative debounce if needed
229
228
  * // return;
230
229
  * // }
@@ -52,7 +52,7 @@ export class SafeExit {
52
52
  * SafeExit.instance.exiting.correction(true);
53
53
  * Console.log(`safe exit via "${eventName}"`);
54
54
  * });
55
- * };
55
+ * }
56
56
  * ```
57
57
  * - example Deno:
58
58
  * ```js
@@ -75,11 +75,11 @@ export class SafeExit {
75
75
  * // optional deno example
76
76
  * listener : (eventName) => {
77
77
  * const sig = Deno.signal(eventName);
78
- * for await (const _ of sig) {
79
- * exiting.correction(true);
80
- * sig.dispose();
81
- * Console.log(`safe exit via "${eventName}"`);
82
- * }
78
+ * for await (const _ of sig) {
79
+ * exiting.correction(true);
80
+ * sig.dispose();
81
+ * Console.log(`safe exit via "${eventName}"`);
82
+ * }
83
83
  * }
84
84
  * });
85
85
  */
@@ -137,13 +137,32 @@ export class SafeExit {
137
137
  * @example
138
138
  * import { SafeExit } from 'vivth';
139
139
  *
140
- * SafeExit.instance.addCallback(()=>{
140
+ * const exitCallback () => {
141
141
  * // code
142
- * })
142
+ * }
143
+ * SafeExit.instance.addCallback(exitCallback);
143
144
  */
144
145
  addCallback = (cb) => {
145
146
  safeCleanUpCBs.add(cb);
146
147
  };
148
+ /**
149
+ * @description
150
+ * - optional exit event removal;
151
+ * - the callbacks will be removed from registered via `addCallback` exiting;
152
+ * @param {()=>(Promise<void>)} cb
153
+ * @example
154
+ * import { SafeExit } from 'vivth';
155
+ *
156
+ * const exitCallback () => {
157
+ * // code
158
+ * }
159
+ * SafeExit.instance.addCallback(exitCallback);
160
+ * // somewhere else
161
+ * SafeExit.instance.removeCallback(exitCallback);
162
+ */
163
+ removeCallback = (cb) => {
164
+ safeCleanUpCBs.delete(cb);
165
+ };
147
166
  /**
148
167
  * @type {()=>void}
149
168
  */
@@ -114,7 +114,10 @@ export class Signal {
114
114
  * @returns {void}
115
115
  */
116
116
  subscriber: (effectInstance) => {
117
- effectInstance.options.removeEffect();
117
+ /**
118
+ * this part is not needed, as the effect might need to react to other signals
119
+ // effectInstance.options.removeEffect();
120
+ */
118
121
  this.subscribers.setOf.delete(effectInstance);
119
122
  },
120
123
  /**
@@ -4,21 +4,23 @@
4
4
  * @description
5
5
  * - create inline base64 url;
6
6
  * - usage:
7
- * >- can be extremely usefull to display file on desktop app webview, without exposing http server;
7
+ * >- can be extremely usefull to display file on desktop app `webview` or any bundled browser, without exposing http server;
8
8
  * @param {string} fileString
9
9
  * @param {string} mimeType
10
10
  * @param {(string:string)=>string} btoaFunction
11
11
  * - check your js runtime `btoa`;
12
12
  * - node compatible:
13
13
  * ```js
14
- * (str, prevBufferEncoding) =>
15
- * Buffer.from(str, prevBufferEncoding).toString('base64')
14
+ * (str, prevBufferEncoding) => {
15
+ * return Buffer.from(str, prevBufferEncoding).toString('base64');
16
+ * }
16
17
  * ```
17
18
  * @returns {string}
18
19
  * @example
19
20
  * import { Base64URL } from 'vivth'
20
21
  * import fileString from './fileString.mjs';
21
22
  *
23
+ * // example for browser;
22
24
  * Base64URL(fileString, 'application/javascript', btoa);
23
25
  */
24
26
  export function Base64URL(fileString, mimeType, btoaFunction) {
@@ -28,4 +30,4 @@ export function Base64URL(fileString, mimeType, btoaFunction) {
28
30
  binary += String.fromCharCode(byte);
29
31
  }
30
32
  return `data:${mimeType.toString()};base64,${btoaFunction(binary)}`;
31
- };
33
+ }
@@ -0,0 +1,134 @@
1
+ // @ts-check
2
+
3
+ import { Console } from '../class/Console.mjs';
4
+ import { Effect } from '../class/Effect.mjs';
5
+ import { Signal } from '../class/Signal.mjs';
6
+ import { LazyFactory } from '../function/LazyFactory.mjs';
7
+ import { TryAsync } from '../function/TryAsync.mjs';
8
+ import { Trace } from './Trace.mjs';
9
+
10
+ /**
11
+ * @typedef {import("../types/VivthDevCodeBlockStringType.mjs").VivthDevCodeBlockStringType} VivthDevCodeBlockStringType
12
+ * @typedef {import('../types/DevTestCB.mjs').DevTestCB} DevTestCB
13
+ */
14
+
15
+ /**
16
+ * @description
17
+ * - class helper for `devTime` only code block;
18
+ */
19
+ export class Dev {
20
+ /**
21
+ * @description
22
+ * - persistent variable(during `devTime` and `bundled`);
23
+ * - can be used as `condition` for checking whether it is in `devTime` or `bundled`;
24
+ * @type {boolean}
25
+ * @example
26
+ * import { Dev } from 'vivth';
27
+ *
28
+ * if (Dev.isDev) {
29
+ * // this code block will presist even on `bundled`;
30
+ * }
31
+ */
32
+ static isDev = true;
33
+ /**
34
+ * @type {Signal<Map<string,Awaited<ReturnType<typeof TryAsync<boolean>>>>>}
35
+ */
36
+ static #notifications = LazyFactory(() => new Signal(new Map()));
37
+ /**
38
+ * @type {DevTestCB}
39
+ */
40
+ static #test = async (testName, testCallback) => {
41
+ testName = `${testName}:'${Trace(4)}'`;
42
+ Dev.#notifications.subscribers.notify(async ({ signalInstance }) => {
43
+ signalInstance.value.set(
44
+ testName,
45
+ await TryAsync(async () => {
46
+ return await testCallback();
47
+ })
48
+ );
49
+ });
50
+ Dev.#effectForCheck['vivth:unwrapLazy;']();
51
+ return {
52
+ removeId: () => {
53
+ Dev.#notifications.subscribers.notify(async ({ signalInstance }) => {
54
+ signalInstance.value.delete(testName);
55
+ });
56
+ },
57
+ };
58
+ };
59
+ static #effectForCheck = LazyFactory(
60
+ () =>
61
+ new Effect(async ({ isLastCalled, subscribe }) => {
62
+ const notifications = subscribe(Dev.#notifications).value;
63
+ if (!(await isLastCalled(100)) || !notifications.size) {
64
+ return;
65
+ }
66
+ /**
67
+ * @type {string[]}
68
+ */
69
+ const succeedTest = [];
70
+ /**
71
+ * @type {string[]}
72
+ */
73
+ const failedTest = [];
74
+ for (const [notificationID, [isCorrect, error]] of notifications) {
75
+ if (error || !isCorrect) {
76
+ failedTest.push(notificationID);
77
+ continue;
78
+ }
79
+ succeedTest.push(notificationID);
80
+ }
81
+ const size = notifications.size;
82
+ /**
83
+ * @type {{
84
+ * testCount:number,
85
+ * succeed?: {count:string, testID:string[]},
86
+ * failed?: {count:string, testID:string[]},
87
+ * }}
88
+ */
89
+ let warn = { testCount: size };
90
+ if (succeedTest.length) {
91
+ warn.succeed = {
92
+ count: `${succeedTest.length} of ${size}`,
93
+ testID: succeedTest,
94
+ };
95
+ }
96
+ if (failedTest.length) {
97
+ warn.failed = {
98
+ count: `${failedTest.length} of ${size}`,
99
+ testID: failedTest,
100
+ };
101
+ }
102
+ Console.warn(warn);
103
+ })
104
+ );
105
+ /**
106
+ * @description
107
+ * - to wrap `devTime` only code block;
108
+ * - when bundled uses `EsBundler` or esbuild with `ToBundledJSPlugin` plugin, the code block will be removed on the bundled version;
109
+ * @param {(options:{test:DevTestCB})=>Promise<void>} callback
110
+ * - also provide `test` method for inline testing:
111
+ * >- which is wrapped in `TryAsync`, throwed errors will automatically return `false`;
112
+ * @param {VivthDevCodeBlockStringType} _closing
113
+ * - it is needed to detect the code block closing;
114
+ * - should use single or double quote and not back tick;
115
+ * @returns {Promise<void>}
116
+ * @example
117
+ * import { Dev, Signal } from 'vivth';
118
+ *
119
+ * Dev.vivthDevCodeBlock(async function () {
120
+ * // this code block will be removed on `bundled` version;
121
+ * }, 'vivthDevCodeBlock');
122
+ *
123
+ * const numberSignal = new Signal(0);
124
+ * Dev.vivthDevCodeBlock(async ({ test }) => {
125
+ * // this code block will be removed on `bundled` version;
126
+ * const [{ removeId: removeTest }] = await Promise.all([
127
+ * test(async () => numberSignal.value === 0)
128
+ * ])
129
+ * }, 'vivthDevCodeBlock');
130
+ */
131
+ static vivthDevCodeBlock = async (callback, _closing) => {
132
+ await callback({ test: Dev.#test });
133
+ };
134
+ }
@@ -0,0 +1,5 @@
1
+ // @ts-check
2
+
3
+ export class Dev {
4
+ static isDev = false;
5
+ }
@@ -0,0 +1,24 @@
1
+ // @ts-check
2
+
3
+ import { Paths } from '../class/Paths.mjs';
4
+
5
+ /**
6
+ * @description
7
+ * - returns position of stack trace as string, formatted as `fileName:lineNumber:columnNumber`;
8
+ * - extremely usefull for:
9
+ * >- jumping positions to code line;
10
+ * >- creating dynamic string id;
11
+ * @param {number} traceIndex
12
+ * @returns {string}
13
+ * @example
14
+ * import { Trace, Console } from 'vivth';
15
+ *
16
+ * Console.log(Trace(3)); // "D://test.mjs:3:13"
17
+ */
18
+ export function Trace(traceIndex) {
19
+ const err = new Error();
20
+ const stack = err.stack?.split('\n');
21
+ const callerLine = stack?.[Math.round(traceIndex)] ?? 'unknown';
22
+ const match = callerLine.match(/([A-Z]:[^ ]*[0-9]|\/[^ )]+:\d+:\d+)/m);
23
+ return Paths.normalize(match?.[1] ?? callerLine.trim());
24
+ }
@@ -3,6 +3,7 @@
3
3
  import { extname, join } from 'node:path';
4
4
  import { readFile } from 'node:fs/promises';
5
5
 
6
+ import prettier from 'prettier';
6
7
  import chokidar from 'chokidar';
7
8
  import { EventSignal } from '../class/EventSignal.mjs';
8
9
  import { parsedFile } from './parsedFile.mjs';
@@ -36,21 +37,22 @@ const acceptableExt = new Set(['.mjs', '.mts', '.ts']);
36
37
  * - this autodocumenter uses [chokidar](https://npmjs.com/package/chokidar) under the hood;
37
38
  * - this class also is used to generate this `README.md`;
38
39
  * - behaviours:
40
+ * >- auto export must follows the following rules;
39
41
  * >1) add `"at"noautodoc` on self closing jsdoc comment to opt out from generating documentation on said file;
40
- * >>- auto export must follows the following rules, and there's no way to override;
41
- * >2) export all named exported 'const'|'function'|'async function'|'class', alphanumeric name, started with Capital letter, same name with fileName on `options.pahts.file`;
42
- * >3) declare typedef of existing typedef with alphanumeric name, started with Capital letter, same name with fileName, and have no valid export like on point <sup>1</sup> on `options.pahts.file`;
43
- * >4) create `README.md` based on, `options.paths.dir` and `README.src.md`;
42
+ * >2) will (generate) export all named exported 'const'|'function'|'async function'|'class', alphanumeric name, started with Capital letter, same name with fileName on `options.paths.file`;
43
+ * >3) will (generate) declare typedef of existing typedef with alphanumeric name, started with Capital letter, same name with fileName, and have no valid export like on point <sup>1</sup> on `options.paths.file`;
44
+ * >4) will (generate) create `README.md` based on, `options.paths.dir` and `README.src.md`;
44
45
  * >5) extract `"at"description` jsdoc:
45
46
  * >>- on static/prop that have depths, all of children should have `"at"static`/`"at"instance` `nameOfImmediateParent`, same block but before `"at"description` comment line;
46
47
  * >>- `"at"description` are treated as plain `markdown`;
47
48
  * >>- first `"at"${string}` after `"at"description` until `"at"example` will be treated as `javascript` comment block on the `markdown`;
48
49
  * >>- `"at"example` are treated as `javascript` block on the `markdown` file, and should be placed last on the same comment block;
49
50
  * >>- you can always look at `vivth/src` files to check how the source, and the `README.md` and `index.mjs` documentation/generation results;
50
- * >6) this types of arrow functions will be converted to regullar function, for concise type emition:
51
+ * >6) this types of arrow functions will be converted to regullar function, for concise type emition, includes:
51
52
  * >>- validly exported function;
52
- * >>- static/instance method(s) with generic template;
53
- * >7) transpile `.ts` and `.mts` to `.mjs` same name and directory;
53
+ * >>- static/instance method with generic template;
54
+ * >7) transpile `.ts` and `.mts` to `.mjs` with same name and directory;
55
+ * >>- use `"at"preserve` to preserve tsdoc comment section;
54
56
  */
55
57
  export class JSautoDOC {
56
58
  /**
@@ -201,7 +203,9 @@ export class JSautoDOC {
201
203
  const readmePath = join(rootPath, this.#paths.readMe);
202
204
  const mjsFilePath = join(rootPath, this.#paths.file);
203
205
  const [[, errorWriteReadme], [, errorWriteMjsFile]] = await Promise.all([
204
- FileSafe.write(readmePath, readme, { encoding }),
206
+ FileSafe.write(readmePath, await prettier.format(readme, { parser: 'markdown' }), {
207
+ encoding,
208
+ }),
205
209
  FileSafe.write(mjsFilePath, mjsFile, { encoding }),
206
210
  ]);
207
211
  if (errorWriteReadme === undefined) {
@@ -244,7 +248,8 @@ export class JSautoDOC {
244
248
  const apiDocuments = [];
245
249
  const mjsMain = ['// @ts-check', this.#generateJSDOCFromstring(this.#copyright)];
246
250
  const mjsTypes = [];
247
- for await (const path_ of filepaths) {
251
+ const sortedFilepaths = [...filepaths].sort((a, b) => a.localeCompare(b));
252
+ for await (const path_ of sortedFilepaths) {
248
253
  const {
249
254
  documented,
250
255
  content,
@@ -256,7 +261,6 @@ export class JSautoDOC {
256
261
  if (trueContent === undefined) {
257
262
  return;
258
263
  }
259
-
260
264
  const hasNoAutoDoc = /\/\*\*[\s\*]*?@noautodoc[\s\*]*?\*\//.test(trueContent);
261
265
  if (hasValidExportObject) {
262
266
  mjsMain.push(
@@ -398,7 +402,7 @@ export class JSautoDOC {
398
402
  this.#filePaths.subscribers.notify(async ({ signalInstance }) => {
399
403
  Console.warn({ [eventName]: path__ });
400
404
  signalInstance.value.delete(path__);
401
- this.#parsedFilesRef.unRef(path__);
405
+ await this.#parsedFilesRef.unRef(path__);
402
406
  });
403
407
  });
404
408
  };
@@ -322,7 +322,7 @@ export class parsedFile {
322
322
  const fullDescTrue_0 = fullDescTrue[0] ?? '';
323
323
  const description = fullDescTrue_0
324
324
  .replace('*', '')
325
- .replace(/(?<!\\)\*\s/g, '\n')
325
+ .replace(/\s*(?<!\\)\*\s/g, '\n')
326
326
  .trim();
327
327
  fullDescTrue.shift();
328
328
  let example;
@@ -0,0 +1,37 @@
1
+ // @ts-check
2
+
3
+ import { Console } from '../class/Console.mjs';
4
+
5
+ /**
6
+ * @description
7
+ * - regex helper for:
8
+ * >- get named import; OR
9
+ * >- alias of named import;
10
+ * @param {string} content
11
+ * @param {string} moduleName
12
+ * @param {string} packageName
13
+ * @returns {string|undefined}
14
+ * @example
15
+ * import { GetNamedImportAlias } from 'vivth';
16
+ *
17
+ * const checkNoAlias = `
18
+ * import { something } from 'packageName';
19
+ * `
20
+ * const checkAlias = `
21
+ * import { something as somethingElse } from 'packageName';
22
+ * `
23
+ * GetNamedImportAlias(checkNoAlias, 'something', 'packageName'); // 'something'
24
+ * GetNamedImportAlias(checkAlias, 'something', 'packageName'); // 'somethingElse'
25
+ */
26
+ export function GetNamedImportAlias(content, moduleName, packageName) {
27
+ const checkIfImportingFromVivthRegex = new RegExp(
28
+ `(import\\s+{\\s*[\\s\\S]*(?<imported>${moduleName})\\s+as\\s+(?<alias>[a-zA-Z0-9]+)[\\s\\S]*\\s*}\\s+from\\s+['"]${packageName}['"])|(import\\s+{\\s*[\\s\\S]*(?<imported>${moduleName})[\\s\\S]*\\s*}\\s+from\\s+['"]${packageName}['"])`,
29
+ 'g'
30
+ );
31
+ const matched = checkIfImportingFromVivthRegex.exec(content);
32
+ if (!matched || !matched.groups) {
33
+ return;
34
+ }
35
+ const { imported, alias } = matched.groups;
36
+ return alias ?? imported;
37
+ }
@@ -33,7 +33,7 @@ import { unwrapLazy } from '../common/lazie.mjs';
33
33
  * const a = myInstance; // not yet initiated;
34
34
  * const b = a.myProp // imediately initiated;
35
35
  * // OR
36
- * myInstance["vivth:unwrapLazy;"]() // forcefully call the callback;
36
+ * myInstance["vivth:unwrapLazy;"]() // forcefully call factory generator;
37
37
  */
38
38
  export function LazyFactory(factory) {
39
39
  /**
@@ -12,9 +12,9 @@ import { FileSafe } from '../class/FileSafe.mjs';
12
12
 
13
13
  /**
14
14
  * @description
15
- * - turn `.mts`||`.ts` file into `.mjs`, no bundling, just translation;
15
+ * - turn `.mts`||`.ts` file into `.mjs`, no bundling, just traspilation;
16
16
  * - on certain circumstance where `.mjs` result needed to be typed, you need to manually add `jsdoc`;
17
- * >- uses `"at"preserve` to register `jsdoc` inline;
17
+ * >- uses `"at"preserve` to register `jsdoc`;
18
18
  * @param {string} path_
19
19
  * - path from `Paths.root`;
20
20
  * @param {Object} [options]
@@ -27,7 +27,7 @@ import { FileSafe } from '../class/FileSafe.mjs';
27
27
  * @example
28
28
  * import { TsToMjs } from 'vivth';
29
29
  *
30
- * TsToMjs('./myFile.mts', { encoding: 'utf-8', overrideDir: './other/dir' });
30
+ * await TsToMjs('./myFile.mts', { encoding: 'utf-8', overrideDir: './other/dir' });
31
31
  */
32
32
  export async function TsToMjs(path_, { overrideDir = undefined, encoding = 'utf-8' } = {}) {
33
33
  if (Paths.root === undefined) {
@@ -0,0 +1,11 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * @callback DevTestCB
5
+ * @param {string} testName
6
+ * @param {()=>Promise<boolean>} testCallback
7
+ * - already wrapped with `TryAsync`:
8
+ * >- if throws error will automatically return false;
9
+ * @returns {Promise<{removeId:()=>void}>}
10
+ * - calling `removeId` will remove the this test from reports;
11
+ */
@@ -1,7 +1,6 @@
1
1
  // @ts-check
2
2
 
3
3
  /**
4
- * @description
5
4
  * - for popular runtimes check;
6
5
  * @typedef {'node' | 'bun' | 'deno' | 'browser' | 'unknown'} Runtime
7
6
  */
@@ -0,0 +1,6 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * - closing helper for `Dev.vivthDevCodeBlock`;
5
+ * @typedef {'vivthDevCodeBlock'} VivthDevCodeBlockStringType
6
+ */
package/tsconfig.json CHANGED
@@ -32,5 +32,10 @@
32
32
  "noUnusedParameters": false,
33
33
  "noPropertyAccessFromIndexSignature": false
34
34
  },
35
- "include": ["./index.mjs", "./src", "./dev"]
35
+ "include": [
36
+ //
37
+ "./index.mjs",
38
+ // "./dev",
39
+ "./src"
40
+ ]
36
41
  }
package/types/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ export { ToBundledJSPlugin } from "./src/bundler/adds/ToBundledJSPlugin.mjs";
1
2
  export { CompileJS } from "./src/bundler/CompileJS.mjs";
2
3
  export { CreateESPlugin } from "./src/bundler/CreateESPlugin.mjs";
3
4
  export { EsBundler } from "./src/bundler/EsBundler.mjs";
@@ -18,13 +19,18 @@ export { SafeExit } from "./src/class/SafeExit.mjs";
18
19
  export { Setup } from "./src/class/Setup.mjs";
19
20
  export { Signal } from "./src/class/Signal.mjs";
20
21
  export { WorkerMainThread } from "./src/class/WorkerMainThread.mjs";
22
+ export { WorkerResult } from "./src/class/WorkerResult.mjs";
23
+ export { WorkerThread } from "./src/class/WorkerThread.mjs";
21
24
  export { Base64URL } from "./src/common/Base64URL.mjs";
22
25
  export { Base64URLFromFile } from "./src/common/Base64URLFromFile.mjs";
26
+ export { Dev } from "./src/common/Dev.mjs";
23
27
  export { EventNameSpace } from "./src/common/EventNameSpace.mjs";
28
+ export { Trace } from "./src/common/Trace.mjs";
24
29
  export { JSautoDOC } from "./src/doc/JSautoDOC.mjs";
25
30
  export { CreateImmutable } from "./src/function/CreateImmutable.mjs";
26
31
  export { EventCheck } from "./src/function/EventCheck.mjs";
27
32
  export { EventObject } from "./src/function/EventObject.mjs";
33
+ export { GetNamedImportAlias } from "./src/function/GetNamedImportAlias.mjs";
28
34
  export { GetRuntime } from "./src/function/GetRuntime.mjs";
29
35
  export { IsAsync } from "./src/function/IsAsync.mjs";
30
36
  export { LazyFactory } from "./src/function/LazyFactory.mjs";
@@ -33,10 +39,8 @@ export { Try } from "./src/function/Try.mjs";
33
39
  export { TryAsync } from "./src/function/TryAsync.mjs";
34
40
  export { TrySync } from "./src/function/TrySync.mjs";
35
41
  export { TsToMjs } from "./src/function/TsToMjs.mjs";
36
- export { WorkerResult } from "./src/class/WorkerResult.mjs";
37
- export { WorkerThread } from "./src/class/WorkerThread.mjs";
38
- export { ToBundledJSPlugin } from "./src/bundler/adds/ToBundledJSPlugin.mjs";
39
42
  export type AnyButUndefined = import("./src/types/AnyButUndefined.mjs").AnyButUndefined;
43
+ export type DevTestCB = import("./src/types/DevTestCB.mjs").DevTestCB;
40
44
  export type ExtnameType = import("./src/types/ExtnameType.mjs").ExtnameType;
41
45
  export type IsListSignal = import("./src/types/IsListSignal.mjs").IsListSignal;
42
46
  export type ListArg = import("./src/types/ListArg.mjs").ListArg;
@@ -46,3 +50,4 @@ export type MutationType = import("./src/types/MutationType.mjs").MutationType;
46
50
  export type QCBFIFOReturn = import("./src/types/QCBFIFOReturn.mjs").QCBFIFOReturn;
47
51
  export type QCBReturn = import("./src/types/QCBReturn.mjs").QCBReturn;
48
52
  export type Runtime = import("./src/types/Runtime.mjs").Runtime;
53
+ export type VivthDevCodeBlockStringType = import("./src/types/VivthDevCodeBlockStringType.mjs").VivthDevCodeBlockStringType;
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * @description
3
3
  * - function to compile `.ts`|`.mts`|`.mjs` file, into a single executable;
4
- * - also generate js representation;
4
+ * - also generate js representation of the `bundled` version of the target;
5
5
  * - uses [pkg](https://www.npmjs.com/package/pkg), [bun](https://bun.com/docs/bundler/executables), and [deno](https://docs.deno.com/runtime/reference/cli/compile/) compiler under the hood;
6
- * >- they are used only as packaging agent, and doesn't necessarily supports their advanced feature, such as, assets bundling(use [FSInline](#fsinline) instead);
6
+ * >- they are used only as packaging/compiler agent, and doesn't necessarily supports their advanced feature, such as, assets bundling(use [`FSInline`](#fsinline) instead);
7
7
  * >- `WorkerThread` will be converted to inline using `FSInline` too;
8
8
  *
9
9
  * !!!WARNING!!!
@@ -22,8 +22,12 @@
22
22
  * @param {string} options.entryPoint
23
23
  * - need to be manually prefixed;
24
24
  * @param {BufferEncoding} [options.encoding]
25
- * - write and read encoding for the sources;
25
+ * - read and write encoding for the sources;
26
26
  * - default: `utf-8`;
27
+ * @param {(entryPointContent:string)=>string} [options.preprocessEntryPoint]
28
+ * - to modify entry point before bundling;
29
+ * - `entryPointContent` is the original string of the entry point;
30
+ * - returned value then passed to `ESBundler`;
27
31
  * @param {boolean} options.minifyFirst
28
32
  * - minify the bundle before compilation;
29
33
  * @param {string} options.outDir
@@ -44,35 +48,59 @@
44
48
  * }>>}
45
49
  * @example
46
50
  * import { join } from 'node:path';
51
+ * import { CompileJS, Console, Paths, Setup } from 'vivth';
47
52
  *
48
- * import { CompileJS, Paths } from 'vivth';
53
+ * const { paths, safeExit } = Setup;
54
+ * new paths({
55
+ * root: process?.env?.INIT_CWD ?? process?.cwd(),
56
+ * });
57
+ * new safeExit({
58
+ * eventNames: ['SIGINT', 'SIGTERM'],
59
+ * terminator: () => process.exit(0), // OR on deno () => Deno.exit\* (0),
60
+ * listener: (eventName) => {
61
+ * process.once(eventName, function () {
62
+ * if (!safeExit.instance) {
63
+ * return;
64
+ * }
65
+ * safeExit.instance.exiting.correction(true);
66
+ * Console.log(`safe exit via "${eventName}"`);
67
+ * });
68
+ * },
69
+ * });
70
+ * const pathRoot = Paths.root;
71
+ * if (pathRoot) {
72
+ * const [[, error], [, errorbun]] = await Promise.all([
73
+ * CompileJS({
74
+ * entryPoint: join(pathRoot, '/dev/myEntryPoint.mjs'),
75
+ * minifyFirst: true,
76
+ * outDir: join(pathRoot, '/dev-pkg/'),
77
+ * compiler: 'pkg',
78
+ * compilerArguments: {
79
+ * target: 'node18-win-x64',
80
+ * },
81
+ * encoding: 'utf-8',
82
+ * }),
83
+ * await CompileJS({
84
+ * entryPoint: join(pathRoot, '/dev/myEntryPoint.mjs'),
85
+ * minifyFirst: true,
86
+ * outDir: join(pathRoot, '/dev-bun/'),
87
+ * compiler: 'bun',
88
+ * compilerArguments: {
89
+ * target: 'bun-win-x64',
90
+ * },
91
+ * encoding: 'utf-8',
92
+ * }),
93
+ * ]);
94
+ * if (error || errorbun) {
95
+ * Console.error({ error, errorbun });
96
+ * }
97
+ * }
49
98
  *
50
- * const [[resultPkg, errorPkg], [resultBun, errorBun]] = await Promise.all([
51
- * CompileJS({
52
- * entryPoint: join(Paths.root, '/dev'),
53
- * minifyFirst: true,
54
- * outDir: join(Paths.root, '/dev-pkg'),
55
- * compiler: 'pkg',
56
- * compilerArguments: {
57
- * target: ['node18-win-x64'],
58
- * },
59
- * esBundlerPlugins: [],
60
- * }),
61
- * CompileJS({
62
- * entryPoint: join(Paths.root, '/dev'),
63
- * minifyFirst: true,
64
- * outDir: join(Paths.root, '/dev-pkg'),
65
- * compiler: 'bun',
66
- * compilerArguments: {
67
- * target: ['bun-win-x64'],
68
- * },
69
- * esBundlerPlugins: [],
70
- * }),
71
- * ])
72
99
  */
73
- export function CompileJS({ entryPoint, minifyFirst, encoding, outDir, compiler, compilerArguments, esBundlerPlugins, }: {
100
+ export function CompileJS({ entryPoint, minifyFirst, encoding, outDir, preprocessEntryPoint, compiler, compilerArguments, esBundlerPlugins, }: {
74
101
  entryPoint: string;
75
102
  encoding?: BufferEncoding | undefined;
103
+ preprocessEntryPoint?: ((entryPointContent: string) => string) | undefined;
76
104
  minifyFirst: boolean;
77
105
  outDir: string;
78
106
  compiler?: "pkg" | "bun" | "deno" | undefined;