@cldmv/slothlet 3.2.3 → 3.3.2

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 (138) hide show
  1. package/README.md +22 -9
  2. package/REFERENCE.md +23 -0
  3. package/dist/lib/builders/api-assignment.mjs +1 -589
  4. package/dist/lib/builders/api_builder.mjs +1 -1155
  5. package/dist/lib/builders/builder.mjs +1 -78
  6. package/dist/lib/builders/modes-processor.mjs +1 -1800
  7. package/dist/lib/errors.mjs +9 -211
  8. package/dist/lib/factories/component-base.mjs +1 -80
  9. package/dist/lib/factories/context.mjs +1 -22
  10. package/dist/lib/handlers/api-cache-manager.mjs +1 -200
  11. package/dist/lib/handlers/api-manager.mjs +1 -2513
  12. package/dist/lib/handlers/context-async.mjs +1 -168
  13. package/dist/lib/handlers/context-live.mjs +1 -168
  14. package/dist/lib/handlers/hook-manager.mjs +1 -773
  15. package/dist/lib/handlers/lifecycle-token.mjs +1 -28
  16. package/dist/lib/handlers/lifecycle.mjs +1 -115
  17. package/dist/lib/handlers/materialize-manager.mjs +1 -48
  18. package/dist/lib/handlers/metadata.mjs +1 -501
  19. package/dist/lib/handlers/ownership.mjs +1 -322
  20. package/dist/lib/handlers/permission-manager.mjs +17 -0
  21. package/dist/lib/handlers/unified-wrapper.mjs +1 -3042
  22. package/dist/lib/handlers/version-manager.mjs +1 -885
  23. package/dist/lib/helpers/class-instance-wrapper.mjs +1 -109
  24. package/dist/lib/helpers/config.mjs +1 -355
  25. package/dist/lib/helpers/eventemitter-context.mjs +1 -349
  26. package/dist/lib/helpers/hint-detector.mjs +1 -47
  27. package/dist/lib/helpers/modes-utils.mjs +1 -37
  28. package/dist/lib/helpers/pattern-matcher.mjs +17 -0
  29. package/dist/lib/helpers/resolve-from-caller.mjs +1 -169
  30. package/dist/lib/helpers/sanitize.mjs +1 -340
  31. package/dist/lib/helpers/utilities.mjs +1 -70
  32. package/dist/lib/i18n/languages/de-de.json +21 -1
  33. package/dist/lib/i18n/languages/en-gb.json +21 -1
  34. package/dist/lib/i18n/languages/en-us.json +21 -1
  35. package/dist/lib/i18n/languages/es-mx.json +21 -1
  36. package/dist/lib/i18n/languages/fr-fr.json +21 -1
  37. package/dist/lib/i18n/languages/hi-in.json +21 -1
  38. package/dist/lib/i18n/languages/ja-jp.json +21 -1
  39. package/dist/lib/i18n/languages/ko-kr.json +21 -1
  40. package/dist/lib/i18n/languages/pt-br.json +21 -1
  41. package/dist/lib/i18n/languages/ru-ru.json +21 -1
  42. package/dist/lib/i18n/languages/zh-cn.json +21 -1
  43. package/dist/lib/i18n/translations.mjs +1 -126
  44. package/dist/lib/modes/eager.mjs +1 -59
  45. package/dist/lib/modes/lazy.mjs +1 -81
  46. package/dist/lib/processors/flatten.mjs +1 -437
  47. package/dist/lib/processors/loader.mjs +1 -339
  48. package/dist/lib/processors/type-generator.mjs +1 -275
  49. package/dist/lib/processors/typescript.mjs +1 -172
  50. package/dist/lib/runtime/runtime-asynclocalstorage.mjs +1 -113
  51. package/dist/lib/runtime/runtime-livebindings.mjs +1 -78
  52. package/dist/lib/runtime/runtime.mjs +1 -102
  53. package/dist/slothlet.mjs +1 -808
  54. package/package.json +37 -31
  55. package/types/dist/lib/builders/api-assignment.d.mts +3 -92
  56. package/types/dist/lib/builders/api-assignment.d.mts.map +1 -1
  57. package/types/dist/lib/builders/api_builder.d.mts +102 -91
  58. package/types/dist/lib/builders/api_builder.d.mts.map +1 -1
  59. package/types/dist/lib/builders/builder.d.mts +1 -55
  60. package/types/dist/lib/builders/builder.d.mts.map +1 -1
  61. package/types/dist/lib/builders/modes-processor.d.mts +3 -27
  62. package/types/dist/lib/builders/modes-processor.d.mts.map +1 -1
  63. package/types/dist/lib/errors.d.mts +19 -109
  64. package/types/dist/lib/errors.d.mts.map +1 -1
  65. package/types/dist/lib/factories/component-base.d.mts +7 -177
  66. package/types/dist/lib/factories/component-base.d.mts.map +1 -1
  67. package/types/dist/lib/factories/context.d.mts +4 -22
  68. package/types/dist/lib/factories/context.d.mts.map +1 -1
  69. package/types/dist/lib/handlers/api-cache-manager.d.mts +20 -203
  70. package/types/dist/lib/handlers/api-cache-manager.d.mts.map +1 -1
  71. package/types/dist/lib/handlers/api-manager.d.mts +33 -408
  72. package/types/dist/lib/handlers/api-manager.d.mts.map +1 -1
  73. package/types/dist/lib/handlers/context-async.d.mts +23 -61
  74. package/types/dist/lib/handlers/context-async.d.mts.map +1 -1
  75. package/types/dist/lib/handlers/context-live.d.mts +22 -59
  76. package/types/dist/lib/handlers/context-live.d.mts.map +1 -1
  77. package/types/dist/lib/handlers/hook-manager.d.mts +46 -185
  78. package/types/dist/lib/handlers/hook-manager.d.mts.map +1 -1
  79. package/types/dist/lib/handlers/lifecycle-token.d.mts +3 -48
  80. package/types/dist/lib/handlers/lifecycle-token.d.mts.map +1 -1
  81. package/types/dist/lib/handlers/lifecycle.d.mts +5 -82
  82. package/types/dist/lib/handlers/lifecycle.d.mts.map +1 -1
  83. package/types/dist/lib/handlers/materialize-manager.d.mts +8 -70
  84. package/types/dist/lib/handlers/materialize-manager.d.mts.map +1 -1
  85. package/types/dist/lib/handlers/metadata.d.mts +17 -221
  86. package/types/dist/lib/handlers/metadata.d.mts.map +1 -1
  87. package/types/dist/lib/handlers/ownership.d.mts +44 -160
  88. package/types/dist/lib/handlers/ownership.d.mts.map +1 -1
  89. package/types/dist/lib/handlers/permission-manager.d.mts +47 -0
  90. package/types/dist/lib/handlers/permission-manager.d.mts.map +1 -0
  91. package/types/dist/lib/handlers/unified-wrapper.d.mts +26 -239
  92. package/types/dist/lib/handlers/unified-wrapper.d.mts.map +1 -1
  93. package/types/dist/lib/handlers/version-manager.d.mts +28 -225
  94. package/types/dist/lib/handlers/version-manager.d.mts.map +1 -1
  95. package/types/dist/lib/helpers/class-instance-wrapper.d.mts +2 -52
  96. package/types/dist/lib/helpers/class-instance-wrapper.d.mts.map +1 -1
  97. package/types/dist/lib/helpers/config.d.mts +125 -123
  98. package/types/dist/lib/helpers/config.d.mts.map +1 -1
  99. package/types/dist/lib/helpers/eventemitter-context.d.mts +3 -29
  100. package/types/dist/lib/helpers/eventemitter-context.d.mts.map +1 -1
  101. package/types/dist/lib/helpers/hint-detector.d.mts +2 -15
  102. package/types/dist/lib/helpers/hint-detector.d.mts.map +1 -1
  103. package/types/dist/lib/helpers/modes-utils.d.mts +3 -30
  104. package/types/dist/lib/helpers/modes-utils.d.mts.map +1 -1
  105. package/types/dist/lib/helpers/pattern-matcher.d.mts +4 -0
  106. package/types/dist/lib/helpers/pattern-matcher.d.mts.map +1 -0
  107. package/types/dist/lib/helpers/resolve-from-caller.d.mts +3 -27
  108. package/types/dist/lib/helpers/resolve-from-caller.d.mts.map +1 -1
  109. package/types/dist/lib/helpers/sanitize.d.mts +4 -92
  110. package/types/dist/lib/helpers/sanitize.d.mts.map +1 -1
  111. package/types/dist/lib/helpers/utilities.d.mts +4 -52
  112. package/types/dist/lib/helpers/utilities.d.mts.map +1 -1
  113. package/types/dist/lib/i18n/translations.d.mts +4 -37
  114. package/types/dist/lib/i18n/translations.d.mts.map +1 -1
  115. package/types/dist/lib/modes/eager.d.mts +8 -30
  116. package/types/dist/lib/modes/eager.d.mts.map +1 -1
  117. package/types/dist/lib/modes/lazy.d.mts +10 -43
  118. package/types/dist/lib/modes/lazy.d.mts.map +1 -1
  119. package/types/dist/lib/processors/flatten.d.mts +56 -107
  120. package/types/dist/lib/processors/flatten.d.mts.map +1 -1
  121. package/types/dist/lib/processors/loader.d.mts +6 -41
  122. package/types/dist/lib/processors/loader.d.mts.map +1 -1
  123. package/types/dist/lib/processors/type-generator.d.mts +2 -16
  124. package/types/dist/lib/processors/type-generator.d.mts.map +1 -1
  125. package/types/dist/lib/processors/typescript.d.mts +6 -53
  126. package/types/dist/lib/processors/typescript.d.mts.map +1 -1
  127. package/types/dist/lib/runtime/runtime-asynclocalstorage.d.mts +3 -71
  128. package/types/dist/lib/runtime/runtime-asynclocalstorage.d.mts.map +1 -1
  129. package/types/dist/lib/runtime/runtime-livebindings.d.mts +2 -37
  130. package/types/dist/lib/runtime/runtime-livebindings.d.mts.map +1 -1
  131. package/types/dist/lib/runtime/runtime.d.mts +3 -39
  132. package/types/dist/lib/runtime/runtime.d.mts.map +1 -1
  133. package/types/dist/slothlet.d.mts +3 -249
  134. package/types/dist/slothlet.d.mts.map +1 -1
  135. package/types/index.d.mts +36 -16
  136. package/types/index.d.mts.map +1 -0
  137. package/AGENT-USAGE.md +0 -736
  138. package/docs/API-RULES.md +0 -712
@@ -14,342 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
-
18
-
19
-
20
- import { readdir, stat } from "node:fs/promises";
21
- import { join, extname, basename, resolve } from "node:path";
22
- import { pathToFileURL } from "node:url";
23
- import { createRequire } from "node:module";
24
- import { ComponentBase } from "@cldmv/slothlet/factories/component-base";
25
-
26
-
27
- export class Loader extends ComponentBase {
28
- static slothletProperty = "loader";
29
-
30
- constructor(slothlet) {
31
- super(slothlet);
32
- }
33
-
34
-
35
- async loadModule(filePath, instanceID, moduleID, cacheBust = null) {
36
- try {
37
-
38
-
39
- if (filePath.endsWith(".cjs")) {
40
- return this.#loadCJSIsolated(filePath);
41
- }
42
-
43
-
44
- const isTypeScript = filePath.endsWith(".ts") || filePath.endsWith(".mts");
45
- const typescriptConfig = this.slothlet.config?.typescript;
46
-
47
- let moduleUrl;
48
-
49
- if (isTypeScript && typescriptConfig?.enabled) {
50
- const mode = typescriptConfig.mode;
51
- if (mode === "strict") {
52
-
53
- if (!typescriptConfig.types?.output) {
54
- throw new this.SlothletError("TS_STRICT_REQUIRES_OUTPUT", {}, null, { validationError: true });
55
- }
56
- if (!typescriptConfig.types?.interfaceName) {
57
- throw new this.SlothletError("TS_STRICT_REQUIRES_INTERFACE_NAME", {}, null, { validationError: true });
58
- }
59
-
60
-
61
- if (!this.slothlet._typesGenerated) {
62
- const { fork } = await import("child_process");
63
- const path = await import("path");
64
- const { fileURLToPath } = await import("url");
65
-
66
-
67
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
68
- const scriptPath = path.resolve(__dirname, "../../../tools/build/generate-types-worker.mjs");
69
-
70
-
71
-
72
- const childConfig = JSON.stringify({
73
- dir: this.slothlet.config.root || this.slothlet.config.dir,
74
- mode: "eager",
75
- typescript: {
76
- enabled: true,
77
- mode: "fast"
78
- },
79
- types: typescriptConfig.types
80
- });
81
-
82
-
83
- await new Promise((resolve, reject) => {
84
- const child = fork(scriptPath, [], {
85
- stdio: ["pipe", "pipe", "pipe", "ipc"],
86
- env: { ...process.env, SLOTHLET_CONFIG: childConfig }
87
- });
88
-
89
- let errorOutput = "";
90
-
91
- child.stderr?.on("data", (data) => {
92
- errorOutput += data.toString();
93
- });
94
-
95
- child.on("message", (msg) => {
96
-
97
-
98
- if (msg.type === "success") {
99
- this.slothlet._typesGenerated = true;
100
- resolve();
101
-
102
-
103
-
104
-
105
- } else if (msg.type === "error") {
106
-
107
-
108
-
109
- reject(new this.SlothletError("TS_TYPE_GENERATION_FAILED", {}, { message: msg.error }));
110
- }
111
-
112
- });
113
-
114
- child.on("error", (error) => {
115
- reject(new this.SlothletError("TS_TYPE_GENERATION_FORK_FAILED", {}, error));
116
- });
117
-
118
- child.on("exit", (code) => {
119
- if (code !== 0 && !this.slothlet._typesGenerated) {
120
- reject(
121
- new this.SlothletError("TS_TYPE_GENERATION_PROCESS_EXITED", { code, output: errorOutput }, null, {
122
- validationError: true
123
- })
124
- );
125
- }
126
- });
127
- });
128
- }
129
-
130
-
131
- const { transformTypeScriptStrict, createDataUrl, formatDiagnostics } = await import("@cldmv/slothlet/processors/typescript");
132
-
133
-
134
- const result = await transformTypeScriptStrict(filePath, {
135
- target: typescriptConfig.target,
136
- module: typescriptConfig.module,
137
- strict: typescriptConfig.strict,
138
- typeDefinitionPath: typescriptConfig.types.output,
139
- compilerOptions: typescriptConfig.compilerOptions
140
- });
141
-
142
-
143
- if (result.diagnostics && result.diagnostics.length > 0) {
144
-
145
- const ts = await import("typescript");
146
- const errors = formatDiagnostics(result.diagnostics, ts.default);
147
-
148
-
149
- const error = new this.SlothletError("TS_TYPE_CHECK_ERRORS", { filePath, errors: errors.join("\n") }, null, {
150
- validationError: true
151
- });
152
- error.diagnostics = result.diagnostics;
153
- throw error;
154
- }
155
-
156
-
157
- moduleUrl = createDataUrl(result.code);
158
- } else {
159
-
160
- const { transformTypeScript, createDataUrl } = await import("@cldmv/slothlet/processors/typescript");
161
-
162
-
163
- const transformedCode = await transformTypeScript(filePath, {
164
- target: typescriptConfig.target,
165
- sourcemap: typescriptConfig.sourcemap
166
- });
167
-
168
-
169
- moduleUrl = createDataUrl(transformedCode);
170
- }
171
- } else {
172
-
173
- const fileUrl = pathToFileURL(filePath).href;
174
-
175
-
176
- moduleUrl = `${fileUrl}?slothlet_instance=${instanceID}`;
177
- if (moduleID) {
178
- moduleUrl += `&module=${moduleID}`;
179
- }
180
-
181
-
182
-
183
-
184
- if (cacheBust) {
185
- moduleUrl += `&_reload=${cacheBust}`;
186
- }
187
- }
188
-
189
- const module = await import(moduleUrl);
190
- return module;
191
- } catch (error) {
192
- throw new this.SlothletError(
193
- "MODULE_IMPORT_FAILED",
194
- {
195
- modulePath: filePath
196
- },
197
- error
198
- );
199
- }
200
- }
201
-
202
-
203
- #loadCJSIsolated(filePath) {
204
- const requireFn = createRequire(filePath);
205
- const resolved = requireFn.resolve(filePath);
206
-
207
-
208
- delete requireFn.cache[resolved];
209
- const exports = requireFn(resolved);
210
-
211
- delete requireFn.cache[resolved];
212
-
213
-
214
-
215
-
216
- const namespace = { default: exports };
217
- if (exports !== null && typeof exports === "object") {
218
- for (const key of Object.keys(exports)) {
219
- if (key !== "default") {
220
- namespace[key] = exports[key];
221
- }
222
- }
223
- }
224
- return namespace;
225
- }
226
-
227
-
228
- async scanDirectory(dir, options = {}) {
229
-
230
- const typescriptConfig = this.slothlet.config?.typescript;
231
- const defaultExtensions = [".mjs", ".cjs", ".js"];
232
- const typescriptExtensions = typescriptConfig?.enabled ? [".ts", ".mts"] : [];
233
- const allExtensions = [...defaultExtensions, ...typescriptExtensions];
234
-
235
- const {
236
- recursive = true,
237
- extensions = allExtensions,
238
- isRootScan = true,
239
- currentDepth = 0,
240
- maxDepth = Infinity,
241
- fileFilter = null
242
- } = options;
243
-
244
- try {
245
- await stat(dir);
246
- } catch (error) {
247
- throw new this.SlothletError(
248
- "INVALID_DIRECTORY",
249
- {
250
- dir
251
- },
252
- error
253
- );
254
- }
255
-
256
- const structure = {
257
- files: [],
258
- directories: []
259
- };
260
-
261
- const entries = await readdir(dir, { withFileTypes: true });
262
-
263
- for (const entry of entries) {
264
- const fullPath = join(dir, entry.name);
265
-
266
- if (entry.isDirectory()) {
267
-
268
-
269
- if (fileFilter) {
270
- continue;
271
- }
272
-
273
-
274
- if (recursive && currentDepth < maxDepth) {
275
- const subStructure = await this.scanDirectory(fullPath, { ...options, isRootScan: false, currentDepth: currentDepth + 1 });
276
- structure.directories.push({
277
- path: fullPath,
278
- name: entry.name,
279
- children: subStructure
280
- });
281
- }
282
- } else if (entry.isFile()) {
283
- const ext = extname(entry.name);
284
- if (extensions.includes(ext)) {
285
-
286
- if (entry.name.startsWith("__")) {
287
- continue;
288
- }
289
-
290
-
291
- if (fileFilter && !fileFilter(entry.name)) {
292
- continue;
293
- }
294
-
295
- const nameWithoutExt = basename(entry.name, ext);
296
- structure.files.push({
297
- path: fullPath,
298
- name: nameWithoutExt,
299
- fullName: entry.name,
300
- moduleID: this.slothlet.helpers.sanitize.getModuleId(fullPath, dir)
301
- });
302
- }
303
- }
304
- }
305
-
306
-
307
- if (isRootScan && structure.files.length === 0 && structure.directories.length === 0) {
308
- new this.SlothletWarning("WARN_DIRECTORY_EMPTY", {
309
- dir,
310
- resolvedPath: resolve(dir)
311
- });
312
- }
313
-
314
- return structure;
315
- }
316
-
317
-
318
- extractExports(module) {
319
- const exports = {};
320
-
321
-
322
- if (module.default !== undefined) {
323
- exports.default = module.default;
324
- }
325
-
326
-
327
- for (const key of Object.keys(module)) {
328
- if (key !== "default" && key !== "module.exports" && typeof key === "string") {
329
- exports[key] = module[key];
330
- }
331
- }
332
-
333
-
334
-
335
-
336
-
337
- if (exports.default && typeof exports.default === "object" && exports.default !== null && "default" in exports.default) {
338
-
339
-
340
- const rootNamedKeys = Object.keys(exports).filter((k) => k !== "default" && k !== "module.exports");
341
- const defaultKeys = Object.keys(exports.default).filter((k) => k !== "default");
342
-
343
-
344
- const isCJSPattern = rootNamedKeys.every((k) => k in exports.default);
345
-
346
- if (isCJSPattern && defaultKeys.length > 0) {
347
-
348
-
349
- exports.default = exports.default.default;
350
- }
351
- }
352
-
353
- return exports;
354
- }
355
- }
17
+ import{readdir,stat}from"node:fs/promises";import{join,extname,basename,resolve}from"node:path";import{pathToFileURL}from"node:url";import{createRequire}from"node:module";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";class Loader extends ComponentBase{static slothletProperty="loader";constructor(slothlet){super(slothlet)}async loadModule(filePath,instanceID,moduleID,cacheBust=null){try{if(filePath.endsWith(".cjs")){return this.#loadCJSIsolated(filePath)}const isTypeScript=filePath.endsWith(".ts")||filePath.endsWith(".mts");const typescriptConfig=this.slothlet.config?.typescript;let moduleUrl;if(isTypeScript&&typescriptConfig?.enabled){const mode=typescriptConfig.mode;if(mode==="strict"){if(!typescriptConfig.types?.output){throw new this.SlothletError("TS_STRICT_REQUIRES_OUTPUT",{},null,{validationError:true})}if(!typescriptConfig.types?.interfaceName){throw new this.SlothletError("TS_STRICT_REQUIRES_INTERFACE_NAME",{},null,{validationError:true})}if(!this.slothlet._typesGenerated){const{fork}=await import("child_process");const path=await import("path");const{fileURLToPath}=await import("url");const __dirname=path.dirname(fileURLToPath(import.meta.url));const scriptPath=path.resolve(__dirname,"../../../tools/build/generate-types-worker.mjs");const childConfig=JSON.stringify({dir:this.slothlet.config.root||this.slothlet.config.dir,mode:"eager",typescript:{enabled:true,mode:"fast"},types:typescriptConfig.types});await new Promise((resolve2,reject)=>{const child=fork(scriptPath,[],{stdio:["pipe","pipe","pipe","ipc"],env:{...process.env,SLOTHLET_CONFIG:childConfig}});let errorOutput="";child.stderr?.on("data",data=>{errorOutput+=data.toString()});child.on("message",msg=>{if(msg.type==="success"){this.slothlet._typesGenerated=true;resolve2()}else if(msg.type==="error"){reject(new this.SlothletError("TS_TYPE_GENERATION_FAILED",{},{message:msg.error}))}});child.on("error",error=>{reject(new this.SlothletError("TS_TYPE_GENERATION_FORK_FAILED",{},error))});child.on("exit",code=>{if(code!==0&&!this.slothlet._typesGenerated){reject(new this.SlothletError("TS_TYPE_GENERATION_PROCESS_EXITED",{code,output:errorOutput},null,{validationError:true}))}})})}const{transformTypeScriptStrict,createDataUrl,formatDiagnostics}=await import("@cldmv/slothlet/processors/typescript");const result=await transformTypeScriptStrict(filePath,{target:typescriptConfig.target,module:typescriptConfig.module,strict:typescriptConfig.strict,typeDefinitionPath:typescriptConfig.types.output,compilerOptions:typescriptConfig.compilerOptions});if(result.diagnostics&&result.diagnostics.length>0){const ts=await import("typescript");const errors=formatDiagnostics(result.diagnostics,ts.default);const error=new this.SlothletError("TS_TYPE_CHECK_ERRORS",{filePath,errors:errors.join("\n")},null,{validationError:true});error.diagnostics=result.diagnostics;throw error}moduleUrl=createDataUrl(result.code)}else{const{transformTypeScript,createDataUrl}=await import("@cldmv/slothlet/processors/typescript");const transformedCode=await transformTypeScript(filePath,{target:typescriptConfig.target,sourcemap:typescriptConfig.sourcemap});moduleUrl=createDataUrl(transformedCode)}}else{const fileUrl=pathToFileURL(filePath).href;moduleUrl=`${fileUrl}?slothlet_instance=${instanceID}`;if(moduleID){moduleUrl+=`&module=${moduleID}`}if(cacheBust){moduleUrl+=`&_reload=${cacheBust}`}}const module=await import(moduleUrl);return module}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}#loadCJSIsolated(filePath){const requireFn=createRequire(filePath);const resolved=requireFn.resolve(filePath);delete requireFn.cache[resolved];const exports=requireFn(resolved);delete requireFn.cache[resolved];const namespace={default:exports};if(exports!==null&&typeof exports==="object"){for(const key of Object.keys(exports)){if(key!=="default"){namespace[key]=exports[key]}}}return namespace}async scanDirectory(dir,options={}){const typescriptConfig=this.slothlet.config?.typescript;const defaultExtensions=[".mjs",".cjs",".js"];const typescriptExtensions=typescriptConfig?.enabled?[".ts",".mts"]:[];const allExtensions=[...defaultExtensions,...typescriptExtensions];const{recursive=true,extensions=allExtensions,isRootScan=true,currentDepth=0,maxDepth=Infinity,fileFilter=null}=options;try{await stat(dir)}catch(error){throw new this.SlothletError("INVALID_DIRECTORY",{dir},error)}const structure={files:[],directories:[]};const entries=await readdir(dir,{withFileTypes:true});for(const entry of entries){const fullPath=join(dir,entry.name);if(entry.isDirectory()){if(fileFilter){continue}if(recursive&&currentDepth<maxDepth){const subStructure=await this.scanDirectory(fullPath,{...options,isRootScan:false,currentDepth:currentDepth+1});structure.directories.push({path:fullPath,name:entry.name,children:subStructure})}}else if(entry.isFile()){const ext=extname(entry.name);if(extensions.includes(ext)){if(entry.name.startsWith("__")){continue}if(fileFilter&&!fileFilter(entry.name)){continue}const nameWithoutExt=basename(entry.name,ext);structure.files.push({path:fullPath,name:nameWithoutExt,fullName:entry.name,moduleID:this.slothlet.helpers.sanitize.getModuleId(fullPath,dir)})}}}if(isRootScan&&structure.files.length===0&&structure.directories.length===0){new this.SlothletWarning("WARN_DIRECTORY_EMPTY",{dir,resolvedPath:resolve(dir)})}return structure}extractExports(module){const exports={};if(module.default!==void 0){exports.default=module.default}for(const key of Object.keys(module)){if(key!=="default"&&key!=="module.exports"&&typeof key==="string"){exports[key]=module[key]}}if(exports.default&&typeof exports.default==="object"&&exports.default!==null&&"default"in exports.default){const rootNamedKeys=Object.keys(exports).filter(k=>k!=="default"&&k!=="module.exports");const defaultKeys=Object.keys(exports.default).filter(k=>k!=="default");const isCJSPattern=rootNamedKeys.every(k=>k in exports.default);if(isCJSPattern&&defaultKeys.length>0){exports.default=exports.default.default}}return exports}}export{Loader};
@@ -14,278 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
-
18
-
19
-
20
-
21
- import fs from "fs";
22
- import path from "path";
23
- import { SlothletError } from "@cldmv/slothlet/errors";
24
-
25
- let typescriptInstance = null;
26
-
27
-
28
- async function getTypeScript() {
29
- if (!typescriptInstance) {
30
- try {
31
- typescriptInstance = await import("typescript");
32
-
33
-
34
-
35
- } catch (error) {
36
- throw new SlothletError("TYPESCRIPT_NOT_INSTALLED", { feature: "type-generation" }, error);
37
- }
38
-
39
- }
40
- return typescriptInstance;
41
- }
42
-
43
-
44
- export async function generateTypes(api, options) {
45
- const ts = await getTypeScript();
46
-
47
- if (!options.output) {
48
- throw new SlothletError("INVALID_CONFIG", {
49
- option: "types.output",
50
- expected: "a string output path",
51
- value: options.output,
52
- hint: "Provide a string output path for the generated .d.ts file, e.g. './types/api.d.ts'.",
53
- validationError: true
54
- });
55
- }
56
-
57
- if (!options.interfaceName) {
58
- throw new SlothletError("INVALID_CONFIG", {
59
- option: "types.interfaceName",
60
- expected: "a string interface name",
61
- value: options.interfaceName,
62
- hint: "Provide a string interface name for the generated TypeScript interface, e.g. 'SlothletAPI'.",
63
- validationError: true
64
- });
65
- }
66
-
67
-
68
- const nodes = traverseAPI(api);
69
-
70
-
71
- for (const node of nodes) {
72
- if (node.metadata?.filePath) {
73
- node.typeInfo = await extractTypesFromFile(node.metadata.filePath, ts);
74
- }
75
- }
76
-
77
-
78
- const declaration = generateDeclaration(nodes, options);
79
-
80
-
81
- const outputPath = path.resolve(options.output);
82
- const outputDir = path.dirname(outputPath);
83
-
84
- if (!fs.existsSync(outputDir)) {
85
- fs.mkdirSync(outputDir, { recursive: true });
86
- }
87
-
88
- fs.writeFileSync(outputPath, declaration, "utf8");
89
-
90
- return {
91
- output: declaration,
92
- filePath: outputPath
93
- };
94
- }
95
-
96
-
97
- function traverseAPI(api, currentPath = [], visited = new Set()) {
98
- const nodes = [];
99
-
100
- if (!api || typeof api !== "object") {
101
- return nodes;
102
- }
103
-
104
-
105
- if (visited.has(api)) {
106
- return nodes;
107
- }
108
- visited.add(api);
109
-
110
- for (const [key, value] of Object.entries(api)) {
111
-
112
- if (key.startsWith("_") || key.startsWith("__") || key === "slothlet" || key === "shutdown" || key === "destroy") {
113
- continue;
114
- }
115
-
116
- const nodePath = [...currentPath, key];
117
- const metadata = value?.__metadata;
118
-
119
- if (typeof value === "function") {
120
- nodes.push({
121
- type: "function",
122
- path: nodePath,
123
- value,
124
- metadata
125
- });
126
- } else if (typeof value === "object" && value !== null) {
127
- nodes.push({
128
- type: "object",
129
- path: nodePath,
130
- value,
131
- metadata
132
- });
133
-
134
-
135
- const childNodes = traverseAPI(value, nodePath, visited);
136
- nodes.push(...childNodes);
137
- }
138
- }
139
-
140
- return nodes;
141
- }
142
-
143
-
144
- async function extractTypesFromFile(filePath, ts) {
145
- try {
146
- const source = fs.readFileSync(filePath, "utf8");
147
- const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true);
148
-
149
- const exports = [];
150
-
151
-
152
- function visit(node) {
153
-
154
- if (ts.isFunctionDeclaration(node) && node.name) {
155
- const hasExport = node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
156
-
157
-
158
- if (hasExport) {
159
- exports.push({
160
- name: node.name.text,
161
- type: "function",
162
- signature: extractFunctionSignature(node, source, ts)
163
- });
164
- }
165
- }
166
-
167
-
168
- if (ts.isVariableStatement(node)) {
169
- const hasExport = node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
170
- if (hasExport) {
171
- for (const decl of node.declarationList.declarations) {
172
- if (!decl.name || !ts.isIdentifier(decl.name)) continue;
173
- const init = decl.initializer;
174
- if (!init) continue;
175
- if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) {
176
- exports.push({
177
- name: decl.name.text,
178
- type: "function",
179
- signature: extractFunctionSignature(init, source, ts)
180
- });
181
- }
182
- }
183
- }
184
- }
185
-
186
- ts.forEachChild(node, visit);
187
- }
188
-
189
- visit(sourceFile);
190
-
191
- return { exports, sourceFile };
192
- } catch (____error) {
193
-
194
- return { exports: [] };
195
- }
196
- }
197
-
198
-
199
- function extractFunctionSignature(node, ____source, ____ts) {
200
- const params = node.parameters
201
- .map((p) => {
202
- const name = p.name.getText(node.getSourceFile());
203
- const type = p.type ? p.type.getText(node.getSourceFile()) : "any";
204
- return `${name}: ${type}`;
205
- })
206
- .join(", ");
207
-
208
- const returnType = node.type ? node.type.getText(node.getSourceFile()) : "any";
209
-
210
- return `(${params}): ${returnType}`;
211
- }
212
-
213
-
214
- function generateDeclaration(nodes, options) {
215
- const interfaceName = options.interfaceName;
216
- const lines = [];
217
-
218
- lines.push("");
219
- lines.push("");
220
-
221
-
222
- const structure = {};
223
-
224
- for (const node of nodes) {
225
- if (node.type === "function") {
226
-
227
-
228
-
229
- const fnName = node.path[node.path.length - 1];
230
- const exportInfo = node.typeInfo?.exports?.find((e) => e.name === fnName);
231
-
232
-
233
- const signature = exportInfo?.signature ?? "(...args: any[]): any";
234
- setNestedProperty(structure, node.path, { type: "function", signature });
235
- }
236
-
237
-
238
- }
239
-
240
-
241
- lines.push(`export interface ${interfaceName} {`);
242
- generateInterfaceContent(structure, lines, 1);
243
- lines.push("}");
244
- lines.push("");
245
-
246
-
247
- lines.push(`declare const self: ${interfaceName};`);
248
- lines.push("");
249
-
250
- return lines.join("\n");
251
- }
252
-
253
-
254
- function setNestedProperty(obj, path, value) {
255
- let current = obj;
256
-
257
- for (let i = 0; i < path.length - 1; i++) {
258
- const key = path[i];
259
- if (!current[key]) {
260
- current[key] = {};
261
- }
262
- current = current[key];
263
- }
264
-
265
- const lastKey = path[path.length - 1];
266
- current[lastKey] = value;
267
- }
268
-
269
-
270
- function generateInterfaceContent(structure, lines, indent) {
271
- const indentation = "\t".repeat(indent);
272
-
273
- for (const [key, value] of Object.entries(structure)) {
274
-
275
-
276
- if (value.type === "function") {
277
- lines.push(`${indentation}${key}${value.signature};`);
278
-
279
-
280
-
281
- } else if (typeof value === "object" && value !== null) {
282
-
283
- lines.push(`${indentation}${key}: {`);
284
- generateInterfaceContent(value, lines, indent + 1);
285
- lines.push(`${indentation}};`);
286
- } else {
287
-
288
- }
289
-
290
- }
291
- }
17
+ import fs from"fs";import path from"path";import{SlothletError}from"@cldmv/slothlet/errors";let typescriptInstance=null;async function getTypeScript(){if(!typescriptInstance){try{typescriptInstance=await import("typescript")}catch(error){throw new SlothletError("TYPESCRIPT_NOT_INSTALLED",{feature:"type-generation"},error)}}return typescriptInstance}async function generateTypes(api,options){const ts=await getTypeScript();if(!options.output){throw new SlothletError("INVALID_CONFIG",{option:"types.output",expected:"a string output path",value:options.output,hint:"Provide a string output path for the generated .d.ts file, e.g. './types/api.d.ts'.",validationError:true})}if(!options.interfaceName){throw new SlothletError("INVALID_CONFIG",{option:"types.interfaceName",expected:"a string interface name",value:options.interfaceName,hint:"Provide a string interface name for the generated TypeScript interface, e.g. 'SlothletAPI'.",validationError:true})}const nodes=traverseAPI(api);for(const node of nodes){if(node.metadata?.filePath){node.typeInfo=await extractTypesFromFile(node.metadata.filePath,ts)}}const declaration=generateDeclaration(nodes,options);const outputPath=path.resolve(options.output);const outputDir=path.dirname(outputPath);if(!fs.existsSync(outputDir)){fs.mkdirSync(outputDir,{recursive:true})}fs.writeFileSync(outputPath,declaration,"utf8");return{output:declaration,filePath:outputPath}}function traverseAPI(api,currentPath=[],visited=new Set){const nodes=[];if(!api||typeof api!=="object"){return nodes}if(visited.has(api)){return nodes}visited.add(api);for(const[key,value]of Object.entries(api)){if(key.startsWith("_")||key.startsWith("__")||key==="slothlet"||key==="shutdown"||key==="destroy"){continue}const nodePath=[...currentPath,key];const metadata=value?.__metadata;if(typeof value==="function"){nodes.push({type:"function",path:nodePath,value,metadata})}else if(typeof value==="object"&&value!==null){nodes.push({type:"object",path:nodePath,value,metadata});const childNodes=traverseAPI(value,nodePath,visited);nodes.push(...childNodes)}}return nodes}async function extractTypesFromFile(filePath,ts){try{let visit=function(node){if(ts.isFunctionDeclaration(node)&&node.name){const hasExport=node.modifiers?.some(m=>m.kind===ts.SyntaxKind.ExportKeyword);if(hasExport){exports.push({name:node.name.text,type:"function",signature:extractFunctionSignature(node,source,ts)})}}if(ts.isVariableStatement(node)){const hasExport=node.modifiers?.some(m=>m.kind===ts.SyntaxKind.ExportKeyword);if(hasExport){for(const decl of node.declarationList.declarations){if(!decl.name||!ts.isIdentifier(decl.name))continue;const init=decl.initializer;if(!init)continue;if(ts.isArrowFunction(init)||ts.isFunctionExpression(init)){exports.push({name:decl.name.text,type:"function",signature:extractFunctionSignature(init,source,ts)})}}}}ts.forEachChild(node,visit)};const source=fs.readFileSync(filePath,"utf8");const sourceFile=ts.createSourceFile(filePath,source,ts.ScriptTarget.Latest,true);const exports=[];visit(sourceFile);return{exports,sourceFile}}catch(____error){return{exports:[]}}}function extractFunctionSignature(node,____source,____ts){const params=node.parameters.map(p=>{const name=p.name.getText(node.getSourceFile());const type=p.type?p.type.getText(node.getSourceFile()):"any";return`${name}: ${type}`}).join(", ");const returnType=node.type?node.type.getText(node.getSourceFile()):"any";return`(${params}): ${returnType}`}function generateDeclaration(nodes,options){const interfaceName=options.interfaceName;const lines=[];lines.push("/**");lines.push(` * Generated TypeScript declarations for Slothlet API`);lines.push(` * @generated ${new Date().toISOString()}`);lines.push(" */");lines.push("");const structure={};for(const node of nodes){if(node.type==="function"){const fnName=node.path[node.path.length-1];const exportInfo=node.typeInfo?.exports?.find(e=>e.name===fnName);const signature=exportInfo?.signature??"(...args: any[]): any";setNestedProperty(structure,node.path,{type:"function",signature})}}lines.push(`export interface ${interfaceName} {`);generateInterfaceContent(structure,lines,1);lines.push("}");lines.push("");lines.push(`declare const self: ${interfaceName};`);lines.push("");return lines.join("\n")}function setNestedProperty(obj,path2,value){let current=obj;for(let i=0;i<path2.length-1;i++){const key=path2[i];if(!current[key]){current[key]={}}current=current[key]}const lastKey=path2[path2.length-1];current[lastKey]=value}function generateInterfaceContent(structure,lines,indent){const indentation=" ".repeat(indent);for(const[key,value]of Object.entries(structure)){if(value.type==="function"){lines.push(`${indentation}${key}${value.signature};`)}else if(typeof value==="object"&&value!==null){lines.push(`${indentation}${key}: {`);generateInterfaceContent(value,lines,indent+1);lines.push(`${indentation}};`)}else{}}}export{generateTypes};