@cldmv/slothlet 3.3.0 → 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 (127) hide show
  1. package/README.md +6 -8
  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 -1385
  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 -2536
  12. package/dist/lib/handlers/context-async.mjs +1 -172
  13. package/dist/lib/handlers/context-live.mjs +1 -173
  14. package/dist/lib/handlers/hook-manager.mjs +1 -667
  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 +1 -392
  21. package/dist/lib/handlers/unified-wrapper.mjs +1 -3110
  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 -439
  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 +1 -125
  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/translations.mjs +1 -126
  33. package/dist/lib/modes/eager.mjs +1 -59
  34. package/dist/lib/modes/lazy.mjs +1 -81
  35. package/dist/lib/processors/flatten.mjs +1 -437
  36. package/dist/lib/processors/loader.mjs +1 -339
  37. package/dist/lib/processors/type-generator.mjs +1 -275
  38. package/dist/lib/processors/typescript.mjs +1 -172
  39. package/dist/lib/runtime/runtime-asynclocalstorage.mjs +1 -113
  40. package/dist/lib/runtime/runtime-livebindings.mjs +1 -78
  41. package/dist/lib/runtime/runtime.mjs +1 -102
  42. package/dist/slothlet.mjs +1 -817
  43. package/package.json +34 -31
  44. package/types/dist/lib/builders/api-assignment.d.mts +3 -92
  45. package/types/dist/lib/builders/api-assignment.d.mts.map +1 -1
  46. package/types/dist/lib/builders/api_builder.d.mts +102 -91
  47. package/types/dist/lib/builders/api_builder.d.mts.map +1 -1
  48. package/types/dist/lib/builders/builder.d.mts +1 -55
  49. package/types/dist/lib/builders/builder.d.mts.map +1 -1
  50. package/types/dist/lib/builders/modes-processor.d.mts +3 -27
  51. package/types/dist/lib/builders/modes-processor.d.mts.map +1 -1
  52. package/types/dist/lib/errors.d.mts +19 -109
  53. package/types/dist/lib/errors.d.mts.map +1 -1
  54. package/types/dist/lib/factories/component-base.d.mts +7 -177
  55. package/types/dist/lib/factories/component-base.d.mts.map +1 -1
  56. package/types/dist/lib/factories/context.d.mts +4 -22
  57. package/types/dist/lib/factories/context.d.mts.map +1 -1
  58. package/types/dist/lib/handlers/api-cache-manager.d.mts +20 -203
  59. package/types/dist/lib/handlers/api-cache-manager.d.mts.map +1 -1
  60. package/types/dist/lib/handlers/api-manager.d.mts +33 -408
  61. package/types/dist/lib/handlers/api-manager.d.mts.map +1 -1
  62. package/types/dist/lib/handlers/context-async.d.mts +23 -61
  63. package/types/dist/lib/handlers/context-async.d.mts.map +1 -1
  64. package/types/dist/lib/handlers/context-live.d.mts +22 -59
  65. package/types/dist/lib/handlers/context-live.d.mts.map +1 -1
  66. package/types/dist/lib/handlers/hook-manager.d.mts +46 -185
  67. package/types/dist/lib/handlers/hook-manager.d.mts.map +1 -1
  68. package/types/dist/lib/handlers/lifecycle-token.d.mts +3 -48
  69. package/types/dist/lib/handlers/lifecycle-token.d.mts.map +1 -1
  70. package/types/dist/lib/handlers/lifecycle.d.mts +5 -82
  71. package/types/dist/lib/handlers/lifecycle.d.mts.map +1 -1
  72. package/types/dist/lib/handlers/materialize-manager.d.mts +8 -70
  73. package/types/dist/lib/handlers/materialize-manager.d.mts.map +1 -1
  74. package/types/dist/lib/handlers/metadata.d.mts +17 -221
  75. package/types/dist/lib/handlers/metadata.d.mts.map +1 -1
  76. package/types/dist/lib/handlers/ownership.d.mts +44 -160
  77. package/types/dist/lib/handlers/ownership.d.mts.map +1 -1
  78. package/types/dist/lib/handlers/permission-manager.d.mts +37 -141
  79. package/types/dist/lib/handlers/permission-manager.d.mts.map +1 -1
  80. package/types/dist/lib/handlers/unified-wrapper.d.mts +26 -239
  81. package/types/dist/lib/handlers/unified-wrapper.d.mts.map +1 -1
  82. package/types/dist/lib/handlers/version-manager.d.mts +28 -225
  83. package/types/dist/lib/handlers/version-manager.d.mts.map +1 -1
  84. package/types/dist/lib/helpers/class-instance-wrapper.d.mts +2 -52
  85. package/types/dist/lib/helpers/class-instance-wrapper.d.mts.map +1 -1
  86. package/types/dist/lib/helpers/config.d.mts +125 -139
  87. package/types/dist/lib/helpers/config.d.mts.map +1 -1
  88. package/types/dist/lib/helpers/eventemitter-context.d.mts +3 -29
  89. package/types/dist/lib/helpers/eventemitter-context.d.mts.map +1 -1
  90. package/types/dist/lib/helpers/hint-detector.d.mts +2 -15
  91. package/types/dist/lib/helpers/hint-detector.d.mts.map +1 -1
  92. package/types/dist/lib/helpers/modes-utils.d.mts +3 -30
  93. package/types/dist/lib/helpers/modes-utils.d.mts.map +1 -1
  94. package/types/dist/lib/helpers/pattern-matcher.d.mts +3 -43
  95. package/types/dist/lib/helpers/pattern-matcher.d.mts.map +1 -1
  96. package/types/dist/lib/helpers/resolve-from-caller.d.mts +3 -27
  97. package/types/dist/lib/helpers/resolve-from-caller.d.mts.map +1 -1
  98. package/types/dist/lib/helpers/sanitize.d.mts +4 -92
  99. package/types/dist/lib/helpers/sanitize.d.mts.map +1 -1
  100. package/types/dist/lib/helpers/utilities.d.mts +4 -52
  101. package/types/dist/lib/helpers/utilities.d.mts.map +1 -1
  102. package/types/dist/lib/i18n/translations.d.mts +4 -37
  103. package/types/dist/lib/i18n/translations.d.mts.map +1 -1
  104. package/types/dist/lib/modes/eager.d.mts +8 -30
  105. package/types/dist/lib/modes/eager.d.mts.map +1 -1
  106. package/types/dist/lib/modes/lazy.d.mts +10 -43
  107. package/types/dist/lib/modes/lazy.d.mts.map +1 -1
  108. package/types/dist/lib/processors/flatten.d.mts +56 -107
  109. package/types/dist/lib/processors/flatten.d.mts.map +1 -1
  110. package/types/dist/lib/processors/loader.d.mts +6 -41
  111. package/types/dist/lib/processors/loader.d.mts.map +1 -1
  112. package/types/dist/lib/processors/type-generator.d.mts +2 -16
  113. package/types/dist/lib/processors/type-generator.d.mts.map +1 -1
  114. package/types/dist/lib/processors/typescript.d.mts +6 -53
  115. package/types/dist/lib/processors/typescript.d.mts.map +1 -1
  116. package/types/dist/lib/runtime/runtime-asynclocalstorage.d.mts +3 -71
  117. package/types/dist/lib/runtime/runtime-asynclocalstorage.d.mts.map +1 -1
  118. package/types/dist/lib/runtime/runtime-livebindings.d.mts +2 -37
  119. package/types/dist/lib/runtime/runtime-livebindings.d.mts.map +1 -1
  120. package/types/dist/lib/runtime/runtime.d.mts +3 -39
  121. package/types/dist/lib/runtime/runtime.d.mts.map +1 -1
  122. package/types/dist/slothlet.d.mts +3 -249
  123. package/types/dist/slothlet.d.mts.map +1 -1
  124. package/types/index.d.mts +36 -16
  125. package/types/index.d.mts.map +1 -0
  126. package/AGENT-USAGE.md +0 -736
  127. package/docs/API-RULES.md +0 -712
@@ -14,1388 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
-
18
-
19
-
20
- import { ComponentBase } from "@cldmv/slothlet/factories/component-base";
21
- import { TYPE_STATES } from "@cldmv/slothlet/handlers/unified-wrapper";
22
- import { getLanguage, initI18n, setLanguage, t, translate } from "@cldmv/slothlet/i18n";
23
-
24
-
25
-
26
-
27
- function _resolvePathOrModuleId(slothlet, pathOrModuleId) {
28
- const history = slothlet.handlers?.apiManager?.state?.addHistory;
29
-
30
-
31
-
32
- if (history) {
33
- let match = null;
34
- for (let i = history.length - 1; i >= 0; i--) {
35
- const entry = history[i];
36
- if (entry?.moduleID === pathOrModuleId) {
37
- match = entry;
38
- break;
39
- }
40
- }
41
- if (match) return match.apiPath;
42
- }
43
- return pathOrModuleId;
44
- }
45
-
46
-
47
- export class ApiBuilder extends ComponentBase {
48
- static slothletProperty = "apiBuilder";
49
-
50
-
51
- constructor(slothlet) {
52
- super(slothlet);
53
- }
54
-
55
-
56
- async buildFinalAPI(userApi) {
57
- this.slothlet.debug("api", {
58
- key: "DEBUG_MODE_BUILD_FINAL_API_CALLED",
59
- diagnostics: this.____config.diagnostics,
60
- userApiKeys: Object.keys(userApi)
61
- });
62
-
63
-
64
-
65
-
66
-
67
-
68
-
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
- if (this.slothlet._ownBuiltins) {
80
- for (const [key, ref] of Object.entries(this.slothlet._ownBuiltins)) {
81
- if (ref && Object.prototype.hasOwnProperty.call(userApi, key) && userApi[key] === ref) {
82
- try {
83
- delete userApi[key];
84
- } catch (_) {
85
-
86
- }
87
- }
88
- }
89
- }
90
-
91
-
92
-
93
-
94
-
95
- this.slothlet.userHooks = {
96
- shutdown: typeof userApi.shutdown === "function" ? userApi.shutdown : null,
97
- destroy: typeof userApi.destroy === "function" ? userApi.destroy : null
98
- };
99
-
100
-
101
-
102
- if (userApi.slothlet) {
103
- new this.SlothletWarning("WARNING_RESERVED_PROPERTY_CONFLICT", { properties: "slothlet" });
104
- }
105
-
106
-
107
- const slothletNamespace = await this.createSlothletNamespace(userApi);
108
-
109
- this.slothlet.debug("api", {
110
- key: "DEBUG_MODE_SLOTHLET_NAMESPACE_CREATED",
111
- namespaceKeys: Object.keys(slothletNamespace),
112
- hasDiag: !!slothletNamespace.diag
113
- });
114
-
115
-
116
- const shutdownFn = this.createShutdownFunction();
117
-
118
-
119
- this.attachBuiltins(userApi, {
120
- slothlet: slothletNamespace,
121
- shutdown: shutdownFn,
122
- destroy: null
123
- });
124
-
125
- this.slothlet.debug("api", {
126
- key: "DEBUG_MODE_BUILT_INS_ATTACHED",
127
- userApiKeys: Object.keys(userApi),
128
- hasSlothlet: !!userApi.slothlet,
129
- hasDiag: !!userApi.slothlet?.diag
130
- });
131
-
132
-
133
- const destroyWithApi = this.createDestroyFunction(userApi);
134
- Object.defineProperty(userApi, "destroy", {
135
- value: destroyWithApi,
136
- enumerable: true,
137
- writable: false,
138
- configurable: true
139
- });
140
-
141
-
142
-
143
- this.slothlet._ownBuiltins = {
144
- shutdown: shutdownFn,
145
- slothlet: slothletNamespace,
146
- destroy: destroyWithApi
147
- };
148
-
149
- return userApi;
150
- }
151
-
152
-
153
- async createSlothletNamespace(userApi) {
154
- const slothlet = this.slothlet;
155
- const config = this.____config;
156
-
157
-
158
- let version = "unknown";
159
- try {
160
- const pkgPath = new URL("../../../package.json", import.meta.url);
161
- const { readFile } = await import("node:fs/promises");
162
- const pkgContent = await readFile(pkgPath, "utf-8");
163
- const pkg = JSON.parse(pkgContent);
164
-
165
-
166
- version = pkg.version || "unknown";
167
-
168
-
169
-
170
- } catch {
171
-
172
- }
173
-
174
- const namespace = {
175
-
176
- i18n: {
177
- setLanguage,
178
- getLanguage,
179
- translate,
180
- t,
181
- initI18n
182
- },
183
-
184
-
185
- version,
186
-
187
-
188
- instanceID: slothlet.instanceID,
189
-
190
-
191
- types: TYPE_STATES,
192
-
193
-
194
- api: {
195
-
196
- add: async function slothlet_api_add(apiPath, folderPath, options = {}, versionConfig = null) {
197
-
198
- if (!config.api?.mutations?.add) {
199
- throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED", {
200
- operation: "api.add",
201
- validationError: true
202
- });
203
- }
204
-
205
-
206
-
207
-
208
-
209
- const {
210
- recordHistory: ____recordHistory,
211
- collisionMode: ____collisionMode,
212
- mutateExisting: ____mutateExisting,
213
- ...filteredOptions
214
- } = options;
215
- return slothlet.handlers.apiManager.addApiComponent({
216
- apiPath,
217
- folderPath,
218
- options: filteredOptions,
219
- versionConfig: versionConfig || null
220
- });
221
- },
222
-
223
-
224
- remove: async function slothlet_api_remove(pathOrModuleId) {
225
-
226
- if (!config.api?.mutations?.remove) {
227
- throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED", {
228
- operation: "api.remove",
229
- validationError: true
230
- });
231
- }
232
- if (typeof pathOrModuleId !== "string") {
233
- throw new slothlet.SlothletError("INVALID_ARGUMENT", {
234
- argument: "pathOrModuleId",
235
- expected: "string",
236
- received: typeof pathOrModuleId,
237
- validationError: true
238
- });
239
- }
240
- return slothlet.handlers.apiManager.removeApiComponent(pathOrModuleId);
241
- },
242
-
243
-
244
- reload: async function slothlet_api_reload(pathOrModuleId, options) {
245
-
246
- if (!config.api?.mutations?.reload) {
247
- throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED", {
248
- operation: "api.reload",
249
- validationError: true
250
- });
251
- }
252
-
253
-
254
- if (pathOrModuleId == null || pathOrModuleId === "" || pathOrModuleId === ".") {
255
- return slothlet.handlers.apiManager.reloadApiComponent({ apiPath: ".", options });
256
- }
257
-
258
- if (typeof pathOrModuleId !== "string") {
259
- throw new slothlet.SlothletError("INVALID_ARGUMENT", {
260
- argument: "pathOrModuleId",
261
- expected: "string, null, undefined, or '.'",
262
- received: typeof pathOrModuleId,
263
- validationError: true
264
- });
265
- }
266
-
267
-
268
- const isModuleId = slothlet.handlers.apiManager.state.addHistory.some((entry) => entry.moduleID === pathOrModuleId);
269
-
270
- if (isModuleId) {
271
- return slothlet.handlers.apiManager.reloadApiComponent({ moduleID: pathOrModuleId, options });
272
- }
273
-
274
-
275
- const normalizedPath = slothlet.handlers.apiManager.normalizeApiPath(pathOrModuleId).apiPath;
276
- const pathParts = normalizedPath.split(".");
277
- let current = slothlet.api;
278
- for (const part of pathParts) {
279
- if (!current || (typeof current !== "object" && typeof current !== "function")) {
280
- throw new slothlet.SlothletError("INVALID_API_PATH", {
281
- apiPath: pathOrModuleId,
282
- validationError: true
283
- });
284
- }
285
- current = current[part];
286
- }
287
-
288
- if (current === undefined) {
289
- throw new slothlet.SlothletError("INVALID_API_PATH", {
290
- apiPath: pathOrModuleId,
291
- validationError: true
292
- });
293
- }
294
-
295
-
296
- return slothlet.handlers.apiManager.reloadApiComponent({ apiPath: normalizedPath, options });
297
- }
298
- },
299
-
300
-
301
- sanitize: function slothlet_sanitize(str) {
302
- if (typeof str !== "string") {
303
- throw new slothlet.SlothletError("INVALID_ARGUMENT", {
304
- argument: "str",
305
- expected: "string",
306
- received: typeof str,
307
- validationError: true
308
- });
309
- }
310
- return slothlet.helpers.sanitize.sanitizePropertyName(str, slothlet.config.sanitize || {});
311
- },
312
-
313
-
314
- context: {
315
-
316
- get: (key) => {
317
-
318
-
319
-
320
-
321
- if (slothlet.contextManager.constructor.name === "LiveContextManager") {
322
- const currentID = slothlet.contextManager.currentInstanceID;
323
-
324
-
325
-
326
-
327
- if (currentID) {
328
- const activeStore = slothlet.contextManager.instances.get(currentID);
329
- const isOurInstance =
330
- currentID === slothlet.instanceID ||
331
- currentID?.startsWith(slothlet.instanceID + "__run_") ||
332
- activeStore?.parentInstanceID === slothlet.instanceID;
333
-
334
- if (isOurInstance && activeStore) {
335
- return key ? activeStore.context[key] : { ...activeStore.context };
336
- }
337
- }
338
-
339
-
340
- const store = slothlet.contextManager.instances.get(slothlet.instanceID);
341
-
342
-
343
-
344
- if (!store) {
345
- const baseContext = slothlet.context || {};
346
- return key ? baseContext[key] : { ...baseContext };
347
- }
348
-
349
-
350
- return key ? store.context[key] : { ...store.context };
351
- }
352
-
353
-
354
- if (slothlet.contextManager.constructor.name === "AsyncContextManager") {
355
- let currentStore = slothlet.contextManager.tryGetContext();
356
-
357
-
358
-
359
- if (!currentStore) {
360
- const baseStore = slothlet.contextManager.instances.get(slothlet.instanceID);
361
-
362
-
363
- const baseContext = baseStore?.context || {};
364
- return key ? baseContext[key] : { ...baseContext };
365
-
366
- }
367
-
368
-
369
- const isOurInstance =
370
- currentStore.instanceID === slothlet.instanceID ||
371
- currentStore.parentInstanceID === slothlet.instanceID ||
372
- currentStore.instanceID.startsWith(slothlet.instanceID + "__run_");
373
-
374
- if (isOurInstance) {
375
-
376
- return key ? currentStore.context[key] : { ...currentStore.context };
377
- }
378
-
379
-
380
- const baseStore = slothlet.contextManager.instances.get(slothlet.instanceID);
381
-
382
-
383
- const baseContext = baseStore?.context || {};
384
- return key ? baseContext[key] : { ...baseContext };
385
-
386
- }
387
-
388
-
389
-
390
-
391
-
392
- const baseContext = slothlet.context || {};
393
- return key ? baseContext[key] : { ...baseContext };
394
-
395
- },
396
-
397
-
398
- diagnostics: () => {
399
-
400
-
401
-
402
-
403
- if (!slothlet.config?.diagnostics) return undefined;
404
- const managerType = slothlet.contextManager.constructor.name;
405
- const result = {
406
- instanceID: slothlet.instanceID,
407
- managerType,
408
- instancesMapSize: slothlet.contextManager.instances.size,
409
- instancesMapKeys: Array.from(slothlet.contextManager.instances.keys()),
410
- baseContext: slothlet.context
411
- };
412
-
413
-
414
- const store = slothlet.contextManager.instances.get(slothlet.instanceID);
415
-
416
-
417
-
418
- result.storeFromInstancesMap = store
419
- ? {
420
- instanceID: store.instanceID,
421
- context: store.context,
422
- createdAt: store.createdAt
423
- }
424
- : null;
425
-
426
-
427
- if (managerType === "AsyncContextManager") {
428
- try {
429
- const currentCtx = slothlet.contextManager.tryGetContext();
430
- result.currentALSContext = currentCtx
431
- ? {
432
- instanceID: currentCtx.instanceID,
433
- context: currentCtx.context,
434
- hasParent: !!currentCtx.parentContext,
435
- parentInstanceID: currentCtx.parentInstanceID
436
- }
437
- : null;
438
-
439
-
440
-
441
- } catch (____error) {
442
- result.currentALSContext = null;
443
- }
444
-
445
- }
446
-
447
-
448
- if (managerType === "LiveContextManager") {
449
- result.currentInstanceID = slothlet.contextManager.currentInstanceID;
450
- }
451
-
452
- return result;
453
- },
454
-
455
-
456
- run: this.createRunFunction(),
457
-
458
-
459
- scope: this.createScopeFunction()
460
- },
461
-
462
-
463
- hook: {
464
-
465
- on: function slothlet_hook_on(typePattern, handler, options = {}) {
466
- if (!slothlet.handlers?.hookManager) {
467
- throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED", { validationError: true });
468
- }
469
- return slothlet.handlers.hookManager.on(typePattern, handler, options);
470
- },
471
-
472
-
473
- remove: function slothlet_hook_remove(filter = {}) {
474
- if (!slothlet.handlers?.hookManager) {
475
- throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED", { validationError: true });
476
- }
477
- return slothlet.handlers.hookManager.remove(filter);
478
- },
479
-
480
-
481
- clear: function slothlet_hook_clear(filter = {}) {
482
- return this.remove(filter);
483
- },
484
-
485
-
486
- off: function slothlet_hook_off(idOrFilter) {
487
- if (!slothlet.handlers?.hookManager) {
488
- throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED", { validationError: true });
489
- }
490
-
491
- const filter = typeof idOrFilter === "string" ? { id: idOrFilter } : idOrFilter;
492
- return slothlet.handlers.hookManager.remove(filter);
493
- },
494
-
495
-
496
- enable: function slothlet_hook_enable(filter = {}) {
497
- if (!slothlet.handlers?.hookManager) {
498
- throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED", { validationError: true });
499
- }
500
- return slothlet.handlers.hookManager.enable(filter);
501
- },
502
-
503
-
504
- disable: function slothlet_hook_disable(filter = {}) {
505
- if (!slothlet.handlers?.hookManager) {
506
- throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED", { validationError: true });
507
- }
508
- return slothlet.handlers.hookManager.disable(filter);
509
- },
510
-
511
-
512
- list: function slothlet_hook_list(filter = {}) {
513
- if (!slothlet.handlers?.hookManager) {
514
- throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED", { validationError: true });
515
- }
516
- return slothlet.handlers.hookManager.list(filter);
517
- }
518
- },
519
-
520
-
521
- metadata: {
522
-
523
- setGlobal: function slothlet_metadata_setGlobal(key, value) {
524
-
525
-
526
-
527
-
528
- if (!slothlet.handlers?.metadata) {
529
- throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE", {
530
- handlersKeys: slothlet.handlers ? Object.keys(slothlet.handlers).join(", ") : "undefined",
531
- validationError: true
532
- });
533
- }
534
-
535
- return slothlet.handlers.metadata.setGlobalMetadata(key, value);
536
- },
537
-
538
-
539
- set: function slothlet_metadata_set(fn, key, value) {
540
- if (!slothlet.handlers?.metadata) {
541
- throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE", {
542
- handlersKeys: slothlet.handlers
543
- ? Object.keys(slothlet.handlers).join(", ")
544
- :
545
-
546
- "undefined",
547
- validationError: true
548
- });
549
- }
550
- return slothlet.handlers.metadata.setUserMetadata(fn, key, value);
551
- },
552
-
553
-
554
- remove: function slothlet_metadata_remove(fn, key) {
555
- return slothlet.handlers.metadata.removeUserMetadata(fn, key);
556
- },
557
-
558
-
559
- setFor: function slothlet_metadata_setFor(pathOrModuleId, keyOrObj, value) {
560
- if (!slothlet.handlers?.metadata) {
561
- throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE", {
562
- handlersKeys: slothlet.handlers
563
- ? Object.keys(slothlet.handlers).join(", ")
564
- :
565
-
566
- "undefined",
567
- validationError: true
568
- });
569
- }
570
- const resolvedPath = _resolvePathOrModuleId(slothlet, pathOrModuleId);
571
- return slothlet.handlers.metadata.setPathMetadata(resolvedPath, keyOrObj, value);
572
- },
573
-
574
-
575
- removeFor: function slothlet_metadata_removeFor(pathOrModuleId, key) {
576
- if (!slothlet.handlers?.metadata) return;
577
- const resolvedPath = _resolvePathOrModuleId(slothlet, pathOrModuleId);
578
- return slothlet.handlers.metadata.removePathMetadata(resolvedPath, key);
579
- },
580
-
581
-
582
- setForVersion: function slothlet_metadata_setForVersion(logicalPath, versionTag, keyOrObj, value) {
583
- if (!slothlet.handlers?.metadata) {
584
- throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE", {
585
- handlersKeys: slothlet.handlers ? Object.keys(slothlet.handlers).join(", ") : "undefined",
586
- validationError: true
587
- });
588
- }
589
- const info = slothlet.handlers?.versionManager?.list(logicalPath);
590
- if (!info || !info.versions?.[versionTag]) {
591
- throw new slothlet.SlothletError("VERSION_NOT_FOUND", {
592
- version: versionTag,
593
- apiPath: logicalPath
594
- });
595
- }
596
- const { moduleID } = info.versions[versionTag];
597
- const resolvedPath = _resolvePathOrModuleId(slothlet, moduleID);
598
- return slothlet.handlers.metadata.setPathMetadata(resolvedPath, keyOrObj, value);
599
- },
600
-
601
-
602
- getForVersion: function slothlet_metadata_getForVersion(logicalPath, versionTag) {
603
-
604
- if (!slothlet.handlers?.metadata) return {};
605
- const info = slothlet.handlers?.versionManager?.list(logicalPath);
606
- if (!info || !info.versions?.[versionTag]) return {};
607
- const { moduleID } = info.versions[versionTag];
608
- const resolvedPath = _resolvePathOrModuleId(slothlet, moduleID);
609
- return slothlet.handlers.metadata.getPathMetadata(resolvedPath);
610
- }
611
- },
612
-
613
-
614
- scope: this.createScopeFunction(),
615
-
616
-
617
- run: this.createRunFunction(),
618
-
619
-
620
- reload: async (options = {}) => {
621
-
622
- if (!config.api?.mutations?.reload) {
623
- throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED", {
624
- operation: "reload",
625
- validationError: true
626
- });
627
- }
628
- return slothlet.reload(options);
629
- },
630
-
631
-
632
- shutdown: async () => {
633
- return slothlet.shutdown();
634
- },
635
-
636
-
637
- owner: {
638
-
639
- get: (apiPath) => {
640
- if (slothlet.handlers?.ownership) {
641
- return slothlet.handlers.ownership.getPathOwnership(apiPath);
642
- }
643
- return null;
644
- }
645
- },
646
-
647
-
648
- materialize: (() => {
649
- const mgr = slothlet.handlers?.materialize;
650
-
651
-
652
- if (!mgr) {
653
- return Object.freeze({
654
- materialized: false,
655
- get: () => ({ total: 0, materialized: 0, remaining: 0, percentage: 100 }),
656
- wait: async () => {}
657
- });
658
- }
659
-
660
- return Object.freeze({
661
- get materialized() {
662
- return mgr.materialized;
663
- },
664
- get: mgr.get.bind(mgr),
665
- wait: mgr.wait.bind(mgr)
666
- });
667
- })(),
668
-
669
-
670
- lifecycle: (() => {
671
- const handler = slothlet.handlers?.lifecycle;
672
- const noop = () => {};
673
- if (!handler) return { on: noop, off: noop };
674
- return {
675
- on: handler.on.bind(handler),
676
- off: handler.off.bind(handler)
677
- };
678
- })(),
679
-
680
-
681
- env: slothlet.envSnapshot,
682
-
683
-
684
- versioning: {
685
-
686
- list: function slothlet_version_list(logicalPath) {
687
-
688
-
689
- if (!slothlet.handlers?.versionManager) return undefined;
690
- return slothlet.handlers.versionManager.list(logicalPath);
691
- },
692
-
693
-
694
- setDefault: function slothlet_version_setDefault(logicalPath, versionTag) {
695
-
696
-
697
- if (!slothlet.handlers?.versionManager) return;
698
- return slothlet.handlers.versionManager.setDefault(logicalPath, versionTag);
699
- },
700
-
701
-
702
- unregister: async function slothlet_version_unregister(logicalPath, versionTag) {
703
-
704
-
705
- if (!slothlet.handlers?.versionManager) return false;
706
-
707
- const info = slothlet.handlers.versionManager.list(logicalPath);
708
- if (!info || !info.versions?.[versionTag]) return false;
709
-
710
-
711
-
712
- const { moduleID: versionedModuleID } = info.versions[versionTag];
713
-
714
-
715
-
716
- await slothlet.handlers.apiManager.removeApiComponent(versionedModuleID);
717
- return true;
718
- },
719
-
720
-
721
- getVersionMetadata: function slothlet_version_getVersionMetadata(logicalPath, versionTag) {
722
-
723
-
724
- if (!slothlet.handlers?.versionManager) return undefined;
725
- return slothlet.handlers.versionManager.getVersionMetadataByPath(logicalPath, versionTag);
726
- },
727
-
728
-
729
- setVersionMetadata: function slothlet_version_setVersionMetadata(logicalPath, versionTag, patch) {
730
-
731
-
732
- if (!slothlet.handlers?.versionManager) return;
733
- return slothlet.handlers.versionManager.setVersionMetadataByPath(logicalPath, versionTag, patch);
734
- }
735
- },
736
-
737
-
738
- permissions: {
739
-
740
- addRule: function slothlet_permissions_addRule(rule) {
741
-
742
- if (!config.api?.mutations?.permissions) {
743
- throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED", {
744
- operation: "api.slothlet.permissions.addRule",
745
- validationError: true
746
- });
747
- }
748
-
749
-
750
- const permissionManager = slothlet.handlers?.permissionManager;
751
-
752
- if (!permissionManager?.addRule) {
753
- throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE", {
754
- validationError: true
755
- });
756
- }
757
-
758
-
759
- const ruleId = permissionManager.addRule(rule, null);
760
-
761
-
762
- if (slothlet.handlers?.apiManager?.state?.operationHistory) {
763
- slothlet.handlers.apiManager.state.operationHistory.push({
764
- type: "addPermissionRule",
765
- rule,
766
- ownerModuleID: null,
767
- ruleId,
768
- timestamp: Date.now()
769
- });
770
- }
771
-
772
- return ruleId;
773
- },
774
-
775
-
776
- removeRule: function slothlet_permissions_removeRule(ruleId) {
777
-
778
- if (!config.api?.mutations?.permissions) {
779
- throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED", {
780
- operation: "api.slothlet.permissions.removeRule",
781
- validationError: true
782
- });
783
- }
784
-
785
-
786
- const permissionManager = slothlet.handlers?.permissionManager;
787
-
788
- if (!permissionManager?.removeRule) {
789
- throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE", {
790
- validationError: true
791
- });
792
- }
793
-
794
-
795
- const ctx = slothlet.contextManager?.tryGetContext?.();
796
- const currentWrapper = ctx?.currentWrapper;
797
- const callerModuleID = currentWrapper?.____slothletInternal?.moduleID ?? null;
798
- const result = slothlet.handlers.permissionManager.removeRule(ruleId, callerModuleID);
799
-
800
-
801
- if (result && slothlet.handlers?.apiManager?.state?.operationHistory) {
802
- slothlet.handlers.apiManager.state.operationHistory.push({
803
- type: "removePermissionRule",
804
- ruleId,
805
- callerModuleID,
806
- timestamp: Date.now()
807
- });
808
- }
809
-
810
- return result;
811
- },
812
-
813
-
814
- self: {
815
-
816
- access: function slothlet_permissions_self_access(target) {
817
-
818
- const permissionManager = slothlet.handlers?.permissionManager;
819
-
820
- if (!permissionManager?.checkAccess) {
821
- throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE", {
822
- validationError: true
823
- });
824
- }
825
-
826
-
827
- const currentWrapper = slothlet.contextManager?.tryGetContext?.()?.currentWrapper;
828
- const callerPath = currentWrapper?.____slothletInternal?.apiPath ?? "";
829
- const callerFilePath = currentWrapper?.____slothletInternal?.filePath ?? null;
830
- return slothlet.handlers.permissionManager.checkAccess(callerPath, target, callerFilePath, null);
831
- },
832
-
833
-
834
- rules: function slothlet_permissions_self_rules() {
835
-
836
- const permissionManager = slothlet.handlers?.permissionManager;
837
-
838
- if (!permissionManager?.getRulesForCaller) {
839
- throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE", {
840
- validationError: true
841
- });
842
- }
843
-
844
-
845
- const currentWrapper = slothlet.contextManager?.tryGetContext?.()?.currentWrapper;
846
- const callerPath = currentWrapper?.____slothletInternal?.apiPath ?? "";
847
- return slothlet.handlers.permissionManager.getRulesForCaller(callerPath);
848
- }
849
- },
850
-
851
-
852
- global: {
853
-
854
- checkAccess: function slothlet_permissions_global_checkAccess(caller, target) {
855
-
856
- const permissionManager = slothlet.handlers?.permissionManager;
857
-
858
- if (!permissionManager?.checkAccess) {
859
- throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE", {
860
- validationError: true
861
- });
862
- }
863
-
864
-
865
- return slothlet.handlers.permissionManager.checkAccess(caller, target);
866
- },
867
-
868
-
869
- rulesForPath: function slothlet_permissions_global_rulesForPath(path) {
870
-
871
- const permissionManager = slothlet.handlers?.permissionManager;
872
-
873
- if (!permissionManager?.getRulesForPath) {
874
- throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE", {
875
- validationError: true
876
- });
877
- }
878
-
879
-
880
- return slothlet.handlers.permissionManager.getRulesForPath(path);
881
- },
882
-
883
-
884
- rulesByModule: function slothlet_permissions_global_rulesByModule(moduleID) {
885
-
886
- const permissionManager = slothlet.handlers?.permissionManager;
887
-
888
- if (!permissionManager?.getRulesByModule) {
889
- throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE", {
890
- validationError: true
891
- });
892
- }
893
-
894
-
895
- return slothlet.handlers.permissionManager.getRulesByModule(moduleID);
896
- }
897
- },
898
-
899
-
900
- control: {
901
-
902
- enable: function slothlet_permissions_control_enable() {
903
-
904
- const permissionManager = slothlet.handlers?.permissionManager;
905
-
906
- if (!permissionManager?.enable) {
907
- throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE", {
908
- validationError: true
909
- });
910
- }
911
-
912
-
913
-
914
-
915
- const ctx = slothlet.contextManager?.tryGetContext?.();
916
- const callerWrapper = ctx?.currentWrapper;
917
- if (callerWrapper) {
918
-
919
-
920
- const callerPath = callerWrapper.____slothletInternal?.apiPath ?? "";
921
- const callerFilePath = callerWrapper.____slothletInternal?.filePath ?? null;
922
-
923
- if (!permissionManager.checkAccess(callerPath, "slothlet.permissions.control.enable", callerFilePath, null)) {
924
- throw new slothlet.SlothletError("PERMISSION_DENIED", {
925
- caller: callerPath,
926
- target: "slothlet.permissions.control.enable"
927
- });
928
- }
929
- }
930
-
931
- slothlet.handlers.permissionManager.enable();
932
- },
933
-
934
-
935
- disable: function slothlet_permissions_control_disable() {
936
-
937
- const permissionManager = slothlet.handlers?.permissionManager;
938
-
939
- if (!permissionManager?.disable) {
940
- throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE", {
941
- validationError: true
942
- });
943
- }
944
-
945
-
946
-
947
-
948
- const ctx = slothlet.contextManager?.tryGetContext?.();
949
- const callerWrapper = ctx?.currentWrapper;
950
- if (callerWrapper) {
951
-
952
-
953
- const callerPath = callerWrapper.____slothletInternal?.apiPath ?? "";
954
- const callerFilePath = callerWrapper.____slothletInternal?.filePath ?? null;
955
-
956
- if (!permissionManager.checkAccess(callerPath, "slothlet.permissions.control.disable", callerFilePath, null)) {
957
- throw new slothlet.SlothletError("PERMISSION_DENIED", {
958
- caller: callerPath,
959
- target: "slothlet.permissions.control.disable"
960
- });
961
- }
962
- }
963
-
964
- slothlet.handlers.permissionManager.disable();
965
- }
966
- }
967
- }
968
- };
969
-
970
-
971
-
972
- if (!config.hook?.enabled && config.diagnostics !== true) {
973
- delete namespace.hooks;
974
- }
975
-
976
-
977
- if (config.diagnostics === true) {
978
- namespace.diag = {
979
-
980
- describe: (showAll = false) => {
981
- if (showAll) {
982
-
983
- return { ...userApi };
984
- }
985
-
986
- return Reflect.ownKeys(userApi);
987
- },
988
-
989
-
990
- reference: slothlet.reference || null,
991
-
992
-
993
- context: slothlet.context || {},
994
-
995
-
996
- inspect: () => {
997
- return slothlet.getDiagnostics();
998
- },
999
-
1000
-
1001
- getAPI: () => {
1002
- return slothlet.getAPI();
1003
- },
1004
-
1005
-
1006
- getOwnership: () => {
1007
- return slothlet.getOwnership();
1008
- },
1009
-
1010
-
1011
- owner: {
1012
-
1013
- get: (apiPath) => {
1014
- if (slothlet.handlers?.ownership) {
1015
- return slothlet.handlers.ownership.getPathOwnership(apiPath);
1016
- }
1017
- return null;
1018
- }
1019
- },
1020
-
1021
-
1022
- caches: {
1023
-
1024
- get: () => {
1025
- if (slothlet.handlers?.apiCacheManager) {
1026
- return slothlet.handlers.apiCacheManager.getCacheDiagnostics();
1027
- }
1028
- return { totalCaches: 0, caches: [] };
1029
- },
1030
-
1031
-
1032
- getAllModuleIDs: () => {
1033
- if (slothlet.handlers?.apiCacheManager) {
1034
- return slothlet.handlers.apiCacheManager.getAllModuleIDs();
1035
- }
1036
- return [];
1037
- },
1038
-
1039
-
1040
- has: (moduleID) => {
1041
- if (slothlet.handlers?.apiCacheManager) {
1042
- return slothlet.handlers.apiCacheManager.has(moduleID);
1043
- }
1044
- return false;
1045
- }
1046
- },
1047
-
1048
-
1049
- SlothletWarning: slothlet.SlothletWarning,
1050
-
1051
-
1052
-
1053
-
1054
- hook: slothlet.handlers?.hookManager
1055
- ? {
1056
-
1057
- get enabled() {
1058
- return slothlet.handlers.hookManager.enabled;
1059
- },
1060
-
1061
-
1062
- compilePattern: (pattern) => {
1063
- return slothlet.handlers.hookManager.getCompilePatternForDiagnostics()(pattern);
1064
- }
1065
- }
1066
- : undefined
1067
-
1068
- };
1069
- }
1070
-
1071
- return namespace;
1072
- }
1073
-
1074
-
1075
- createShutdownFunction() {
1076
- const slothlet = this.slothlet;
1077
- const shutdownFunction = {
1078
- shutdown: async () => {
1079
-
1080
- if (slothlet.userHooks?.shutdown && typeof slothlet.userHooks.shutdown === "function") {
1081
- await slothlet.userHooks.shutdown();
1082
- }
1083
- return slothlet.shutdown();
1084
- }
1085
- }.shutdown;
1086
- return shutdownFunction;
1087
- }
1088
-
1089
-
1090
- createRunFunction() {
1091
- const slothlet = this.slothlet;
1092
-
1093
- const scopeFunc = this.createScopeFunction();
1094
-
1095
- const runFunction = {
1096
- run: async (contextData, callback, ...args) => {
1097
-
1098
- if (slothlet.config.scope === false) {
1099
- throw new slothlet.SlothletError("SCOPE_DISABLED", {}, null, { validationError: true });
1100
- }
1101
-
1102
-
1103
- if (!contextData || typeof contextData !== "object") {
1104
- throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT", { received: typeof contextData }, null, { validationError: true });
1105
- }
1106
- if (typeof callback !== "function") {
1107
- throw new slothlet.SlothletError("SCOPE_INVALID_CALLBACK", { received: typeof callback }, null, { validationError: true });
1108
- }
1109
-
1110
-
1111
-
1112
- return scopeFunc({
1113
- context: contextData,
1114
- fn: callback,
1115
- args: args,
1116
- merge: slothlet.config.scope?.merge || "shallow",
1117
- isolation: slothlet.config.scope?.isolation || "partial"
1118
- });
1119
- }
1120
- }.run;
1121
- return runFunction;
1122
- }
1123
-
1124
-
1125
- createScopeFunction() {
1126
- const slothlet = this.slothlet;
1127
- const scopeFunction = {
1128
- scope: async (options) => {
1129
-
1130
- if (slothlet.config.scope === false) {
1131
- throw new slothlet.SlothletError("SCOPE_DISABLED", {}, null, { validationError: true });
1132
- }
1133
-
1134
-
1135
- if (!options || typeof options !== "object") {
1136
- throw new slothlet.SlothletError("SCOPE_INVALID_OPTIONS", { received: typeof options }, null, { validationError: true });
1137
- }
1138
- if (!options.fn || typeof options.fn !== "function") {
1139
- throw new slothlet.SlothletError("SCOPE_INVALID_FN", { received: typeof options?.fn }, null, { validationError: true });
1140
- }
1141
- if (!options.context || typeof options.context !== "object") {
1142
- throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT_OBJECT", { received: typeof options?.context }, null, {
1143
- validationError: true
1144
- });
1145
- }
1146
-
1147
- const { context: contextData, fn, args = [], merge = "shallow", isolation } = options;
1148
-
1149
-
1150
- if (merge !== "shallow" && merge !== "deep") {
1151
- throw new slothlet.SlothletError("SCOPE_INVALID_MERGE_STRATEGY", { merge }, null, { validationError: true });
1152
- }
1153
-
1154
-
1155
- const isolationMode = isolation || slothlet.config.scope?.isolation || "partial";
1156
-
1157
-
1158
- if (isolationMode !== "partial" && isolationMode !== "full") {
1159
- throw new slothlet.SlothletError("SCOPE_INVALID_ISOLATION_MODE", { isolationMode }, null, { validationError: true });
1160
- }
1161
-
1162
-
1163
- const contextManager = slothlet.contextManager;
1164
- if (!contextManager) {
1165
- throw new slothlet.SlothletError("NO_CONTEXT_MANAGER", { validationError: true });
1166
- }
1167
-
1168
- const { utilities } = slothlet.helpers;
1169
-
1170
-
1171
- if (contextManager.constructor.name === "LiveContextManager") {
1172
-
1173
- let currentStore = null;
1174
-
1175
-
1176
- const currentID = contextManager.currentInstanceID;
1177
- if (currentID) {
1178
- const activeStore = contextManager.instances.get(currentID);
1179
- const isOurContext =
1180
- currentID === slothlet.instanceID ||
1181
- activeStore?.parentInstanceID === slothlet.instanceID ||
1182
- currentID.startsWith(slothlet.instanceID + "__run_");
1183
-
1184
- if (isOurContext) {
1185
- currentStore = activeStore;
1186
- }
1187
- }
1188
-
1189
-
1190
- if (!currentStore) {
1191
- currentStore = contextManager.instances.get(slothlet.instanceID);
1192
- }
1193
-
1194
- if (!currentStore) {
1195
- throw new slothlet.SlothletError("CONTEXT_NOT_FOUND", {
1196
- instanceID: slothlet.instanceID,
1197
- availableInstances: [...contextManager.instances.keys()].join(", ") || "none",
1198
- validationError: true
1199
- });
1200
- }
1201
-
1202
-
1203
-
1204
- let mergedContext;
1205
- if (merge === "deep") {
1206
- mergedContext = utilities.deepMerge(currentStore.context, contextData);
1207
-
1208
- mergedContext = structuredClone(mergedContext);
1209
- } else {
1210
-
1211
- const clonedParent = structuredClone(currentStore.context);
1212
- mergedContext = { ...clonedParent, ...contextData };
1213
- }
1214
-
1215
-
1216
- const childInstanceID = `${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
1217
-
1218
- const childStore = {
1219
- instanceID: childInstanceID,
1220
- context: mergedContext,
1221
- self: isolationMode === "full" ? utilities.deepClone(currentStore.self) : currentStore.self,
1222
- config: currentStore.config,
1223
- createdAt: currentStore.createdAt,
1224
- parentInstanceID: slothlet.instanceID
1225
- };
1226
-
1227
-
1228
- contextManager.instances.set(childInstanceID, childStore);
1229
- const previousInstanceID = contextManager.currentInstanceID;
1230
-
1231
- try {
1232
-
1233
- contextManager.currentInstanceID = childInstanceID;
1234
-
1235
-
1236
- return await fn(...args);
1237
- } finally {
1238
-
1239
- contextManager.currentInstanceID = previousInstanceID;
1240
- contextManager.instances.delete(childInstanceID);
1241
- }
1242
- }
1243
-
1244
-
1245
- if (contextManager.constructor.name === "AsyncContextManager") {
1246
-
1247
- let currentStore = null;
1248
-
1249
-
1250
- const activeStore = contextManager.tryGetContext();
1251
- if (activeStore) {
1252
- const isOurContext =
1253
- activeStore.instanceID === slothlet.instanceID ||
1254
- activeStore.parentInstanceID === slothlet.instanceID ||
1255
- activeStore.instanceID.startsWith(slothlet.instanceID + "__run_");
1256
-
1257
- if (isOurContext) {
1258
- currentStore = activeStore;
1259
- }
1260
- }
1261
-
1262
-
1263
- if (!currentStore) {
1264
- const baseStore = contextManager.instances.get(slothlet.instanceID);
1265
- if (!baseStore) {
1266
- throw new slothlet.SlothletError("CONTEXT_NOT_FOUND", {
1267
- instanceID: slothlet.instanceID,
1268
- availableInstances: [...contextManager.instances.keys()].join(", ") || "none",
1269
- validationError: true
1270
- });
1271
- }
1272
- currentStore = baseStore;
1273
- }
1274
-
1275
-
1276
-
1277
- let mergedContext;
1278
- if (merge === "deep") {
1279
- mergedContext = utilities.deepMerge(currentStore.context, contextData);
1280
-
1281
- mergedContext = structuredClone(mergedContext);
1282
- } else {
1283
-
1284
- const clonedParent = structuredClone(currentStore.context);
1285
- mergedContext = { ...clonedParent, ...contextData };
1286
- }
1287
-
1288
-
1289
- const childInstanceID = `${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
1290
-
1291
- const childStore = {
1292
- instanceID: childInstanceID,
1293
- context: mergedContext,
1294
- self: isolationMode === "full" ? utilities.deepClone(currentStore.self) : currentStore.self,
1295
- config: currentStore.config,
1296
- createdAt: currentStore.createdAt,
1297
- parentInstanceID: slothlet.instanceID
1298
- };
1299
-
1300
-
1301
- contextManager.instances.set(childInstanceID, childStore);
1302
-
1303
- try {
1304
-
1305
- return await contextManager.als.run(childStore, async () => {
1306
- return await fn(...args);
1307
- });
1308
- } finally {
1309
-
1310
- contextManager.instances.delete(childInstanceID);
1311
- }
1312
- }
1313
-
1314
- throw new slothlet.SlothletError("UNSUPPORTED_CONTEXT_MANAGER", {
1315
- manager: contextManager.constructor.name,
1316
- validationError: true
1317
- });
1318
- }
1319
- }.scope;
1320
- return scopeFunction;
1321
- }
1322
-
1323
-
1324
- createDestroyFunction(api) {
1325
- const slothlet = this.slothlet;
1326
- const destroyFunction = {
1327
- destroy: async () => {
1328
-
1329
- if (slothlet.userHooks?.destroy && typeof slothlet.userHooks.destroy === "function") {
1330
- await slothlet.userHooks.destroy();
1331
- }
1332
-
1333
-
1334
- if (api && typeof api.shutdown === "function") {
1335
- await api.shutdown();
1336
- } else {
1337
-
1338
- await slothlet.shutdown();
1339
- }
1340
-
1341
-
1342
-
1343
-
1344
- slothlet.isDestroyed = true;
1345
-
1346
-
1347
- const objectsToClear = [api, slothlet.api].filter((obj) => obj && typeof obj === "object");
1348
-
1349
- for (const obj of objectsToClear) {
1350
- const keys = Object.keys(obj);
1351
- for (const key of keys) {
1352
- try {
1353
- delete obj[key];
1354
- } catch (_) {
1355
-
1356
- }
1357
- }
1358
- }
1359
-
1360
-
1361
- slothlet.api = null;
1362
- }
1363
- }.destroy;
1364
- return destroyFunction;
1365
- }
1366
-
1367
-
1368
- attachBuiltins(userApi, builtins) {
1369
-
1370
-
1371
- Object.defineProperty(userApi, "slothlet", {
1372
- value: builtins.slothlet,
1373
- enumerable: true,
1374
- writable: false,
1375
- configurable: true
1376
- });
1377
-
1378
-
1379
- Object.defineProperty(userApi, "shutdown", {
1380
- value: builtins.shutdown,
1381
- enumerable: true,
1382
- writable: false,
1383
- configurable: true
1384
- });
1385
-
1386
-
1387
-
1388
-
1389
-
1390
-
1391
- if (builtins.destroy !== null) {
1392
- Object.defineProperty(userApi, "destroy", {
1393
- value: builtins.destroy,
1394
- enumerable: true,
1395
- writable: false,
1396
- configurable: true
1397
- });
1398
- }
1399
-
1400
- }
1401
- }
17
+ import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{TYPE_STATES}from"@cldmv/slothlet/handlers/unified-wrapper";import{getLanguage,initI18n,setLanguage,t,translate}from"@cldmv/slothlet/i18n";function _resolvePathOrModuleId(slothlet,pathOrModuleId){const history=slothlet.handlers?.apiManager?.state?.addHistory;if(history){let match=null;for(let i=history.length-1;i>=0;i--){const entry=history[i];if(entry?.moduleID===pathOrModuleId){match=entry;break}}if(match)return match.apiPath}return pathOrModuleId}class ApiBuilder extends ComponentBase{static slothletProperty="apiBuilder";constructor(slothlet){super(slothlet)}async buildFinalAPI(userApi){this.slothlet.debug("api",{key:"DEBUG_MODE_BUILD_FINAL_API_CALLED",diagnostics:this.____config.diagnostics,userApiKeys:Object.keys(userApi)});if(this.slothlet._ownBuiltins){for(const[key,ref]of Object.entries(this.slothlet._ownBuiltins)){if(ref&&Object.prototype.hasOwnProperty.call(userApi,key)&&userApi[key]===ref){try{delete userApi[key]}catch(_){}}}}this.slothlet.userHooks={shutdown:typeof userApi.shutdown==="function"?userApi.shutdown:null,destroy:typeof userApi.destroy==="function"?userApi.destroy:null};if(userApi.slothlet){new this.SlothletWarning("WARNING_RESERVED_PROPERTY_CONFLICT",{properties:"slothlet"})}const slothletNamespace=await this.createSlothletNamespace(userApi);this.slothlet.debug("api",{key:"DEBUG_MODE_SLOTHLET_NAMESPACE_CREATED",namespaceKeys:Object.keys(slothletNamespace),hasDiag:!!slothletNamespace.diag});const shutdownFn=this.createShutdownFunction();this.attachBuiltins(userApi,{slothlet:slothletNamespace,shutdown:shutdownFn,destroy:null});this.slothlet.debug("api",{key:"DEBUG_MODE_BUILT_INS_ATTACHED",userApiKeys:Object.keys(userApi),hasSlothlet:!!userApi.slothlet,hasDiag:!!userApi.slothlet?.diag});const destroyWithApi=this.createDestroyFunction(userApi);Object.defineProperty(userApi,"destroy",{value:destroyWithApi,enumerable:true,writable:false,configurable:true});this.slothlet._ownBuiltins={shutdown:shutdownFn,slothlet:slothletNamespace,destroy:destroyWithApi};return userApi}async createSlothletNamespace(userApi){const slothlet=this.slothlet;const config=this.____config;let version="unknown";try{const pkgPath=new URL("../../../package.json",import.meta.url);const{readFile}=await import("node:fs/promises");const pkgContent=await readFile(pkgPath,"utf-8");const pkg=JSON.parse(pkgContent);version=pkg.version||"unknown"}catch{}const namespace={i18n:{setLanguage,getLanguage,translate,t,initI18n},version,instanceID:slothlet.instanceID,types:TYPE_STATES,api:{add:async function slothlet_api_add(apiPath,folderPath,options={},versionConfig=null){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.add",validationError:true})}const{recordHistory:____recordHistory,collisionMode:____collisionMode,mutateExisting:____mutateExisting,...filteredOptions}=options;return slothlet.handlers.apiManager.addApiComponent({apiPath,folderPath,options:filteredOptions,versionConfig:versionConfig||null})},remove:async function slothlet_api_remove(pathOrModuleId){if(!config.api?.mutations?.remove){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.remove",validationError:true})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string",received:typeof pathOrModuleId,validationError:true})}return slothlet.handlers.apiManager.removeApiComponent(pathOrModuleId)},reload:async function slothlet_api_reload(pathOrModuleId,options){if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.reload",validationError:true})}if(pathOrModuleId==null||pathOrModuleId===""||pathOrModuleId==="."){return slothlet.handlers.apiManager.reloadApiComponent({apiPath:".",options})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string, null, undefined, or '.'",received:typeof pathOrModuleId,validationError:true})}const isModuleId=slothlet.handlers.apiManager.state.addHistory.some(entry=>entry.moduleID===pathOrModuleId);if(isModuleId){return slothlet.handlers.apiManager.reloadApiComponent({moduleID:pathOrModuleId,options})}const normalizedPath=slothlet.handlers.apiManager.normalizeApiPath(pathOrModuleId).apiPath;const pathParts=normalizedPath.split(".");let current=slothlet.api;for(const part of pathParts){if(!current||typeof current!=="object"&&typeof current!=="function"){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}current=current[part]}if(current===void 0){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}return slothlet.handlers.apiManager.reloadApiComponent({apiPath:normalizedPath,options})}},sanitize:function slothlet_sanitize(str){if(typeof str!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"str",expected:"string",received:typeof str,validationError:true})}return slothlet.helpers.sanitize.sanitizePropertyName(str,slothlet.config.sanitize||{})},context:{get:key=>{if(slothlet.contextManager.constructor.name==="LiveContextManager"){const currentID=slothlet.contextManager.currentInstanceID;if(currentID){const activeStore=slothlet.contextManager.instances.get(currentID);const isOurInstance=currentID===slothlet.instanceID||currentID?.startsWith(slothlet.instanceID+"__run_")||activeStore?.parentInstanceID===slothlet.instanceID;if(isOurInstance&&activeStore){return key?activeStore.context[key]:{...activeStore.context}}}const store=slothlet.contextManager.instances.get(slothlet.instanceID);if(!store){const baseContext2=slothlet.context||{};return key?baseContext2[key]:{...baseContext2}}return key?store.context[key]:{...store.context}}if(slothlet.contextManager.constructor.name==="AsyncContextManager"){let currentStore=slothlet.contextManager.tryGetContext();if(!currentStore){const baseStore2=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext3=baseStore2?.context||{};return key?baseContext3[key]:{...baseContext3}}const isOurInstance=currentStore.instanceID===slothlet.instanceID||currentStore.parentInstanceID===slothlet.instanceID||currentStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurInstance){return key?currentStore.context[key]:{...currentStore.context}}const baseStore=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext2=baseStore?.context||{};return key?baseContext2[key]:{...baseContext2}}const baseContext=slothlet.context||{};return key?baseContext[key]:{...baseContext}},diagnostics:()=>{if(!slothlet.config?.diagnostics)return void 0;const managerType=slothlet.contextManager.constructor.name;const result={instanceID:slothlet.instanceID,managerType,instancesMapSize:slothlet.contextManager.instances.size,instancesMapKeys:Array.from(slothlet.contextManager.instances.keys()),baseContext:slothlet.context};const store=slothlet.contextManager.instances.get(slothlet.instanceID);result.storeFromInstancesMap=store?{instanceID:store.instanceID,context:store.context,createdAt:store.createdAt}:null;if(managerType==="AsyncContextManager"){try{const currentCtx=slothlet.contextManager.tryGetContext();result.currentALSContext=currentCtx?{instanceID:currentCtx.instanceID,context:currentCtx.context,hasParent:!!currentCtx.parentContext,parentInstanceID:currentCtx.parentInstanceID}:null}catch(____error){result.currentALSContext=null}}if(managerType==="LiveContextManager"){result.currentInstanceID=slothlet.contextManager.currentInstanceID}return result},run:this.createRunFunction(),scope:this.createScopeFunction()},hook:{on:function slothlet_hook_on(typePattern,handler,options={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.on(typePattern,handler,options)},remove:function slothlet_hook_remove(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.remove(filter)},clear:function slothlet_hook_clear(filter={}){return this.remove(filter)},off:function slothlet_hook_off(idOrFilter){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}const filter=typeof idOrFilter==="string"?{id:idOrFilter}:idOrFilter;return slothlet.handlers.hookManager.remove(filter)},enable:function slothlet_hook_enable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.enable(filter)},disable:function slothlet_hook_disable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.disable(filter)},list:function slothlet_hook_list(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.list(filter)}},metadata:{setGlobal:function slothlet_metadata_setGlobal(key,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}return slothlet.handlers.metadata.setGlobalMetadata(key,value)},set:function slothlet_metadata_set(fn,key,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}return slothlet.handlers.metadata.setUserMetadata(fn,key,value)},remove:function slothlet_metadata_remove(fn,key){return slothlet.handlers.metadata.removeUserMetadata(fn,key)},setFor:function slothlet_metadata_setFor(pathOrModuleId,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},removeFor:function slothlet_metadata_removeFor(pathOrModuleId,key){if(!slothlet.handlers?.metadata)return;const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.removePathMetadata(resolvedPath,key)},setForVersion:function slothlet_metadata_setForVersion(logicalPath,versionTag,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag]){throw new slothlet.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},getForVersion:function slothlet_metadata_getForVersion(logicalPath,versionTag){if(!slothlet.handlers?.metadata)return{};const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag])return{};const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.getPathMetadata(resolvedPath)}},scope:this.createScopeFunction(),run:this.createRunFunction(),reload:async(options={})=>{if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"reload",validationError:true})}return slothlet.reload(options)},shutdown:async()=>{return slothlet.shutdown()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},materialize:(()=>{const mgr=slothlet.handlers?.materialize;if(!mgr){return Object.freeze({materialized:false,get:()=>({total:0,materialized:0,remaining:0,percentage:100}),wait:async()=>{}})}return Object.freeze({get materialized(){return mgr.materialized},get:mgr.get.bind(mgr),wait:mgr.wait.bind(mgr)})})(),lifecycle:(()=>{const handler=slothlet.handlers?.lifecycle;const noop=()=>{};if(!handler)return{on:noop,off:noop};return{on:handler.on.bind(handler),off:handler.off.bind(handler)}})(),env:slothlet.envSnapshot,versioning:{list:function slothlet_version_list(logicalPath){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.list(logicalPath)},setDefault:function slothlet_version_setDefault(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setDefault(logicalPath,versionTag)},unregister:async function slothlet_version_unregister(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return false;const info=slothlet.handlers.versionManager.list(logicalPath);if(!info||!info.versions?.[versionTag])return false;const{moduleID:versionedModuleID}=info.versions[versionTag];await slothlet.handlers.apiManager.removeApiComponent(versionedModuleID);return true},getVersionMetadata:function slothlet_version_getVersionMetadata(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.getVersionMetadataByPath(logicalPath,versionTag)},setVersionMetadata:function slothlet_version_setVersionMetadata(logicalPath,versionTag,patch){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setVersionMetadataByPath(logicalPath,versionTag,patch)}},permissions:{addRule:function slothlet_permissions_addRule(rule){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.addRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.addRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ruleId=permissionManager.addRule(rule,null);if(slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"addPermissionRule",rule,ownerModuleID:null,ruleId,timestamp:Date.now()})}return ruleId},removeRule:function slothlet_permissions_removeRule(ruleId){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.removeRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.removeRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ctx=slothlet.contextManager?.tryGetContext?.();const currentWrapper=ctx?.currentWrapper;const callerModuleID=currentWrapper?.____slothletInternal?.moduleID??null;const result=slothlet.handlers.permissionManager.removeRule(ruleId,callerModuleID);if(result&&slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"removePermissionRule",ruleId,callerModuleID,timestamp:Date.now()})}return result},self:{access:function slothlet_permissions_self_access(target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const currentWrapper=slothlet.contextManager?.tryGetContext?.()?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";const callerFilePath=currentWrapper?.____slothletInternal?.filePath??null;return slothlet.handlers.permissionManager.checkAccess(callerPath,target,callerFilePath,null)},rules:function slothlet_permissions_self_rules(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForCaller){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const currentWrapper=slothlet.contextManager?.tryGetContext?.()?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";return slothlet.handlers.permissionManager.getRulesForCaller(callerPath)}},global:{checkAccess:function slothlet_permissions_global_checkAccess(caller,target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.checkAccess(caller,target)},rulesForPath:function slothlet_permissions_global_rulesForPath(path){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForPath){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesForPath(path)},rulesByModule:function slothlet_permissions_global_rulesByModule(moduleID){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesByModule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesByModule(moduleID)}},control:{enable:function slothlet_permissions_control_enable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.enable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ctx=slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx?.currentWrapper;if(callerWrapper){const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;if(!permissionManager.checkAccess(callerPath,"slothlet.permissions.control.enable",callerFilePath,null)){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:"slothlet.permissions.control.enable"})}}slothlet.handlers.permissionManager.enable()},disable:function slothlet_permissions_control_disable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.disable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ctx=slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx?.currentWrapper;if(callerWrapper){const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;if(!permissionManager.checkAccess(callerPath,"slothlet.permissions.control.disable",callerFilePath,null)){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:"slothlet.permissions.control.disable"})}}slothlet.handlers.permissionManager.disable()}}}};if(!config.hook?.enabled&&config.diagnostics!==true){delete namespace.hooks}if(config.diagnostics===true){namespace.diag={describe:(showAll=false)=>{if(showAll){return{...userApi}}return Reflect.ownKeys(userApi)},reference:slothlet.reference||null,context:slothlet.context||{},inspect:()=>{return slothlet.getDiagnostics()},getAPI:()=>{return slothlet.getAPI()},getOwnership:()=>{return slothlet.getOwnership()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},caches:{get:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getCacheDiagnostics()}return{totalCaches:0,caches:[]}},getAllModuleIDs:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getAllModuleIDs()}return[]},has:moduleID=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.has(moduleID)}return false}},SlothletWarning:slothlet.SlothletWarning,hook:slothlet.handlers?.hookManager?{get enabled(){return slothlet.handlers.hookManager.enabled},compilePattern:pattern=>{return slothlet.handlers.hookManager.getCompilePatternForDiagnostics()(pattern)}}:void 0}}return namespace}createShutdownFunction(){const slothlet=this.slothlet;const shutdownFunction={shutdown:async()=>{if(slothlet.userHooks?.shutdown&&typeof slothlet.userHooks.shutdown==="function"){await slothlet.userHooks.shutdown()}return slothlet.shutdown()}}.shutdown;return shutdownFunction}createRunFunction(){const slothlet=this.slothlet;const scopeFunc=this.createScopeFunction();const runFunction={run:async(contextData,callback,...args)=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!contextData||typeof contextData!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT",{received:typeof contextData},null,{validationError:true})}if(typeof callback!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_CALLBACK",{received:typeof callback},null,{validationError:true})}return scopeFunc({context:contextData,fn:callback,args,merge:slothlet.config.scope?.merge||"shallow",isolation:slothlet.config.scope?.isolation||"partial"})}}.run;return runFunction}createScopeFunction(){const slothlet=this.slothlet;const scopeFunction={scope:async options=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!options||typeof options!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_OPTIONS",{received:typeof options},null,{validationError:true})}if(!options.fn||typeof options.fn!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_FN",{received:typeof options?.fn},null,{validationError:true})}if(!options.context||typeof options.context!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT_OBJECT",{received:typeof options?.context},null,{validationError:true})}const{context:contextData,fn,args=[],merge="shallow",isolation}=options;if(merge!=="shallow"&&merge!=="deep"){throw new slothlet.SlothletError("SCOPE_INVALID_MERGE_STRATEGY",{merge},null,{validationError:true})}const isolationMode=isolation||slothlet.config.scope?.isolation||"partial";if(isolationMode!=="partial"&&isolationMode!=="full"){throw new slothlet.SlothletError("SCOPE_INVALID_ISOLATION_MODE",{isolationMode},null,{validationError:true})}const contextManager=slothlet.contextManager;if(!contextManager){throw new slothlet.SlothletError("NO_CONTEXT_MANAGER",{validationError:true})}const{utilities}=slothlet.helpers;if(contextManager.constructor.name==="LiveContextManager"){let currentStore=null;const currentID=contextManager.currentInstanceID;if(currentID){const activeStore=contextManager.instances.get(currentID);const isOurContext=currentID===slothlet.instanceID||activeStore?.parentInstanceID===slothlet.instanceID||currentID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){currentStore=contextManager.instances.get(slothlet.instanceID)}if(!currentStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?utilities.deepClone(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID};contextManager.instances.set(childInstanceID,childStore);const previousInstanceID=contextManager.currentInstanceID;try{contextManager.currentInstanceID=childInstanceID;return await fn(...args)}finally{contextManager.currentInstanceID=previousInstanceID;contextManager.instances.delete(childInstanceID)}}if(contextManager.constructor.name==="AsyncContextManager"){let currentStore=null;const activeStore=contextManager.tryGetContext();if(activeStore){const isOurContext=activeStore.instanceID===slothlet.instanceID||activeStore.parentInstanceID===slothlet.instanceID||activeStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){const baseStore=contextManager.instances.get(slothlet.instanceID);if(!baseStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}currentStore=baseStore}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?utilities.deepClone(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID};contextManager.instances.set(childInstanceID,childStore);try{return await contextManager.als.run(childStore,async()=>{return await fn(...args)})}finally{contextManager.instances.delete(childInstanceID)}}throw new slothlet.SlothletError("UNSUPPORTED_CONTEXT_MANAGER",{manager:contextManager.constructor.name,validationError:true})}}.scope;return scopeFunction}createDestroyFunction(api){const slothlet=this.slothlet;const destroyFunction={destroy:async()=>{if(slothlet.userHooks?.destroy&&typeof slothlet.userHooks.destroy==="function"){await slothlet.userHooks.destroy()}if(api&&typeof api.shutdown==="function"){await api.shutdown()}else{await slothlet.shutdown()}slothlet.isDestroyed=true;const objectsToClear=[api,slothlet.api].filter(obj=>obj&&typeof obj==="object");for(const obj of objectsToClear){const keys=Object.keys(obj);for(const key of keys){try{delete obj[key]}catch(_){}}}slothlet.api=null}}.destroy;return destroyFunction}attachBuiltins(userApi,builtins){Object.defineProperty(userApi,"slothlet",{value:builtins.slothlet,enumerable:true,writable:false,configurable:true});Object.defineProperty(userApi,"shutdown",{value:builtins.shutdown,enumerable:true,writable:false,configurable:true});if(builtins.destroy!==null){Object.defineProperty(userApi,"destroy",{value:builtins.destroy,enumerable:true,writable:false,configurable:true})}}}export{ApiBuilder};