@cldmv/slothlet 3.16.2 → 3.16.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,18 +43,18 @@ Every feature has been hardened with a comprehensive test suite - over **5,300 t
43
43
 
44
44
  ## ✨ What's New
45
45
 
46
- ### Latest: v3.16.2 (September 2026)
46
+ ### Latest: v3.16.3 (September 2026)
47
47
 
48
- - **Routine cascades now resolve `self.*`** — a root-cascade routine call (`api.<name>()` / `api.slothlet.<name>()`, or an auto-fired `startup` / `shutdown` / `destroy` routine) ran its contributors with no active extent, so any contributor reaching ambient `self.*` threw `RUNTIME_NO_ACTIVE_CONTEXT_SELF` while the same contribution called per-path (`api.<path>.<name>()`) worked. Routines now run every contributor inside the instance extent under its own leaf wrapper, so each runs exactly as if called directly — `self.*` resolves and permission/caller identity is the contributor itself, cascade and per-path alike (#394).
49
- - **Docs build & contributor-guide fixes** — repairs the post-release docs-site build that had failed since v3.16.0 on an unparseable JSDoc `@param` type (now a proper `@callback` typedef, no public type change) (#385), and refreshes `CONTRIBUTING.md` for the v4 flow (#386).
50
- - [View full v3.16.2 Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.16.2.md)
48
+ - **`impl:created` / `impl:changed` stop leaking the raw callable** — the public lifecycle events carried the module's raw, unwrapped implementation (`data.impl`) and fired per contribution before collision resolution, so they announced leaves a later merge discarded. They now fire **post-placement, once, only for the contribution that owns the path**, and carry the wrapped leaf on `data.wrapper.__impl` — never the enforcement-bypassing raw callable. Read `data.wrapper.__impl` instead of `data.impl` (#398).
49
+ - **Routine cascade lives only at `api.<name>`** — a routine's root cascade was also mirrored onto slothlet's own control namespace as `api.slothlet.<name>()`. That duplicate is gone; call `api.<name>()` (e.g. `api.initialize()`). The `shutdown` / `destroy` dispose builtins still respond at `api.slothlet.shutdown` / `destroy` as before (#399).
50
+ - [View full v3.16.3 Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.16.3.md)
51
51
 
52
52
  ### Recent Releases
53
53
 
54
+ - **v3.16.2** (September 2026) — Routine root cascades now run each contributor inside the instance extent, so ambient `self.*` resolves under `api.<name>()` and the auto-fired `startup` / `shutdown` / `destroy` routines exactly as a per-path call does; plus a post-release docs-build repair (unparseable JSDoc `@param` → `@callback` typedef, no public type change) and a contributor-guide refresh for the v4 flow (#394, #385, #386) ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.16.2.md))
54
55
  - **v3.16.1** (September 2026) — Widened the optional `typescript` peer to `^6.0.3 || ^7.0.0` so consumers can adopt TypeScript 7 without an `npm ci` `ERESOLVE` conflict against `@cldmv/slothlet`; shipped `.d.ts` verified clean under TypeScript 7.0.2 (#382) ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.16.1.md))
55
56
  - **v3.16.0** (September 2026) — Stackable lifecycle routines (`routines` config + root cascade) replacing the deprecated `collectLifecycleHooks`, a `stackRoutines` flag decoupled from `collisionMode`, a large collision/ownership/routine-stacking correctness pass with reactive per-path stack self-heal, and the remaining live-runtime deferred-callback boundaries pinned; minimum Node raised to `>=22.12.0` (#341, #365, #366, #362, #369) ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.16.0.md))
56
- - **v3.15.3** (September 2026) — Wrap-on-set / `api.add()` live Proxy delegation, plus hook-lifecycle default fixes: `self.X = obj` and `api.slothlet.api.add()` now give a genuinely live, two-way view onto the underlying object instead of a frozen snapshot, including `EventEmitter`-derived values (#340, #342); hook-subset default `||` bug fixed to `??` (#343, #344) ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.15.3.md))
57
- - **v3.15.2** (September 2026) — Core context/composition bug-fix release: async-leaf class-instance context propagation, wrap-on-set context/permission parity with `add()`, `add()` no longer hangs on a socket or circular value, and an EventEmitter context-patch memory leak fix ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.15.2.md)) 📚 **For complete version history and detailed release notes, see [docs/changelog/](https://github.com/CLDMV/slothlet/tree/master/docs/changelog/) folder.**
57
+ - **v3.15.3** (September 2026) — Wrap-on-set / `api.add()` live Proxy delegation, plus hook-lifecycle default fixes: `self.X = obj` and `api.slothlet.api.add()` now give a genuinely live, two-way view onto the underlying object instead of a frozen snapshot, including `EventEmitter`-derived values (#340, #342); hook-subset default `||` bug fixed to `??` (#343, #344) ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.15.3.md)) 📚 **For complete version history and detailed release notes, see [docs/changelog/](https://github.com/CLDMV/slothlet/tree/master/docs/changelog/) folder.**
58
58
 
59
59
  ---
60
60
 
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{ComponentBase}from"#factories/component-base";import{t}from"@cldmv/slothlet/i18n";import{UnifiedWrapper,resolveWrapper}from"#handlers/unified-wrapper";import{getInstanceToken}from"#handlers/lifecycle-token";class ModesProcessor extends ComponentBase{static slothletProperty="modesProcessor";constructor(slothlet){super(slothlet)}#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext){const resolved=collisionModeOverride||this.slothlet.helpers.modesUtils.getOwnershipCollisionMode(this.slothlet.config,collisionContext);return resolved==="replace"||resolved==="merge-replace"?resolved:"merge"}async#assignWithRoutineRevert(apiPath,moduleID,assign){const priorFn=this.slothlet.handlers.routineManager?.snapshotRawEntry(apiPath,moduleID);const priorOwnershipEntry=this.slothlet.handlers.ownership?.snapshotPathEntry(apiPath,moduleID);const priorRawEntries=this.slothlet.handlers.routineManager?.snapshotRawEntries(moduleID)??new Map;const priorOwnershipEntries=this.slothlet.handlers.ownership?.snapshotModuleEntries(moduleID)??new Map;let constructedWrapper=null;const registerWrapper=wrapper=>{constructedWrapper=wrapper};const revert=()=>{if(constructedWrapper){this.slothlet.handlers.routineManager?.revertSpeculativeSubtree(constructedWrapper,moduleID,apiPath,priorRawEntries);this.slothlet.handlers.ownership?.revertSpeculativeSubtree(constructedWrapper,moduleID,apiPath,priorOwnershipEntries);this.slothlet.handlers.apiManager?.invalidateSpeculativeWrappers(constructedWrapper)}else{this.slothlet.handlers.routineManager?.revertRawEntry(apiPath,moduleID,priorFn);this.#revertOwnershipEntry(apiPath,moduleID,priorOwnershipEntry)}};let assigned;try{assigned=await assign(registerWrapper)}catch(err){revert();throw err}if(!assigned){revert()}return assigned}#revertOwnershipEntry(apiPath,moduleID,priorOwnershipEntry){const ownership=this.slothlet.handlers.ownership;if(!ownership)return;if(priorOwnershipEntry)ownership.restoreEntry(moduleID,apiPath,priorOwnershipEntry);else ownership.removePath(apiPath,moduleID)}async processFiles(api,files,directory,currentDepth,mode,isRoot,recursive,populateDirectly=false,apiPathPrefix="",collisionContext="initial",moduleID=null,sourceFolder=null,cacheBust=null,collisionModeOverride=null,rootUnwrap=false){const modes_effectiveCollisionMode=collisionModeOverride||(collisionContext==="initial"?this.slothlet.config.collision?.initial:this.slothlet.config.collision?.api)||"replace";const buildApiPath=path=>{if(!path)return apiPathPrefix;if(!apiPathPrefix)return path;if(path.startsWith(`${apiPathPrefix}.`)){return path}if(isRoot){if(rootUnwrap){const cut=path.indexOf(".");return cut===-1?apiPathPrefix:`${apiPathPrefix}.${path.slice(cut+1)}`}const mountLeaf=apiPathPrefix.split(".").pop();if(path===mountLeaf)return apiPathPrefix;if(path.startsWith(`${mountLeaf}.`))return`${apiPathPrefix}.${path.slice(mountLeaf.length+1)}`}return`${apiPathPrefix}.${path}`};let rootDefaultFunction=null;const rootContributors=[];const categoryName=isRoot&&!populateDirectly?null:this.slothlet.helpers.sanitize.sanitizePropertyName(directory.name);let targetApi=isRoot&&!populateDirectly?api:populateDirectly?api:api[categoryName]=api[categoryName]||{};const childPathPrefix=populateDirectly||!categoryName?apiPathPrefix:buildApiPath(categoryName);const isRootFile=currentDepth===0&&!populateDirectly;const effectiveMode=mode==="lazy"&&isRootFile?"eager":mode;const shouldWrap=!(effectiveMode==="lazy"&&populateDirectly);if(!isRoot&&shouldWrap&&!populateDirectly){const existingTarget=api[categoryName];if(existingTarget&&resolveWrapper(existingTarget)){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_REUSE_EXISTING_WRAPPER",categoryName,apiPath:resolveWrapper(existingTarget)?.apiPath})}targetApi=existingTarget}else if(existingTarget===void 0||typeof existingTarget==="object"&&existingTarget!==null){const initialImpl=resolveWrapper(existingTarget)?{}:this.slothlet.helpers.modesUtils.cloneWrapperImpl(existingTarget||{},mode);if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_WRAPPER_CREATED",categoryName,apiPath:buildApiPath(categoryName)})}const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:buildApiPath(categoryName),initialImpl,filePath:directory.path,moduleID:moduleID||categoryName,sourceFolder});api[categoryName]=wrapper.createProxy();if(this.slothlet.handlers?.metadata){this.slothlet.handlers.metadata.tagSystemMetadata(wrapper,{filePath:directory.path,apiPath:buildApiPath(categoryName),moduleID:moduleID||"base",sourceFolder:sourceFolder||directory.path},getInstanceToken(this.slothlet))}if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_WRAPPER_ASSIGNED",categoryName})}targetApi=api[categoryName];if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_CREATED",categoryName,apiPath:wrapper.apiPath});this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_TARGET_API_STATUS",isWrapper:!!resolveWrapper(targetApi),targetApiKeys:Object.keys(targetApi)})}}}if(!isRoot&&this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{message:await t("DEBUG_MODE_PROCESSING_DIRECTORY",{mode,categoryName,currentDepth})})}const loadedModules=[];for(const file of files){if(this.slothlet.config.debug?.modes&&categoryName==="string"){this.slothlet.debug("modes",{key:"DEBUG_MODE_PROCESSING_FILE",categoryName,file:file.name,isRoot,populateDirectly,mode})}try{const exports=file.synthetic?file.exports:this.slothlet.processors.loader.extractExports(await this.slothlet.processors.loader.loadModule(file.path,this.slothlet.instanceID,moduleID,cacheBust));const moduleName=this.slothlet.helpers.sanitize.sanitizePropertyName(file.name);const moduleKeys=Object.keys(exports).filter(k=>k!=="default");const analysis={hasDefault:exports.default!==void 0,hasNamed:moduleKeys.length>0,defaultExportType:exports.default?typeof exports.default:null};loadedModules.push({file,mod:exports,moduleName,moduleKeys,analysis})}catch(error){if(error.name==="SlothletError")throw error;throw new this.SlothletError("MODULE_LOAD_FAILED",{modulePath:file.path,moduleID:moduleID||file.moduleID},error)}}const hasMultipleDefaults=loadedModules.filter(m=>m.analysis.hasDefault).length>1;for(const{file,mod,moduleName,moduleKeys,analysis}of loadedModules){if(this.slothlet.config.debug?.modes&&categoryName==="logger"){this.slothlet.debug("modes",{key:"DEBUG_MODE_PROCESSING_MODULE",categoryName,moduleName,hasDefault:analysis.hasDefault,moduleKeys,targetApiType:typeof targetApi,targetApiCallable:typeof targetApi==="function"})}const isAddapiFile=moduleName==="addapi"||file.name==="addapi"||file.fullName&&["addapi.mjs","addapi.cjs","addapi.js","addapi.ts"].includes(file.fullName.toLowerCase());const isAddapiObjectDefault=isAddapiFile&&analysis.hasDefault&&typeof mod.default!=="function";const isRootContributor=isRoot&&analysis.hasDefault&&typeof mod.default==="function"&&!isAddapiObjectDefault;if(moduleName==="config"||moduleKeys.some(k=>k.includes("Config")||k.includes("config"))){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FILE_PROCESSING",module:moduleName,category:categoryName||"(none)",isRoot,hasDefault:analysis.hasDefault,moduleKeys})}}if(isRootContributor){const defaultFunc=this.slothlet.helpers.modesUtils.ensureNamedExportFunction(mod.default,moduleName);for(const key of moduleKeys){if(!this.slothlet.processors.flatten.shouldAttachNamedExport(key,mod[key],defaultFunc,mod.default)){continue}defaultFunc[key]=mod[key]}rootContributors.push({moduleName,file,defaultFunc});continue}else{const decision=await this.slothlet.processors.flatten.getFlatteningDecision({mod,moduleName,categoryName:categoryName||moduleName,analysis,hasMultipleDefaults,moduleKeys,t});if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{message:await t("DEBUG_MODE_MODULE_DECISION",{mode,moduleName,reason:decision.reason})})}const propertyName=decision.preferredName||moduleName;const effectiveCategoryName=categoryName||moduleName;let{moduleContent}=this.slothlet.processors.flatten.processModuleForAPI({mod,decision,moduleName,propertyName,moduleKeys,analysis,file,collisionContext,apiPathPrefix:apiPathPrefix||"",collisionModeOverride:modes_effectiveCollisionMode});if(!isRoot&&moduleName===categoryName){if(moduleKeys.length===1&&moduleKeys[0]===moduleName&&!analysis.hasDefault){const exportedValue=mod[moduleName];if(typeof exportedValue==="object"&&exportedValue!==null){if(this.slothlet.config.debug?.modes&&categoryName==="string"){this.slothlet.debug("modes",{key:"DEBUG_MODE_SINGLE_FILE_FOLDER_DETECTED",categoryName,populateDirectly,isRoot,mode,exportKeys:Object.keys(exportedValue)})}if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:buildApiPath(categoryName),initialImpl:exportedValue,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:moduleID||file.moduleID,sourceFolder});api[categoryName]=wrapper.createProxy();targetApi=api[categoryName]}else{this.slothlet.debug("modes",{key:"DEBUG_MODE_SINGLE_FILE_FOLDER_WRAPPED",categoryName,implKeys:Object.keys(exportedValue)})}for(const key of Object.keys(exportedValue)){if(this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath:buildApiPath(`${categoryName}.${key}`),source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}continue}}else if(analysis.hasDefault){const namedKeys=moduleKeys.length>0?moduleKeys:Object.keys(mod).filter(key=>key!=="default");const callableModule=typeof mod.default==="function"?this.slothlet.helpers.modesUtils.ensureNamedExportFunction(mod.default,categoryName):moduleContent;if(namedKeys.length>0){for(const key of namedKeys){if(key in callableModule){continue}if(!this.slothlet.processors.flatten.shouldAttachNamedExport(key,mod[key],callableModule,mod.default)){continue}callableModule[key]=mod[key]}}const modes_carryWinners=new Set;const existingCategory=api[categoryName];const existingCategoryW=resolveWrapper(existingCategory);const modes_samePreviousModule=existingCategoryW?.____slothletInternal?.filePath===file.path;const modes_eagerCollisionMode=collisionModeOverride||(collisionContext==="initial"?this.slothlet.config.collision?.initial:this.slothlet.config.collision?.api)||"merge";if(existingCategory&&!modes_samePreviousModule&&typeof existingCategory==="function"&&(modes_eagerCollisionMode==="merge"||modes_eagerCollisionMode==="warn")){for(const namedKey of namedKeys){if(!Object.prototype.hasOwnProperty.call(existingCategory,namedKey)){existingCategory[namedKey]=mod[namedKey]}}targetApi=existingCategory;continue}if(existingCategory&&!modes_samePreviousModule&&modes_eagerCollisionMode!=="replace"&&(typeof existingCategory==="object"||typeof existingCategory==="function")){for(const existingKey of Object.keys(existingCategory)){const existingKeyOnCallable=Object.prototype.hasOwnProperty.call(callableModule,existingKey);if(modes_eagerCollisionMode==="merge-replace"&&existingKeyOnCallable){continue}if(existingKeyOnCallable){modes_carryWinners.add(existingKey)}callableModule[existingKey]=existingCategory[existingKey]}}moduleContent=callableModule;if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:buildApiPath(categoryName),initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(callableModule,mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:moduleID||file.moduleID,sourceFolder});api[categoryName]=wrapper.createProxy();targetApi=api[categoryName]}else{api[categoryName]=moduleContent;targetApi=api[categoryName]}const needsSeparateNamedExports=typeof mod.default==="function";if(needsSeparateNamedExports&&namedKeys.length>0){for(const key of namedKeys){if(modes_carryWinners.has(key)){continue}const modes_namedApiPath=buildApiPath(`${categoryName}.${key}`);const modes_namedModuleID=moduleID||file.moduleID;const modes_namedAssigned=await this.#assignWithRoutineRevert(modes_namedApiPath,modes_namedModuleID,registerWrapper=>{if(shouldWrap){const namedWrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_namedApiPath,initialImpl:mod[key],materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_namedModuleID,sourceFolder});registerWrapper(namedWrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,namedWrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,mod[key],{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_namedAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath:buildApiPath(`${categoryName}.${key}`),source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}}if(this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath:buildApiPath(categoryName),source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}continue}else if(moduleKeys.length>0){const hasMatchingObject=moduleKeys.some(key=>key===moduleName&&typeof mod[key]==="object"&&mod[key]!==null&&!Array.isArray(mod[key]));if(hasMatchingObject){const matchingObj=mod[moduleName];for(const[propKey,propValue]of Object.entries(matchingObj)){const modes_hybridApiPath=buildApiPath(`${categoryName}.${propKey}`);const modes_hybridModuleID=moduleID||file.moduleID;const modes_hybridAssigned=await this.#assignWithRoutineRevert(modes_hybridApiPath,modes_hybridModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_hybridApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(propValue,mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_hybridModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,propKey,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,propKey,propValue,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_hybridAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_hybridModuleID,apiPath:modes_hybridApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}for(const key of moduleKeys){if(key!==moduleName){const modes_hybridOtherApiPath=buildApiPath(`${categoryName}.${key}`);const modes_hybridOtherModuleID=moduleID||file.moduleID;const modes_hybridOtherAssigned=await this.#assignWithRoutineRevert(modes_hybridOtherApiPath,modes_hybridOtherModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_hybridOtherApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(mod[key],mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_hybridOtherModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,mod[key],{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_hybridOtherAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_hybridOtherModuleID,apiPath:modes_hybridOtherApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}}}else{if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_FILE",moduleName,categoryName,exportCount:moduleKeys.length});this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_TARGET_STATUS",isWrapper:!!resolveWrapper(targetApi),keysBefore:Object.keys(targetApi)})}for(const key of moduleKeys){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_ASSIGNING",propKey:key})}const modes_multiApiPath=buildApiPath(`${categoryName}.${key}`);const modes_multiModuleID=moduleID||file.moduleID;const modes_multiAssigned=await this.#assignWithRoutineRevert(modes_multiApiPath,modes_multiModuleID,async registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_multiApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(mod[key],mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_multiModuleID,sourceFolder});registerWrapper(wrapper);const assigned=await this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode});if(assigned){this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_ASSIGNED",propKey:key,keysAfter:Object.keys(targetApi)})}else{this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_BLOCKED",propKey:key})}return assigned}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,mod[key],{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_multiAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_multiModuleID,apiPath:modes_multiApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}}continue}}if(!analysis.hasDefault&&moduleKeys.length===1&&!isRoot){const key=moduleKeys[0];const keyValue=mod[key];const isMatchingObject=key===moduleName&&typeof keyValue==="object"&&keyValue!==null&&!Array.isArray(keyValue);if(!isMatchingObject){const normalizedKey=key.toLowerCase().replace(/[-_]/g,"");const normalizedModuleName=moduleName.toLowerCase().replace(/[-_]/g,"");if(normalizedKey===normalizedModuleName){const preferredName=key;const modes_preferredApiPath=buildApiPath(`${categoryName}.${preferredName}`);const modes_preferredModuleID=moduleID||file.moduleID;const modes_preferredAssigned=await this.#assignWithRoutineRevert(modes_preferredApiPath,modes_preferredModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_preferredApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(mod[key],mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_preferredModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,preferredName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,preferredName,mod[key],{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_preferredAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_preferredModuleID,apiPath:modes_preferredApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}continue}}}if(decision.flattenToRoot&&moduleContent&&!isRoot&&!this.slothlet.config.suppressFixes?.has("C03_116")){const modes_hoistedAssigned=new Set;for(const key of Object.keys(moduleContent)){const value=moduleContent[key];const keyPath=apiPathPrefix?`${apiPathPrefix}.${key}`:`${categoryName}.${key}`;const modes_hoistedApiPath=buildApiPath(keyPath);const modes_hoistedModuleID=moduleID||file.moduleID;const modes_hoistedOneAssigned=await this.#assignWithRoutineRevert(modes_hoistedApiPath,modes_hoistedModuleID,registerWrapper=>{if(shouldWrap&&typeof value==="function"){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_hoistedApiPath,initialImpl:value,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_hoistedModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,value,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_hoistedOneAssigned)modes_hoistedAssigned.add(key)}if(this.slothlet.handlers.ownership){for(const key of Object.keys(moduleContent)){if(!modes_hoistedAssigned.has(key))continue;const apiPath=apiPathPrefix?`${apiPathPrefix}.${key}`:`${categoryName}.${key}`;this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}continue}if(decision.flattenToCategory&&moduleContent&&effectiveCategoryName){const isAddapiFile2=decision.flattenType==="addapi-metadata-default"||decision.flattenType==="addapi-special-file";if(isAddapiFile2&&typeof moduleContent==="object"&&!Array.isArray(moduleContent)&&typeof moduleContent!=="function"){const modes_addapiAssigned=new Set;for(const key of Object.keys(moduleContent)){const value=moduleContent[key];const keyPath=isRoot?key:`${apiPathPrefix?apiPathPrefix+".":""}${key}`;const modes_addapiApiPath=buildApiPath(keyPath);const modes_addapiModuleID=moduleID||file.moduleID;const modes_addapiOneAssigned=await this.#assignWithRoutineRevert(modes_addapiApiPath,modes_addapiModuleID,registerWrapper=>{if(shouldWrap&&typeof value==="function"){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_addapiApiPath,initialImpl:value,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_addapiModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,value,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_addapiOneAssigned)modes_addapiAssigned.add(key)}if(this.slothlet.handlers.ownership){for(const key of Object.keys(moduleContent)){if(!modes_addapiAssigned.has(key))continue;const apiPath=isRoot?key:apiPathPrefix?`${apiPathPrefix}.${key}`:key;this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),config:this.slothlet.config})}}}else{const localPath=populateDirectly?"":effectiveCategoryName;const modes_categoryApiPath=buildApiPath(localPath);const modes_categoryModuleID=moduleID||file.moduleID;const modes_categoryAssigned=await this.#assignWithRoutineRevert(modes_categoryApiPath,modes_categoryModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_categoryApiPath,initialImpl:moduleContent,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_categoryModuleID,sourceFolder,isCallable:typeof moduleContent==="function"});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,effectiveCategoryName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,effectiveCategoryName,moduleContent,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_categoryAssigned&&this.slothlet.handlers.ownership){const apiPath=buildApiPath(localPath);this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),config:this.slothlet.config})}}continue}const modes_propertyApiPath=buildApiPath(isRoot?propertyName:`${categoryName}.${propertyName}`);const modes_propertyModuleID=moduleID||file.moduleID;const modes_propertyAssigned=await this.#assignWithRoutineRevert(modes_propertyApiPath,modes_propertyModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_propertyApiPath,initialImpl:moduleContent,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_propertyModuleID,sourceFolder});registerWrapper(wrapper);this.slothlet.debug("modes",{key:"DEBUG_MODE_FILE_WRAPPER_ASSIGNMENT",propertyName,apiPath:modes_propertyApiPath,overwriting:propertyName in targetApi?resolveWrapper(targetApi[propertyName])?"wrapper":"value":"nothing"});return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,propertyName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,propertyName,moduleContent,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(this.slothlet.config.debug?.modes&&categoryName==="logger"){this.slothlet.debug("modes",{key:"DEBUG_MODE_AFTER_ASSIGNMENT_STATUS",targetApiType:typeof targetApi,propertyName,hasProperty:propertyName in targetApi,implType:typeof resolveWrapper(targetApi)?.____slothletInternal.impl,implHasProperty:!!resolveWrapper(targetApi)?.____slothletInternal.impl?.utils})}if(modes_propertyAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_propertyModuleID,apiPath:modes_propertyApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),config:this.slothlet.config})}}}if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_SUBDIRECTORY_CHECK",isRoot,categoryName,hasDirectory:!!directory,hasChildren:!!directory?.children,directoryCount:directory?.children?.directories?.length||0})}this.slothlet.debug("modes",{key:"DEBUG_MODE_DIRECTORY_CHECK",hasChildren:!!directory?.children,hasDirectories:!!directory?.children?.directories,length:directory?.children?.directories?.length||0});if(directory?.children?.directories){this.slothlet.debug("modes",{key:"DEBUG_MODE_DIRECTORY_CHECK_PASSED",recursive});if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_SUBDIRECTORIES_FOUND",subdirectoryCount:directory.children.directories.length,recursive})}if(recursive){this.slothlet.debug("modes",{key:"DEBUG_MODE_SUBDIRECTORY_LOOP_START",count:directory.children.directories.length});for(const subDir of directory.children.directories){this.slothlet.debug("modes",{key:"DEBUG_MODE_PROCESSING_SUBDIRECTORY",name:subDir.name,fileCount:subDir.children.files.length,subdirCount:subDir.children.directories.length});const subDirName=this.slothlet.helpers.sanitize.sanitizePropertyName(subDir.name);if(subDir.children.files.length===1&&subDir.children.directories.length===0){const file=subDir.children.files[0];const moduleName=this.slothlet.helpers.sanitize.sanitizePropertyName(file.name);const genericFilenames=["singlefile","index","main","default"];const isGeneric=genericFilenames.includes(moduleName.toLowerCase());const filenameMatchesFolder=moduleName===subDirName;if(isGeneric||filenameMatchesFolder){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_LEVEL_FLATTEN_CHECK",subDir:subDirName,file:moduleName,isGeneric,filenameMatches:filenameMatchesFolder});const mod=await this.slothlet.processors.loader.loadModule(file.path,this.slothlet.instanceID,moduleID,cacheBust);const exports=this.slothlet.processors.loader.extractExports(mod);const moduleKeys=Object.keys(exports).filter(k=>k!=="default");const analysis={hasDefault:exports.default!==void 0,hasNamed:moduleKeys.length>0,defaultExportType:exports.default?typeof exports.default:null};const modContent=exports.default!==void 0?exports.default:exports;const categoryDecision=await this.slothlet.processors.flatten.buildCategoryDecisions({categoryName:subDirName,mod:modContent,moduleName,fileBaseName:file.name,analysis,moduleKeys,currentDepth:currentDepth+1,moduleFiles:subDir.children.files,t});if(categoryDecision.shouldFlatten){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_LEVEL_FLATTEN_SKIP_RECURSION",subDir:subDirName});let implToWrap;if(categoryDecision.flattenType==="addapi-metadata-default"){implToWrap={};for(const key of moduleKeys){if(key!=="default"){implToWrap[key]=exports[key]}}}else if(moduleName===subDirName&&moduleKeys.includes(subDirName)){implToWrap=exports[subDirName]}else if(exports.default!==void 0){implToWrap=exports.default;if(moduleKeys.length>0){if(typeof implToWrap==="function"){const collisionConfig=this.slothlet.config.api?.collision||this.slothlet.config.collision;const collisionMode=collisionModeOverride||(collisionContext==="initial"?collisionConfig?.initial:collisionConfig?.api)||"merge";for(const key of moduleKeys){if(key!=="default"){const hasExisting=implToWrap[key]!==void 0;if(hasExisting){if(collisionMode==="merge"||collisionMode==="skip"){continue}else if(collisionMode==="error"){throw new this.slothlet.SlothletError("COLLISION_DEFAULT_EXPORT_ERROR",{key,apiPath:`${apiPathPrefix}.${subDirName}`},null,{validationError:true})}else if(collisionMode==="warn"){new this.slothlet.SlothletWarning("WARNING_COLLISION_DEFAULT_EXPORT_OVERWRITE",{key,apiPath:`${apiPathPrefix}.${subDirName}`})}}implToWrap[key]=exports[key]}}}else if(typeof implToWrap==="object"&&implToWrap!==null){for(const key of moduleKeys){if(key!=="default"&&!(key in implToWrap)){implToWrap[key]=exports[key]}}}}}else{implToWrap=modContent}const modes_eagerCollisionConfig=this.slothlet.config.api?.collision||this.slothlet.config.collision;const modes_eagerCollisionMode=collisionModeOverride||(collisionContext==="initial"?modes_eagerCollisionConfig?.initial:modes_eagerCollisionConfig?.api)||"merge";const modes_existingAtKey=targetApi[subDirName];if(modes_existingAtKey!==void 0&&modes_eagerCollisionMode!=="replace"&&modes_eagerCollisionMode!=="skip"){const modes_existingWrapper=resolveWrapper(modes_existingAtKey);if(modes_existingWrapper){if(modes_existingWrapper.____slothletInternal?.materializeFunc&&!modes_existingWrapper.____slothletInternal?.state?.materialized){await modes_existingWrapper._materialize()}if(modes_existingWrapper.____slothletInternal?.impl&&!modes_existingWrapper.____slothletInternal?.state?.childrenAdopted){modes_existingWrapper.___adoptImplChildren()}const modes_existingImpl=modes_existingWrapper.__impl;if(modes_existingImpl&&typeof modes_existingImpl==="object"&&!Array.isArray(modes_existingImpl)){if(typeof implToWrap==="object"&&implToWrap!==null){for(const[k,v]of Object.entries(modes_existingImpl)){if(!(k in implToWrap)){implToWrap[k]=v}}}else if(typeof implToWrap==="function"){for(const[k,v]of Object.entries(modes_existingImpl)){if(implToWrap[k]===void 0){implToWrap[k]=v}}}}const modes_existingChildKeys=Object.keys(modes_existingWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const ck of modes_existingChildKeys){if(typeof implToWrap==="object"&&implToWrap!==null&&!(ck in implToWrap)){implToWrap[ck]=modes_existingWrapper[ck]}else if(typeof implToWrap==="function"&&implToWrap[ck]===void 0){implToWrap[ck]=modes_existingWrapper[ck]}}this.slothlet.debug("modes",{key:"DEBUG_MODE_FILE_FOLDER_COLLISION_MERGED",subDir:subDirName,mergedKeys:Object.keys(implToWrap)})}}const modes_subDirApiPath=buildApiPath(categoryName?`${categoryName}.${subDirName}`:subDirName);const modes_subDirModuleID=moduleID||file.moduleID;const modes_subDirAssigned=await this.#assignWithRoutineRevert(modes_subDirApiPath,modes_subDirModuleID,registerWrapper=>{const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_subDirApiPath,initialImpl:implToWrap,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_subDirModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,subDirName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_subDirAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_subDirModuleID,apiPath:modes_subDirApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),config:this.slothlet.config})}continue}}}const currentCategoryName=apiPathPrefix?apiPathPrefix.split(".").pop():categoryName;if(subDirName===currentCategoryName&&currentCategoryName!==null){await this.processFiles(targetApi,subDir.children.files,subDir,currentDepth+1,mode,false,recursive,true,apiPathPrefix,collisionContext,moduleID,sourceFolder,cacheBust,collisionModeOverride);continue}await this.processFiles(targetApi,subDir.children.files,{name:subDirName,path:subDir.path,children:subDir.children},currentDepth+1,mode,false,recursive,false,childPathPrefix,collisionContext,moduleID,sourceFolder,cacheBust,collisionModeOverride)}}else{for(const subDir of directory.children.directories){const subDirName=this.slothlet.helpers.sanitize.sanitizePropertyName(subDir.name);const lazy_currentCategoryName=apiPathPrefix?apiPathPrefix.split(".").pop():categoryName;if(subDirName===lazy_currentCategoryName&&lazy_currentCategoryName!==null&&!populateDirectly){await this.processFiles(targetApi,subDir.children.files,subDir,currentDepth+1,"eager",false,true,true,apiPathPrefix,collisionContext,moduleID,sourceFolder,cacheBust,collisionModeOverride);continue}const apiPath=buildApiPath(categoryName?`${categoryName}.${subDirName}`:subDirName);if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CREATING_LAZY_SUBDIRECTORY",apiPath,fileCount:subDir.children.files.length})}const collisionConfig=this.slothlet.config.api?.collision;const modes_initialCollisionMode=collisionModeOverride||(collisionContext==="initial"?collisionConfig?.initial:collisionConfig?.api)||"replace";let modes_fileFolderImpl=null;const modes_lazyExisting=targetApi[subDirName];if(modes_initialCollisionMode!=="replace"&&resolveWrapper(modes_lazyExisting)){const modes_lazyExistingW=resolveWrapper(modes_lazyExisting);const existImpl=modes_lazyExistingW.__impl;if(existImpl&&typeof existImpl==="object"&&!Array.isArray(existImpl)){modes_fileFolderImpl={...existImpl}}const existChildKeys=Object.keys(modes_lazyExistingW).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const ck of existChildKeys){if(!modes_fileFolderImpl)modes_fileFolderImpl={};if(!(ck in modes_fileFolderImpl)){modes_fileFolderImpl[ck]=modes_lazyExistingW[ck]}}}await this.#assignWithRoutineRevert(apiPath,moduleID,registerWrapper=>{const lazySubDirProxy=this.createLazySubdirectoryWrapper(subDir,apiPath,moduleID,sourceFolder,cacheBust,modes_fileFolderImpl,modes_initialCollisionMode,collisionContext);registerWrapper(resolveWrapper(lazySubDirProxy));return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,subDirName,lazySubDirProxy,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_initialCollisionMode})});const modes_assignedCollision=resolveWrapper(targetApi[subDirName]);if(modes_assignedCollision?.____slothletInternal.needsImmediateChildAdoption){await modes_assignedCollision._materialize()}const modes_keptCallable=resolveWrapper(targetApi[subDirName]);const modes_offSlotFolder=modes_keptCallable?.____slothletInternal.offSlotCollisionFolder;if(modes_offSlotFolder){await modes_offSlotFolder._materialize();this.slothlet.builders.apiAssignment.mergeOffSlotCollisionFolder(modes_keptCallable)}}}}if(isRoot&&rootContributors.length>0){if(rootContributors.length===1){const{moduleName,file,defaultFunc}=rootContributors[0];rootDefaultFunction=defaultFunc;if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{message:await t("DEBUG_MODE_ROOT_CONTRIBUTOR",{mode,functionName:defaultFunc.name||"anonymous"})})}if(this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath:buildApiPath(moduleName),source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}else{if(!this.____config?.silent){new this.SlothletWarning("WARNING_MULTIPLE_ROOT_CONTRIBUTORS",{rootContributors:rootContributors.map(rc=>rc.moduleName).join(", "),firstContributor:rootContributors[0].moduleName})}await this.emitImplDiagnostic("warning",{apiPath:"",code:"WARNING_MULTIPLE_ROOT_CONTRIBUTORS",context:{rootContributors:rootContributors.map(rc=>rc.moduleName).join(", "),firstContributor:rootContributors[0].moduleName},source:"buildAPI",moduleID});for(const{moduleName,file,defaultFunc}of rootContributors){const modes_rootApiPath=buildApiPath(moduleName);const modes_rootModuleID=moduleID||file.moduleID;const modes_rootAssigned=await this.#assignWithRoutineRevert(modes_rootApiPath,modes_rootModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_rootApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(defaultFunc,mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_rootModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,moduleName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,moduleName,defaultFunc,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_rootAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_rootModuleID,apiPath:modes_rootApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}}}return rootDefaultFunction}createLazySubdirectoryWrapper(dir,apiPath,moduleID=null,sourceFolder=null,cacheBust=null,fileFolderCollisionImpl=null,collisionMode="merge",collisionContext="initial"){const lazy_materializeFunc=this.slothlet.modes.lazy.createNamedMaterializeFunc(apiPath,async()=>{if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_MATERIALIZE_FUNCTION_STARTING",dir:dir.name,fileCount:dir.children.files?.length||0})}const categoryName=this.slothlet.helpers.sanitize.sanitizePropertyName(dir.name);const materialized={};const actualSourceFolder=sourceFolder?`${sourceFolder}/${dir.name}`.replace(/\\/g,"/"):`${this.slothlet.config?.dir}/${dir.name}`.replace(/\\/g,"/");const parentPrefix=apiPath.includes(".")?apiPath.split(".").slice(0,-1).join("."):"";const subDirs=dir.children.directories||[];if(dir.children.files.length===1&&subDirs.length===0){const file=dir.children.files[0];const moduleName=this.slothlet.helpers.sanitize.sanitizePropertyName(file.name);const genericFilenames=["singlefile","index","main","default"];const isGeneric=genericFilenames.includes(moduleName.toLowerCase());const filenameMatchesFolder=moduleName===categoryName;if(isGeneric||filenameMatchesFolder){const mod=await this.slothlet.processors.loader.loadModule(file.path,this.slothlet.instanceID,moduleID,cacheBust);const exports=this.slothlet.processors.loader.extractExports(mod);const moduleKeys=Object.keys(exports).filter(k=>k!=="default");const analysis={hasDefault:exports.default!==void 0,hasNamed:moduleKeys.length>0,defaultExportType:exports.default?typeof exports.default:null};const modContent=exports.default!==void 0?exports.default:exports;const categoryDecision=await this.slothlet.processors.flatten.buildCategoryDecisions({categoryName,mod:modContent,moduleName,fileBaseName:file.name,analysis,moduleKeys,currentDepth:apiPath.split(".").length,moduleFiles:dir.children.files,t});if(categoryDecision.shouldFlatten){let implToWrap;if(categoryDecision.flattenType==="addapi-metadata-default"){implToWrap=exports.default;for(const key of moduleKeys){if(key!=="default"){implToWrap[key]=exports[key]}}}else if(moduleName===categoryName&&moduleKeys.includes(categoryName)){implToWrap=exports[categoryName]}else if(exports.default!==void 0){implToWrap=exports.default;if(moduleKeys.length>0&&(typeof implToWrap==="function"||typeof implToWrap==="object"&&implToWrap!==null)){for(const key of moduleKeys){if(!this.slothlet.processors.flatten.shouldAttachNamedExport(key,exports[key],implToWrap,exports.default)){continue}const hasExisting=Object.prototype.hasOwnProperty.call(implToWrap,key);if(hasExisting){if(collisionMode==="merge"||collisionMode==="skip"){continue}else if(collisionMode==="error"){throw new this.slothlet.SlothletError("COLLISION_DEFAULT_EXPORT_ERROR",{key,apiPath},null,{validationError:true})}else if(collisionMode==="warn"){new this.slothlet.SlothletWarning("WARNING_COLLISION_DEFAULT_EXPORT_OVERWRITE",{key,apiPath})}}implToWrap[key]=exports[key]}}}else{implToWrap=modContent}if(implToWrap&&typeof implToWrap==="object"&&this.slothlet.handlers?.lifecycle){for(const key of Object.keys(implToWrap)){const value=implToWrap[key];if(typeof value==="function"){this.slothlet.handlers.lifecycle.emit("impl:created",{apiPath:`${apiPath}.${key}`,impl:value,wrapper:Object.freeze({__impl:value}),source:"lazy-materialization",moduleID,filePath:file.path,sourceFolder:sourceFolder||this.slothlet.config?.dir})}}}if(implToWrap&&typeof implToWrap==="object"){const childPaths={};for(const key of Object.keys(implToWrap)){if(typeof key!=="symbol"&&key!=="__childFilePaths"&&key!=="__filePath"){childPaths[key]=file.path}}implToWrap.__childFilePaths=childPaths}if(fileFolderCollisionImpl&&typeof implToWrap==="object"&&implToWrap!==null){for(const[k,v]of Object.entries(fileFolderCollisionImpl)){if(!(k in implToWrap)){implToWrap[k]=v}}}else if(fileFolderCollisionImpl&&typeof implToWrap==="function"){for(const[k,v]of Object.entries(fileFolderCollisionImpl)){if(implToWrap[k]===void 0){implToWrap[k]=v}}}return implToWrap}}}await this.processFiles(materialized,dir.children.files,{name:dir.name,children:dir.children},0,"eager",false,false,true,parentPrefix,collisionContext,moduleID,actualSourceFolder,cacheBust,collisionMode);if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_MATERIALIZE_FUNCTION_RETURNING_IMPL",dir:dir.name,keys:Object.keys(materialized)})}if(fileFolderCollisionImpl){for(const[k,v]of Object.entries(fileFolderCollisionImpl)){if(!(k in materialized)){materialized[k]=v}}}const materializedKeys=Object.keys(materialized);const _hasCategoryFile=dir.children.files.some(f=>this.slothlet.helpers.sanitize.sanitizePropertyName(f.name)===categoryName);if(_hasCategoryFile&&materializedKeys.includes(categoryName)&&materializedKeys.length>1){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_PATTERN_MATCH",dir:dir.name,categoryName,keys:materializedKeys})}let mainValue=materialized[categoryName];const mainValueW=resolveWrapper(mainValue);const extractedImpl=mainValueW?UnifiedWrapper._extractFullImpl(mainValueW):null;if(extractedImpl!==null&&extractedImpl!==void 0){mainValue=extractedImpl;if(typeof extractedImpl==="function"){for(const wrapperChildKey of Object.keys(mainValueW)){if(!wrapperChildKey.startsWith("_")&&!Object.prototype.hasOwnProperty.call(extractedImpl,wrapperChildKey)){Object.defineProperty(extractedImpl,wrapperChildKey,{value:mainValueW[wrapperChildKey],writable:false,enumerable:true,configurable:true})}}}}for(const key of materializedKeys){if(key!==categoryName){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_PATTERN_ATTACH_PROPERTY",categoryName,propKey:key,valueType:typeof materialized[key]})}mainValue[key]=materialized[key]}}if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_PATTERN_RETURN",categoryName,keys:Object.keys(mainValue).filter(k=>!k.startsWith("__"))})}return mainValue}if(materializedKeys.length===1&&materializedKeys[0]===categoryName){const nestedValue=materialized[categoryName];if(nestedValue&&resolveWrapper(nestedValue)!==null){const attachedKeys=Object.keys(nestedValue).filter(key=>key!=="____slothletInternal");if(attachedKeys.length>0){return nestedValue}return nestedValue.__impl??nestedValue}else{return nestedValue}}return materialized});const wrapper=new UnifiedWrapper(this.slothlet,{mode:"lazy",apiPath,materializeFunc:lazy_materializeFunc,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:dir.path,moduleID,sourceFolder});if(collisionMode){wrapper.____slothletInternal.state.collisionMode=collisionMode}const shouldPrePopulate=collisionMode==="merge"||collisionMode==="warn";if(fileFolderCollisionImpl&&shouldPrePopulate){for(const[k,v]of Object.entries(fileFolderCollisionImpl)){if(typeof k==="string"&&!k.startsWith("_")&&!k.startsWith("__")){Object.defineProperty(wrapper,k,{value:v,writable:false,enumerable:true,configurable:true})}}}return wrapper.createProxy()}async applyRootContributor(api,rootFunction,mode){if(rootFunction){Object.assign(rootFunction,api);if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{message:await t("DEBUG_MODE_ROOT_CONTRIBUTOR_APPLIED",{mode,properties:Object.keys(api).length})})}return rootFunction}return api}}export{ModesProcessor};
17
+ import{ComponentBase}from"#factories/component-base";import{t}from"@cldmv/slothlet/i18n";import{UnifiedWrapper,resolveWrapper}from"#handlers/unified-wrapper";import{getInstanceToken}from"#handlers/lifecycle-token";class ModesProcessor extends ComponentBase{static slothletProperty="modesProcessor";constructor(slothlet){super(slothlet)}#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext){const resolved=collisionModeOverride||this.slothlet.helpers.modesUtils.getOwnershipCollisionMode(this.slothlet.config,collisionContext);return resolved==="replace"||resolved==="merge-replace"?resolved:"merge"}async#assignWithRoutineRevert(apiPath,moduleID,assign){const priorFn=this.slothlet.handlers.routineManager?.snapshotRawEntry(apiPath,moduleID);const priorOwnershipEntry=this.slothlet.handlers.ownership?.snapshotPathEntry(apiPath,moduleID);const priorRawEntries=this.slothlet.handlers.routineManager?.snapshotRawEntries(moduleID)??new Map;const priorOwnershipEntries=this.slothlet.handlers.ownership?.snapshotModuleEntries(moduleID)??new Map;let constructedWrapper=null;const registerWrapper=wrapper=>{constructedWrapper=wrapper};const revert=()=>{if(constructedWrapper){this.slothlet.handlers.routineManager?.revertSpeculativeSubtree(constructedWrapper,moduleID,apiPath,priorRawEntries);this.slothlet.handlers.ownership?.revertSpeculativeSubtree(constructedWrapper,moduleID,apiPath,priorOwnershipEntries);this.slothlet.handlers.apiManager?.invalidateSpeculativeWrappers(constructedWrapper)}else{this.slothlet.handlers.routineManager?.revertRawEntry(apiPath,moduleID,priorFn);this.#revertOwnershipEntry(apiPath,moduleID,priorOwnershipEntry)}};let assigned;try{assigned=await assign(registerWrapper)}catch(err){revert();throw err}if(!assigned){revert()}return assigned}#revertOwnershipEntry(apiPath,moduleID,priorOwnershipEntry){const ownership=this.slothlet.handlers.ownership;if(!ownership)return;if(priorOwnershipEntry)ownership.restoreEntry(moduleID,apiPath,priorOwnershipEntry);else ownership.removePath(apiPath,moduleID)}async processFiles(api,files,directory,currentDepth,mode,isRoot,recursive,populateDirectly=false,apiPathPrefix="",collisionContext="initial",moduleID=null,sourceFolder=null,cacheBust=null,collisionModeOverride=null,rootUnwrap=false){const modes_effectiveCollisionMode=collisionModeOverride||(collisionContext==="initial"?this.slothlet.config.collision?.initial:this.slothlet.config.collision?.api)||"replace";const buildApiPath=path=>{if(!path)return apiPathPrefix;if(!apiPathPrefix)return path;if(path.startsWith(`${apiPathPrefix}.`)){return path}if(isRoot){if(rootUnwrap){const cut=path.indexOf(".");return cut===-1?apiPathPrefix:`${apiPathPrefix}.${path.slice(cut+1)}`}const mountLeaf=apiPathPrefix.split(".").pop();if(path===mountLeaf)return apiPathPrefix;if(path.startsWith(`${mountLeaf}.`))return`${apiPathPrefix}.${path.slice(mountLeaf.length+1)}`}return`${apiPathPrefix}.${path}`};let rootDefaultFunction=null;const rootContributors=[];const categoryName=isRoot&&!populateDirectly?null:this.slothlet.helpers.sanitize.sanitizePropertyName(directory.name);let targetApi=isRoot&&!populateDirectly?api:populateDirectly?api:api[categoryName]=api[categoryName]||{};const childPathPrefix=populateDirectly||!categoryName?apiPathPrefix:buildApiPath(categoryName);const isRootFile=currentDepth===0&&!populateDirectly;const effectiveMode=mode==="lazy"&&isRootFile?"eager":mode;const shouldWrap=!(effectiveMode==="lazy"&&populateDirectly);if(!isRoot&&shouldWrap&&!populateDirectly){const existingTarget=api[categoryName];if(existingTarget&&resolveWrapper(existingTarget)){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_REUSE_EXISTING_WRAPPER",categoryName,apiPath:resolveWrapper(existingTarget)?.apiPath})}targetApi=existingTarget}else if(existingTarget===void 0||typeof existingTarget==="object"&&existingTarget!==null){const initialImpl=resolveWrapper(existingTarget)?{}:this.slothlet.helpers.modesUtils.cloneWrapperImpl(existingTarget||{},mode);if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_WRAPPER_CREATED",categoryName,apiPath:buildApiPath(categoryName)})}const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:buildApiPath(categoryName),initialImpl,filePath:directory.path,moduleID:moduleID||categoryName,sourceFolder});api[categoryName]=wrapper.createProxy();if(this.slothlet.handlers?.metadata){this.slothlet.handlers.metadata.tagSystemMetadata(wrapper,{filePath:directory.path,apiPath:buildApiPath(categoryName),moduleID:moduleID||"base",sourceFolder:sourceFolder||directory.path},getInstanceToken(this.slothlet))}if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_WRAPPER_ASSIGNED",categoryName})}targetApi=api[categoryName];if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_CREATED",categoryName,apiPath:wrapper.apiPath});this.slothlet.debug("modes",{key:"DEBUG_MODE_CATEGORY_TARGET_API_STATUS",isWrapper:!!resolveWrapper(targetApi),targetApiKeys:Object.keys(targetApi)})}}}if(!isRoot&&this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{message:await t("DEBUG_MODE_PROCESSING_DIRECTORY",{mode,categoryName,currentDepth})})}const loadedModules=[];for(const file of files){if(this.slothlet.config.debug?.modes&&categoryName==="string"){this.slothlet.debug("modes",{key:"DEBUG_MODE_PROCESSING_FILE",categoryName,file:file.name,isRoot,populateDirectly,mode})}try{const exports=file.synthetic?file.exports:this.slothlet.processors.loader.extractExports(await this.slothlet.processors.loader.loadModule(file.path,this.slothlet.instanceID,moduleID,cacheBust));const moduleName=this.slothlet.helpers.sanitize.sanitizePropertyName(file.name);const moduleKeys=Object.keys(exports).filter(k=>k!=="default");const analysis={hasDefault:exports.default!==void 0,hasNamed:moduleKeys.length>0,defaultExportType:exports.default?typeof exports.default:null};loadedModules.push({file,mod:exports,moduleName,moduleKeys,analysis})}catch(error){if(error.name==="SlothletError")throw error;throw new this.SlothletError("MODULE_LOAD_FAILED",{modulePath:file.path,moduleID:moduleID||file.moduleID},error)}}const hasMultipleDefaults=loadedModules.filter(m=>m.analysis.hasDefault).length>1;for(const{file,mod,moduleName,moduleKeys,analysis}of loadedModules){if(this.slothlet.config.debug?.modes&&categoryName==="logger"){this.slothlet.debug("modes",{key:"DEBUG_MODE_PROCESSING_MODULE",categoryName,moduleName,hasDefault:analysis.hasDefault,moduleKeys,targetApiType:typeof targetApi,targetApiCallable:typeof targetApi==="function"})}const isAddapiFile=moduleName==="addapi"||file.name==="addapi"||file.fullName&&["addapi.mjs","addapi.cjs","addapi.js","addapi.ts"].includes(file.fullName.toLowerCase());const isAddapiObjectDefault=isAddapiFile&&analysis.hasDefault&&typeof mod.default!=="function";const isRootContributor=isRoot&&analysis.hasDefault&&typeof mod.default==="function"&&!isAddapiObjectDefault;if(moduleName==="config"||moduleKeys.some(k=>k.includes("Config")||k.includes("config"))){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FILE_PROCESSING",module:moduleName,category:categoryName||"(none)",isRoot,hasDefault:analysis.hasDefault,moduleKeys})}}if(isRootContributor){const defaultFunc=this.slothlet.helpers.modesUtils.ensureNamedExportFunction(mod.default,moduleName);for(const key of moduleKeys){if(!this.slothlet.processors.flatten.shouldAttachNamedExport(key,mod[key],defaultFunc,mod.default)){continue}defaultFunc[key]=mod[key]}rootContributors.push({moduleName,file,defaultFunc});continue}else{const decision=await this.slothlet.processors.flatten.getFlatteningDecision({mod,moduleName,categoryName:categoryName||moduleName,analysis,hasMultipleDefaults,moduleKeys,t});if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{message:await t("DEBUG_MODE_MODULE_DECISION",{mode,moduleName,reason:decision.reason})})}const propertyName=decision.preferredName||moduleName;const effectiveCategoryName=categoryName||moduleName;let{moduleContent}=this.slothlet.processors.flatten.processModuleForAPI({mod,decision,moduleName,propertyName,moduleKeys,analysis,file,collisionContext,apiPathPrefix:apiPathPrefix||"",collisionModeOverride:modes_effectiveCollisionMode});if(!isRoot&&moduleName===categoryName){if(moduleKeys.length===1&&moduleKeys[0]===moduleName&&!analysis.hasDefault){const exportedValue=mod[moduleName];if(typeof exportedValue==="object"&&exportedValue!==null){if(this.slothlet.config.debug?.modes&&categoryName==="string"){this.slothlet.debug("modes",{key:"DEBUG_MODE_SINGLE_FILE_FOLDER_DETECTED",categoryName,populateDirectly,isRoot,mode,exportKeys:Object.keys(exportedValue)})}if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:buildApiPath(categoryName),initialImpl:exportedValue,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:moduleID||file.moduleID,sourceFolder});api[categoryName]=wrapper.createProxy();targetApi=api[categoryName]}else{this.slothlet.debug("modes",{key:"DEBUG_MODE_SINGLE_FILE_FOLDER_WRAPPED",categoryName,implKeys:Object.keys(exportedValue)})}for(const key of Object.keys(exportedValue)){if(this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath:buildApiPath(`${categoryName}.${key}`),source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}continue}}else if(analysis.hasDefault){const namedKeys=moduleKeys.length>0?moduleKeys:Object.keys(mod).filter(key=>key!=="default");const callableModule=typeof mod.default==="function"?this.slothlet.helpers.modesUtils.ensureNamedExportFunction(mod.default,categoryName):moduleContent;if(namedKeys.length>0){for(const key of namedKeys){if(key in callableModule){continue}if(!this.slothlet.processors.flatten.shouldAttachNamedExport(key,mod[key],callableModule,mod.default)){continue}callableModule[key]=mod[key]}}const modes_carryWinners=new Set;const existingCategory=api[categoryName];const existingCategoryW=resolveWrapper(existingCategory);const modes_samePreviousModule=existingCategoryW?.____slothletInternal?.filePath===file.path;const modes_eagerCollisionMode=collisionModeOverride||(collisionContext==="initial"?this.slothlet.config.collision?.initial:this.slothlet.config.collision?.api)||"merge";if(existingCategory&&!modes_samePreviousModule&&typeof existingCategory==="function"&&(modes_eagerCollisionMode==="merge"||modes_eagerCollisionMode==="warn")){for(const namedKey of namedKeys){if(!Object.prototype.hasOwnProperty.call(existingCategory,namedKey)){existingCategory[namedKey]=mod[namedKey]}}targetApi=existingCategory;continue}if(existingCategory&&!modes_samePreviousModule&&modes_eagerCollisionMode!=="replace"&&(typeof existingCategory==="object"||typeof existingCategory==="function")){for(const existingKey of Object.keys(existingCategory)){const existingKeyOnCallable=Object.prototype.hasOwnProperty.call(callableModule,existingKey);if(modes_eagerCollisionMode==="merge-replace"&&existingKeyOnCallable){continue}if(existingKeyOnCallable){modes_carryWinners.add(existingKey)}callableModule[existingKey]=existingCategory[existingKey]}}moduleContent=callableModule;if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:buildApiPath(categoryName),initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(callableModule,mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:moduleID||file.moduleID,sourceFolder});api[categoryName]=wrapper.createProxy();targetApi=api[categoryName]}else{api[categoryName]=moduleContent;targetApi=api[categoryName]}const needsSeparateNamedExports=typeof mod.default==="function";if(needsSeparateNamedExports&&namedKeys.length>0){for(const key of namedKeys){if(modes_carryWinners.has(key)){continue}const modes_namedApiPath=buildApiPath(`${categoryName}.${key}`);const modes_namedModuleID=moduleID||file.moduleID;const modes_namedAssigned=await this.#assignWithRoutineRevert(modes_namedApiPath,modes_namedModuleID,registerWrapper=>{if(shouldWrap){const namedWrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_namedApiPath,initialImpl:mod[key],materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_namedModuleID,sourceFolder});registerWrapper(namedWrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,namedWrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,mod[key],{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_namedAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath:buildApiPath(`${categoryName}.${key}`),source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}}if(this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath:buildApiPath(categoryName),source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}continue}else if(moduleKeys.length>0){const hasMatchingObject=moduleKeys.some(key=>key===moduleName&&typeof mod[key]==="object"&&mod[key]!==null&&!Array.isArray(mod[key]));if(hasMatchingObject){const matchingObj=mod[moduleName];for(const[propKey,propValue]of Object.entries(matchingObj)){const modes_hybridApiPath=buildApiPath(`${categoryName}.${propKey}`);const modes_hybridModuleID=moduleID||file.moduleID;const modes_hybridAssigned=await this.#assignWithRoutineRevert(modes_hybridApiPath,modes_hybridModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_hybridApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(propValue,mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_hybridModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,propKey,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,propKey,propValue,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_hybridAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_hybridModuleID,apiPath:modes_hybridApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}for(const key of moduleKeys){if(key!==moduleName){const modes_hybridOtherApiPath=buildApiPath(`${categoryName}.${key}`);const modes_hybridOtherModuleID=moduleID||file.moduleID;const modes_hybridOtherAssigned=await this.#assignWithRoutineRevert(modes_hybridOtherApiPath,modes_hybridOtherModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_hybridOtherApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(mod[key],mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_hybridOtherModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,mod[key],{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_hybridOtherAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_hybridOtherModuleID,apiPath:modes_hybridOtherApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}}}else{if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_FILE",moduleName,categoryName,exportCount:moduleKeys.length});this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_TARGET_STATUS",isWrapper:!!resolveWrapper(targetApi),keysBefore:Object.keys(targetApi)})}for(const key of moduleKeys){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_ASSIGNING",propKey:key})}const modes_multiApiPath=buildApiPath(`${categoryName}.${key}`);const modes_multiModuleID=moduleID||file.moduleID;const modes_multiAssigned=await this.#assignWithRoutineRevert(modes_multiApiPath,modes_multiModuleID,async registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_multiApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(mod[key],mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_multiModuleID,sourceFolder});registerWrapper(wrapper);const assigned=await this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode});if(assigned){this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_ASSIGNED",propKey:key,keysAfter:Object.keys(targetApi)})}else{this.slothlet.debug("modes",{key:"DEBUG_MODE_FLATTEN_MULTI_EXPORT_BLOCKED",propKey:key})}return assigned}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,mod[key],{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_multiAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_multiModuleID,apiPath:modes_multiApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}}continue}}if(!analysis.hasDefault&&moduleKeys.length===1&&!isRoot){const key=moduleKeys[0];const keyValue=mod[key];const isMatchingObject=key===moduleName&&typeof keyValue==="object"&&keyValue!==null&&!Array.isArray(keyValue);if(!isMatchingObject){const normalizedKey=key.toLowerCase().replace(/[-_]/g,"");const normalizedModuleName=moduleName.toLowerCase().replace(/[-_]/g,"");if(normalizedKey===normalizedModuleName){const preferredName=key;const modes_preferredApiPath=buildApiPath(`${categoryName}.${preferredName}`);const modes_preferredModuleID=moduleID||file.moduleID;const modes_preferredAssigned=await this.#assignWithRoutineRevert(modes_preferredApiPath,modes_preferredModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_preferredApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(mod[key],mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_preferredModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,preferredName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,preferredName,mod[key],{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_preferredAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_preferredModuleID,apiPath:modes_preferredApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}continue}}}if(decision.flattenToRoot&&moduleContent&&!isRoot&&!this.slothlet.config.suppressFixes?.has("C03_116")){const modes_hoistedAssigned=new Set;for(const key of Object.keys(moduleContent)){const value=moduleContent[key];const keyPath=apiPathPrefix?`${apiPathPrefix}.${key}`:`${categoryName}.${key}`;const modes_hoistedApiPath=buildApiPath(keyPath);const modes_hoistedModuleID=moduleID||file.moduleID;const modes_hoistedOneAssigned=await this.#assignWithRoutineRevert(modes_hoistedApiPath,modes_hoistedModuleID,registerWrapper=>{if(shouldWrap&&typeof value==="function"){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_hoistedApiPath,initialImpl:value,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_hoistedModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,value,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_hoistedOneAssigned)modes_hoistedAssigned.add(key)}if(this.slothlet.handlers.ownership){for(const key of Object.keys(moduleContent)){if(!modes_hoistedAssigned.has(key))continue;const apiPath=apiPathPrefix?`${apiPathPrefix}.${key}`:`${categoryName}.${key}`;this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}continue}if(decision.flattenToCategory&&moduleContent&&effectiveCategoryName){const isAddapiFile2=decision.flattenType==="addapi-metadata-default"||decision.flattenType==="addapi-special-file";if(isAddapiFile2&&typeof moduleContent==="object"&&!Array.isArray(moduleContent)&&typeof moduleContent!=="function"){const modes_addapiAssigned=new Set;for(const key of Object.keys(moduleContent)){const value=moduleContent[key];const keyPath=isRoot?key:`${apiPathPrefix?apiPathPrefix+".":""}${key}`;const modes_addapiApiPath=buildApiPath(keyPath);const modes_addapiModuleID=moduleID||file.moduleID;const modes_addapiOneAssigned=await this.#assignWithRoutineRevert(modes_addapiApiPath,modes_addapiModuleID,registerWrapper=>{if(shouldWrap&&typeof value==="function"){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_addapiApiPath,initialImpl:value,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_addapiModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,key,value,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_addapiOneAssigned)modes_addapiAssigned.add(key)}if(this.slothlet.handlers.ownership){for(const key of Object.keys(moduleContent)){if(!modes_addapiAssigned.has(key))continue;const apiPath=isRoot?key:apiPathPrefix?`${apiPathPrefix}.${key}`:key;this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),config:this.slothlet.config})}}}else{const localPath=populateDirectly?"":effectiveCategoryName;const modes_categoryApiPath=buildApiPath(localPath);const modes_categoryModuleID=moduleID||file.moduleID;const modes_categoryAssigned=await this.#assignWithRoutineRevert(modes_categoryApiPath,modes_categoryModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_categoryApiPath,initialImpl:moduleContent,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_categoryModuleID,sourceFolder,isCallable:typeof moduleContent==="function"});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,effectiveCategoryName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,effectiveCategoryName,moduleContent,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_categoryAssigned&&this.slothlet.handlers.ownership){const apiPath=buildApiPath(localPath);this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),config:this.slothlet.config})}}continue}const modes_propertyApiPath=buildApiPath(isRoot?propertyName:`${categoryName}.${propertyName}`);const modes_propertyModuleID=moduleID||file.moduleID;const modes_propertyAssigned=await this.#assignWithRoutineRevert(modes_propertyApiPath,modes_propertyModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_propertyApiPath,initialImpl:moduleContent,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_propertyModuleID,sourceFolder});registerWrapper(wrapper);this.slothlet.debug("modes",{key:"DEBUG_MODE_FILE_WRAPPER_ASSIGNMENT",propertyName,apiPath:modes_propertyApiPath,overwriting:propertyName in targetApi?resolveWrapper(targetApi[propertyName])?"wrapper":"value":"nothing"});return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,propertyName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,propertyName,moduleContent,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(this.slothlet.config.debug?.modes&&categoryName==="logger"){this.slothlet.debug("modes",{key:"DEBUG_MODE_AFTER_ASSIGNMENT_STATUS",targetApiType:typeof targetApi,propertyName,hasProperty:propertyName in targetApi,implType:typeof resolveWrapper(targetApi)?.____slothletInternal.impl,implHasProperty:!!resolveWrapper(targetApi)?.____slothletInternal.impl?.utils})}if(modes_propertyAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_propertyModuleID,apiPath:modes_propertyApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),config:this.slothlet.config})}}}if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_SUBDIRECTORY_CHECK",isRoot,categoryName,hasDirectory:!!directory,hasChildren:!!directory?.children,directoryCount:directory?.children?.directories?.length||0})}this.slothlet.debug("modes",{key:"DEBUG_MODE_DIRECTORY_CHECK",hasChildren:!!directory?.children,hasDirectories:!!directory?.children?.directories,length:directory?.children?.directories?.length||0});if(directory?.children?.directories){this.slothlet.debug("modes",{key:"DEBUG_MODE_DIRECTORY_CHECK_PASSED",recursive});if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_SUBDIRECTORIES_FOUND",subdirectoryCount:directory.children.directories.length,recursive})}if(recursive){this.slothlet.debug("modes",{key:"DEBUG_MODE_SUBDIRECTORY_LOOP_START",count:directory.children.directories.length});for(const subDir of directory.children.directories){this.slothlet.debug("modes",{key:"DEBUG_MODE_PROCESSING_SUBDIRECTORY",name:subDir.name,fileCount:subDir.children.files.length,subdirCount:subDir.children.directories.length});const subDirName=this.slothlet.helpers.sanitize.sanitizePropertyName(subDir.name);if(subDir.children.files.length===1&&subDir.children.directories.length===0){const file=subDir.children.files[0];const moduleName=this.slothlet.helpers.sanitize.sanitizePropertyName(file.name);const genericFilenames=["singlefile","index","main","default"];const isGeneric=genericFilenames.includes(moduleName.toLowerCase());const filenameMatchesFolder=moduleName===subDirName;if(isGeneric||filenameMatchesFolder){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_LEVEL_FLATTEN_CHECK",subDir:subDirName,file:moduleName,isGeneric,filenameMatches:filenameMatchesFolder});const mod=await this.slothlet.processors.loader.loadModule(file.path,this.slothlet.instanceID,moduleID,cacheBust);const exports=this.slothlet.processors.loader.extractExports(mod);const moduleKeys=Object.keys(exports).filter(k=>k!=="default");const analysis={hasDefault:exports.default!==void 0,hasNamed:moduleKeys.length>0,defaultExportType:exports.default?typeof exports.default:null};const modContent=exports.default!==void 0?exports.default:exports;const categoryDecision=await this.slothlet.processors.flatten.buildCategoryDecisions({categoryName:subDirName,mod:modContent,moduleName,fileBaseName:file.name,analysis,moduleKeys,currentDepth:currentDepth+1,moduleFiles:subDir.children.files,t});if(categoryDecision.shouldFlatten){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_LEVEL_FLATTEN_SKIP_RECURSION",subDir:subDirName});let implToWrap;if(categoryDecision.flattenType==="addapi-metadata-default"){implToWrap={};for(const key of moduleKeys){if(key!=="default"){implToWrap[key]=exports[key]}}}else if(moduleName===subDirName&&moduleKeys.includes(subDirName)){implToWrap=exports[subDirName]}else if(exports.default!==void 0){implToWrap=exports.default;if(moduleKeys.length>0){if(typeof implToWrap==="function"){const collisionConfig=this.slothlet.config.api?.collision||this.slothlet.config.collision;const collisionMode=collisionModeOverride||(collisionContext==="initial"?collisionConfig?.initial:collisionConfig?.api)||"merge";for(const key of moduleKeys){if(key!=="default"){const hasExisting=implToWrap[key]!==void 0;if(hasExisting){if(collisionMode==="merge"||collisionMode==="skip"){continue}else if(collisionMode==="error"){throw new this.slothlet.SlothletError("COLLISION_DEFAULT_EXPORT_ERROR",{key,apiPath:`${apiPathPrefix}.${subDirName}`},null,{validationError:true})}else if(collisionMode==="warn"){new this.slothlet.SlothletWarning("WARNING_COLLISION_DEFAULT_EXPORT_OVERWRITE",{key,apiPath:`${apiPathPrefix}.${subDirName}`})}}implToWrap[key]=exports[key]}}}else if(typeof implToWrap==="object"&&implToWrap!==null){for(const key of moduleKeys){if(key!=="default"&&!(key in implToWrap)){implToWrap[key]=exports[key]}}}}}else{implToWrap=modContent}const modes_eagerCollisionConfig=this.slothlet.config.api?.collision||this.slothlet.config.collision;const modes_eagerCollisionMode=collisionModeOverride||(collisionContext==="initial"?modes_eagerCollisionConfig?.initial:modes_eagerCollisionConfig?.api)||"merge";const modes_existingAtKey=targetApi[subDirName];if(modes_existingAtKey!==void 0&&modes_eagerCollisionMode!=="replace"&&modes_eagerCollisionMode!=="skip"){const modes_existingWrapper=resolveWrapper(modes_existingAtKey);if(modes_existingWrapper){if(modes_existingWrapper.____slothletInternal?.materializeFunc&&!modes_existingWrapper.____slothletInternal?.state?.materialized){await modes_existingWrapper._materialize()}if(modes_existingWrapper.____slothletInternal?.impl&&!modes_existingWrapper.____slothletInternal?.state?.childrenAdopted){modes_existingWrapper.___adoptImplChildren()}const modes_existingImpl=modes_existingWrapper.__impl;if(modes_existingImpl&&typeof modes_existingImpl==="object"&&!Array.isArray(modes_existingImpl)){if(typeof implToWrap==="object"&&implToWrap!==null){for(const[k,v]of Object.entries(modes_existingImpl)){if(!(k in implToWrap)){implToWrap[k]=v}}}else if(typeof implToWrap==="function"){for(const[k,v]of Object.entries(modes_existingImpl)){if(implToWrap[k]===void 0){implToWrap[k]=v}}}}const modes_existingChildKeys=Object.keys(modes_existingWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const ck of modes_existingChildKeys){if(typeof implToWrap==="object"&&implToWrap!==null&&!(ck in implToWrap)){implToWrap[ck]=modes_existingWrapper[ck]}else if(typeof implToWrap==="function"&&implToWrap[ck]===void 0){implToWrap[ck]=modes_existingWrapper[ck]}}this.slothlet.debug("modes",{key:"DEBUG_MODE_FILE_FOLDER_COLLISION_MERGED",subDir:subDirName,mergedKeys:Object.keys(implToWrap)})}}const modes_subDirApiPath=buildApiPath(categoryName?`${categoryName}.${subDirName}`:subDirName);const modes_subDirModuleID=moduleID||file.moduleID;const modes_subDirAssigned=await this.#assignWithRoutineRevert(modes_subDirApiPath,modes_subDirModuleID,registerWrapper=>{const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_subDirApiPath,initialImpl:implToWrap,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_subDirModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,subDirName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_subDirAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_subDirModuleID,apiPath:modes_subDirApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),config:this.slothlet.config})}continue}}}const currentCategoryName=apiPathPrefix?apiPathPrefix.split(".").pop():categoryName;if(subDirName===currentCategoryName&&currentCategoryName!==null){await this.processFiles(targetApi,subDir.children.files,subDir,currentDepth+1,mode,false,recursive,true,apiPathPrefix,collisionContext,moduleID,sourceFolder,cacheBust,collisionModeOverride);continue}await this.processFiles(targetApi,subDir.children.files,{name:subDirName,path:subDir.path,children:subDir.children},currentDepth+1,mode,false,recursive,false,childPathPrefix,collisionContext,moduleID,sourceFolder,cacheBust,collisionModeOverride)}}else{for(const subDir of directory.children.directories){const subDirName=this.slothlet.helpers.sanitize.sanitizePropertyName(subDir.name);const lazy_currentCategoryName=apiPathPrefix?apiPathPrefix.split(".").pop():categoryName;if(subDirName===lazy_currentCategoryName&&lazy_currentCategoryName!==null&&!populateDirectly){await this.processFiles(targetApi,subDir.children.files,subDir,currentDepth+1,"eager",false,true,true,apiPathPrefix,collisionContext,moduleID,sourceFolder,cacheBust,collisionModeOverride);continue}const apiPath=buildApiPath(categoryName?`${categoryName}.${subDirName}`:subDirName);if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_CREATING_LAZY_SUBDIRECTORY",apiPath,fileCount:subDir.children.files.length})}const collisionConfig=this.slothlet.config.api?.collision;const modes_initialCollisionMode=collisionModeOverride||(collisionContext==="initial"?collisionConfig?.initial:collisionConfig?.api)||"replace";let modes_fileFolderImpl=null;const modes_lazyExisting=targetApi[subDirName];if(modes_initialCollisionMode!=="replace"&&resolveWrapper(modes_lazyExisting)){const modes_lazyExistingW=resolveWrapper(modes_lazyExisting);const existImpl=modes_lazyExistingW.__impl;if(existImpl&&typeof existImpl==="object"&&!Array.isArray(existImpl)){modes_fileFolderImpl={...existImpl}}const existChildKeys=Object.keys(modes_lazyExistingW).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const ck of existChildKeys){if(!modes_fileFolderImpl)modes_fileFolderImpl={};if(!(ck in modes_fileFolderImpl)){modes_fileFolderImpl[ck]=modes_lazyExistingW[ck]}}}await this.#assignWithRoutineRevert(apiPath,moduleID,registerWrapper=>{const lazySubDirProxy=this.createLazySubdirectoryWrapper(subDir,apiPath,moduleID,sourceFolder,cacheBust,modes_fileFolderImpl,modes_initialCollisionMode,collisionContext);registerWrapper(resolveWrapper(lazySubDirProxy));return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,subDirName,lazySubDirProxy,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_initialCollisionMode})});const modes_assignedCollision=resolveWrapper(targetApi[subDirName]);if(modes_assignedCollision?.____slothletInternal.needsImmediateChildAdoption){await modes_assignedCollision._materialize()}const modes_keptCallable=resolveWrapper(targetApi[subDirName]);const modes_offSlotFolder=modes_keptCallable?.____slothletInternal.offSlotCollisionFolder;if(modes_offSlotFolder){await modes_offSlotFolder._materialize();this.slothlet.builders.apiAssignment.mergeOffSlotCollisionFolder(modes_keptCallable)}}}}if(isRoot&&rootContributors.length>0){if(rootContributors.length===1){const{moduleName,file,defaultFunc}=rootContributors[0];rootDefaultFunction=defaultFunc;if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{message:await t("DEBUG_MODE_ROOT_CONTRIBUTOR",{mode,functionName:defaultFunc.name||"anonymous"})})}if(this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:moduleID||file.moduleID,apiPath:buildApiPath(moduleName),source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}else{if(!this.____config?.silent){new this.SlothletWarning("WARNING_MULTIPLE_ROOT_CONTRIBUTORS",{rootContributors:rootContributors.map(rc=>rc.moduleName).join(", "),firstContributor:rootContributors[0].moduleName})}await this.emitImplDiagnostic("warning",{apiPath:"",code:"WARNING_MULTIPLE_ROOT_CONTRIBUTORS",context:{rootContributors:rootContributors.map(rc=>rc.moduleName).join(", "),firstContributor:rootContributors[0].moduleName},source:"buildAPI",moduleID});for(const{moduleName,file,defaultFunc}of rootContributors){const modes_rootApiPath=buildApiPath(moduleName);const modes_rootModuleID=moduleID||file.moduleID;const modes_rootAssigned=await this.#assignWithRoutineRevert(modes_rootApiPath,modes_rootModuleID,registerWrapper=>{if(shouldWrap){const wrapper=new UnifiedWrapper(this.slothlet,{mode:effectiveMode,apiPath:modes_rootApiPath,initialImpl:this.slothlet.helpers.modesUtils.cloneWrapperImpl(defaultFunc,mode),materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:file.path,moduleID:modes_rootModuleID,sourceFolder});registerWrapper(wrapper);return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,moduleName,wrapper.createProxy(),{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})}return this.slothlet.builders.apiAssignment.assignToApiPath(targetApi,moduleName,defaultFunc,{useCollisionDetection:true,config:this.slothlet.config,collisionContext,collisionModeOverride:modes_effectiveCollisionMode})});if(modes_rootAssigned&&this.slothlet.handlers.ownership){this.slothlet.handlers.ownership.register({moduleID:modes_rootModuleID,apiPath:modes_rootApiPath,source:"core",collisionMode:this.#resolveOwnershipCollisionMode(collisionModeOverride,collisionContext),filePath:file.path})}}}}return rootDefaultFunction}createLazySubdirectoryWrapper(dir,apiPath,moduleID=null,sourceFolder=null,cacheBust=null,fileFolderCollisionImpl=null,collisionMode="merge",collisionContext="initial"){const lazy_materializeFunc=this.slothlet.modes.lazy.createNamedMaterializeFunc(apiPath,async()=>{if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_MATERIALIZE_FUNCTION_STARTING",dir:dir.name,fileCount:dir.children.files?.length||0})}const categoryName=this.slothlet.helpers.sanitize.sanitizePropertyName(dir.name);const materialized={};const actualSourceFolder=sourceFolder?`${sourceFolder}/${dir.name}`.replace(/\\/g,"/"):`${this.slothlet.config?.dir}/${dir.name}`.replace(/\\/g,"/");const parentPrefix=apiPath.includes(".")?apiPath.split(".").slice(0,-1).join("."):"";const subDirs=dir.children.directories||[];if(dir.children.files.length===1&&subDirs.length===0){const file=dir.children.files[0];const moduleName=this.slothlet.helpers.sanitize.sanitizePropertyName(file.name);const genericFilenames=["singlefile","index","main","default"];const isGeneric=genericFilenames.includes(moduleName.toLowerCase());const filenameMatchesFolder=moduleName===categoryName;if(isGeneric||filenameMatchesFolder){const mod=await this.slothlet.processors.loader.loadModule(file.path,this.slothlet.instanceID,moduleID,cacheBust);const exports=this.slothlet.processors.loader.extractExports(mod);const moduleKeys=Object.keys(exports).filter(k=>k!=="default");const analysis={hasDefault:exports.default!==void 0,hasNamed:moduleKeys.length>0,defaultExportType:exports.default?typeof exports.default:null};const modContent=exports.default!==void 0?exports.default:exports;const categoryDecision=await this.slothlet.processors.flatten.buildCategoryDecisions({categoryName,mod:modContent,moduleName,fileBaseName:file.name,analysis,moduleKeys,currentDepth:apiPath.split(".").length,moduleFiles:dir.children.files,t});if(categoryDecision.shouldFlatten){let implToWrap;if(categoryDecision.flattenType==="addapi-metadata-default"){implToWrap=exports.default;for(const key of moduleKeys){if(key!=="default"){implToWrap[key]=exports[key]}}}else if(moduleName===categoryName&&moduleKeys.includes(categoryName)){implToWrap=exports[categoryName]}else if(exports.default!==void 0){implToWrap=exports.default;if(moduleKeys.length>0&&(typeof implToWrap==="function"||typeof implToWrap==="object"&&implToWrap!==null)){for(const key of moduleKeys){if(!this.slothlet.processors.flatten.shouldAttachNamedExport(key,exports[key],implToWrap,exports.default)){continue}const hasExisting=Object.prototype.hasOwnProperty.call(implToWrap,key);if(hasExisting){if(collisionMode==="merge"||collisionMode==="skip"){continue}else if(collisionMode==="error"){throw new this.slothlet.SlothletError("COLLISION_DEFAULT_EXPORT_ERROR",{key,apiPath},null,{validationError:true})}else if(collisionMode==="warn"){new this.slothlet.SlothletWarning("WARNING_COLLISION_DEFAULT_EXPORT_OVERWRITE",{key,apiPath})}}implToWrap[key]=exports[key]}}}else{implToWrap=modContent}if(implToWrap&&typeof implToWrap==="object"&&this.slothlet.handlers?.lifecycle){for(const key of Object.keys(implToWrap)){const value=implToWrap[key];if(typeof value==="function"){this.slothlet.handlers.lifecycle.emitInternal("impl:created",{apiPath:`${apiPath}.${key}`,wrapper:Object.freeze({__impl:value}),source:"lazy-materialization",moduleID,filePath:file.path,sourceFolder:sourceFolder||this.slothlet.config?.dir})}}}if(implToWrap&&typeof implToWrap==="object"){const childPaths={};for(const key of Object.keys(implToWrap)){if(typeof key!=="symbol"&&key!=="__childFilePaths"&&key!=="__filePath"){childPaths[key]=file.path}}implToWrap.__childFilePaths=childPaths}if(fileFolderCollisionImpl&&typeof implToWrap==="object"&&implToWrap!==null){for(const[k,v]of Object.entries(fileFolderCollisionImpl)){if(!(k in implToWrap)){implToWrap[k]=v}}}else if(fileFolderCollisionImpl&&typeof implToWrap==="function"){for(const[k,v]of Object.entries(fileFolderCollisionImpl)){if(implToWrap[k]===void 0){implToWrap[k]=v}}}return implToWrap}}}await this.processFiles(materialized,dir.children.files,{name:dir.name,children:dir.children},0,"eager",false,false,true,parentPrefix,collisionContext,moduleID,actualSourceFolder,cacheBust,collisionMode);if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_MATERIALIZE_FUNCTION_RETURNING_IMPL",dir:dir.name,keys:Object.keys(materialized)})}if(fileFolderCollisionImpl){for(const[k,v]of Object.entries(fileFolderCollisionImpl)){if(!(k in materialized)){materialized[k]=v}}}const materializedKeys=Object.keys(materialized);const _hasCategoryFile=dir.children.files.some(f=>this.slothlet.helpers.sanitize.sanitizePropertyName(f.name)===categoryName);if(_hasCategoryFile&&materializedKeys.includes(categoryName)&&materializedKeys.length>1){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_PATTERN_MATCH",dir:dir.name,categoryName,keys:materializedKeys})}let mainValue=materialized[categoryName];const mainValueW=resolveWrapper(mainValue);const extractedImpl=mainValueW?UnifiedWrapper._extractFullImpl(mainValueW):null;if(extractedImpl!==null&&extractedImpl!==void 0){mainValue=extractedImpl;if(typeof extractedImpl==="function"){for(const wrapperChildKey of Object.keys(mainValueW)){if(!wrapperChildKey.startsWith("_")&&!Object.prototype.hasOwnProperty.call(extractedImpl,wrapperChildKey)){Object.defineProperty(extractedImpl,wrapperChildKey,{value:mainValueW[wrapperChildKey],writable:false,enumerable:true,configurable:true})}}}}for(const key of materializedKeys){if(key!==categoryName){if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_PATTERN_ATTACH_PROPERTY",categoryName,propKey:key,valueType:typeof materialized[key]})}mainValue[key]=materialized[key]}}if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{key:"DEBUG_MODE_FOLDER_PATTERN_RETURN",categoryName,keys:Object.keys(mainValue).filter(k=>!k.startsWith("__"))})}return mainValue}if(materializedKeys.length===1&&materializedKeys[0]===categoryName){const nestedValue=materialized[categoryName];if(nestedValue&&resolveWrapper(nestedValue)!==null){const attachedKeys=Object.keys(nestedValue).filter(key=>key!=="____slothletInternal");if(attachedKeys.length>0){return nestedValue}return nestedValue.__impl??nestedValue}else{return nestedValue}}return materialized});const wrapper=new UnifiedWrapper(this.slothlet,{mode:"lazy",apiPath,materializeFunc:lazy_materializeFunc,materializeOnCreate:this.slothlet.config.backgroundMaterialize,filePath:dir.path,moduleID,sourceFolder});if(collisionMode){wrapper.____slothletInternal.state.collisionMode=collisionMode}const shouldPrePopulate=collisionMode==="merge"||collisionMode==="warn";if(fileFolderCollisionImpl&&shouldPrePopulate){for(const[k,v]of Object.entries(fileFolderCollisionImpl)){if(typeof k==="string"&&!k.startsWith("_")&&!k.startsWith("__")){Object.defineProperty(wrapper,k,{value:v,writable:false,enumerable:true,configurable:true})}}}return wrapper.createProxy()}async applyRootContributor(api,rootFunction,mode){if(rootFunction){Object.assign(rootFunction,api);if(this.slothlet.config.debug?.modes){this.slothlet.debug("modes",{message:await t("DEBUG_MODE_ROOT_CONTRIBUTOR_APPLIED",{mode,properties:Object.keys(api).length})})}return rootFunction}return api}}export{ModesProcessor};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{ComponentBase}from"#factories/component-base";import{getInstanceToken}from"#handlers/lifecycle-token";class Lifecycle extends ComponentBase{static slothletProperty="lifecycle";constructor(slothlet){super(slothlet);this.subscribers=new Map;this.eventLog=[];this.maxLogSize=1e3}subscribe(event,handler){if(!this.subscribers.has(event)){this.subscribers.set(event,new Set)}this.subscribers.get(event).add(handler);return()=>{const handlers=this.subscribers.get(event);if(handlers){handlers.delete(handler)}}}on(event,handler){return this.subscribe(event,handler)}off(event,handler){const handlers=this.subscribers.get(event);if(handlers){handlers.delete(handler)}}unsubscribe(event,handler){this.off(event,handler)}async emit(event,data){if(this.____config?.debug?.lifecycle){this.eventLog.push({event,data:{...data},timestamp:Date.now()});if(this.eventLog.length>this.maxLogSize){this.eventLog.shift()}this.slothlet.debug("lifecycle",{key:"DEBUG_MODE_LIFECYCLE_EVENT",event,apiPath:data.apiPath,source:data.source,moduleID:data.moduleID})}const handlers=this.subscribers.get(event);if(handlers){const handlerPromises=[];const token=getInstanceToken(this.slothlet);for(const handler of handlers){try{const result=handler(data,token);if(result&&typeof result.then==="function"){handlerPromises.push(result.catch(error=>{if(!this.____config?.silent){new this.SlothletWarning("WARNING_LIFECYCLE_HANDLER_ERROR",{event},error)}}))}}catch(error){if(!this.____config?.silent){new this.SlothletWarning("WARNING_LIFECYCLE_HANDLER_ERROR",{event},error)}}}if(handlerPromises.length>0){await Promise.all(handlerPromises)}}}}export{Lifecycle};
17
+ import{ComponentBase}from"#factories/component-base";import{getInstanceToken}from"#handlers/lifecycle-token";class Lifecycle extends ComponentBase{static slothletProperty="lifecycle";constructor(slothlet){super(slothlet);this.subscribers=new Map;this.internalSubscribers=new Map;this.eventLog=[];this.maxLogSize=1e3}subscribe(event,handler){if(!this.subscribers.has(event)){this.subscribers.set(event,new Set)}this.subscribers.get(event).add(handler);return()=>{const handlers=this.subscribers.get(event);if(handlers){handlers.delete(handler)}}}on(event,handler){return this.subscribe(event,handler)}subscribeInternal(event,handler){if(!this.internalSubscribers.has(event)){this.internalSubscribers.set(event,new Set)}this.internalSubscribers.get(event).add(handler);return()=>{const handlers=this.internalSubscribers.get(event);if(handlers){handlers.delete(handler)}}}off(event,handler){const handlers=this.subscribers.get(event);if(handlers){handlers.delete(handler)}}unsubscribe(event,handler){this.off(event,handler)}async emit(event,data){this.#logEvent(event,data);await this.#notify(this.subscribers.get(event),event,data)}async emitInternal(event,data){this.#logEvent(event,data);await this.#notify(this.internalSubscribers.get(event),event,data)}#logEvent(event,data){if(this.____config?.debug?.lifecycle){this.eventLog.push({event,data:{...data},timestamp:Date.now()});if(this.eventLog.length>this.maxLogSize){this.eventLog.shift()}this.slothlet.debug("lifecycle",{key:"DEBUG_MODE_LIFECYCLE_EVENT",event,apiPath:data.apiPath,source:data.source,moduleID:data.moduleID})}}async#notify(handlers,event,data){if(!handlers)return;const handlerPromises=[];const token=getInstanceToken(this.slothlet);for(const handler of handlers){try{const result=handler(data,token);if(result&&typeof result.then==="function"){handlerPromises.push(result.catch(error=>{if(!this.____config?.silent){new this.SlothletWarning("WARNING_LIFECYCLE_HANDLER_ERROR",{event},error)}}))}}catch(error){if(!this.____config?.silent){new this.SlothletWarning("WARNING_LIFECYCLE_HANDLER_ERROR",{event},error)}}}if(handlerPromises.length>0){await Promise.all(handlerPromises)}}}export{Lifecycle};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{ComponentBase}from"#factories/component-base";import{SlothletError}from"@cldmv/slothlet/errors";import{resolveWrapper}from"#handlers/unified-wrapper";import{isFrameworkInternal}from"#handlers/framework-internals";import{compilePattern,expandBraces}from"@cldmv/slothlet/helpers/pattern-matcher";const ROOT_BUILTIN_NAMES=new Set(["shutdown","destroy"]);class RoutineManager extends ComponentBase{static slothletProperty="routineManager";constructor(slothlet){super(slothlet);this.raw=[];this.rawWrappers=new Map;this.recording=true;this.patternCache=new Map}reset(){this.raw=[];this.rawWrappers.clear();this.patternCache.clear()}get#routines(){return this.slothlet.config?.routines??[]}#moduleWrappers(moduleID){let inner=this.rawWrappers.get(moduleID);if(!inner){inner=new Map;this.rawWrappers.set(moduleID,inner)}return inner}#findRoutine(name){return this.#routines.find(routine=>routine.name===name)}#compile(pattern){let matcher=this.patternCache.get(pattern);if(!matcher){matcher=compilePattern(pattern);this.patternCache.set(pattern,matcher)}return matcher}#matches(routine,entry){const{name,recursive}=routine;if(name.startsWith("^")){return this.#compile(name.slice(1))(entry.apiPath)}const endpoint=this.slothlet.handlers.ownership?.getModuleEndpoint(entry.moduleID);if(endpoint===void 0)return false;let relative;if(endpoint==="."||endpoint==="")relative=entry.apiPath;else if(entry.apiPath===endpoint)relative="";else if(entry.apiPath.startsWith(`${endpoint}.`))relative=entry.apiPath.slice(endpoint.length+1);else return false;if(relative==="")return false;if(this.#compile(name)(relative))return true;return recursive&&this.#compile(`**.${name}`)(relative)}#requiresDescent(routine){if(routine.name.startsWith("^"))return true;if(routine.recursive)return true;return routine.name.includes(".")}#isCurrentOwner(entry){const ownership=this.slothlet.handlers.ownership;if(!ownership)return true;const owner=ownership.getCurrentOwner(entry.apiPath);if(!owner)return true;return owner.moduleID===entry.moduleID}#applyStackFilter(entries){if(this.slothlet.config?.stackRoutines)return entries;return entries.filter(entry=>this.#isCurrentOwner(entry))}#contributorsFor(name){const routine=this.#findRoutine(name);if(!routine)return[];return this.#applyStackFilter(this.raw.filter(entry=>this.#matches(routine,entry)))}#groupByPath(entries){const groups=new Map;for(const entry of entries){let group=groups.get(entry.apiPath);if(!group){group=[];groups.set(entry.apiPath,group)}group.push(entry)}return groups}onImplCreated(data){if(!this.recording)return;if(this.#routines.length===0)return;const apiPath=data?.apiPath;if(typeof apiPath!=="string"||apiPath.length===0)return;const moduleID=data.moduleID;const fn=data.wrapper?.__impl;const existingIndex=this.raw.findIndex(e=>e.apiPath===apiPath&&e.moduleID===moduleID);if(typeof fn==="function"&&fn.__slothletRoutineStack===true){return}if(typeof fn!=="function"){if(existingIndex!==-1)this.raw.splice(existingIndex,1);this.rawWrappers.get(moduleID)?.delete(apiPath);return}const entry={apiPath,moduleID,fn};if(existingIndex===-1)this.raw.push(entry);else this.raw[existingIndex]=entry;const wrapper=resolveWrapper(data.impl);if(wrapper)this.#moduleWrappers(moduleID).set(apiPath,wrapper);setImmediate(()=>{this.#reactivelyPatchStack(entry).catch(()=>{})})}async#reactivelyPatchStack(entry){if(this.slothlet.____buildDepth>0)return;const api=this.slothlet.api;if(!api)return;const lastDot=entry.apiPath.lastIndexOf(".");const parentPath=lastDot===-1?"":entry.apiPath.slice(0,lastDot);const key=lastDot===-1?entry.apiPath:entry.apiPath.slice(lastDot+1);if(parentPath===""&&ROOT_BUILTIN_NAMES.has(key))return;let winner=null;let winnerGroup=null;const matchingRoutines=[];for(const routine of this.#routines){let group;try{group=this.#applyStackFilter(this.raw.filter(e=>e.apiPath===entry.apiPath&&this.#matches(routine,e)))}catch{continue}if(group.length===0)continue;matchingRoutines.push(routine);winner=routine;winnerGroup=group}if(!winner)return;const isCascadeSlot=parentPath===""&&key===winner.name;const contested=matchingRoutines.length>1;if(!isCascadeSlot&&winnerGroup.length<2&&!contested)return;const target=await this.#resolveContainer(api,parentPath);if(target===null||target===void 0||typeof target!=="object"&&typeof target!=="function")return;if(this.slothlet.____buildDepth>0)return;if(this.slothlet.api!==api)return;const targetWrapper=resolveWrapper(target);if(targetWrapper&&targetWrapper.____slothletInternal?.invalid)return;let freshWinnerGroup;try{freshWinnerGroup=this.#applyStackFilter(this.raw.filter(e=>e.apiPath===entry.apiPath&&this.#matches(winner,e)))}catch{return}if(freshWinnerGroup.length===0)return;if(!isCascadeSlot&&freshWinnerGroup.length<2&&!contested)return;if(isCascadeSlot){let current2;try{current2=target[key]}catch{return}if(!(typeof current2==="function"&&current2.__slothletRoutineCascade===true&&current2.__slothletRoutineName===winner.name)){this.recording=false;try{target[key]=this.#buildCascadeCallable(winner.name)}catch{}finally{this.recording=true}}if(api.slothlet&&(typeof api.slothlet==="object"||typeof api.slothlet==="function")){let slothletCurrent;try{slothletCurrent=api.slothlet[key]}catch{return}if(!(typeof slothletCurrent==="function"&&slothletCurrent.__slothletRoutineCascade===true&&slothletCurrent.__slothletRoutineName===winner.name)){this.recording=false;try{api.slothlet[key]=this.#buildCascadeCallable(winner.name)}catch{}finally{this.recording=true}}}return}let current;try{current=target[key]}catch{return}if(typeof current==="function"&&current.__slothletRoutineStack===true&&current.__slothletRoutineName===winner.name){return}this.recording=false;try{target[key]=this.#buildStackedCallable(entry.apiPath,winner)}catch{}finally{this.recording=true}}onImplRemoved(data){const apiPath=data?.apiPath;const moduleID=data?.moduleID;if(typeof apiPath!=="string"||!moduleID)return;this.raw=this.raw.filter(e=>!(e.apiPath===apiPath&&e.moduleID===moduleID));this.rawWrappers.get(moduleID)?.delete(apiPath)}pruneSubtree(apiPath,moduleID){const prefix=`${apiPath}.`;const matching=this.raw.filter(e=>e.moduleID===moduleID&&(e.apiPath===apiPath||e.apiPath.startsWith(prefix)));if(matching.length===0)return;this.raw=this.raw.filter(e=>!matching.includes(e));const moduleWrappers=this.rawWrappers.get(moduleID);if(!moduleWrappers)return;for(const entry of matching){this.slothlet.handlers.apiManager?.invalidateSpeculativeWrappers(moduleWrappers.get(entry.apiPath));moduleWrappers.delete(entry.apiPath)}}pruneModule(moduleID){this.raw=this.raw.filter(e=>e.moduleID!==moduleID);const moduleWrappers=this.rawWrappers.get(moduleID);if(!moduleWrappers)return;for(const wrapper of moduleWrappers.values()){this.slothlet.handlers.apiManager?.invalidateSpeculativeWrappers(wrapper)}this.rawWrappers.delete(moduleID)}snapshotRawEntries(moduleID){const snapshot=new Map;const moduleWrappers=this.rawWrappers.get(moduleID);this.raw.forEach((entry,index)=>{if(entry.moduleID===moduleID)snapshot.set(entry.apiPath,{fn:entry.fn,index,wrapper:moduleWrappers?.get(entry.apiPath)})});return snapshot}snapshotRawEntry(apiPath,moduleID){const index=this.raw.findIndex(e=>e.apiPath===apiPath&&e.moduleID===moduleID);if(index===-1)return void 0;return{fn:this.raw[index].fn,index,wrapper:this.rawWrappers.get(moduleID)?.get(apiPath)}}revertRawEntry(apiPath,moduleID,priorEntry){const idx=this.raw.findIndex(e=>e.apiPath===apiPath&&e.moduleID===moduleID);if(priorEntry!==void 0){const entry={apiPath,moduleID,fn:priorEntry.fn};if(idx!==-1)this.raw[idx]=entry;else this.raw.splice(Math.min(priorEntry.index,this.raw.length),0,entry);if(priorEntry.wrapper)this.#moduleWrappers(moduleID).set(apiPath,priorEntry.wrapper);else this.rawWrappers.get(moduleID)?.delete(apiPath)}else{if(idx!==-1)this.raw.splice(idx,1);this.rawWrappers.get(moduleID)?.delete(apiPath)}}revertSpeculativeSubtree(api,moduleID,path,priorEntries,visited=new WeakSet){if(!api||typeof api!=="object"&&typeof api!=="function")return;if(visited.has(api)){return}visited.add(api);const revert=revertPath=>{const prior=priorEntries.get(revertPath);if(prior){const idx=this.raw.findIndex(e=>e.apiPath===revertPath&&e.moduleID===moduleID);if(idx!==-1)this.raw[idx]={apiPath:revertPath,moduleID,fn:prior.fn};else this.raw.splice(Math.min(prior.index,this.raw.length),0,{apiPath:revertPath,moduleID,fn:prior.fn});if(prior.wrapper)this.#moduleWrappers(moduleID).set(revertPath,prior.wrapper);else this.rawWrappers.get(moduleID)?.delete(revertPath)}else{this.raw=this.raw.filter(e=>!(e.apiPath===revertPath&&e.moduleID===moduleID));this.rawWrappers.get(moduleID)?.delete(revertPath)}};if(path){revert(path)}for(const[key,value]of Object.entries(api)){const skipProps=["__metadata","__type","_materialize","_impl","____slothletInternal"];if(skipProps.includes(key)){continue}const childPath=path?`${path}.${key}`:key;if(typeof value==="function"||value&&typeof value==="object"){revert(childPath);if(typeof value==="object"&&!Array.isArray(value)){this.revertSpeculativeSubtree(value,moduleID,childPath,priorEntries,visited)}}}}revertSpeculativeState(moduleID,priorEntries){const currentEntries=this.raw.filter(e=>e.moduleID===moduleID);const allPaths=new Set([...currentEntries.map(e=>e.apiPath),...priorEntries.keys()]);const moduleWrappers=this.rawWrappers.get(moduleID);for(const path of allPaths){const prior=priorEntries.get(path);const currentEntry=currentEntries.find(e=>e.apiPath===path);if(!currentEntry||currentEntry.fn!==prior?.fn){moduleWrappers?.get(path)?.___invalidate();if(prior?.wrapper)moduleWrappers?.set(path,prior.wrapper);else moduleWrappers?.delete(path)}if(prior){const idx=this.raw.findIndex(e=>e.apiPath===path&&e.moduleID===moduleID);if(idx!==-1)this.raw[idx]={apiPath:path,moduleID,fn:prior.fn};else this.raw.splice(Math.min(prior.index,this.raw.length),0,{apiPath:path,moduleID,fn:prior.fn})}else{this.raw=this.raw.filter(e=>!(e.apiPath===path&&e.moduleID===moduleID))}}}async#runEntries(apiPath,entries,args=[]){const lastDot=apiPath.lastIndexOf(".");const parentPath=lastDot===-1?"":apiPath.slice(0,lastDot);const receiver=parentPath===""?this.slothlet.api:await this.#resolveContainer(this.slothlet.api,parentPath);if(receiver===void 0){return{results:[],failures:[]}}const results=[];const failures=[];const contextManager=this.slothlet.contextManager;const instanceID=this.slothlet.instanceID;const canEnterExtent=contextManager&&typeof contextManager.runInContext==="function"&&contextManager.instances?.has?.(instanceID);for(const{moduleID,fn}of entries){try{if(canEnterExtent){const wrapper=this.rawWrappers.get(moduleID)?.get(apiPath);results.push(await contextManager.runInContext(instanceID,fn,receiver,args,wrapper,true))}else{results.push(await Reflect.apply(fn,receiver,args))}}catch(error){failures.push({apiPath,moduleID,error})}}return{results,failures}}#throwAggregate(failures){const failureEntries=failures.map(({apiPath,moduleID})=>{const entry={apiPath,moduleID};Object.defineProperty(entry,"toString",{value:()=>`${apiPath} (${moduleID})`,enumerable:false});return entry});Object.defineProperty(failureEntries,"toString",{value:()=>failureEntries.map(String).join(", "),enumerable:false});throw new SlothletError("ROUTINE_FAILED",{apiPath:failures[0].apiPath,moduleID:failures[0].moduleID,count:failures.length,failures:failureEntries},failures[0].error)}async runPath(apiPath,args=[],routine=null){if(!this.slothlet.api)return void 0;const pathEntries=this.raw.filter(entry=>entry.apiPath===apiPath);const scopedEntries=routine?pathEntries.filter(entry=>this.#matches(routine,entry)):pathEntries;const entries=this.#applyStackFilter(scopedEntries);const{results,failures}=await this.#runEntries(apiPath,entries,args);if(failures.length>0)this.#throwAggregate(failures);return results.length===1?results[0]:results}async#materializeTree(root){if(!root)return;const seen=new Set;const visit=async(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>15||seen.has(obj))return;seen.add(obj);try{if(isFrameworkInternal(obj))return;const wrapper=resolveWrapper(obj);if(wrapper){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){try{await wrapper._materialize()}catch{return}}for(const key of Object.keys(wrapper)){if(!key.startsWith("____"))await visit(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){await visit(obj[key],depth+1)}}catch{}};const isApiRoot=root===this.slothlet.api;for(const key of Object.keys(root)){if(isApiRoot&&(key==="slothlet"||key==="shutdown"||key==="destroy"))continue;if(key.startsWith("____"))continue;await visit(root[key])}}async#materializeGlobPath(node,segments){if(node===null||node===void 0||segments.length===0)return;const nodeType=typeof node;if(nodeType!=="object"&&nodeType!=="function")return;const nodeWrapper=resolveWrapper(node);if(nodeWrapper&&nodeWrapper.____slothletInternal.mode==="lazy"&&!nodeWrapper.____slothletInternal.state.materialized){try{await nodeWrapper._materialize()}catch{return}}const[segment,...rest]=segments;if(segment==="**"){await this.#materializeTree(node);return}if(!/[*?]/.test(segment)){let child;try{child=node[segment]}catch{return}await this.#materializeGlobPath(child,rest);return}let keys;try{keys=Object.keys(node)}catch{return}const matches=this.#compile(segment);for(const key of keys){if(!matches(key))continue;let child;try{child=node[key]}catch{continue}await this.#materializeGlobPath(child,rest)}}async#materializeFor(routine){if(!this.#requiresDescent(routine))return;if(routine.name.startsWith("^")){await this.#materializeTree(this.slothlet.api);return}const ownership=this.slothlet.handlers.ownership;const endpoints=ownership?new Set(ownership.moduleEndpoints.values()):new Set;if(!routine.recursive&&!routine.name.startsWith("!")){const segmentChains=expandBraces(routine.name).map(alternative=>alternative.split("."));for(const endpoint of endpoints){const mountRoot=endpoint==="."||endpoint===""?this.slothlet.api:await this.#resolveContainer(this.slothlet.api,endpoint);if(mountRoot===null||mountRoot===void 0)continue;for(const segments of segmentChains){await this.#materializeGlobPath(mountRoot,segments)}}return}if(endpoints.has(".")||endpoints.has("")){await this.#materializeTree(this.slothlet.api);return}for(const endpoint of endpoints){const mountRoot=await this.#resolveContainer(this.slothlet.api,endpoint);await this.#materializeTree(mountRoot)}}#orderPaths(apiPaths,order){if(order!=="depth")return apiPaths;return apiPaths.map((apiPath,index)=>({apiPath,index,depth:apiPath.split(".").length})).sort((a,b)=>b.depth-a.depth||a.index-b.index).map(entry=>entry.apiPath)}async runCascade(name,args=[],skipMaterialize=false){if(!this.slothlet.api)return void 0;const routine=this.#findRoutine(name);if(!routine)return void 0;if(!skipMaterialize)await this.#materializeFor(routine);const groups=this.#groupByPath(this.#contributorsFor(name));const orderedPaths=this.#orderPaths([...groups.keys()],routine.order);const results=[];const failures=[];for(const apiPath of orderedPaths){const outcome=await this.#runEntries(apiPath,groups.get(apiPath),args);results.push(outcome.results.length===1?outcome.results[0]:outcome.results);failures.push(...outcome.failures)}if(failures.length>0)this.#throwAggregate(failures);return results.length===1?results[0]:results}async#runModeRoutines(mode){if(!this.slothlet.config?.autoRoutines)return;const routines=this.#routines.filter(routine=>routine.mode===mode);if(routines.length===0)return;for(const routine of routines){await this.#materializeFor(routine)}await this.rebuildStacks(this.slothlet.api);for(const routine of routines){await this.runCascade(routine.name,[],true)}}async runShutdownModeRoutines(){return this.#runModeRoutines("shutdown")}async runDestroyModeRoutines(){return this.#runModeRoutines("destroy")}async runStartupModeRoutines(){return this.#runModeRoutines("startup")}async#resolveContainer(api,path){if(path==="")return api;let node=api;for(const part of path.split(".")){if(node===null||node===void 0)return void 0;try{node=node[part]}catch{return void 0}const wrapper=resolveWrapper(node);if(wrapper&&wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){try{await wrapper._materialize()}catch{return void 0}}}return node}#buildStackedCallable(apiPath,routine){const manager=this;const stacked=async function slothletRoutineStack(...args){return manager.runPath(apiPath,args,routine)};Object.defineProperty(stacked,"__slothletRoutineStack",{value:true,enumerable:false});Object.defineProperty(stacked,"__slothletRoutineName",{value:routine.name,enumerable:false});return stacked}#buildCascadeCallable(name){const manager=this;const cascade=async function slothletRoutineCascade(...args){return manager.runCascade(name,args)};Object.defineProperty(cascade,"__slothletRoutineStack",{value:true,enumerable:false});Object.defineProperty(cascade,"__slothletRoutineCascade",{value:true,enumerable:false});Object.defineProperty(cascade,"__slothletRoutineName",{value:name,enumerable:false});return cascade}async rebuildStacks(api){if(!api||typeof api!=="object"&&typeof api!=="function")return;this.recording=false;try{for(const routine of this.#routines){const groups=this.#groupByPath(this.#contributorsFor(routine.name));for(const apiPath of groups.keys()){const lastDot=apiPath.lastIndexOf(".");const parentPath=lastDot===-1?"":apiPath.slice(0,lastDot);const key=lastDot===-1?apiPath:apiPath.slice(lastDot+1);if(parentPath===""&&ROOT_BUILTIN_NAMES.has(key))continue;if(parentPath===""&&key===routine.name)continue;const target=await this.#resolveContainer(api,parentPath);if(target===null||target===void 0||typeof target!=="object"&&typeof target!=="function")continue;try{target[key]=this.#buildStackedCallable(apiPath,routine)}catch{}}if(ROOT_BUILTIN_NAMES.has(routine.name))continue;const cascade=this.#buildCascadeCallable(routine.name);try{api[routine.name]=cascade}catch{}if(api.slothlet&&(typeof api.slothlet==="object"||typeof api.slothlet==="function")){try{api.slothlet[routine.name]=cascade}catch{}}}}finally{this.recording=true}}}export{RoutineManager};
17
+ import{ComponentBase}from"#factories/component-base";import{SlothletError}from"@cldmv/slothlet/errors";import{resolveWrapper}from"#handlers/unified-wrapper";import{isFrameworkInternal}from"#handlers/framework-internals";import{compilePattern,expandBraces}from"@cldmv/slothlet/helpers/pattern-matcher";const ROOT_BUILTIN_NAMES=new Set(["shutdown","destroy"]);class RoutineManager extends ComponentBase{static slothletProperty="routineManager";constructor(slothlet){super(slothlet);this.raw=[];this.rawWrappers=new Map;this.recording=true;this.patternCache=new Map}reset(){this.raw=[];this.rawWrappers.clear();this.patternCache.clear()}get#routines(){return this.slothlet.config?.routines??[]}#moduleWrappers(moduleID){let inner=this.rawWrappers.get(moduleID);if(!inner){inner=new Map;this.rawWrappers.set(moduleID,inner)}return inner}#findRoutine(name){return this.#routines.find(routine=>routine.name===name)}#compile(pattern){let matcher=this.patternCache.get(pattern);if(!matcher){matcher=compilePattern(pattern);this.patternCache.set(pattern,matcher)}return matcher}#matches(routine,entry){const{name,recursive}=routine;if(name.startsWith("^")){return this.#compile(name.slice(1))(entry.apiPath)}const endpoint=this.slothlet.handlers.ownership?.getModuleEndpoint(entry.moduleID);if(endpoint===void 0)return false;let relative;if(endpoint==="."||endpoint==="")relative=entry.apiPath;else if(entry.apiPath===endpoint)relative="";else if(entry.apiPath.startsWith(`${endpoint}.`))relative=entry.apiPath.slice(endpoint.length+1);else return false;if(relative==="")return false;if(this.#compile(name)(relative))return true;return recursive&&this.#compile(`**.${name}`)(relative)}#requiresDescent(routine){if(routine.name.startsWith("^"))return true;if(routine.recursive)return true;return routine.name.includes(".")}#isCurrentOwner(entry){const ownership=this.slothlet.handlers.ownership;if(!ownership)return true;const owner=ownership.getCurrentOwner(entry.apiPath);if(!owner)return true;return owner.moduleID===entry.moduleID}#applyStackFilter(entries){if(this.slothlet.config?.stackRoutines)return entries;return entries.filter(entry=>this.#isCurrentOwner(entry))}#contributorsFor(name){const routine=this.#findRoutine(name);if(!routine)return[];return this.#applyStackFilter(this.raw.filter(entry=>this.#matches(routine,entry)))}#groupByPath(entries){const groups=new Map;for(const entry of entries){let group=groups.get(entry.apiPath);if(!group){group=[];groups.set(entry.apiPath,group)}group.push(entry)}return groups}onImplCreated(data){if(!this.recording)return;if(this.#routines.length===0)return;const apiPath=data?.apiPath;if(typeof apiPath!=="string"||apiPath.length===0)return;const moduleID=data.moduleID;const fn=data.wrapper?.__impl;const existingIndex=this.raw.findIndex(e=>e.apiPath===apiPath&&e.moduleID===moduleID);if(typeof fn==="function"&&fn.__slothletRoutineStack===true){return}if(typeof fn!=="function"){if(existingIndex!==-1)this.raw.splice(existingIndex,1);this.rawWrappers.get(moduleID)?.delete(apiPath);return}const entry={apiPath,moduleID,fn};if(existingIndex===-1)this.raw.push(entry);else this.raw[existingIndex]=entry;const wrapper=resolveWrapper(data.__wrapperRef);if(wrapper)this.#moduleWrappers(moduleID).set(apiPath,wrapper);setImmediate(()=>{this.#reactivelyPatchStack(entry).catch(()=>{})})}async#reactivelyPatchStack(entry){if(this.slothlet.____buildDepth>0)return;const api=this.slothlet.api;if(!api)return;const lastDot=entry.apiPath.lastIndexOf(".");const parentPath=lastDot===-1?"":entry.apiPath.slice(0,lastDot);const key=lastDot===-1?entry.apiPath:entry.apiPath.slice(lastDot+1);if(parentPath===""&&ROOT_BUILTIN_NAMES.has(key))return;let winner=null;let winnerGroup=null;const matchingRoutines=[];for(const routine of this.#routines){let group;try{group=this.#applyStackFilter(this.raw.filter(e=>e.apiPath===entry.apiPath&&this.#matches(routine,e)))}catch{continue}if(group.length===0)continue;matchingRoutines.push(routine);winner=routine;winnerGroup=group}if(!winner)return;const isCascadeSlot=parentPath===""&&key===winner.name;const contested=matchingRoutines.length>1;if(!isCascadeSlot&&winnerGroup.length<2&&!contested)return;const target=await this.#resolveContainer(api,parentPath);if(target===null||target===void 0||typeof target!=="object"&&typeof target!=="function")return;if(this.slothlet.____buildDepth>0)return;if(this.slothlet.api!==api)return;const targetWrapper=resolveWrapper(target);if(targetWrapper&&targetWrapper.____slothletInternal?.invalid)return;let freshWinnerGroup;try{freshWinnerGroup=this.#applyStackFilter(this.raw.filter(e=>e.apiPath===entry.apiPath&&this.#matches(winner,e)))}catch{return}if(freshWinnerGroup.length===0)return;if(!isCascadeSlot&&freshWinnerGroup.length<2&&!contested)return;if(isCascadeSlot){let current2;try{current2=target[key]}catch{return}if(!(typeof current2==="function"&&current2.__slothletRoutineCascade===true&&current2.__slothletRoutineName===winner.name)){this.recording=false;try{target[key]=this.#buildCascadeCallable(winner.name)}catch{}finally{this.recording=true}}return}let current;try{current=target[key]}catch{return}if(typeof current==="function"&&current.__slothletRoutineStack===true&&current.__slothletRoutineName===winner.name){return}this.recording=false;try{target[key]=this.#buildStackedCallable(entry.apiPath,winner)}catch{}finally{this.recording=true}}onImplRemoved(data){const apiPath=data?.apiPath;const moduleID=data?.moduleID;if(typeof apiPath!=="string"||!moduleID)return;this.raw=this.raw.filter(e=>!(e.apiPath===apiPath&&e.moduleID===moduleID));this.rawWrappers.get(moduleID)?.delete(apiPath)}pruneSubtree(apiPath,moduleID){const prefix=`${apiPath}.`;const matching=this.raw.filter(e=>e.moduleID===moduleID&&(e.apiPath===apiPath||e.apiPath.startsWith(prefix)));if(matching.length===0)return;this.raw=this.raw.filter(e=>!matching.includes(e));const moduleWrappers=this.rawWrappers.get(moduleID);if(!moduleWrappers)return;for(const entry of matching){this.slothlet.handlers.apiManager?.invalidateSpeculativeWrappers(moduleWrappers.get(entry.apiPath));moduleWrappers.delete(entry.apiPath)}}pruneModule(moduleID){this.raw=this.raw.filter(e=>e.moduleID!==moduleID);const moduleWrappers=this.rawWrappers.get(moduleID);if(!moduleWrappers)return;for(const wrapper of moduleWrappers.values()){this.slothlet.handlers.apiManager?.invalidateSpeculativeWrappers(wrapper)}this.rawWrappers.delete(moduleID)}snapshotRawEntries(moduleID){const snapshot=new Map;const moduleWrappers=this.rawWrappers.get(moduleID);this.raw.forEach((entry,index)=>{if(entry.moduleID===moduleID)snapshot.set(entry.apiPath,{fn:entry.fn,index,wrapper:moduleWrappers?.get(entry.apiPath)})});return snapshot}snapshotRawEntry(apiPath,moduleID){const index=this.raw.findIndex(e=>e.apiPath===apiPath&&e.moduleID===moduleID);if(index===-1)return void 0;return{fn:this.raw[index].fn,index,wrapper:this.rawWrappers.get(moduleID)?.get(apiPath)}}revertRawEntry(apiPath,moduleID,priorEntry){const idx=this.raw.findIndex(e=>e.apiPath===apiPath&&e.moduleID===moduleID);if(priorEntry!==void 0){const entry={apiPath,moduleID,fn:priorEntry.fn};if(idx!==-1)this.raw[idx]=entry;else this.raw.splice(Math.min(priorEntry.index,this.raw.length),0,entry);if(priorEntry.wrapper)this.#moduleWrappers(moduleID).set(apiPath,priorEntry.wrapper);else this.rawWrappers.get(moduleID)?.delete(apiPath)}else{if(idx!==-1)this.raw.splice(idx,1);this.rawWrappers.get(moduleID)?.delete(apiPath)}}revertSpeculativeSubtree(api,moduleID,path,priorEntries,visited=new WeakSet){if(!api||typeof api!=="object"&&typeof api!=="function")return;if(visited.has(api)){return}visited.add(api);const revert=revertPath=>{const prior=priorEntries.get(revertPath);if(prior){const idx=this.raw.findIndex(e=>e.apiPath===revertPath&&e.moduleID===moduleID);if(idx!==-1)this.raw[idx]={apiPath:revertPath,moduleID,fn:prior.fn};else this.raw.splice(Math.min(prior.index,this.raw.length),0,{apiPath:revertPath,moduleID,fn:prior.fn});if(prior.wrapper)this.#moduleWrappers(moduleID).set(revertPath,prior.wrapper);else this.rawWrappers.get(moduleID)?.delete(revertPath)}else{this.raw=this.raw.filter(e=>!(e.apiPath===revertPath&&e.moduleID===moduleID));this.rawWrappers.get(moduleID)?.delete(revertPath)}};if(path){revert(path)}for(const[key,value]of Object.entries(api)){const skipProps=["__metadata","__type","_materialize","_impl","____slothletInternal"];if(skipProps.includes(key)){continue}const childPath=path?`${path}.${key}`:key;if(typeof value==="function"||value&&typeof value==="object"){revert(childPath);if(typeof value==="object"&&!Array.isArray(value)){this.revertSpeculativeSubtree(value,moduleID,childPath,priorEntries,visited)}}}}revertSpeculativeState(moduleID,priorEntries){const currentEntries=this.raw.filter(e=>e.moduleID===moduleID);const allPaths=new Set([...currentEntries.map(e=>e.apiPath),...priorEntries.keys()]);const moduleWrappers=this.rawWrappers.get(moduleID);for(const path of allPaths){const prior=priorEntries.get(path);const currentEntry=currentEntries.find(e=>e.apiPath===path);if(!currentEntry||currentEntry.fn!==prior?.fn){moduleWrappers?.get(path)?.___invalidate();if(prior?.wrapper)moduleWrappers?.set(path,prior.wrapper);else moduleWrappers?.delete(path)}if(prior){const idx=this.raw.findIndex(e=>e.apiPath===path&&e.moduleID===moduleID);if(idx!==-1)this.raw[idx]={apiPath:path,moduleID,fn:prior.fn};else this.raw.splice(Math.min(prior.index,this.raw.length),0,{apiPath:path,moduleID,fn:prior.fn})}else{this.raw=this.raw.filter(e=>!(e.apiPath===path&&e.moduleID===moduleID))}}}async#runEntries(apiPath,entries,args=[]){const lastDot=apiPath.lastIndexOf(".");const parentPath=lastDot===-1?"":apiPath.slice(0,lastDot);const receiver=parentPath===""?this.slothlet.api:await this.#resolveContainer(this.slothlet.api,parentPath);if(receiver===void 0){return{results:[],failures:[]}}const results=[];const failures=[];const contextManager=this.slothlet.contextManager;const instanceID=this.slothlet.instanceID;const canEnterExtent=contextManager&&typeof contextManager.runInContext==="function"&&contextManager.instances?.has?.(instanceID);for(const{moduleID,fn}of entries){try{if(canEnterExtent){const wrapper=this.rawWrappers.get(moduleID)?.get(apiPath);results.push(await contextManager.runInContext(instanceID,fn,receiver,args,wrapper,true))}else{results.push(await Reflect.apply(fn,receiver,args))}}catch(error){failures.push({apiPath,moduleID,error})}}return{results,failures}}#throwAggregate(failures){const failureEntries=failures.map(({apiPath,moduleID})=>{const entry={apiPath,moduleID};Object.defineProperty(entry,"toString",{value:()=>`${apiPath} (${moduleID})`,enumerable:false});return entry});Object.defineProperty(failureEntries,"toString",{value:()=>failureEntries.map(String).join(", "),enumerable:false});throw new SlothletError("ROUTINE_FAILED",{apiPath:failures[0].apiPath,moduleID:failures[0].moduleID,count:failures.length,failures:failureEntries},failures[0].error)}async runPath(apiPath,args=[],routine=null){if(!this.slothlet.api)return void 0;const pathEntries=this.raw.filter(entry=>entry.apiPath===apiPath);const scopedEntries=routine?pathEntries.filter(entry=>this.#matches(routine,entry)):pathEntries;const entries=this.#applyStackFilter(scopedEntries);const{results,failures}=await this.#runEntries(apiPath,entries,args);if(failures.length>0)this.#throwAggregate(failures);return results.length===1?results[0]:results}async#materializeTree(root){if(!root)return;const seen=new Set;const visit=async(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>15||seen.has(obj))return;seen.add(obj);try{if(isFrameworkInternal(obj))return;const wrapper=resolveWrapper(obj);if(wrapper){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){try{await wrapper._materialize()}catch{return}}for(const key of Object.keys(wrapper)){if(!key.startsWith("____"))await visit(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){await visit(obj[key],depth+1)}}catch{}};const isApiRoot=root===this.slothlet.api;for(const key of Object.keys(root)){if(isApiRoot&&(key==="slothlet"||key==="shutdown"||key==="destroy"))continue;if(key.startsWith("____"))continue;await visit(root[key])}}async#materializeGlobPath(node,segments){if(node===null||node===void 0||segments.length===0)return;const nodeType=typeof node;if(nodeType!=="object"&&nodeType!=="function")return;const nodeWrapper=resolveWrapper(node);if(nodeWrapper&&nodeWrapper.____slothletInternal.mode==="lazy"&&!nodeWrapper.____slothletInternal.state.materialized){try{await nodeWrapper._materialize()}catch{return}}const[segment,...rest]=segments;if(segment==="**"){await this.#materializeTree(node);return}if(!/[*?]/.test(segment)){let child;try{child=node[segment]}catch{return}await this.#materializeGlobPath(child,rest);return}let keys;try{keys=Object.keys(node)}catch{return}const matches=this.#compile(segment);for(const key of keys){if(!matches(key))continue;let child;try{child=node[key]}catch{continue}await this.#materializeGlobPath(child,rest)}}async#materializeFor(routine){if(!this.#requiresDescent(routine))return;if(routine.name.startsWith("^")){await this.#materializeTree(this.slothlet.api);return}const ownership=this.slothlet.handlers.ownership;const endpoints=ownership?new Set(ownership.moduleEndpoints.values()):new Set;if(!routine.recursive&&!routine.name.startsWith("!")){const segmentChains=expandBraces(routine.name).map(alternative=>alternative.split("."));for(const endpoint of endpoints){const mountRoot=endpoint==="."||endpoint===""?this.slothlet.api:await this.#resolveContainer(this.slothlet.api,endpoint);if(mountRoot===null||mountRoot===void 0)continue;for(const segments of segmentChains){await this.#materializeGlobPath(mountRoot,segments)}}return}if(endpoints.has(".")||endpoints.has("")){await this.#materializeTree(this.slothlet.api);return}for(const endpoint of endpoints){const mountRoot=await this.#resolveContainer(this.slothlet.api,endpoint);await this.#materializeTree(mountRoot)}}#orderPaths(apiPaths,order){if(order!=="depth")return apiPaths;return apiPaths.map((apiPath,index)=>({apiPath,index,depth:apiPath.split(".").length})).sort((a,b)=>b.depth-a.depth||a.index-b.index).map(entry=>entry.apiPath)}async runCascade(name,args=[],skipMaterialize=false){if(!this.slothlet.api)return void 0;const routine=this.#findRoutine(name);if(!routine)return void 0;if(!skipMaterialize)await this.#materializeFor(routine);const groups=this.#groupByPath(this.#contributorsFor(name));const orderedPaths=this.#orderPaths([...groups.keys()],routine.order);const results=[];const failures=[];for(const apiPath of orderedPaths){const outcome=await this.#runEntries(apiPath,groups.get(apiPath),args);results.push(outcome.results.length===1?outcome.results[0]:outcome.results);failures.push(...outcome.failures)}if(failures.length>0)this.#throwAggregate(failures);return results.length===1?results[0]:results}async#runModeRoutines(mode){if(!this.slothlet.config?.autoRoutines)return;const routines=this.#routines.filter(routine=>routine.mode===mode);if(routines.length===0)return;for(const routine of routines){await this.#materializeFor(routine)}await this.rebuildStacks(this.slothlet.api);for(const routine of routines){await this.runCascade(routine.name,[],true)}}async runShutdownModeRoutines(){return this.#runModeRoutines("shutdown")}async runDestroyModeRoutines(){return this.#runModeRoutines("destroy")}async runStartupModeRoutines(){return this.#runModeRoutines("startup")}async#resolveContainer(api,path){if(path==="")return api;let node=api;for(const part of path.split(".")){if(node===null||node===void 0)return void 0;try{node=node[part]}catch{return void 0}const wrapper=resolveWrapper(node);if(wrapper&&wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){try{await wrapper._materialize()}catch{return void 0}}}return node}#buildStackedCallable(apiPath,routine){const manager=this;const stacked=async function slothletRoutineStack(...args){return manager.runPath(apiPath,args,routine)};Object.defineProperty(stacked,"__slothletRoutineStack",{value:true,enumerable:false});Object.defineProperty(stacked,"__slothletRoutineName",{value:routine.name,enumerable:false});return stacked}#buildCascadeCallable(name){const manager=this;const cascade=async function slothletRoutineCascade(...args){return manager.runCascade(name,args)};Object.defineProperty(cascade,"__slothletRoutineStack",{value:true,enumerable:false});Object.defineProperty(cascade,"__slothletRoutineCascade",{value:true,enumerable:false});Object.defineProperty(cascade,"__slothletRoutineName",{value:name,enumerable:false});return cascade}async rebuildStacks(api){if(!api||typeof api!=="object"&&typeof api!=="function")return;this.recording=false;try{for(const routine of this.#routines){const groups=this.#groupByPath(this.#contributorsFor(routine.name));for(const apiPath of groups.keys()){const lastDot=apiPath.lastIndexOf(".");const parentPath=lastDot===-1?"":apiPath.slice(0,lastDot);const key=lastDot===-1?apiPath:apiPath.slice(lastDot+1);if(parentPath===""&&ROOT_BUILTIN_NAMES.has(key))continue;if(parentPath===""&&key===routine.name)continue;const target=await this.#resolveContainer(api,parentPath);if(target===null||target===void 0||typeof target!=="object"&&typeof target!=="function")continue;try{target[key]=this.#buildStackedCallable(apiPath,routine)}catch{}}if(ROOT_BUILTIN_NAMES.has(routine.name))continue;const cascade=this.#buildCascadeCallable(routine.name);try{api[routine.name]=cascade}catch{}}}finally{this.recording=true}}}export{RoutineManager};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- const ____COLLISION_MERGED_PROPERTY=Symbol("collisionMergedProperty");import{isNode,util,EventEmitter}from"@cldmv/slothlet/helpers/platform";import{ComponentBase}from"#factories/component-base";import{TRUSTED_ROOT,genuineWrappers}from"#handlers/trusted-root";import{isFrameworkInternal,isFrameworkMarkerKey}from"#handlers/framework-internals";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");const hasOwn=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);function resolveEnforcedCaller(wrapper,ctxOverride){const ownInstanceID=wrapper.slothlet.instanceID;const ctx=ctxOverride!==void 0?ctxOverride:wrapper.slothlet.contextManager?.tryGetContext?.(ownInstanceID);const identity=ctxOverride!==void 0?ctxOverride:wrapper.slothlet.contextManager?.getCallerIdentity?.(ownInstanceID);if(identity?.unresolved)return{verdict:"deny"};const callerWrapper=identity?.currentWrapper;if(!callerWrapper){const store=ctx??wrapper.slothlet.contextManager?.instances?.get(wrapper.slothlet.instanceID);if(store&&store[TRUSTED_ROOT]===true)return{verdict:"allow"};if(wrapper.slothlet.config?.permissions?.failOpenOnAbsentCaller)return{verdict:"allow"};return{verdict:"deny"}}if(!genuineWrappers.has(callerWrapper))return{verdict:"deny"};return{verdict:"enforce",callerWrapper,ctx}}function runtime_enforceReadGate(wrapper,prop,resolvedValue,callerOverride){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return;if(!runtime_isTerminalData(resolvedValue))return;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);const decision=runtime_readGateDecision(wrapper,targetPath,callerOverride);if(decision.allowed)return;throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:decision.caller,target:targetPath})}function runtime_isTerminalData(value){return value!==Object(value)||value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer}function runtime_readGateDecision(wrapper,targetPath,callerOverride){if(isFrameworkInternal(wrapper)){const leafKey=targetPath.slice(targetPath.lastIndexOf(".")+1);if(isFrameworkMarkerKey(leafKey))return{allowed:true,caller:null}}const decision=resolveEnforcedCaller(wrapper,callerOverride);if(decision.verdict==="allow"){const hostPm=wrapper.slothlet.handlers.permissionManager;if(hostPm.isPrivateTarget?.(targetPath)&&!hostPm.enforceAccess(null,targetPath,null,wrapper.____slothletInternal.filePath,null)){return{allowed:false,caller:null}}return{allowed:true,caller:null}}if(decision.verdict==="deny")return{allowed:false,caller:null};const{callerWrapper,ctx}=decision;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const allowed=wrapper.slothlet.handlers.permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,ctx.context??null);return{allowed,caller:callerPath}}function runtime_isReadRedacted(wrapper,prop){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return false;const impl=wrapper.____slothletInternal?.impl;const desc=(impl&&(typeof impl==="object"||typeof impl==="function")?Object.getOwnPropertyDescriptor(impl,prop):void 0)??Object.getOwnPropertyDescriptor(wrapper,prop);if(!desc||!("value"in desc)||!runtime_isTerminalData(runtime_unwrapLeafValue(desc.value)))return false;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);return!runtime_readGateDecision(wrapper,targetPath).allowed}function runtime_unwrapLeafValue(value){let current=value;for(let depth=0;depth<8;depth++){if(!current||typeof current!=="object"&&typeof current!=="function")return current;const inner=_proxyRegistry.get(current)??(hasOwn(current,"____slothletInternal")?current:null);if(!inner)return current;current=inner.____slothletInternal?.impl}return current}function runtime_redactSerialized(wrapper,data,basePath,seen){if(!data||typeof data!=="object"||Array.isArray(data)||seen.has(data))return;seen.add(data);for(const key of Object.keys(data)){const value=data[key];const targetPath=`${basePath}.${key}`;if(runtime_isTerminalData(value)){if(!runtime_readGateDecision(wrapper,targetPath).allowed)delete data[key]}else{runtime_redactSerialized(wrapper,value,targetPath,seen)}}}function enforcePermission(wrapper){const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return;const targetPath=wrapper.____slothletInternal.apiPath;const decision=resolveEnforcedCaller(wrapper);if(decision.verdict==="allow"){if(permissionManager.isPrivateTarget?.(targetPath)&&!permissionManager.enforceAccess(null,targetPath,null,wrapper.____slothletInternal.filePath,null)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}return}if(decision.verdict==="deny"){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}const{callerWrapper,ctx}=decision;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=ctx?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}const capturedViews=new WeakMap;function runtime_enforceCapturedCaller(wrapper,capturedCaller,targetPathOverride){const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return;const targetPath=targetPathOverride??wrapper.____slothletInternal.apiPath;const callerPath=capturedCaller.____slothletInternal?.apiPath??"";const callerFilePath=capturedCaller.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=wrapper.slothlet.contextManager?.tryGetContext?.()?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}function runtime_capturedView(child,capturedCaller){let byChild=capturedViews.get(capturedCaller);if(!byChild){byChild=new WeakMap;capturedViews.set(capturedCaller,byChild)}const existing=byChild.get(child);if(existing)return existing;const inner=resolveWrapper(child);const view=new Proxy(child,{apply(target,thisArg,args){runtime_enforceCapturedCaller(inner,capturedCaller);return Reflect.apply(target,thisArg,args)},construct(target,args,newTarget){runtime_enforceCapturedCaller(inner,capturedCaller);return Reflect.construct(target,args,newTarget===view?target:newTarget)},get(target,prop){const resolved=Reflect.get(target,prop);if(resolved!==void 0&&typeof prop==="string"&&runtime_isTerminalData(resolved)){const context=inner.slothlet.contextManager?.tryGetContext?.()?.context??null;runtime_enforceReadGate(inner,prop,resolved,{currentWrapper:capturedCaller,context});return resolved}if(resolveWrapper(resolved)===null)return resolved;return runtime_capturedView(resolved,capturedCaller)}});byChild.set(child,view);return view}function runtime_bindCapturedIdentity(wrapper,prop,value){if(typeof prop!=="string")return value;if(value===null||typeof value!=="object"&&typeof value!=="function")return value;const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return value;if(permissionManager.isCaptureEnabled?.()===false)return value;const inner=resolveWrapper(value);if(inner===null)return value;const innerPath=inner.____slothletInternal?.apiPath;if(!innerPath||innerPath.split(".").pop()!==prop)return value;const capturedCaller=wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;if(!capturedCaller)return value;return runtime_capturedView(value,capturedCaller)}function runtime_guardPromotedResult(promise,path,SlothletErrorCtor){const refuse=()=>{throw new SlothletErrorCtor("HOOK_PROMOTED_RESULT_NOT_AWAITED",{path},null,{validationError:true})};return new Proxy(promise,{get(target,prop,receiver){if(prop===Symbol.toPrimitive||prop==="valueOf"||prop==="toString"||prop==="toJSON"){return refuse}const value=Reflect.get(target,prop,receiver);if(prop==="then"||prop==="catch"||prop==="finally")return value.bind(target);return value}})}function unwrapError(error){if(error&&error.name==="SlothletError"&&error.originalError){return error.originalError}return error}const wrapperDebugEnabled=isNode&&(process.env.SLOTHLET_DEBUG_WRAPPER==="1"||process.env.SLOTHLET_DEBUG_WRAPPER==="true"||process.env.SLOTHLET_DEBUG_SCRIPT_VERBOSE==="1"||process.env.SLOTHLET_DEBUG_SCRIPT_VERBOSE==="true");const IMPL_METADATA_KEYS=new Set(["__childFilePaths","__filePath","__childFilePathsPreMaterialize"]);function isFrameworkReservedKey(key){if(typeof key!=="string")return false;return UnifiedWrapper.INTERNAL_KEYS.has(key)||IMPL_METADATA_KEYS.has(key)}const TYPE_STATES={UNMATERIALIZED:Symbol("unmaterialized"),IN_FLIGHT:Symbol("inFlight")};function getSafeFunctionName(apiPath,fallback){const parts=String(apiPath||"").split(".").filter(part=>part&&part!=="null");const baseName=parts.length>0?parts[parts.length-1]:"";let safeName=String(baseName||"").replace(/[^A-Za-z0-9_$]/g,"_");if(!safeName||!/^[A-Za-z_$]/.test(safeName[0])){safeName=safeName?`_${safeName}`:""}return safeName||fallback}function createNamedProxyTarget(nameHint,fallback){const safeName=getSafeFunctionName(nameHint,fallback);return{[safeName]:function(){}}[safeName]}const _proxyRegistry=new WeakMap;class UnifiedWrapper extends ComponentBase{#internal=null;get ____slothletInternal(){if(!(#internal in this))return void 0;return this.#internal}constructor(slothlet,{mode,apiPath,initialImpl=null,materializeFunc=null,isCallable,materializeOnCreate=false,filePath=null,moduleID=null,sourceFolder=null,__adoptVisited=null,deferChildAdopt=false}){super(slothlet);const isCallableExplicit=typeof isCallable==="boolean";const isCallableValue=isCallableExplicit?isCallable:typeof initialImpl==="function"||initialImpl&&typeof initialImpl.default==="function";const isCallableLocked=isCallableValue||isCallableExplicit;const internal=Object.create(null);internal.id=Math.random().toString(36).substr(2,9);internal.mode=mode;internal.apiPath=apiPath;internal.materializeOnCreate=materializeOnCreate;internal.isCallable=isCallableValue;internal.isCallableLocked=isCallableLocked;internal.moduleID=moduleID;internal.filePath=filePath;internal.sourceFolder=sourceFolder;internal.adoptVisited=__adoptVisited;internal.deferChildAdopt=deferChildAdopt;internal.invalid=false;internal.state={materialized:initialImpl!==null,inFlight:false,collisionMode:"merge"};internal.displayName=apiPath?`${String(apiPath).replace(/\./g,"__")}__UnifiedWrapper`:"UnifiedWrapper";this.#internal=internal;const wrapper=this;Object.defineProperty(internal,"wrapper",{get(){return wrapper},enumerable:false,configurable:false});internal.callableImpl=null;internal.waitingProxyCache=new Map;internal.waitingProxyCacheByContext=new WeakMap;internal.proxy=null;const isRootLiveIdentity=deferChildAdopt||EventEmitter&&initialImpl instanceof EventEmitter;internal.impl=isRootLiveIdentity?initialImpl:UnifiedWrapper._cloneImpl(initialImpl);internal.materializeFunc=materializeFunc;if(filePath&&slothlet.handlers?.lifecycle){slothlet.handlers.lifecycle.emit("impl:created",{apiPath,impl:this,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),source:"initial",moduleID,filePath,sourceFolder:sourceFolder||slothlet.config?.dir})}if(initialImpl!==null&&filePath&&slothlet.handlers?.lifecycle){slothlet.handlers.lifecycle.emit("impl:created",{apiPath,impl:initialImpl,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),source:"initial",moduleID,filePath,sourceFolder:sourceFolder||slothlet.config?.dir})}if(initialImpl!==null&&!deferChildAdopt){const implKeys=Object.keys(initialImpl||{});if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&apiPath&&(apiPath==="config"||apiPath.startsWith("config."))){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAPPER_CONSTRUCTOR_IMPL_KEYS",apiPath,keyCount:implKeys.length,keySample:implKeys.slice(0,5)})}this.___adoptImplChildren();if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&apiPath&&(apiPath==="config"||apiPath.startsWith("config."))){const childKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAPPER_CONSTRUCTOR_AFTER_ADOPT",apiPath,childCount:childKeys.length,childKeySample:childKeys.slice(0,5)})}}if(mode==="lazy"){slothlet._registerLazyWrapper();if(slothlet.config.tracking?.materialization){setImmediate(()=>{this._materialize().catch(err=>{if(slothlet.config?.debug?.materialize){slothlet.debug("materialize",{key:"DEBUG_MODE_BACKGROUND_MATERIALIZE_ERROR",apiPath:this.____slothletInternal?.apiPath,error:err.message})}})})}}}____inspectCustom(____depth,____options,____inspect){const w=_proxyRegistry.get(this)??this;const childKeys=Object.keys(w).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!w.____slothletInternal?.isCallable){const inspectObj={};for(const key of childKeys){inspectObj[key]=w[key]}return inspectObj}if(w.____slothletInternal?.mode==="lazy"&&w.____slothletInternal?.state&&!w.____slothletInternal?.state.materialized&&w.____slothletInternal?.proxy){return w.____slothletInternal.proxy}return w.____slothletInternal?.impl}get __impl(){return this.____slothletInternal.impl}static _cloneImpl(value){if(value&&typeof value==="object"&&!Array.isArray(value)&&typeof value!=="function"){const isProxy=util.types.isProxy(value);if(isProxy){if(resolveWrapper(value)){const clone={};for(const key of Reflect.ownKeys(value)){try{clone[key]=value[key]}catch{}}return clone}return value}const uw_cloneDescriptors=Object.getOwnPropertyDescriptors(value);return Object.create(Object.getPrototypeOf(value),uw_cloneDescriptors)}return value}static _extractFullImpl(wrapper){if(!wrapper)return null;const impl=wrapper.____slothletInternal.impl;if(impl===null||impl===void 0)return impl;if(typeof impl!=="object"&&typeof impl!=="function")return impl;if(typeof impl==="function")return impl;if(Array.isArray(impl))return impl.slice();const extractFullImpl_result={};for(const key of Object.keys(impl)){if(isFrameworkReservedKey(key))continue;extractFullImpl_result[key]=impl[key]}if(impl.__childFilePaths){extractFullImpl_result.__childFilePaths=impl.__childFilePaths}if(impl.__childFilePathsPreMaterialize){extractFullImpl_result.__childFilePathsPreMaterialize=impl.__childFilePathsPreMaterialize}for(const key of Object.keys(wrapper)){if(UnifiedWrapper.INTERNAL_KEYS.has(key))continue;if(key in extractFullImpl_result)continue;const extractFullImpl_child=wrapper[key];const _extractChildW=resolveWrapper(extractFullImpl_child);if(_extractChildW){extractFullImpl_result[key]=UnifiedWrapper._extractFullImpl(_extractChildW)}else{extractFullImpl_result[key]=extractFullImpl_child}}return extractFullImpl_result}_applyNewImpl(newImpl,forceReuseChildren=false){this.____slothletInternal.impl=UnifiedWrapper._cloneImpl(newImpl);this.____slothletInternal.invalid=false;if(!this.____slothletInternal.isCallableLocked&&!this.____slothletInternal.isCallable&&(typeof newImpl==="function"||newImpl&&typeof newImpl.default==="function")){this.____slothletInternal.isCallable=true;this.____slothletInternal.isCallableLocked=true}if(!this.____slothletInternal.filePath&&this.____slothletInternal.impl&&this.____slothletInternal.impl.__filePath){this.____slothletInternal.filePath=this.____slothletInternal.impl.__filePath;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_APPLY_IMPL_UPDATE_PATH",apiPath:this.____slothletInternal.apiPath,filePath:this.____slothletInternal.filePath})}this.___adoptImplChildren(forceReuseChildren)}___setImpl(newImpl,moduleID=null,forceReuseChildren=false){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_SETIMPL_CALLED",apiPath:this.____slothletInternal.apiPath,newImplKeys:Object.keys(newImpl||{})})}this._applyNewImpl(newImpl,forceReuseChildren);if(newImpl&&this.slothlet.handlers?.lifecycle){const wrapperMetadata=this.slothlet.handlers.metadata.getMetadata(this);const extractedModuleId=moduleID||wrapperMetadata?.baseModuleID||null;this.slothlet.handlers.lifecycle.emit("impl:changed",{apiPath:this.____slothletInternal.apiPath,impl:newImpl,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),source:"hot-reload",moduleID:extractedModuleId,filePath:wrapperMetadata?.filePath,sourceFolder:wrapperMetadata?.sourceFolder})}this.____slothletInternal.state.materialized=true;this.____slothletInternal.state.inFlight=false;if(this.slothlet._onWrapperMaterialized){this.slothlet._onWrapperMaterialized()}}___resetLazy(newMaterializeFunc){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_RESETLAZY_CALLED",apiPath:this.____slothletInternal.apiPath,hadImpl:this.____slothletInternal.impl!==null,hadChildren:Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).length});for(const key of Reflect.ownKeys(this)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"))){continue}const child=this[key];const childRaw=resolveWrapper(child);if(childRaw){childRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}this.____slothletInternal.impl=null;this.____slothletInternal.invalid=false;this.____slothletInternal.state.materialized=false;this.____slothletInternal.state.inFlight=false;this.____slothletInternal.materializationPromise=null;this.____slothletInternal.materializeFunc=newMaterializeFunc;if(this.____slothletInternal.waitingProxyCache){this.____slothletInternal.waitingProxyCache.clear()}this.____slothletInternal.waitingProxyCacheByContext=new WeakMap;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_RESETLAZY_COMPLETE",apiPath:this.____slothletInternal.apiPath})}async ___materialize(){if(this.____slothletInternal.state.materialized){return}if(this.____slothletInternal.invalid){return}if(this.____slothletInternal.materializationPromise){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_AWAIT",apiPath:this.____slothletInternal.apiPath});return this.____slothletInternal.materializationPromise}if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_START",apiPath:this.apiPath})}this.____slothletInternal.materializationPromise=(async()=>{this.____slothletInternal.state.inFlight=true;try{if(this.____slothletInternal.materializeFunc){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_CALLING_FUNC",apiPath:this.____slothletInternal.apiPath})}const lazy_setImpl=value=>{if(this.____slothletInternal.invalid)return;this._applyNewImpl(value)};const result=await this.____slothletInternal.materializeFunc(lazy_setImpl);if(this.____slothletInternal.invalid){return}if(!this.____slothletInternal.impl){this._applyNewImpl(result)}this.____slothletInternal.state.materialized=true;if(this.slothlet._onWrapperMaterialized){this.slothlet._onWrapperMaterialized()}if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_COMPLETE",apiPath:this.____slothletInternal.apiPath,resultType:typeof result,resultKeys:Object.keys(result||{})})}}}catch(error){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_ERROR",apiPath:this.____slothletInternal.apiPath,error:error.message})}throw error}finally{this.____slothletInternal.state.inFlight=false;this.____slothletInternal.materializationPromise=null}})();return this.____slothletInternal.materializationPromise}_materialize(){return this.___materialize()}___invalidate(){this.____slothletInternal.invalid=true;this.____slothletInternal.impl=null;for(const key of Reflect.ownKeys(this)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"))){continue}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}___adoptImplChildren(forceReuseChildren=false){const preExistingKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_START",apiPath:this.____slothletInternal.apiPath,wrapperId:this.____slothletInternal.id||"no-id",preExistingKeys:preExistingKeys.join(","),collisionMode:this.____slothletInternal.state.collisionMode});const threadedVisited=this.____slothletInternal.adoptVisited;this.____slothletInternal.adoptVisited=null;if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){return}if(util.types.isProxy(this.____slothletInternal.impl))return;if(Array.isArray(this.____slothletInternal.impl))return;if(EventEmitter&&this.____slothletInternal.impl instanceof EventEmitter)return;const adoptVisited=threadedVisited||new WeakSet;const ownKeys=Reflect.ownKeys(this.____slothletInternal.impl);const internalKeys=new Set(["__impl","___setImpl","___resetLazy","_materialize","_impl","_state","_invalid","____slothlet","____slothletInternal"]);const keepImplProperties=typeof this.____slothletInternal.impl==="function"||this.____slothletInternal.impl&&typeof this.____slothletInternal.impl==="object"&&typeof this.____slothletInternal.impl.default==="function";if(keepImplProperties&&this.____slothletInternal.impl&&typeof this.____slothletInternal.impl==="object"&&typeof this.____slothletInternal.impl.default==="function"){internalKeys.add("default")}const observedKeys=new Set;const existingKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));const storedCollisionMode=this.____slothletInternal.state.collisionMode;const isMergeScenario=storedCollisionMode!=="replace"&&existingKeys.length>0;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT",apiPath:this.____slothletInternal.apiPath,mode:this.____slothletInternal.mode,storedCollisionMode,existingKeys:existingKeys.join(","),isMergeScenario});const savedChildren=new Map;if(storedCollisionMode==="replace"&&existingKeys.length>0){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_REPLACE_CLEARING",count:existingKeys.length});for(const key of existingKeys){const child=this[key];if(resolveWrapper(child)!==null){savedChildren.set(key,child)}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}else{for(const key of existingKeys){observedKeys.add(key)}}const metadataKeys=new Set(["__childFilePaths","__filePath","__childFilePathsPreMaterialize"]);const skipKeys=typeof this.____slothletInternal.impl==="function"?new Set(["length","name","prototype"]):null;for(const key of ownKeys){if(internalKeys.has(key)){continue}if(typeof key==="string"&&metadataKeys.has(key)){continue}if(skipKeys&&typeof key==="string"&&skipKeys.has(key)){continue}if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){break}const descriptor=Object.getOwnPropertyDescriptor(this.____slothletInternal.impl,key);if(!descriptor){continue}const value=this.____slothletInternal.impl[key];if(value===this.____slothletInternal.impl){continue}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_PROCESS",apiPath:this.____slothletInternal.apiPath,propKey:key,typeOf:typeof value,valueName:value?.name})}observedKeys.add(key);if(hasOwn(this,key)&&!key.toString().startsWith("_")){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_CHECK",apiPath:this.____slothletInternal.apiPath,propKey:key,has__collisionMergedKeys:!!this.____slothletInternal.collisionMergedKeys,inSet:this.____slothletInternal.collisionMergedKeys?.has(key)})}const isCollisionMerged=this.____slothletInternal.collisionMergedKeys&&this.____slothletInternal.collisionMergedKeys.has(key);if(isCollisionMerged&&!forceReuseChildren){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_SKIP_COLLISION_MERGED",apiPath:this.____slothletInternal.apiPath,propKey:key})}if(descriptor.configurable){delete this.____slothletInternal.impl[key]}continue}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_ALLOW_NOT_COLLISION_MERGED",apiPath:this.____slothletInternal.apiPath,propKey:key})}}const existingChild=savedChildren.get(key)||this[key];let wrapped;const skipChildReuse=!forceReuseChildren&&this.____slothletInternal.mode==="lazy"&&storedCollisionMode==="replace";const existingChildUA=existingChild?resolveWrapper(existingChild):null;if(existingChildUA?.____slothletInternal?.userAssigned){wrapped=existingChild}else if(!skipChildReuse&&existingChild&&resolveWrapper(existingChild)!==null){if(resolveWrapper(value)!==null){const newWrapper=resolveWrapper(value);let rawImpl=newWrapper?newWrapper.____slothletInternal.impl:null;if(rawImpl&&typeof rawImpl==="object"&&!Array.isArray(rawImpl)&&typeof rawImpl!=="function"&&Object.keys(rawImpl).filter(k=>!k.startsWith("__")).length===0){const wrapperOwnKeys=Object.keys(newWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(wrapperOwnKeys.length>0){rawImpl=UnifiedWrapper._extractFullImpl(newWrapper)}}if(rawImpl!==null&&rawImpl!==void 0){resolveWrapper(existingChild).___setImpl(rawImpl,this.____slothletInternal.moduleID,true)}else if(newWrapper&&newWrapper.____slothletInternal.materializeFunc){const existingChildWrapper=resolveWrapper(existingChild);if(existingChildWrapper){existingChildWrapper.___resetLazy(newWrapper.____slothletInternal.materializeFunc)}}wrapped=existingChild}else{resolveWrapper(existingChild).___setImpl(value,this.____slothletInternal.moduleID,true);wrapped=existingChild}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_REUSE_CHILD_WRAPPER",apiPath:this.____slothletInternal.apiPath,propKey:key})}}else{wrapped=this.___createChildWrapper(key,value,adoptVisited,this.____slothletInternal.deferChildAdopt);if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_WRAP",apiPath:this.____slothletInternal.apiPath,propKey:key,wrapped:wrapped?"YES":wrapped===null?"NULL":"NO"})}}if(wrapped){const existing=this[key];const existingDescriptor=Object.getOwnPropertyDescriptor(this,key);if(existing===wrapped||existingDescriptor&&!existingDescriptor.configurable){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:existingDescriptor&&!existingDescriptor.configurable?"DEBUG_MODE_ADOPT_SKIP_NON_CONFIGURABLE":"DEBUG_MODE_ADOPT_SKIP_SAME_WRAPPER",apiPath:this.____slothletInternal.apiPath,propKey:key})}}else{if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_DEFINE",apiPath:this.____slothletInternal.apiPath,propKey:key})}Object.defineProperty(this,key,{value:wrapped,writable:false,enumerable:true,configurable:true});if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_DEFINED",apiPath:this.____slothletInternal.apiPath,propKey:key})}}if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}else if(wrapped===null&&this.____slothletInternal.deferChildAdopt&&(value===null||typeof value!=="object"&&typeof value!=="function")){Object.defineProperty(this,key,{get:()=>{const currentImpl=this.____slothletInternal.impl;return currentImpl?currentImpl[key]:void 0},set:newValue=>{const currentImpl=this.____slothletInternal.impl;if(currentImpl)currentImpl[key]=newValue},enumerable:true,configurable:true})}else if(wrapped===null){Object.defineProperty(this,key,{value,writable:false,enumerable:true,configurable:true});if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}else{Object.defineProperty(this,key,{value,writable:false,enumerable:true,configurable:true});if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}}if(!isMergeScenario){const currentKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of currentKeys){if(!observedKeys.has(key)){const existing=this[key];const existingRaw=resolveWrapper(existing);if(existingRaw){existingRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}}if(this._mergeAfterMaterialize){const{existingWrapper,isMergeReplace:____isMergeReplace}=this._mergeAfterMaterialize;const existingKeys2=Object.keys(existingWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of existingKeys2){if(!(key in this)||key.startsWith("_")||key.startsWith("__")){const child=existingWrapper[key];Object.defineProperty(this,key,{value:child,writable:false,enumerable:true,configurable:true})}}delete this._mergeAfterMaterialize}}___createChildWrapper(key,value,visited=null,deferChildAdopt=false){if(value===void 0){return void 0}if(value===null){return null}if(value&&resolveWrapper(value)!==null){return value}if(value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer){return null}if(deferChildAdopt&&typeof value!=="object"&&typeof value!=="function"){return null}const trackCycle=typeof value==="object"||typeof value==="function";if(trackCycle){visited??=new WeakSet;if(visited.has(value)){return null}}let childImpl=value;const isChildLiveIdentity=deferChildAdopt||EventEmitter&&childImpl instanceof EventEmitter;if(!isChildLiveIdentity&&childImpl&&typeof childImpl==="object"){if(Array.isArray(childImpl)){childImpl=childImpl.slice()}else{const descriptors=Object.getOwnPropertyDescriptors(childImpl);childImpl=Object.create(Object.getPrototypeOf(childImpl),descriptors)}}const parentMetadata=this.slothlet.handlers?.metadata?.getMetadata(this);const childExistingMetadata=this.slothlet.handlers?.metadata?.getMetadata(value);let childFilePath=childExistingMetadata?.filePath||null;let childModuleId=null;if(!childFilePath){const keyStr=typeof key==="symbol"?String(key):key;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_CHECK",apiPath:this.apiPath,propKey:keyStr,has_impl:!!this.____slothletInternal.impl,has__childFilePaths:!!(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths),has__childFilePathsPreMaterialize:!!this.____slothletInternal.childFilePathsPreMaterialize,parentFilePath:parentMetadata?.filePath});if(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_AVAILABLE",keys:Object.keys(this.____slothletInternal.impl.__childFilePaths).join(","),propKey:keyStr,found:!!this.____slothletInternal.impl.__childFilePaths[key]})}if(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths&&this.____slothletInternal.impl.__childFilePaths[key]){childFilePath=this.____slothletInternal.impl.__childFilePaths[key];this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_USING",childFilePath})}else if(this.____slothletInternal.childFilePathsPreMaterialize&&this.____slothletInternal.childFilePathsPreMaterialize[key]){childFilePath=this.____slothletInternal.childFilePathsPreMaterialize[key];this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_PRE_MAT",childFilePath})}else{childFilePath=parentMetadata?.filePath||null;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_FALLBACK",childFilePath})}}if(parentMetadata?.baseModuleID){childModuleId=parentMetadata.baseModuleID}const childSourceFolder=childExistingMetadata?.sourceFolder||parentMetadata?.sourceFolder||null;if(trackCycle){visited.add(value)}let nestedWrapper;try{nestedWrapper=new UnifiedWrapper(this.slothlet,{mode:"eager",apiPath:this.____slothletInternal.apiPath?`${this.____slothletInternal.apiPath}.${typeof key==="symbol"?String(key):key}`:String(key),initialImpl:childImpl,isCallable:typeof childImpl==="function",filePath:childFilePath,moduleID:childModuleId,sourceFolder:childSourceFolder,__adoptVisited:visited,deferChildAdopt})}finally{if(trackCycle){visited.delete(value)}}return nestedWrapper.createProxy()}___createWaitingProxy(propChain=[]){const wrapper=this;const __readGateStore=wrapper.slothlet.contextManager?.tryGetContext?.();const __readGateCaller=__readGateStore?{currentWrapper:wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null,context:__readGateStore.context,[TRUSTED_ROOT]:__readGateStore[TRUSTED_ROOT]===true}:null;const __callerKey=__readGateCaller?.currentWrapper?.____slothletInternal?.apiPath??"";const cacheKey=`${__callerKey}::${propChain.join(".")}`;const __readGateContextRef=__readGateStore?.context??null;const useContextBucket=__readGateContextRef&&typeof __readGateContextRef==="object";let cache;if(useContextBucket){cache=wrapper.____slothletInternal.waitingProxyCacheByContext.get(__readGateContextRef);if(!cache){cache=new Map;wrapper.____slothletInternal.waitingProxyCacheByContext.set(__readGateContextRef,cache)}}else{cache=wrapper.____slothletInternal.waitingProxyCache}if(cache.has(cacheKey)){return cache.get(cacheKey)}const waitingTarget=createNamedProxyTarget(`${wrapper.____slothletInternal.apiPath}_waitingProxy`,"waitingProxyTarget");const waitingProxy=new Proxy(waitingTarget,{get(___target,prop){if(prop==="then"){return(onFulfilled,onRejected)=>{const waitingProxy_thenResolve=async()=>{if(!wrapper.____slothletInternal.state.materialized){await wrapper._materialize()}let current=wrapper;let __gateParent=null;let __gateProp=null;const __descendRest=(startValue,nextIndex)=>{let descended=startValue;for(let __di=nextIndex;__di<propChain.length;__di++){if(descended===null||descended===void 0)return void 0;descended=descended[propChain[__di]]}return descended};for(let __chainIndex=0;__chainIndex<propChain.length;__chainIndex++){const chainProp=propChain[__chainIndex];if(!current)return void 0;if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){let result=current.____slothletInternal.impl;for(let i=__chainIndex;i<propChain.length;i++){result=result[propChain[i]]}return result}const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&hasOwn(current,chainProp)){const child=current[chainProp];const _childW=resolveWrapper(child);if(_childW){__gateParent=current;__gateProp=chainProp;current=_childW;if(current.____slothletInternal.mode==="lazy"&&!current.____slothletInternal.state.materialized){await current._materialize()}continue}if(__chainIndex<propChain.length-1){const descendedChild=__descendRest(child,__chainIndex+1);if(descendedChild!==void 0){runtime_enforceReadGate(current,propChain.slice(__chainIndex).join("."),descendedChild,__readGateCaller)}return descendedChild}runtime_enforceReadGate(current,chainProp,child,__readGateCaller);return child}if(current.____slothletInternal.impl&&current.____slothletInternal.impl[chainProp]!==void 0){const implValue=current.____slothletInternal.impl[chainProp];if(__chainIndex<propChain.length-1){const descendedImpl=__descendRest(implValue,__chainIndex+1);if(descendedImpl!==void 0){runtime_enforceReadGate(current,propChain.slice(__chainIndex).join("."),descendedImpl,__readGateCaller)}return descendedImpl}runtime_enforceReadGate(current,chainProp,implValue,__readGateCaller);return implValue}return void 0}if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl}if(__gateParent){runtime_enforceReadGate(__gateParent,__gateProp,current.____slothletInternal.impl,__readGateCaller)}const finalImpl=current.____slothletInternal.impl;const callableCarriesWrapperMembers=typeof finalImpl==="function"&&Object.keys(current).some(key=>!isFrameworkReservedKey(key)&&!Object.prototype.hasOwnProperty.call(finalImpl,key));if(callableCarriesWrapperMembers||finalImpl!==null&&typeof finalImpl==="object"&&!Array.isArray(finalImpl)&&!runtime_isTerminalData(finalImpl)){const resolvedProxy=current.____slothletInternal.proxy;const __capturedReader=__readGateCaller?.currentWrapper??null;const __pm=wrapper.slothlet.handlers?.permissionManager;if(__capturedReader&&__pm&&__pm.isEnabled()&&__pm.isCaptureEnabled?.()!==false){return runtime_capturedView(resolvedProxy,__capturedReader)}return resolvedProxy}return finalImpl};waitingProxy_thenResolve().then(onFulfilled,onRejected)}}if(prop==="____slothletInternal")return void 0;if(prop==="_materialize")return wrapper._materialize.bind(wrapper);if(prop==="__mode")return wrapper.____slothletInternal.mode;if(prop==="__materialized")return wrapper.____slothletInternal.state.materialized;if(prop==="__inFlight")return wrapper.____slothletInternal.state.inFlight;if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(prop===util.inspect.custom){if(wrapper.____slothletInternal.state.inFlight){return waitingTarget}if(!wrapper.____slothletInternal.state.materialized){return waitingTarget}if(wrapper.____slothletInternal.impl){let current=wrapper.____slothletInternal.impl;for(const chainProp of propChain){if(!current){return void 0}current=current[chainProp]}return current}return waitingTarget}if(prop==="__type"){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE",apiPath:wrapper.apiPath,propChain:propChain.join(","),materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null});if(wrapper.____slothletInternal.state.materialized||wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){let current=wrapper.createProxy();for(const chainProp of propChain){if(!current)break;const currentWrapper=resolveWrapper(current);if(currentWrapper){const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&hasOwn(currentWrapper,chainProp)){current=currentWrapper[chainProp];wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_WRAPPER",chainProp:String(chainProp),typeOf:typeof current});continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&&currentWrapper.____slothletInternal.impl!==null&&chainProp in currentWrapper.____slothletInternal.impl){current=currentWrapper.____slothletInternal.impl[chainProp];wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_IMPL",chainProp:String(chainProp),typeOf:typeof current});continue}}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_DIRECT",chainProp:String(chainProp),typeOf:typeof current});current=current[chainProp]}const resolvedType=typeof current==="function"?"function":typeof current==="object"&&current!==null?"object":typeof current;wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_RESOLVED",apiPath:wrapper.apiPath,propChain:propChain.join(","),resolvedType});return resolvedType}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_INFLIGHT",apiPath:wrapper.apiPath,propChain:propChain.join(",")});return TYPE_STATES.IN_FLIGHT}if(prop==="__metadata"){if(wrapper.slothlet.handlers?.metadata){return wrapper.slothlet.handlers.metadata.getMetadata(wrapper)}return{}}if(typeof prop==="symbol")return void 0;if(prop==="length"){return 0}if(prop==="name")return waitingTarget.name||"waitingProxyTarget";if(prop==="toString"){return Function.prototype.toString.bind(waitingTarget)}if(prop==="valueOf"){return Function.prototype.valueOf.bind(waitingTarget)}if(prop==="toJSON"){return()=>void 0}if(prop==="__slothletPath")return wrapper.____slothletInternal.apiPath;if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){let result=wrapper.____slothletInternal.impl;for(const chainProp of propChain){result=result[chainProp]}return result[prop]}if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){let current=wrapper;let remainingChain=[...propChain];for(let i=0;i<propChain.length;i++){const chainProp=propChain[i];if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){let proxyResult=current.____slothletInternal.impl;for(const remainingProp of remainingChain){proxyResult=proxyResult[remainingProp]}return proxyResult[prop]}const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&current&&hasOwn(current,chainProp)){const cached=current[chainProp];const _cachedW2=resolveWrapper(cached);if(_cachedW2){current=_cachedW2;remainingChain.shift()}else{return void 0}}else{return void 0}}if(current&&current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl[prop]}const isFinalInternal=isFrameworkReservedKey(prop);if(!isFinalInternal&&hasOwn(current,prop)){return current[prop]}return void 0}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_PREMATURE",apiPath:wrapper.____slothletInternal.apiPath,prop});return wrapper[prop]}if(wrapper.____slothletInternal.needsImmediateChildAdoption&&wrapper.____slothletInternal.materializeFunc&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT",apiPath:wrapper.____slothletInternal.apiPath,prop});wrapper._materialize().catch(err=>{wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT_ERROR",apiPath:wrapper.apiPath,error:err.message})});const isInternal2=isFrameworkReservedKey(prop);if(!isInternal2&&hasOwn(wrapper,prop)){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT_SUCCESS",apiPath:wrapper.____slothletInternal.apiPath,prop});return wrapper[prop]}}if(wrapper.____slothletInternal.state.inFlight){return wrapper.___createWaitingProxy([...propChain,prop])}return wrapper.___createWaitingProxy([...propChain,prop])},async apply(___target,___thisArg,args){const ___liveCallerWrapper=wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null;const ___capture=wrapper.slothlet.handlers?.permissionManager?.isCaptureEnabled()!==false;const ___creationCallerWrapper=___capture?__readGateCaller?.currentWrapper??null:null;const ___capturedCallerWrapper=___liveCallerWrapper??___creationCallerWrapper;wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_ENTRY",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(","),args:args.join(",")});const chainLabel=propChain.map(prop=>String(prop)).join(".");if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_MATERIALIZE",apiPath:wrapper.____slothletInternal.apiPath});await wrapper._materialize();wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_MATERIALIZED",apiPath:wrapper.____slothletInternal.apiPath})}else if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&wrapper.____slothletInternal.state.inFlight){if(wrapper.____slothletInternal.materializationPromise){await wrapper.____slothletInternal.materializationPromise}else{await wrapper._materialize()}}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_START_WALK",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(",")});let current=wrapper.createProxy();let lastWrapper=wrapper;let lastObject=null;for(const prop of propChain){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_WALK",prop:String(prop),typeOf:typeof current,constructorName:current?.constructor?.name});if(!current){if(propChain.some(p=>typeof p==="symbol")){return void 0}if(wrapper.____slothletInternal.invalid||wrapper.____slothletInternal.impl===null||lastWrapper&&(lastWrapper.__invalid||lastWrapper._impl===null)){return void 0}const finalProp=propChain[propChain.length-1];if(finalProp==="hasAttribute"||finalProp==="toJSON"||finalProp===Symbol.toStringTag||finalProp==="constructor"||typeof finalProp==="symbol"||typeof prop==="symbol"){return void 0}throw new wrapper.slothlet.SlothletError("CHAIN_ACCESS_UNDEFINED",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel,prop:String(prop)},null,{validationError:true})}const currentWrapper=resolveWrapper(current);if(currentWrapper){const state=currentWrapper.____slothletInternal.state;if(!state.materialized){if(!state.inFlight&&typeof current._materialize==="function"){await current._materialize()}while(!currentWrapper.____slothletInternal.state.materialized){const nextState=currentWrapper.____slothletInternal.state;if(!nextState.inFlight&&!nextState.materialized){throw new wrapper.slothlet.SlothletError("CHAIN_MATERIALIZE_FAILED",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel,prop:String(prop)},null,{validationError:true})}await new Promise(resolve=>setImmediate(resolve))}}}if(currentWrapper){lastWrapper=currentWrapper;const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(currentWrapper,prop)){lastObject=current;current=currentWrapper[prop];continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&&currentWrapper.____slothletInternal.impl!==null&&prop in currentWrapper.____slothletInternal.impl){lastObject=currentWrapper.____slothletInternal.impl;current=currentWrapper.____slothletInternal.impl[prop];continue}}lastObject=current;current=current[prop]}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(","),typeOf:typeof current,currentName:current?.name,isFunction:typeof current==="function"});if(typeof current==="function"){if(___creationCallerWrapper&&___creationCallerWrapper!==___capturedCallerWrapper){const ___resolvedInner=resolveWrapper(current);const ___targetPath=___resolvedInner?.____slothletInternal?.apiPath??[wrapper.____slothletInternal.apiPath,...propChain].filter(Boolean).join(".");runtime_enforceCapturedCaller(wrapper,___creationCallerWrapper,___targetPath)}if(___capturedCallerWrapper&&wrapper.slothlet.contextManager){const ___instanceStore=wrapper.slothlet.contextManager.instances?.get?.(wrapper.instanceID);if(___instanceStore&&!___instanceStore.currentWrapper){return wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,()=>Reflect.apply(current,lastObject,args),null,[],___capturedCallerWrapper,true)}}const ___identityStore=___capturedCallerWrapper?wrapper.slothlet.contextManager?.instances?.get?.(wrapper.instanceID):null;if(!___identityStore)return Reflect.apply(current,lastObject,args);const ___previousAuthoritative=___identityStore.__authoritativeWrapper;___identityStore.__authoritativeWrapper=___capturedCallerWrapper;try{return Reflect.apply(current,lastObject,args)}finally{___identityStore.__authoritativeWrapper=___previousAuthoritative}}const _finalChainProp=propChain[propChain.length-1];if(_finalChainProp==="hasAttribute"||_finalChainProp==="toJSON"){return void 0}if(current===void 0||current===null){throw new wrapper.slothlet.SlothletError("CHAIN_NOT_CALLABLE",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel},null,{validationError:true})}throw new wrapper.slothlet.SlothletError("CHAIN_NOT_CALLABLE",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel},null,{validationError:true})},getPrototypeOf:()=>null});_proxyRegistry.set(waitingProxy,wrapper);cache.set(cacheKey,waitingProxy);return waitingProxy}createProxy(){const wrapper=this;if(wrapper.____slothletInternal.proxy){return wrapper.____slothletInternal.proxy}if(wrapper.____slothletInternal.materializeOnCreate&&wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&wrapper.____slothletInternal.materializeFunc){wrapper._materialize().catch(()=>{})}const mightBeCallable=wrapper.____slothletInternal.isCallable||wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.isCallableLocked;let proxyTarget;if(mightBeCallable){proxyTarget=createNamedProxyTarget(wrapper.____slothletInternal.apiPath,"callableProxy")}else if(Array.isArray(wrapper.____slothletInternal.impl)){proxyTarget=wrapper.____slothletInternal.impl}else{proxyTarget=wrapper}if(!Array.isArray(proxyTarget)&&!(util.inspect.custom in proxyTarget)){Object.defineProperty(proxyTarget,util.inspect.custom,{value:function(){const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!wrapper.____slothletInternal.isCallable){const obj={};for(const key of childKeys){const child=wrapper[key];if(child&&typeof child.createProxy==="function"){obj[key]=child.createProxy()}else{obj[key]=child}}return obj}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&(wrapper.____slothletInternal.impl===null||wrapper.____slothletInternal.impl===void 0)){return wrapper.____slothletInternal.proxy||wrapper}return wrapper.____slothletInternal.impl},writable:false,enumerable:false,configurable:true})}const getTrap=(target,prop,____receiver)=>{const enforceReadGate=resolvedValue=>runtime_enforceReadGate(wrapper,prop,resolvedValue);if(target!==wrapper&&prop in target){const desc=Object.getOwnPropertyDescriptor(target,prop);if(desc&&!desc.configurable){if(typeof prop==="string"&&prop.startsWith("__")){return wrapper[prop]}return target[prop]}}if(target===wrapper&&typeof prop==="string"){const desc=Object.getOwnPropertyDescriptor(target,prop);if(desc&&!desc.configurable){return target[prop]}}const isInternalProp=isFrameworkReservedKey(prop);const allowedInternals=new Set(["_materialize","__mode","__apiPath","__isCallable","__materializeOnCreate","__displayName","__type","__materialized","__inFlight","__slothletPath","__metadata","__filePath","__sourceFolder","__moduleID"]);if(isInternalProp&&!allowedInternals.has(prop)){return void 0}if(prop==="power"||prop==="add"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_START",apiPath:wrapper.____slothletInternal.apiPath,prop:String(prop),mode:wrapper.____slothletInternal.mode,collisionMode:wrapper.____slothletInternal.state.collisionMode||"none",materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null,inWrapper:!isInternalProp&&hasOwn(wrapper,prop)})}if(prop==="__mode")return wrapper.____slothletInternal.mode;if(prop==="__apiPath")return wrapper.____slothletInternal.apiPath;if(prop==="__isCallable")return wrapper.____slothletInternal.isCallable;if(prop==="__materializeOnCreate")return wrapper.____slothletInternal.materializeOnCreate;if(prop==="__materialized")return wrapper.____slothletInternal.state.materialized;if(prop==="__inFlight")return wrapper.____slothletInternal.state.inFlight;if(prop==="__displayName")return wrapper.____slothletInternal.displayName;if(prop==="__type"){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return TYPE_STATES.IN_FLIGHT}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){return TYPE_STATES.UNMATERIALIZED}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return"function"}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return"function"}if(impl&&typeof impl==="object"){return"object"}if(typeof impl==="string"){return"string"}if(typeof impl==="number"){return"number"}if(typeof impl==="boolean"){return"boolean"}if(typeof impl==="symbol"){return"symbol"}if(typeof impl==="bigint"){return"bigint"}return"undefined"}if(prop==="_materialize")return wrapper._materialize.bind(wrapper);if(prop==="__slothletPath")return wrapper.____slothletInternal.apiPath;if(prop==="__metadata"){if(wrapper.slothlet.handlers?.metadata){return wrapper.slothlet.handlers.metadata.getMetadata(wrapper)}return{}}if(prop==="__filePath")return wrapper.____slothletInternal.filePath??void 0;if(prop==="__sourceFolder")return wrapper.____slothletInternal.sourceFolder??void 0;if(prop==="__moduleID")return wrapper.____slothletInternal.moduleID??void 0;if(prop==="__invalid")return wrapper.____slothletInternal.invalid;{const arrImpl=wrapper.____slothletInternal.impl;if(Array.isArray(arrImpl)){const isIndex=typeof prop==="string"&&/^(?:0|[1-9]\d*)$/.test(prop);if(!isIndex){const arrValue=Reflect.get(arrImpl,prop,arrImpl);enforceReadGate(arrValue);return arrValue}}}if(prop==="then"){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){return(onFulfilled,onRejected)=>wrapper._materialize().then(()=>onFulfilled(wrapper.____slothletInternal.proxy)).catch(onRejected)}return void 0}if(prop==="constructor"){const internal=wrapper.____slothletInternal;const constructorImpl=internal.impl;const constructorIsLiveIdentity=internal.deferChildAdopt||EventEmitter&&constructorImpl instanceof EventEmitter;if(constructorIsLiveIdentity&&constructorImpl&&typeof constructorImpl==="object"&&constructorImpl.constructor){return constructorImpl.constructor}return Object.prototype.constructor}if(prop===util.inspect.custom){return()=>{const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!wrapper.____slothletInternal.isCallable){const obj={};for(const key of childKeys){const child=wrapper[key];if(child&&typeof child.createProxy==="function"){obj[key]=child.createProxy()}else{obj[key]=child}}return obj}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&(wrapper.____slothletInternal.impl===null||wrapper.____slothletInternal.impl===void 0)){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_INSPECT_LAZY_UNMATERIALIZED",apiPath:wrapper.apiPath,wrapper,____proxy:wrapper.____slothletInternal.proxy});return wrapper||wrapper.____slothletInternal.proxy}return wrapper.____slothletInternal.impl}}if(prop===Symbol.toStringTag){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return"Function"}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return"Function"}return"Object"}if(typeof prop==="symbol")return void 0;if(prop==="length"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.length}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.length}return 0}if(prop==="name"){if(wrapper.____slothletInternal.apiPath){const pathParts=wrapper.____slothletInternal.apiPath.split(".");const lastPart=pathParts[pathParts.length-1];if(lastPart){return lastPart}}return target.name||"unifiedWrapperProxy"}if(prop==="toString"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.toString.bind(impl)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.toString.bind(impl.default)}if(typeof target==="function"){return Function.prototype.toString.bind(target)}return()=>`[UnifiedWrapper: ${wrapper.____slothletInternal.apiPath}]`}if(prop==="valueOf"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.valueOf.bind(impl)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.valueOf.bind(impl.default)}return Function.prototype.valueOf.bind(target)}if(prop==="toJSON"){const impl=wrapper.____slothletInternal.impl;if(impl&&typeof impl.toJSON==="function"){return impl.toJSON.bind(impl)}return()=>{const data=UnifiedWrapper._extractFullImpl(wrapper);if(data&&typeof data==="object"){delete data.__childFilePaths;delete data.__childFilePathsPreMaterialize}const pm=wrapper.slothlet.handlers?.permissionManager;if(pm&&pm.isEnabled()&&pm.isReadGatingEnabled()){runtime_redactSerialized(wrapper,data,wrapper.____slothletInternal.apiPath,new WeakSet)}return data}}if(wrapper.____slothletInternal.invalid){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(hasOwn(wrapper,prop)){if(wrapper.____slothletInternal.state.collisionMode==="replace"&&(prop==="power"||prop==="add")){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_CACHED_REPLACE",apiPath:wrapper.apiPath,prop:String(prop),collisionMode:wrapper.____slothletInternal.state.collisionMode,wrapperKeys:Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).join(", ")})}this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_CACHED",apiPath:wrapper.____slothletInternal.apiPath,prop:String(prop),materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null});const cached=wrapper[prop];const _cachedWrapper=resolveWrapper(cached);if(_cachedWrapper?.____slothletInternal?.impl!==null&&_cachedWrapper?.____slothletInternal?.impl!==void 0){const cachedImpl=_cachedWrapper.____slothletInternal.impl;const cachedType=typeof cachedImpl;if(cachedType==="string"||cachedType==="number"||cachedType==="boolean"||cachedType==="bigint"||cachedType==="symbol"){enforceReadGate(cachedImpl);return cachedImpl}}if(_cachedWrapper){const cachedWrapper=_cachedWrapper;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}enforceReadGate(cached);return cached}if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){if(typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){return wrapper.____slothletInternal.impl[prop]}if(hasOwn(wrapper,prop)){if(prop==="power"||prop==="add"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_PROXYGET_ACCESSING",prop,wrapperId:wrapper.____slothletInternal.id,apiPath:wrapper.apiPath,collisionMode:wrapper.____slothletInternal.state.collisionMode||"none"});this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_PROXYGET_FOUND",wrapperKeys:Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).join(", ")})}const cached=wrapper[prop];const _cachedWrapper4=resolveWrapper(cached);if(_cachedWrapper4){const cachedWrapper=_cachedWrapper4;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}enforceReadGate(cached);return cached}}const isInternalProp2=typeof prop==="string"&&UnifiedWrapper.INTERNAL_KEYS.has(prop);if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.materialized&&!isInternalProp2&&!hasOwn(wrapper,prop)&&wrapper.____slothletInternal.impl&&!(prop in wrapper.____slothletInternal.impl)){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&(wrapper.____slothletInternal.state.inFlight||!wrapper.____slothletInternal.impl)){if(!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}this.slothlet.debug("wrapper",{key:"DEBUG_MODE_LAZY_GET_CREATE_WAITING_PROXY",prop:String(prop),collisionMode:wrapper.____slothletInternal.state.collisionMode||"none",apiPath:wrapper.____slothletInternal.apiPath});if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){const value2=wrapper.____slothletInternal.impl[prop];return value2}return wrapper.___createWaitingProxy([prop])}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){const value2=wrapper.____slothletInternal.impl[prop];return value2}let value=wrapper.____slothletInternal.impl?wrapper.____slothletInternal.impl[prop]:void 0;if(value===void 0&&wrapper.____slothletInternal.impl){const descriptor=Object.getOwnPropertyDescriptor(wrapper.____slothletInternal.impl,prop);if(descriptor&&descriptor.get){value=descriptor.get.call(wrapper.____slothletInternal.impl)}}if(value===void 0&&Object.prototype.hasOwnProperty.call(target,prop)){value=target[prop]}if(value===void 0){return void 0}enforceReadGate(value);const valueType=typeof value;if(value===null||valueType==="string"||valueType==="number"||valueType==="boolean"||valueType==="bigint"||valueType==="symbol"){return value}if(value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer){return value}if(value&&typeof value==="object"&&util.types.isProxy(value)){return value}if(value&&(typeof value==="object"||typeof value==="function")&&resolveWrapper(value)!==null){return value}const currentImpl=wrapper.____slothletInternal.impl;if(typeof currentImpl==="function"&&!Object.prototype.propertyIsEnumerable.call(currentImpl,prop)){return value}const wrapped=wrapper.___createChildWrapper(prop,value,null,wrapper.____slothletInternal.deferChildAdopt);if(wrapped){Object.defineProperty(wrapper,prop,{value:wrapped,writable:false,enumerable:true,configurable:true});return wrapped}return value};const applyTrap=(target,thisArg,args)=>{if(wrapper.____slothletInternal.invalid){throw new TypeError(`${wrapper.____slothletInternal.apiPath||"api"} is invalidated`)}const thisArgWrapper=resolveWrapper(thisArg);const thisArgImpl=thisArgWrapper?.____slothletInternal?.impl;const thisArgImplIsUsable=thisArgImpl!==null&&(typeof thisArgImpl==="object"||typeof thisArgImpl==="function");const thisArgIsLiveIdentity=thisArgWrapper&&thisArgImplIsUsable&&(thisArgWrapper.____slothletInternal.deferChildAdopt||EventEmitter&&thisArgImpl instanceof EventEmitter);const effectiveThisArg=thisArgIsLiveIdentity?thisArgImpl:thisArg;enforcePermission(wrapper);const hookManager=wrapper.slothlet.handlers?.hookManager;const hasHooks=hookManager&&hookManager.enabled&&!wrapper.____slothletInternal.apiPath.startsWith("slothlet.hook");const api=wrapper.slothlet.boundApi;const ctx=wrapper.slothlet.config?.context||{};if(hasHooks){const ___strategy=hookManager.getDispatchStrategy(wrapper.____slothletInternal.apiPath);if(___strategy.asyncBefore||___strategy.asyncAfter){const ___path=wrapper.____slothletInternal.apiPath;const ___leafIsAsync=util.types.isAsyncFunction(wrapper.____slothletInternal.impl)||util.types.isAsyncFunction(wrapper.____slothletInternal.impl?.default);const ___promotedRun=(async()=>{let beforeResult;try{beforeResult=await hookManager.executeBeforeHooksAsync(___path,args,api,ctx)}catch(error){hookManager.executeAlwaysHooks(___path,args,void 0,true,[unwrapError(error)],api,ctx);throw error}args=beforeResult.args;if(beforeResult.shortCircuit){hookManager.executeAlwaysHooks(___path,args,beforeResult.value,false,[],api,ctx);return beforeResult.value}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){await wrapper._materialize()}const impl=wrapper.____slothletInternal.impl;let settled;try{let raw;if(typeof impl==="function"){raw=wrapper.slothlet.contextManager?wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl,effectiveThisArg,args,wrapper):impl.apply(effectiveThisArg,args)}else if(impl&&typeof impl==="object"&&typeof impl.default==="function"){raw=wrapper.slothlet.contextManager?wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl.default,impl,args,wrapper):impl.default.apply(impl,args)}else{throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:___path,actualType:typeof impl},null,{validationError:true})}settled=raw&&typeof raw==="object"&&typeof raw.then==="function"?await raw:raw}catch(error){const originalError=unwrapError(error);if(!error[ERROR_HOOK_PROCESSED]){const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(___path,originalError,sourceInfo,args,api,ctx)}hookManager.executeAlwaysHooks(___path,args,void 0,true,[originalError],api,ctx);if(wrapper.slothlet.config?.hook?.suppressErrors===true)return void 0;throw error}let promotedFinal;try{const afterResult=await hookManager.executeAfterHooksAsync(___path,settled,args,api,ctx);promotedFinal=afterResult.modified?afterResult.result:settled}catch(error){hookManager.executeAlwaysHooks(___path,args,void 0,true,[unwrapError(error)],api,ctx);throw error}hookManager.executeAlwaysHooks(___path,args,promotedFinal,false,[],api,ctx);return promotedFinal})();return ___leafIsAsync?___promotedRun:runtime_guardPromotedResult(___promotedRun,___path,wrapper.SlothletError)}}let result;let finalResult;let isAsync=false;let lastSyncError=null;try{if(hasHooks){const beforeResult=hookManager.executeBeforeHooks(wrapper.____slothletInternal.apiPath,args,api,ctx);args=beforeResult.args;if(beforeResult.shortCircuit){finalResult=beforeResult.value;return beforeResult.value}}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return new Promise((resolve,reject)=>{const checkMaterialized=()=>{if(wrapper.____slothletInternal.state.materialized){const impl2=wrapper.____slothletInternal.impl;try{if(typeof impl2==="function"){if(wrapper.slothlet.contextManager){resolve(wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl2,effectiveThisArg,args,wrapper,true))}else{resolve(impl2.apply(effectiveThisArg,args))}}else if(impl2&&typeof impl2==="object"&&typeof impl2.default==="function"){if(wrapper.contextManager){resolve(wrapper.contextManager.runInContext(wrapper.instanceID,impl2.default,impl2,args,wrapper,true))}else{resolve(impl2.default.apply(impl2,args))}}else{reject(new wrapper.slothlet.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl2},null,{validationError:true}))}}catch(err){reject(err)}return}if(!wrapper.____slothletInternal.state.inFlight){reject(new wrapper.slothlet.SlothletError("INVALID_CONFIG_LAZY_MATERIALIZATION_FAILED",{apiPath:wrapper.____slothletInternal.apiPath},null,{validationError:true}));return}setImmediate(checkMaterialized)};checkMaterialized()})}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){if(wrapper.slothlet.contextManager){result=wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl,effectiveThisArg,args,wrapper,true)}else{result=impl.apply(effectiveThisArg,args)}}else if(impl&&typeof impl==="object"&&typeof impl.default==="function"){if(wrapper.slothlet.contextManager){result=wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl.default,impl,args,wrapper,true)}else{result=impl.default.apply(impl,args)}}else{throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl},null,{validationError:true})}if(result&&typeof result==="object"&&typeof result.then==="function"){isAsync=true;return result.then(resolvedResult=>{try{if(hasHooks){const afterResult=hookManager.executeAfterHooks(wrapper.____slothletInternal.apiPath,resolvedResult,args,api,ctx);const finalResult2=afterResult.modified?afterResult.result:resolvedResult;hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,finalResult2,false,[],api,ctx);return finalResult2}return resolvedResult}catch(error){if(hasHooks){const originalError=unwrapError(error);const sourceInfo={type:"after",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx);hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,void 0,true,[originalError],api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error}},error=>{if(hasHooks&&!error[ERROR_HOOK_PROCESSED]){const originalError=unwrapError(error);const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx)}if(hasHooks){const originalError=unwrapError(error);hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,void 0,true,[originalError],api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error})}finalResult=result;if(hasHooks){const afterResult=hookManager.executeAfterHooks(wrapper.____slothletInternal.apiPath,result,args,api,ctx);if(afterResult.modified){finalResult=afterResult.result}}return finalResult}catch(error){lastSyncError=error;if(hasHooks&&!error[ERROR_HOOK_PROCESSED]){const originalError=unwrapError(error);const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error}finally{if(hasHooks&&!isAsync){const syncError=lastSyncError;const resultValue=syncError?void 0:typeof finalResult!=="undefined"?finalResult:result;const errors=syncError?[unwrapError(syncError)]:[];hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,resultValue,!!syncError,errors,api,ctx)}}};const hasTrap=(target,prop)=>{if(prop==="_materialize"){return true}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){return true}if(!isInternal&&wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")&&prop in wrapper.____slothletInternal.impl){return true}return Object.prototype.hasOwnProperty.call(target,prop)};const getOwnPropertyDescriptorTrap=(target,prop)=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(prop==="____slothletInternal")return void 0;if(prop==="prototype"&&typeof target==="function"){const desc=Object.getOwnPropertyDescriptor(target,"prototype");if(desc){return desc}}const ownDesc=Object.getOwnPropertyDescriptor(target,prop);if((!ownDesc||ownDesc.configurable)&&runtime_isReadRedacted(wrapper,prop)){return void 0}if(Object.prototype.hasOwnProperty.call(target,prop)){return Object.getOwnPropertyDescriptor(target,prop)}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){const desc=Object.getOwnPropertyDescriptor(wrapper,prop);if(desc){return desc}}if(!isInternal&&wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")&&prop in wrapper.____slothletInternal.impl){return Object.getOwnPropertyDescriptor(wrapper.____slothletInternal.impl,prop)}return void 0};const ownKeysTrap=target=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const keys=new Set;if(typeof target==="function"||target&&target.__isCallable){keys.add("prototype");keys.add("length");keys.add("name")}for(const key of Reflect.ownKeys(target)){const descriptor=Object.getOwnPropertyDescriptor(target,key);if(!descriptor.configurable||descriptor.enumerable){keys.add(key)}}if(target!==wrapper){for(const key of Reflect.ownKeys(wrapper)){const descriptor=Object.getOwnPropertyDescriptor(wrapper,key);if(descriptor&&descriptor.enumerable){keys.add(key)}}}const implKeys=wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")?Reflect.ownKeys(wrapper.____slothletInternal.impl):[];for(const key of implKeys){if(key!=="prototype"&&!IMPL_METADATA_KEYS.has(key)){keys.add(key)}}for(const key of keys){const targetDesc=Object.getOwnPropertyDescriptor(target,key);if(targetDesc&&!targetDesc.configurable)continue;if(runtime_isReadRedacted(wrapper,key))keys.delete(key)}return Array.from(keys)};const setTrap=(target,prop,value)=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize()}if(UnifiedWrapper.INTERNAL_KEYS.has(prop)&&prop!=="_materialize")return true;const internalKeys=new Set(["_materialize"]);if(!internalKeys.has(prop)){const isObjectOrFunctionValue=value!==null&&(typeof value==="object"||typeof value==="function");if(!isObjectOrFunctionValue){const liveImpl=wrapper.____slothletInternal.impl;const isLiveIdentityWrapper=wrapper.____slothletInternal.deferChildAdopt||EventEmitter&&liveImpl instanceof EventEmitter;const hasLiveImpl=isLiveIdentityWrapper&&liveImpl!==null&&liveImpl!==void 0&&(typeof liveImpl==="object"||typeof liveImpl==="function");if(hasLiveImpl){const setSucceeded=Reflect.set(liveImpl,prop,value);if(!setSucceeded)return false;const existingDescriptor=Object.getOwnPropertyDescriptor(wrapper,prop);if(!existingDescriptor||typeof existingDescriptor.set!=="function"){Object.defineProperty(wrapper,prop,{get:()=>{const currentImpl=wrapper.____slothletInternal.impl;return currentImpl?currentImpl[prop]:void 0},set:newValue=>{const currentImpl=wrapper.____slothletInternal.impl;if(currentImpl)currentImpl[prop]=newValue},enumerable:true,configurable:true})}return true}}if(hasOwn(wrapper,prop)){delete wrapper[prop]}let stored=value;const inBuild=wrapper.slothlet.____buildDepth>0;if(!inBuild&&value!==null&&(typeof value==="object"||typeof value==="function")&&!util.types.isProxy(value)&&resolveWrapper(value)===null){const wrapped=wrapper.___createChildWrapper(prop,value,null,true);if(wrapped!==null&&wrapped!==void 0){const wrappedInternal=resolveWrapper(wrapped);if(wrappedInternal)wrappedInternal.____slothletInternal.userAssigned=true;stored=wrapped}}Object.defineProperty(wrapper,prop,{value:stored,writable:false,enumerable:true,configurable:true})}else{target[prop]=value}return true};const deletePropertyTrap=(target,prop)=>{const internalKeys=new Set(["____slothletInternal","__impl","___setImpl","___resetLazy","_materialize","___invalidate","_impl","___getState","__state","__mode","__apiPath","__slothletPath","__isCallable","__materializeOnCreate","__displayName","__type","__metadata","__invalid","__filePath","__sourceFolder","__moduleID","__materialized","__inFlight"]);if(internalKeys.has(prop)){return true}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){const childWrapper=wrapper[prop];const childWrapperRaw=resolveWrapper(childWrapper);if(childWrapperRaw){childWrapperRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(wrapper,prop);if(descriptor?.configurable){delete wrapper[prop]}}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&prop in wrapper.____slothletInternal.impl){delete wrapper.____slothletInternal.impl[prop]}delete target[prop];return true};const constructTrap=(target,args,newTarget)=>{if(wrapper.____slothletInternal.invalid){throw new TypeError(`${wrapper.____slothletInternal.apiPath||"api"} is invalidated`)}enforcePermission(wrapper);if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return Promise.resolve(wrapper.____slothletInternal.materializationPromise).then(()=>{if(!wrapper.____slothletInternal.state.materialized){throw new wrapper.slothlet.SlothletError("INVALID_CONFIG_LAZY_MATERIALIZATION_FAILED",{apiPath:wrapper.____slothletInternal.apiPath},null,{validationError:true})}const impl2=wrapper.____slothletInternal.impl;if(typeof impl2==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl2:newTarget;return Reflect.construct(impl2,args,effectiveNewTarget)}if(impl2&&typeof impl2==="object"&&typeof impl2.default==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl2.default:newTarget;return Reflect.construct(impl2.default,args,effectiveNewTarget)}throw new wrapper.slothlet.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl2},null,{validationError:true})})}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl:newTarget;return Reflect.construct(impl,args,effectiveNewTarget)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl.default:newTarget;return Reflect.construct(impl.default,args,effectiveNewTarget)}throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl},null,{validationError:true})};wrapper.____slothletInternal.proxy=new Proxy(proxyTarget,{get:(target,prop,receiver)=>runtime_bindCapturedIdentity(wrapper,prop,getTrap(target,prop,receiver)),apply:applyTrap,construct:constructTrap,has:hasTrap,getOwnPropertyDescriptor:getOwnPropertyDescriptorTrap,ownKeys:ownKeysTrap,set:setTrap,deleteProperty:deletePropertyTrap,getPrototypeOf:target=>{const internal=wrapper.____slothletInternal;const impl=internal.impl;if(Array.isArray(impl))return Array.prototype;if(!Reflect.isExtensible(target))return Reflect.getPrototypeOf(target);const isLiveIdentity=internal.deferChildAdopt||EventEmitter&&impl instanceof EventEmitter;if(isLiveIdentity&&impl&&typeof impl==="object")return Object.getPrototypeOf(impl);return null}});_proxyRegistry.set(wrapper.____slothletInternal.proxy,wrapper);genuineWrappers.add(wrapper);return wrapper.____slothletInternal.proxy}}Object.defineProperty(UnifiedWrapper.prototype,util.inspect.custom,{value:UnifiedWrapper.prototype.____inspectCustom,writable:true,enumerable:false,configurable:true});function resolveWrapper(value){if(!value)return null;const registered=_proxyRegistry.get(value);if(registered)return registered;if(value instanceof UnifiedWrapper&&value.____slothletInternal!=null)return value;return null}export{IMPL_METADATA_KEYS,TYPE_STATES,UnifiedWrapper,isFrameworkReservedKey,resolveWrapper};
17
+ const ____COLLISION_MERGED_PROPERTY=Symbol("collisionMergedProperty");import{isNode,util,EventEmitter}from"@cldmv/slothlet/helpers/platform";import{ComponentBase}from"#factories/component-base";import{TRUSTED_ROOT,genuineWrappers}from"#handlers/trusted-root";import{isFrameworkInternal,isFrameworkMarkerKey}from"#handlers/framework-internals";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");const hasOwn=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);function resolveEnforcedCaller(wrapper,ctxOverride){const ownInstanceID=wrapper.slothlet.instanceID;const ctx=ctxOverride!==void 0?ctxOverride:wrapper.slothlet.contextManager?.tryGetContext?.(ownInstanceID);const identity=ctxOverride!==void 0?ctxOverride:wrapper.slothlet.contextManager?.getCallerIdentity?.(ownInstanceID);if(identity?.unresolved)return{verdict:"deny"};const callerWrapper=identity?.currentWrapper;if(!callerWrapper){const store=ctx??wrapper.slothlet.contextManager?.instances?.get(wrapper.slothlet.instanceID);if(store&&store[TRUSTED_ROOT]===true)return{verdict:"allow"};if(wrapper.slothlet.config?.permissions?.failOpenOnAbsentCaller)return{verdict:"allow"};return{verdict:"deny"}}if(!genuineWrappers.has(callerWrapper))return{verdict:"deny"};return{verdict:"enforce",callerWrapper,ctx}}function runtime_enforceReadGate(wrapper,prop,resolvedValue,callerOverride){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return;if(!runtime_isTerminalData(resolvedValue))return;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);const decision=runtime_readGateDecision(wrapper,targetPath,callerOverride);if(decision.allowed)return;throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:decision.caller,target:targetPath})}function runtime_isTerminalData(value){return value!==Object(value)||value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer}function runtime_readGateDecision(wrapper,targetPath,callerOverride){if(isFrameworkInternal(wrapper)){const leafKey=targetPath.slice(targetPath.lastIndexOf(".")+1);if(isFrameworkMarkerKey(leafKey))return{allowed:true,caller:null}}const decision=resolveEnforcedCaller(wrapper,callerOverride);if(decision.verdict==="allow"){const hostPm=wrapper.slothlet.handlers.permissionManager;if(hostPm.isPrivateTarget?.(targetPath)&&!hostPm.enforceAccess(null,targetPath,null,wrapper.____slothletInternal.filePath,null)){return{allowed:false,caller:null}}return{allowed:true,caller:null}}if(decision.verdict==="deny")return{allowed:false,caller:null};const{callerWrapper,ctx}=decision;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const allowed=wrapper.slothlet.handlers.permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,ctx.context??null);return{allowed,caller:callerPath}}function runtime_isReadRedacted(wrapper,prop){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return false;const impl=wrapper.____slothletInternal?.impl;const desc=(impl&&(typeof impl==="object"||typeof impl==="function")?Object.getOwnPropertyDescriptor(impl,prop):void 0)??Object.getOwnPropertyDescriptor(wrapper,prop);if(!desc||!("value"in desc)||!runtime_isTerminalData(runtime_unwrapLeafValue(desc.value)))return false;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);return!runtime_readGateDecision(wrapper,targetPath).allowed}function runtime_unwrapLeafValue(value){let current=value;for(let depth=0;depth<8;depth++){if(!current||typeof current!=="object"&&typeof current!=="function")return current;const inner=_proxyRegistry.get(current)??(hasOwn(current,"____slothletInternal")?current:null);if(!inner)return current;current=inner.____slothletInternal?.impl}return current}function runtime_redactSerialized(wrapper,data,basePath,seen){if(!data||typeof data!=="object"||Array.isArray(data)||seen.has(data))return;seen.add(data);for(const key of Object.keys(data)){const value=data[key];const targetPath=`${basePath}.${key}`;if(runtime_isTerminalData(value)){if(!runtime_readGateDecision(wrapper,targetPath).allowed)delete data[key]}else{runtime_redactSerialized(wrapper,value,targetPath,seen)}}}function enforcePermission(wrapper){const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return;const targetPath=wrapper.____slothletInternal.apiPath;const decision=resolveEnforcedCaller(wrapper);if(decision.verdict==="allow"){if(permissionManager.isPrivateTarget?.(targetPath)&&!permissionManager.enforceAccess(null,targetPath,null,wrapper.____slothletInternal.filePath,null)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}return}if(decision.verdict==="deny"){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}const{callerWrapper,ctx}=decision;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=ctx?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}const capturedViews=new WeakMap;function runtime_enforceCapturedCaller(wrapper,capturedCaller,targetPathOverride){const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return;const targetPath=targetPathOverride??wrapper.____slothletInternal.apiPath;const callerPath=capturedCaller.____slothletInternal?.apiPath??"";const callerFilePath=capturedCaller.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=wrapper.slothlet.contextManager?.tryGetContext?.()?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}function runtime_capturedView(child,capturedCaller){let byChild=capturedViews.get(capturedCaller);if(!byChild){byChild=new WeakMap;capturedViews.set(capturedCaller,byChild)}const existing=byChild.get(child);if(existing)return existing;const inner=resolveWrapper(child);const view=new Proxy(child,{apply(target,thisArg,args){runtime_enforceCapturedCaller(inner,capturedCaller);return Reflect.apply(target,thisArg,args)},construct(target,args,newTarget){runtime_enforceCapturedCaller(inner,capturedCaller);return Reflect.construct(target,args,newTarget===view?target:newTarget)},get(target,prop){const resolved=Reflect.get(target,prop);if(resolved!==void 0&&typeof prop==="string"&&runtime_isTerminalData(resolved)){const context=inner.slothlet.contextManager?.tryGetContext?.()?.context??null;runtime_enforceReadGate(inner,prop,resolved,{currentWrapper:capturedCaller,context});return resolved}if(resolveWrapper(resolved)===null)return resolved;return runtime_capturedView(resolved,capturedCaller)}});byChild.set(child,view);return view}function runtime_bindCapturedIdentity(wrapper,prop,value){if(typeof prop!=="string")return value;if(value===null||typeof value!=="object"&&typeof value!=="function")return value;const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return value;if(permissionManager.isCaptureEnabled?.()===false)return value;const inner=resolveWrapper(value);if(inner===null)return value;const innerPath=inner.____slothletInternal?.apiPath;if(!innerPath||innerPath.split(".").pop()!==prop)return value;const capturedCaller=wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;if(!capturedCaller)return value;return runtime_capturedView(value,capturedCaller)}function runtime_guardPromotedResult(promise,path,SlothletErrorCtor){const refuse=()=>{throw new SlothletErrorCtor("HOOK_PROMOTED_RESULT_NOT_AWAITED",{path},null,{validationError:true})};return new Proxy(promise,{get(target,prop,receiver){if(prop===Symbol.toPrimitive||prop==="valueOf"||prop==="toString"||prop==="toJSON"){return refuse}const value=Reflect.get(target,prop,receiver);if(prop==="then"||prop==="catch"||prop==="finally")return value.bind(target);return value}})}function unwrapError(error){if(error&&error.name==="SlothletError"&&error.originalError){return error.originalError}return error}const wrapperDebugEnabled=isNode&&(process.env.SLOTHLET_DEBUG_WRAPPER==="1"||process.env.SLOTHLET_DEBUG_WRAPPER==="true"||process.env.SLOTHLET_DEBUG_SCRIPT_VERBOSE==="1"||process.env.SLOTHLET_DEBUG_SCRIPT_VERBOSE==="true");const IMPL_METADATA_KEYS=new Set(["__childFilePaths","__filePath","__childFilePathsPreMaterialize"]);function isFrameworkReservedKey(key){if(typeof key!=="string")return false;return UnifiedWrapper.INTERNAL_KEYS.has(key)||IMPL_METADATA_KEYS.has(key)}const TYPE_STATES={UNMATERIALIZED:Symbol("unmaterialized"),IN_FLIGHT:Symbol("inFlight")};function getSafeFunctionName(apiPath,fallback){const parts=String(apiPath||"").split(".").filter(part=>part&&part!=="null");const baseName=parts.length>0?parts[parts.length-1]:"";let safeName=String(baseName||"").replace(/[^A-Za-z0-9_$]/g,"_");if(!safeName||!/^[A-Za-z_$]/.test(safeName[0])){safeName=safeName?`_${safeName}`:""}return safeName||fallback}function createNamedProxyTarget(nameHint,fallback){const safeName=getSafeFunctionName(nameHint,fallback);return{[safeName]:function(){}}[safeName]}const _proxyRegistry=new WeakMap;class UnifiedWrapper extends ComponentBase{#internal=null;get ____slothletInternal(){if(!(#internal in this))return void 0;return this.#internal}constructor(slothlet,{mode,apiPath,initialImpl=null,materializeFunc=null,isCallable,materializeOnCreate=false,filePath=null,moduleID=null,sourceFolder=null,__adoptVisited=null,deferChildAdopt=false}){super(slothlet);const isCallableExplicit=typeof isCallable==="boolean";const isCallableValue=isCallableExplicit?isCallable:typeof initialImpl==="function"||initialImpl&&typeof initialImpl.default==="function";const isCallableLocked=isCallableValue||isCallableExplicit;const internal=Object.create(null);internal.id=Math.random().toString(36).substr(2,9);internal.mode=mode;internal.apiPath=apiPath;internal.materializeOnCreate=materializeOnCreate;internal.isCallable=isCallableValue;internal.isCallableLocked=isCallableLocked;internal.moduleID=moduleID;internal.filePath=filePath;internal.sourceFolder=sourceFolder;internal.adoptVisited=__adoptVisited;internal.deferChildAdopt=deferChildAdopt;internal.invalid=false;internal.state={materialized:initialImpl!==null,inFlight:false,collisionMode:"merge"};internal.displayName=apiPath?`${String(apiPath).replace(/\./g,"__")}__UnifiedWrapper`:"UnifiedWrapper";this.#internal=internal;const wrapper=this;Object.defineProperty(internal,"wrapper",{get(){return wrapper},enumerable:false,configurable:false});internal.callableImpl=null;internal.waitingProxyCache=new Map;internal.waitingProxyCacheByContext=new WeakMap;internal.proxy=null;const isRootLiveIdentity=deferChildAdopt||EventEmitter&&initialImpl instanceof EventEmitter;internal.impl=isRootLiveIdentity?initialImpl:UnifiedWrapper._cloneImpl(initialImpl);internal.materializeFunc=materializeFunc;if(filePath&&slothlet.handlers?.lifecycle){slothlet.handlers.lifecycle.emitInternal("impl:created",{apiPath,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),__wrapperRef:this,source:"initial",moduleID,filePath,sourceFolder:sourceFolder||slothlet.config?.dir})}if(initialImpl!==null&&!deferChildAdopt){const implKeys=Object.keys(initialImpl||{});if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&apiPath&&(apiPath==="config"||apiPath.startsWith("config."))){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAPPER_CONSTRUCTOR_IMPL_KEYS",apiPath,keyCount:implKeys.length,keySample:implKeys.slice(0,5)})}this.___adoptImplChildren();if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&apiPath&&(apiPath==="config"||apiPath.startsWith("config."))){const childKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAPPER_CONSTRUCTOR_AFTER_ADOPT",apiPath,childCount:childKeys.length,childKeySample:childKeys.slice(0,5)})}}if(mode==="lazy"){slothlet._registerLazyWrapper();if(slothlet.config.tracking?.materialization){setImmediate(()=>{this._materialize().catch(err=>{if(slothlet.config?.debug?.materialize){slothlet.debug("materialize",{key:"DEBUG_MODE_BACKGROUND_MATERIALIZE_ERROR",apiPath:this.____slothletInternal?.apiPath,error:err.message})}})})}}}____inspectCustom(____depth,____options,____inspect){const w=_proxyRegistry.get(this)??this;const childKeys=Object.keys(w).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!w.____slothletInternal?.isCallable){const inspectObj={};for(const key of childKeys){inspectObj[key]=w[key]}return inspectObj}if(w.____slothletInternal?.mode==="lazy"&&w.____slothletInternal?.state&&!w.____slothletInternal?.state.materialized&&w.____slothletInternal?.proxy){return w.____slothletInternal.proxy}return w.____slothletInternal?.impl}get __impl(){return this.____slothletInternal.impl}static _cloneImpl(value){if(value&&typeof value==="object"&&!Array.isArray(value)&&typeof value!=="function"){const isProxy=util.types.isProxy(value);if(isProxy){if(resolveWrapper(value)){const clone={};for(const key of Reflect.ownKeys(value)){try{clone[key]=value[key]}catch{}}return clone}return value}const uw_cloneDescriptors=Object.getOwnPropertyDescriptors(value);return Object.create(Object.getPrototypeOf(value),uw_cloneDescriptors)}return value}static _extractFullImpl(wrapper){if(!wrapper)return null;const impl=wrapper.____slothletInternal.impl;if(impl===null||impl===void 0)return impl;if(typeof impl!=="object"&&typeof impl!=="function")return impl;if(typeof impl==="function")return impl;if(Array.isArray(impl))return impl.slice();const extractFullImpl_result={};for(const key of Object.keys(impl)){if(isFrameworkReservedKey(key))continue;extractFullImpl_result[key]=impl[key]}if(impl.__childFilePaths){extractFullImpl_result.__childFilePaths=impl.__childFilePaths}if(impl.__childFilePathsPreMaterialize){extractFullImpl_result.__childFilePathsPreMaterialize=impl.__childFilePathsPreMaterialize}for(const key of Object.keys(wrapper)){if(UnifiedWrapper.INTERNAL_KEYS.has(key))continue;if(key in extractFullImpl_result)continue;const extractFullImpl_child=wrapper[key];const _extractChildW=resolveWrapper(extractFullImpl_child);if(_extractChildW){extractFullImpl_result[key]=UnifiedWrapper._extractFullImpl(_extractChildW)}else{extractFullImpl_result[key]=extractFullImpl_child}}return extractFullImpl_result}_applyNewImpl(newImpl,forceReuseChildren=false){this.____slothletInternal.impl=UnifiedWrapper._cloneImpl(newImpl);this.____slothletInternal.invalid=false;if(!this.____slothletInternal.isCallableLocked&&!this.____slothletInternal.isCallable&&(typeof newImpl==="function"||newImpl&&typeof newImpl.default==="function")){this.____slothletInternal.isCallable=true;this.____slothletInternal.isCallableLocked=true}if(!this.____slothletInternal.filePath&&this.____slothletInternal.impl&&this.____slothletInternal.impl.__filePath){this.____slothletInternal.filePath=this.____slothletInternal.impl.__filePath;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_APPLY_IMPL_UPDATE_PATH",apiPath:this.____slothletInternal.apiPath,filePath:this.____slothletInternal.filePath})}this.___adoptImplChildren(forceReuseChildren)}___setImpl(newImpl,moduleID=null,forceReuseChildren=false){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_SETIMPL_CALLED",apiPath:this.____slothletInternal.apiPath,newImplKeys:Object.keys(newImpl||{})})}this._applyNewImpl(newImpl,forceReuseChildren);if(newImpl&&this.slothlet.handlers?.lifecycle){const wrapperMetadata=this.slothlet.handlers.metadata.getMetadata(this);const extractedModuleId=moduleID||wrapperMetadata?.baseModuleID||null;this.slothlet.handlers.lifecycle.emitInternal("impl:changed",{apiPath:this.____slothletInternal.apiPath,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),__wrapperRef:this,source:"hot-reload",moduleID:extractedModuleId,filePath:wrapperMetadata?.filePath,sourceFolder:wrapperMetadata?.sourceFolder})}this.____slothletInternal.state.materialized=true;this.____slothletInternal.state.inFlight=false;if(this.slothlet._onWrapperMaterialized){this.slothlet._onWrapperMaterialized()}}___resetLazy(newMaterializeFunc){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_RESETLAZY_CALLED",apiPath:this.____slothletInternal.apiPath,hadImpl:this.____slothletInternal.impl!==null,hadChildren:Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).length});for(const key of Reflect.ownKeys(this)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"))){continue}const child=this[key];const childRaw=resolveWrapper(child);if(childRaw){childRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}this.____slothletInternal.impl=null;this.____slothletInternal.invalid=false;this.____slothletInternal.state.materialized=false;this.____slothletInternal.state.inFlight=false;this.____slothletInternal.materializationPromise=null;this.____slothletInternal.materializeFunc=newMaterializeFunc;if(this.____slothletInternal.waitingProxyCache){this.____slothletInternal.waitingProxyCache.clear()}this.____slothletInternal.waitingProxyCacheByContext=new WeakMap;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_RESETLAZY_COMPLETE",apiPath:this.____slothletInternal.apiPath})}async ___materialize(){if(this.____slothletInternal.state.materialized){return}if(this.____slothletInternal.invalid){return}if(this.____slothletInternal.materializationPromise){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_AWAIT",apiPath:this.____slothletInternal.apiPath});return this.____slothletInternal.materializationPromise}if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_START",apiPath:this.apiPath})}this.____slothletInternal.materializationPromise=(async()=>{this.____slothletInternal.state.inFlight=true;try{if(this.____slothletInternal.materializeFunc){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_CALLING_FUNC",apiPath:this.____slothletInternal.apiPath})}const lazy_setImpl=value=>{if(this.____slothletInternal.invalid)return;this._applyNewImpl(value)};const result=await this.____slothletInternal.materializeFunc(lazy_setImpl);if(this.____slothletInternal.invalid){return}if(!this.____slothletInternal.impl){this._applyNewImpl(result)}this.____slothletInternal.state.materialized=true;if(this.slothlet._onWrapperMaterialized){this.slothlet._onWrapperMaterialized()}if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_COMPLETE",apiPath:this.____slothletInternal.apiPath,resultType:typeof result,resultKeys:Object.keys(result||{})})}}}catch(error){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_ERROR",apiPath:this.____slothletInternal.apiPath,error:error.message})}throw error}finally{this.____slothletInternal.state.inFlight=false;this.____slothletInternal.materializationPromise=null}})();return this.____slothletInternal.materializationPromise}_materialize(){return this.___materialize()}___invalidate(){this.____slothletInternal.invalid=true;this.____slothletInternal.impl=null;for(const key of Reflect.ownKeys(this)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"))){continue}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}___adoptImplChildren(forceReuseChildren=false){const preExistingKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_START",apiPath:this.____slothletInternal.apiPath,wrapperId:this.____slothletInternal.id||"no-id",preExistingKeys:preExistingKeys.join(","),collisionMode:this.____slothletInternal.state.collisionMode});const threadedVisited=this.____slothletInternal.adoptVisited;this.____slothletInternal.adoptVisited=null;if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){return}if(util.types.isProxy(this.____slothletInternal.impl))return;if(Array.isArray(this.____slothletInternal.impl))return;if(EventEmitter&&this.____slothletInternal.impl instanceof EventEmitter)return;const adoptVisited=threadedVisited||new WeakSet;const ownKeys=Reflect.ownKeys(this.____slothletInternal.impl);const internalKeys=new Set(["__impl","___setImpl","___resetLazy","_materialize","_impl","_state","_invalid","____slothlet","____slothletInternal"]);const keepImplProperties=typeof this.____slothletInternal.impl==="function"||this.____slothletInternal.impl&&typeof this.____slothletInternal.impl==="object"&&typeof this.____slothletInternal.impl.default==="function";if(keepImplProperties&&this.____slothletInternal.impl&&typeof this.____slothletInternal.impl==="object"&&typeof this.____slothletInternal.impl.default==="function"){internalKeys.add("default")}const observedKeys=new Set;const existingKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));const storedCollisionMode=this.____slothletInternal.state.collisionMode;const isMergeScenario=storedCollisionMode!=="replace"&&existingKeys.length>0;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT",apiPath:this.____slothletInternal.apiPath,mode:this.____slothletInternal.mode,storedCollisionMode,existingKeys:existingKeys.join(","),isMergeScenario});const savedChildren=new Map;if(storedCollisionMode==="replace"&&existingKeys.length>0){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_REPLACE_CLEARING",count:existingKeys.length});for(const key of existingKeys){const child=this[key];if(resolveWrapper(child)!==null){savedChildren.set(key,child)}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}else{for(const key of existingKeys){observedKeys.add(key)}}const metadataKeys=new Set(["__childFilePaths","__filePath","__childFilePathsPreMaterialize"]);const skipKeys=typeof this.____slothletInternal.impl==="function"?new Set(["length","name","prototype"]):null;for(const key of ownKeys){if(internalKeys.has(key)){continue}if(typeof key==="string"&&metadataKeys.has(key)){continue}if(skipKeys&&typeof key==="string"&&skipKeys.has(key)){continue}if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){break}const descriptor=Object.getOwnPropertyDescriptor(this.____slothletInternal.impl,key);if(!descriptor){continue}const value=this.____slothletInternal.impl[key];if(value===this.____slothletInternal.impl){continue}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_PROCESS",apiPath:this.____slothletInternal.apiPath,propKey:key,typeOf:typeof value,valueName:value?.name})}observedKeys.add(key);if(hasOwn(this,key)&&!key.toString().startsWith("_")){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_CHECK",apiPath:this.____slothletInternal.apiPath,propKey:key,has__collisionMergedKeys:!!this.____slothletInternal.collisionMergedKeys,inSet:this.____slothletInternal.collisionMergedKeys?.has(key)})}const isCollisionMerged=this.____slothletInternal.collisionMergedKeys&&this.____slothletInternal.collisionMergedKeys.has(key);if(isCollisionMerged&&!forceReuseChildren){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_SKIP_COLLISION_MERGED",apiPath:this.____slothletInternal.apiPath,propKey:key})}if(descriptor.configurable){delete this.____slothletInternal.impl[key]}continue}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_ALLOW_NOT_COLLISION_MERGED",apiPath:this.____slothletInternal.apiPath,propKey:key})}}const existingChild=savedChildren.get(key)||this[key];let wrapped;const skipChildReuse=!forceReuseChildren&&this.____slothletInternal.mode==="lazy"&&storedCollisionMode==="replace";const existingChildUA=existingChild?resolveWrapper(existingChild):null;if(existingChildUA?.____slothletInternal?.userAssigned){wrapped=existingChild}else if(!skipChildReuse&&existingChild&&resolveWrapper(existingChild)!==null){if(resolveWrapper(value)!==null){const newWrapper=resolveWrapper(value);let rawImpl=newWrapper?newWrapper.____slothletInternal.impl:null;if(rawImpl&&typeof rawImpl==="object"&&!Array.isArray(rawImpl)&&typeof rawImpl!=="function"&&Object.keys(rawImpl).filter(k=>!k.startsWith("__")).length===0){const wrapperOwnKeys=Object.keys(newWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(wrapperOwnKeys.length>0){rawImpl=UnifiedWrapper._extractFullImpl(newWrapper)}}if(rawImpl!==null&&rawImpl!==void 0){resolveWrapper(existingChild).___setImpl(rawImpl,this.____slothletInternal.moduleID,true)}else if(newWrapper&&newWrapper.____slothletInternal.materializeFunc){const existingChildWrapper=resolveWrapper(existingChild);if(existingChildWrapper){existingChildWrapper.___resetLazy(newWrapper.____slothletInternal.materializeFunc)}}wrapped=existingChild}else{resolveWrapper(existingChild).___setImpl(value,this.____slothletInternal.moduleID,true);wrapped=existingChild}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_REUSE_CHILD_WRAPPER",apiPath:this.____slothletInternal.apiPath,propKey:key})}}else{wrapped=this.___createChildWrapper(key,value,adoptVisited,this.____slothletInternal.deferChildAdopt);if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_WRAP",apiPath:this.____slothletInternal.apiPath,propKey:key,wrapped:wrapped?"YES":wrapped===null?"NULL":"NO"})}}if(wrapped){const existing=this[key];const existingDescriptor=Object.getOwnPropertyDescriptor(this,key);if(existing===wrapped||existingDescriptor&&!existingDescriptor.configurable){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:existingDescriptor&&!existingDescriptor.configurable?"DEBUG_MODE_ADOPT_SKIP_NON_CONFIGURABLE":"DEBUG_MODE_ADOPT_SKIP_SAME_WRAPPER",apiPath:this.____slothletInternal.apiPath,propKey:key})}}else{if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_DEFINE",apiPath:this.____slothletInternal.apiPath,propKey:key})}Object.defineProperty(this,key,{value:wrapped,writable:false,enumerable:true,configurable:true});if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_DEFINED",apiPath:this.____slothletInternal.apiPath,propKey:key})}}if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}else if(wrapped===null&&this.____slothletInternal.deferChildAdopt&&(value===null||typeof value!=="object"&&typeof value!=="function")){Object.defineProperty(this,key,{get:()=>{const currentImpl=this.____slothletInternal.impl;return currentImpl?currentImpl[key]:void 0},set:newValue=>{const currentImpl=this.____slothletInternal.impl;if(currentImpl)currentImpl[key]=newValue},enumerable:true,configurable:true})}else if(wrapped===null){Object.defineProperty(this,key,{value,writable:false,enumerable:true,configurable:true});if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}else{Object.defineProperty(this,key,{value,writable:false,enumerable:true,configurable:true});if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}}if(!isMergeScenario){const currentKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of currentKeys){if(!observedKeys.has(key)){const existing=this[key];const existingRaw=resolveWrapper(existing);if(existingRaw){existingRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}}if(this._mergeAfterMaterialize){const{existingWrapper,isMergeReplace:____isMergeReplace}=this._mergeAfterMaterialize;const existingKeys2=Object.keys(existingWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of existingKeys2){if(!(key in this)||key.startsWith("_")||key.startsWith("__")){const child=existingWrapper[key];Object.defineProperty(this,key,{value:child,writable:false,enumerable:true,configurable:true})}}delete this._mergeAfterMaterialize}}___createChildWrapper(key,value,visited=null,deferChildAdopt=false){if(value===void 0){return void 0}if(value===null){return null}if(value&&resolveWrapper(value)!==null){return value}if(value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer){return null}if(deferChildAdopt&&typeof value!=="object"&&typeof value!=="function"){return null}const trackCycle=typeof value==="object"||typeof value==="function";if(trackCycle){visited??=new WeakSet;if(visited.has(value)){return null}}let childImpl=value;const isChildLiveIdentity=deferChildAdopt||EventEmitter&&childImpl instanceof EventEmitter;if(!isChildLiveIdentity&&childImpl&&typeof childImpl==="object"){if(Array.isArray(childImpl)){childImpl=childImpl.slice()}else{const descriptors=Object.getOwnPropertyDescriptors(childImpl);childImpl=Object.create(Object.getPrototypeOf(childImpl),descriptors)}}const parentMetadata=this.slothlet.handlers?.metadata?.getMetadata(this);const childExistingMetadata=this.slothlet.handlers?.metadata?.getMetadata(value);let childFilePath=childExistingMetadata?.filePath||null;let childModuleId=null;if(!childFilePath){const keyStr=typeof key==="symbol"?String(key):key;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_CHECK",apiPath:this.apiPath,propKey:keyStr,has_impl:!!this.____slothletInternal.impl,has__childFilePaths:!!(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths),has__childFilePathsPreMaterialize:!!this.____slothletInternal.childFilePathsPreMaterialize,parentFilePath:parentMetadata?.filePath});if(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_AVAILABLE",keys:Object.keys(this.____slothletInternal.impl.__childFilePaths).join(","),propKey:keyStr,found:!!this.____slothletInternal.impl.__childFilePaths[key]})}if(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths&&this.____slothletInternal.impl.__childFilePaths[key]){childFilePath=this.____slothletInternal.impl.__childFilePaths[key];this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_USING",childFilePath})}else if(this.____slothletInternal.childFilePathsPreMaterialize&&this.____slothletInternal.childFilePathsPreMaterialize[key]){childFilePath=this.____slothletInternal.childFilePathsPreMaterialize[key];this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_PRE_MAT",childFilePath})}else{childFilePath=parentMetadata?.filePath||null;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_FALLBACK",childFilePath})}}if(parentMetadata?.baseModuleID){childModuleId=parentMetadata.baseModuleID}const childSourceFolder=childExistingMetadata?.sourceFolder||parentMetadata?.sourceFolder||null;if(trackCycle){visited.add(value)}let nestedWrapper;try{nestedWrapper=new UnifiedWrapper(this.slothlet,{mode:"eager",apiPath:this.____slothletInternal.apiPath?`${this.____slothletInternal.apiPath}.${typeof key==="symbol"?String(key):key}`:String(key),initialImpl:childImpl,isCallable:typeof childImpl==="function",filePath:childFilePath,moduleID:childModuleId,sourceFolder:childSourceFolder,__adoptVisited:visited,deferChildAdopt})}finally{if(trackCycle){visited.delete(value)}}return nestedWrapper.createProxy()}___createWaitingProxy(propChain=[]){const wrapper=this;const __readGateStore=wrapper.slothlet.contextManager?.tryGetContext?.();const __readGateCaller=__readGateStore?{currentWrapper:wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null,context:__readGateStore.context,[TRUSTED_ROOT]:__readGateStore[TRUSTED_ROOT]===true}:null;const __callerKey=__readGateCaller?.currentWrapper?.____slothletInternal?.apiPath??"";const cacheKey=`${__callerKey}::${propChain.join(".")}`;const __readGateContextRef=__readGateStore?.context??null;const useContextBucket=__readGateContextRef&&typeof __readGateContextRef==="object";let cache;if(useContextBucket){cache=wrapper.____slothletInternal.waitingProxyCacheByContext.get(__readGateContextRef);if(!cache){cache=new Map;wrapper.____slothletInternal.waitingProxyCacheByContext.set(__readGateContextRef,cache)}}else{cache=wrapper.____slothletInternal.waitingProxyCache}if(cache.has(cacheKey)){return cache.get(cacheKey)}const waitingTarget=createNamedProxyTarget(`${wrapper.____slothletInternal.apiPath}_waitingProxy`,"waitingProxyTarget");const waitingProxy=new Proxy(waitingTarget,{get(___target,prop){if(prop==="then"){return(onFulfilled,onRejected)=>{const waitingProxy_thenResolve=async()=>{if(!wrapper.____slothletInternal.state.materialized){await wrapper._materialize()}let current=wrapper;let __gateParent=null;let __gateProp=null;const __descendRest=(startValue,nextIndex)=>{let descended=startValue;for(let __di=nextIndex;__di<propChain.length;__di++){if(descended===null||descended===void 0)return void 0;descended=descended[propChain[__di]]}return descended};for(let __chainIndex=0;__chainIndex<propChain.length;__chainIndex++){const chainProp=propChain[__chainIndex];if(!current)return void 0;if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){let result=current.____slothletInternal.impl;for(let i=__chainIndex;i<propChain.length;i++){result=result[propChain[i]]}return result}const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&hasOwn(current,chainProp)){const child=current[chainProp];const _childW=resolveWrapper(child);if(_childW){__gateParent=current;__gateProp=chainProp;current=_childW;if(current.____slothletInternal.mode==="lazy"&&!current.____slothletInternal.state.materialized){await current._materialize()}continue}if(__chainIndex<propChain.length-1){const descendedChild=__descendRest(child,__chainIndex+1);if(descendedChild!==void 0){runtime_enforceReadGate(current,propChain.slice(__chainIndex).join("."),descendedChild,__readGateCaller)}return descendedChild}runtime_enforceReadGate(current,chainProp,child,__readGateCaller);return child}if(current.____slothletInternal.impl&&current.____slothletInternal.impl[chainProp]!==void 0){const implValue=current.____slothletInternal.impl[chainProp];if(__chainIndex<propChain.length-1){const descendedImpl=__descendRest(implValue,__chainIndex+1);if(descendedImpl!==void 0){runtime_enforceReadGate(current,propChain.slice(__chainIndex).join("."),descendedImpl,__readGateCaller)}return descendedImpl}runtime_enforceReadGate(current,chainProp,implValue,__readGateCaller);return implValue}return void 0}if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl}if(__gateParent){runtime_enforceReadGate(__gateParent,__gateProp,current.____slothletInternal.impl,__readGateCaller)}const finalImpl=current.____slothletInternal.impl;const callableCarriesWrapperMembers=typeof finalImpl==="function"&&Object.keys(current).some(key=>!isFrameworkReservedKey(key)&&!Object.prototype.hasOwnProperty.call(finalImpl,key));if(callableCarriesWrapperMembers||finalImpl!==null&&typeof finalImpl==="object"&&!Array.isArray(finalImpl)&&!runtime_isTerminalData(finalImpl)){const resolvedProxy=current.____slothletInternal.proxy;const __capturedReader=__readGateCaller?.currentWrapper??null;const __pm=wrapper.slothlet.handlers?.permissionManager;if(__capturedReader&&__pm&&__pm.isEnabled()&&__pm.isCaptureEnabled?.()!==false){return runtime_capturedView(resolvedProxy,__capturedReader)}return resolvedProxy}return finalImpl};waitingProxy_thenResolve().then(onFulfilled,onRejected)}}if(prop==="____slothletInternal")return void 0;if(prop==="_materialize")return wrapper._materialize.bind(wrapper);if(prop==="__mode")return wrapper.____slothletInternal.mode;if(prop==="__materialized")return wrapper.____slothletInternal.state.materialized;if(prop==="__inFlight")return wrapper.____slothletInternal.state.inFlight;if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(prop===util.inspect.custom){if(wrapper.____slothletInternal.state.inFlight){return waitingTarget}if(!wrapper.____slothletInternal.state.materialized){return waitingTarget}if(wrapper.____slothletInternal.impl){let current=wrapper.____slothletInternal.impl;for(const chainProp of propChain){if(!current){return void 0}current=current[chainProp]}return current}return waitingTarget}if(prop==="__type"){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE",apiPath:wrapper.apiPath,propChain:propChain.join(","),materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null});if(wrapper.____slothletInternal.state.materialized||wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){let current=wrapper.createProxy();for(const chainProp of propChain){if(!current)break;const currentWrapper=resolveWrapper(current);if(currentWrapper){const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&hasOwn(currentWrapper,chainProp)){current=currentWrapper[chainProp];wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_WRAPPER",chainProp:String(chainProp),typeOf:typeof current});continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&&currentWrapper.____slothletInternal.impl!==null&&chainProp in currentWrapper.____slothletInternal.impl){current=currentWrapper.____slothletInternal.impl[chainProp];wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_IMPL",chainProp:String(chainProp),typeOf:typeof current});continue}}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_DIRECT",chainProp:String(chainProp),typeOf:typeof current});current=current[chainProp]}const resolvedType=typeof current==="function"?"function":typeof current==="object"&&current!==null?"object":typeof current;wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_RESOLVED",apiPath:wrapper.apiPath,propChain:propChain.join(","),resolvedType});return resolvedType}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_INFLIGHT",apiPath:wrapper.apiPath,propChain:propChain.join(",")});return TYPE_STATES.IN_FLIGHT}if(prop==="__metadata"){if(wrapper.slothlet.handlers?.metadata){return wrapper.slothlet.handlers.metadata.getMetadata(wrapper)}return{}}if(typeof prop==="symbol")return void 0;if(prop==="length"){return 0}if(prop==="name")return waitingTarget.name||"waitingProxyTarget";if(prop==="toString"){return Function.prototype.toString.bind(waitingTarget)}if(prop==="valueOf"){return Function.prototype.valueOf.bind(waitingTarget)}if(prop==="toJSON"){return()=>void 0}if(prop==="__slothletPath")return wrapper.____slothletInternal.apiPath;if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){let result=wrapper.____slothletInternal.impl;for(const chainProp of propChain){result=result[chainProp]}return result[prop]}if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){let current=wrapper;let remainingChain=[...propChain];for(let i=0;i<propChain.length;i++){const chainProp=propChain[i];if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){let proxyResult=current.____slothletInternal.impl;for(const remainingProp of remainingChain){proxyResult=proxyResult[remainingProp]}return proxyResult[prop]}const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&current&&hasOwn(current,chainProp)){const cached=current[chainProp];const _cachedW2=resolveWrapper(cached);if(_cachedW2){current=_cachedW2;remainingChain.shift()}else{return void 0}}else{return void 0}}if(current&&current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl[prop]}const isFinalInternal=isFrameworkReservedKey(prop);if(!isFinalInternal&&hasOwn(current,prop)){return current[prop]}return void 0}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_PREMATURE",apiPath:wrapper.____slothletInternal.apiPath,prop});return wrapper[prop]}if(wrapper.____slothletInternal.needsImmediateChildAdoption&&wrapper.____slothletInternal.materializeFunc&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT",apiPath:wrapper.____slothletInternal.apiPath,prop});wrapper._materialize().catch(err=>{wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT_ERROR",apiPath:wrapper.apiPath,error:err.message})});const isInternal2=isFrameworkReservedKey(prop);if(!isInternal2&&hasOwn(wrapper,prop)){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT_SUCCESS",apiPath:wrapper.____slothletInternal.apiPath,prop});return wrapper[prop]}}if(wrapper.____slothletInternal.state.inFlight){return wrapper.___createWaitingProxy([...propChain,prop])}return wrapper.___createWaitingProxy([...propChain,prop])},async apply(___target,___thisArg,args){const ___liveCallerWrapper=wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null;const ___capture=wrapper.slothlet.handlers?.permissionManager?.isCaptureEnabled()!==false;const ___creationCallerWrapper=___capture?__readGateCaller?.currentWrapper??null:null;const ___capturedCallerWrapper=___liveCallerWrapper??___creationCallerWrapper;wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_ENTRY",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(","),args:args.join(",")});const chainLabel=propChain.map(prop=>String(prop)).join(".");if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_MATERIALIZE",apiPath:wrapper.____slothletInternal.apiPath});await wrapper._materialize();wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_MATERIALIZED",apiPath:wrapper.____slothletInternal.apiPath})}else if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&wrapper.____slothletInternal.state.inFlight){if(wrapper.____slothletInternal.materializationPromise){await wrapper.____slothletInternal.materializationPromise}else{await wrapper._materialize()}}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_START_WALK",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(",")});let current=wrapper.createProxy();let lastWrapper=wrapper;let lastObject=null;for(const prop of propChain){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_WALK",prop:String(prop),typeOf:typeof current,constructorName:current?.constructor?.name});if(!current){if(propChain.some(p=>typeof p==="symbol")){return void 0}if(wrapper.____slothletInternal.invalid||wrapper.____slothletInternal.impl===null||lastWrapper&&(lastWrapper.__invalid||lastWrapper._impl===null)){return void 0}const finalProp=propChain[propChain.length-1];if(finalProp==="hasAttribute"||finalProp==="toJSON"||finalProp===Symbol.toStringTag||finalProp==="constructor"||typeof finalProp==="symbol"||typeof prop==="symbol"){return void 0}throw new wrapper.slothlet.SlothletError("CHAIN_ACCESS_UNDEFINED",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel,prop:String(prop)},null,{validationError:true})}const currentWrapper=resolveWrapper(current);if(currentWrapper){const state=currentWrapper.____slothletInternal.state;if(!state.materialized){if(!state.inFlight&&typeof current._materialize==="function"){await current._materialize()}while(!currentWrapper.____slothletInternal.state.materialized){const nextState=currentWrapper.____slothletInternal.state;if(!nextState.inFlight&&!nextState.materialized){throw new wrapper.slothlet.SlothletError("CHAIN_MATERIALIZE_FAILED",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel,prop:String(prop)},null,{validationError:true})}await new Promise(resolve=>setImmediate(resolve))}}}if(currentWrapper){lastWrapper=currentWrapper;const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(currentWrapper,prop)){lastObject=current;current=currentWrapper[prop];continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&&currentWrapper.____slothletInternal.impl!==null&&prop in currentWrapper.____slothletInternal.impl){lastObject=currentWrapper.____slothletInternal.impl;current=currentWrapper.____slothletInternal.impl[prop];continue}}lastObject=current;current=current[prop]}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(","),typeOf:typeof current,currentName:current?.name,isFunction:typeof current==="function"});if(typeof current==="function"){if(___creationCallerWrapper&&___creationCallerWrapper!==___capturedCallerWrapper){const ___resolvedInner=resolveWrapper(current);const ___targetPath=___resolvedInner?.____slothletInternal?.apiPath??[wrapper.____slothletInternal.apiPath,...propChain].filter(Boolean).join(".");runtime_enforceCapturedCaller(wrapper,___creationCallerWrapper,___targetPath)}if(___capturedCallerWrapper&&wrapper.slothlet.contextManager){const ___instanceStore=wrapper.slothlet.contextManager.instances?.get?.(wrapper.instanceID);if(___instanceStore&&!___instanceStore.currentWrapper){return wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,()=>Reflect.apply(current,lastObject,args),null,[],___capturedCallerWrapper,true)}}const ___identityStore=___capturedCallerWrapper?wrapper.slothlet.contextManager?.instances?.get?.(wrapper.instanceID):null;if(!___identityStore)return Reflect.apply(current,lastObject,args);const ___previousAuthoritative=___identityStore.__authoritativeWrapper;___identityStore.__authoritativeWrapper=___capturedCallerWrapper;try{return Reflect.apply(current,lastObject,args)}finally{___identityStore.__authoritativeWrapper=___previousAuthoritative}}const _finalChainProp=propChain[propChain.length-1];if(_finalChainProp==="hasAttribute"||_finalChainProp==="toJSON"){return void 0}if(current===void 0||current===null){throw new wrapper.slothlet.SlothletError("CHAIN_NOT_CALLABLE",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel},null,{validationError:true})}throw new wrapper.slothlet.SlothletError("CHAIN_NOT_CALLABLE",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel},null,{validationError:true})},getPrototypeOf:()=>null});_proxyRegistry.set(waitingProxy,wrapper);cache.set(cacheKey,waitingProxy);return waitingProxy}createProxy(){const wrapper=this;if(wrapper.____slothletInternal.proxy){return wrapper.____slothletInternal.proxy}if(wrapper.____slothletInternal.materializeOnCreate&&wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&wrapper.____slothletInternal.materializeFunc){wrapper._materialize().catch(()=>{})}const mightBeCallable=wrapper.____slothletInternal.isCallable||wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.isCallableLocked;let proxyTarget;if(mightBeCallable){proxyTarget=createNamedProxyTarget(wrapper.____slothletInternal.apiPath,"callableProxy")}else if(Array.isArray(wrapper.____slothletInternal.impl)){proxyTarget=wrapper.____slothletInternal.impl}else{proxyTarget=wrapper}if(!Array.isArray(proxyTarget)&&!(util.inspect.custom in proxyTarget)){Object.defineProperty(proxyTarget,util.inspect.custom,{value:function(){const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!wrapper.____slothletInternal.isCallable){const obj={};for(const key of childKeys){const child=wrapper[key];if(child&&typeof child.createProxy==="function"){obj[key]=child.createProxy()}else{obj[key]=child}}return obj}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&(wrapper.____slothletInternal.impl===null||wrapper.____slothletInternal.impl===void 0)){return wrapper.____slothletInternal.proxy||wrapper}return wrapper.____slothletInternal.impl},writable:false,enumerable:false,configurable:true})}const getTrap=(target,prop,____receiver)=>{const enforceReadGate=resolvedValue=>runtime_enforceReadGate(wrapper,prop,resolvedValue);if(target!==wrapper&&prop in target){const desc=Object.getOwnPropertyDescriptor(target,prop);if(desc&&!desc.configurable){if(typeof prop==="string"&&prop.startsWith("__")){return wrapper[prop]}return target[prop]}}if(target===wrapper&&typeof prop==="string"){const desc=Object.getOwnPropertyDescriptor(target,prop);if(desc&&!desc.configurable){return target[prop]}}const isInternalProp=isFrameworkReservedKey(prop);const allowedInternals=new Set(["_materialize","__mode","__apiPath","__isCallable","__materializeOnCreate","__displayName","__type","__materialized","__inFlight","__slothletPath","__metadata","__filePath","__sourceFolder","__moduleID"]);if(isInternalProp&&!allowedInternals.has(prop)){return void 0}if(prop==="power"||prop==="add"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_START",apiPath:wrapper.____slothletInternal.apiPath,prop:String(prop),mode:wrapper.____slothletInternal.mode,collisionMode:wrapper.____slothletInternal.state.collisionMode||"none",materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null,inWrapper:!isInternalProp&&hasOwn(wrapper,prop)})}if(prop==="__mode")return wrapper.____slothletInternal.mode;if(prop==="__apiPath")return wrapper.____slothletInternal.apiPath;if(prop==="__isCallable")return wrapper.____slothletInternal.isCallable;if(prop==="__materializeOnCreate")return wrapper.____slothletInternal.materializeOnCreate;if(prop==="__materialized")return wrapper.____slothletInternal.state.materialized;if(prop==="__inFlight")return wrapper.____slothletInternal.state.inFlight;if(prop==="__displayName")return wrapper.____slothletInternal.displayName;if(prop==="__type"){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return TYPE_STATES.IN_FLIGHT}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){return TYPE_STATES.UNMATERIALIZED}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return"function"}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return"function"}if(impl&&typeof impl==="object"){return"object"}if(typeof impl==="string"){return"string"}if(typeof impl==="number"){return"number"}if(typeof impl==="boolean"){return"boolean"}if(typeof impl==="symbol"){return"symbol"}if(typeof impl==="bigint"){return"bigint"}return"undefined"}if(prop==="_materialize")return wrapper._materialize.bind(wrapper);if(prop==="__slothletPath")return wrapper.____slothletInternal.apiPath;if(prop==="__metadata"){if(wrapper.slothlet.handlers?.metadata){return wrapper.slothlet.handlers.metadata.getMetadata(wrapper)}return{}}if(prop==="__filePath")return wrapper.____slothletInternal.filePath??void 0;if(prop==="__sourceFolder")return wrapper.____slothletInternal.sourceFolder??void 0;if(prop==="__moduleID")return wrapper.____slothletInternal.moduleID??void 0;if(prop==="__invalid")return wrapper.____slothletInternal.invalid;{const arrImpl=wrapper.____slothletInternal.impl;if(Array.isArray(arrImpl)){const isIndex=typeof prop==="string"&&/^(?:0|[1-9]\d*)$/.test(prop);if(!isIndex){const arrValue=Reflect.get(arrImpl,prop,arrImpl);enforceReadGate(arrValue);return arrValue}}}if(prop==="then"){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){return(onFulfilled,onRejected)=>wrapper._materialize().then(()=>onFulfilled(wrapper.____slothletInternal.proxy)).catch(onRejected)}return void 0}if(prop==="constructor"){const internal=wrapper.____slothletInternal;const constructorImpl=internal.impl;const constructorIsLiveIdentity=internal.deferChildAdopt||EventEmitter&&constructorImpl instanceof EventEmitter;if(constructorIsLiveIdentity&&constructorImpl&&typeof constructorImpl==="object"&&constructorImpl.constructor){return constructorImpl.constructor}return Object.prototype.constructor}if(prop===util.inspect.custom){return()=>{const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!wrapper.____slothletInternal.isCallable){const obj={};for(const key of childKeys){const child=wrapper[key];if(child&&typeof child.createProxy==="function"){obj[key]=child.createProxy()}else{obj[key]=child}}return obj}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&(wrapper.____slothletInternal.impl===null||wrapper.____slothletInternal.impl===void 0)){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_INSPECT_LAZY_UNMATERIALIZED",apiPath:wrapper.apiPath,wrapper,____proxy:wrapper.____slothletInternal.proxy});return wrapper||wrapper.____slothletInternal.proxy}return wrapper.____slothletInternal.impl}}if(prop===Symbol.toStringTag){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return"Function"}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return"Function"}return"Object"}if(typeof prop==="symbol")return void 0;if(prop==="length"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.length}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.length}return 0}if(prop==="name"){if(wrapper.____slothletInternal.apiPath){const pathParts=wrapper.____slothletInternal.apiPath.split(".");const lastPart=pathParts[pathParts.length-1];if(lastPart){return lastPart}}return target.name||"unifiedWrapperProxy"}if(prop==="toString"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.toString.bind(impl)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.toString.bind(impl.default)}if(typeof target==="function"){return Function.prototype.toString.bind(target)}return()=>`[UnifiedWrapper: ${wrapper.____slothletInternal.apiPath}]`}if(prop==="valueOf"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.valueOf.bind(impl)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.valueOf.bind(impl.default)}return Function.prototype.valueOf.bind(target)}if(prop==="toJSON"){const impl=wrapper.____slothletInternal.impl;if(impl&&typeof impl.toJSON==="function"){return impl.toJSON.bind(impl)}return()=>{const data=UnifiedWrapper._extractFullImpl(wrapper);if(data&&typeof data==="object"){delete data.__childFilePaths;delete data.__childFilePathsPreMaterialize}const pm=wrapper.slothlet.handlers?.permissionManager;if(pm&&pm.isEnabled()&&pm.isReadGatingEnabled()){runtime_redactSerialized(wrapper,data,wrapper.____slothletInternal.apiPath,new WeakSet)}return data}}if(wrapper.____slothletInternal.invalid){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(hasOwn(wrapper,prop)){if(wrapper.____slothletInternal.state.collisionMode==="replace"&&(prop==="power"||prop==="add")){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_CACHED_REPLACE",apiPath:wrapper.apiPath,prop:String(prop),collisionMode:wrapper.____slothletInternal.state.collisionMode,wrapperKeys:Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).join(", ")})}this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_CACHED",apiPath:wrapper.____slothletInternal.apiPath,prop:String(prop),materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null});const cached=wrapper[prop];const _cachedWrapper=resolveWrapper(cached);if(_cachedWrapper?.____slothletInternal?.impl!==null&&_cachedWrapper?.____slothletInternal?.impl!==void 0){const cachedImpl=_cachedWrapper.____slothletInternal.impl;const cachedType=typeof cachedImpl;if(cachedType==="string"||cachedType==="number"||cachedType==="boolean"||cachedType==="bigint"||cachedType==="symbol"){enforceReadGate(cachedImpl);return cachedImpl}}if(_cachedWrapper){const cachedWrapper=_cachedWrapper;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}enforceReadGate(cached);return cached}if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){if(typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){return wrapper.____slothletInternal.impl[prop]}if(hasOwn(wrapper,prop)){if(prop==="power"||prop==="add"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_PROXYGET_ACCESSING",prop,wrapperId:wrapper.____slothletInternal.id,apiPath:wrapper.apiPath,collisionMode:wrapper.____slothletInternal.state.collisionMode||"none"});this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_PROXYGET_FOUND",wrapperKeys:Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).join(", ")})}const cached=wrapper[prop];const _cachedWrapper4=resolveWrapper(cached);if(_cachedWrapper4){const cachedWrapper=_cachedWrapper4;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}enforceReadGate(cached);return cached}}const isInternalProp2=typeof prop==="string"&&UnifiedWrapper.INTERNAL_KEYS.has(prop);if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.materialized&&!isInternalProp2&&!hasOwn(wrapper,prop)&&wrapper.____slothletInternal.impl&&!(prop in wrapper.____slothletInternal.impl)){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&(wrapper.____slothletInternal.state.inFlight||!wrapper.____slothletInternal.impl)){if(!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}this.slothlet.debug("wrapper",{key:"DEBUG_MODE_LAZY_GET_CREATE_WAITING_PROXY",prop:String(prop),collisionMode:wrapper.____slothletInternal.state.collisionMode||"none",apiPath:wrapper.____slothletInternal.apiPath});if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){const value2=wrapper.____slothletInternal.impl[prop];return value2}return wrapper.___createWaitingProxy([prop])}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){const value2=wrapper.____slothletInternal.impl[prop];return value2}let value=wrapper.____slothletInternal.impl?wrapper.____slothletInternal.impl[prop]:void 0;if(value===void 0&&wrapper.____slothletInternal.impl){const descriptor=Object.getOwnPropertyDescriptor(wrapper.____slothletInternal.impl,prop);if(descriptor&&descriptor.get){value=descriptor.get.call(wrapper.____slothletInternal.impl)}}if(value===void 0&&Object.prototype.hasOwnProperty.call(target,prop)){value=target[prop]}if(value===void 0){return void 0}enforceReadGate(value);const valueType=typeof value;if(value===null||valueType==="string"||valueType==="number"||valueType==="boolean"||valueType==="bigint"||valueType==="symbol"){return value}if(value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer){return value}if(value&&typeof value==="object"&&util.types.isProxy(value)){return value}if(value&&(typeof value==="object"||typeof value==="function")&&resolveWrapper(value)!==null){return value}const currentImpl=wrapper.____slothletInternal.impl;if(typeof currentImpl==="function"&&!Object.prototype.propertyIsEnumerable.call(currentImpl,prop)){return value}const wrapped=wrapper.___createChildWrapper(prop,value,null,wrapper.____slothletInternal.deferChildAdopt);if(wrapped){Object.defineProperty(wrapper,prop,{value:wrapped,writable:false,enumerable:true,configurable:true});return wrapped}return value};const applyTrap=(target,thisArg,args)=>{if(wrapper.____slothletInternal.invalid){throw new TypeError(`${wrapper.____slothletInternal.apiPath||"api"} is invalidated`)}const thisArgWrapper=resolveWrapper(thisArg);const thisArgImpl=thisArgWrapper?.____slothletInternal?.impl;const thisArgImplIsUsable=thisArgImpl!==null&&(typeof thisArgImpl==="object"||typeof thisArgImpl==="function");const thisArgIsLiveIdentity=thisArgWrapper&&thisArgImplIsUsable&&(thisArgWrapper.____slothletInternal.deferChildAdopt||EventEmitter&&thisArgImpl instanceof EventEmitter);const effectiveThisArg=thisArgIsLiveIdentity?thisArgImpl:thisArg;enforcePermission(wrapper);const hookManager=wrapper.slothlet.handlers?.hookManager;const hasHooks=hookManager&&hookManager.enabled&&!wrapper.____slothletInternal.apiPath.startsWith("slothlet.hook");const api=wrapper.slothlet.boundApi;const ctx=wrapper.slothlet.config?.context||{};if(hasHooks){const ___strategy=hookManager.getDispatchStrategy(wrapper.____slothletInternal.apiPath);if(___strategy.asyncBefore||___strategy.asyncAfter){const ___path=wrapper.____slothletInternal.apiPath;const ___leafIsAsync=util.types.isAsyncFunction(wrapper.____slothletInternal.impl)||util.types.isAsyncFunction(wrapper.____slothletInternal.impl?.default);const ___promotedRun=(async()=>{let beforeResult;try{beforeResult=await hookManager.executeBeforeHooksAsync(___path,args,api,ctx)}catch(error){hookManager.executeAlwaysHooks(___path,args,void 0,true,[unwrapError(error)],api,ctx);throw error}args=beforeResult.args;if(beforeResult.shortCircuit){hookManager.executeAlwaysHooks(___path,args,beforeResult.value,false,[],api,ctx);return beforeResult.value}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){await wrapper._materialize()}const impl=wrapper.____slothletInternal.impl;let settled;try{let raw;if(typeof impl==="function"){raw=wrapper.slothlet.contextManager?wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl,effectiveThisArg,args,wrapper):impl.apply(effectiveThisArg,args)}else if(impl&&typeof impl==="object"&&typeof impl.default==="function"){raw=wrapper.slothlet.contextManager?wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl.default,impl,args,wrapper):impl.default.apply(impl,args)}else{throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:___path,actualType:typeof impl},null,{validationError:true})}settled=raw&&typeof raw==="object"&&typeof raw.then==="function"?await raw:raw}catch(error){const originalError=unwrapError(error);if(!error[ERROR_HOOK_PROCESSED]){const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(___path,originalError,sourceInfo,args,api,ctx)}hookManager.executeAlwaysHooks(___path,args,void 0,true,[originalError],api,ctx);if(wrapper.slothlet.config?.hook?.suppressErrors===true)return void 0;throw error}let promotedFinal;try{const afterResult=await hookManager.executeAfterHooksAsync(___path,settled,args,api,ctx);promotedFinal=afterResult.modified?afterResult.result:settled}catch(error){hookManager.executeAlwaysHooks(___path,args,void 0,true,[unwrapError(error)],api,ctx);throw error}hookManager.executeAlwaysHooks(___path,args,promotedFinal,false,[],api,ctx);return promotedFinal})();return ___leafIsAsync?___promotedRun:runtime_guardPromotedResult(___promotedRun,___path,wrapper.SlothletError)}}let result;let finalResult;let isAsync=false;let lastSyncError=null;try{if(hasHooks){const beforeResult=hookManager.executeBeforeHooks(wrapper.____slothletInternal.apiPath,args,api,ctx);args=beforeResult.args;if(beforeResult.shortCircuit){finalResult=beforeResult.value;return beforeResult.value}}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return new Promise((resolve,reject)=>{const checkMaterialized=()=>{if(wrapper.____slothletInternal.state.materialized){const impl2=wrapper.____slothletInternal.impl;try{if(typeof impl2==="function"){if(wrapper.slothlet.contextManager){resolve(wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl2,effectiveThisArg,args,wrapper,true))}else{resolve(impl2.apply(effectiveThisArg,args))}}else if(impl2&&typeof impl2==="object"&&typeof impl2.default==="function"){if(wrapper.contextManager){resolve(wrapper.contextManager.runInContext(wrapper.instanceID,impl2.default,impl2,args,wrapper,true))}else{resolve(impl2.default.apply(impl2,args))}}else{reject(new wrapper.slothlet.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl2},null,{validationError:true}))}}catch(err){reject(err)}return}if(!wrapper.____slothletInternal.state.inFlight){reject(new wrapper.slothlet.SlothletError("INVALID_CONFIG_LAZY_MATERIALIZATION_FAILED",{apiPath:wrapper.____slothletInternal.apiPath},null,{validationError:true}));return}setImmediate(checkMaterialized)};checkMaterialized()})}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){if(wrapper.slothlet.contextManager){result=wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl,effectiveThisArg,args,wrapper,true)}else{result=impl.apply(effectiveThisArg,args)}}else if(impl&&typeof impl==="object"&&typeof impl.default==="function"){if(wrapper.slothlet.contextManager){result=wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl.default,impl,args,wrapper,true)}else{result=impl.default.apply(impl,args)}}else{throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl},null,{validationError:true})}if(result&&typeof result==="object"&&typeof result.then==="function"){isAsync=true;return result.then(resolvedResult=>{try{if(hasHooks){const afterResult=hookManager.executeAfterHooks(wrapper.____slothletInternal.apiPath,resolvedResult,args,api,ctx);const finalResult2=afterResult.modified?afterResult.result:resolvedResult;hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,finalResult2,false,[],api,ctx);return finalResult2}return resolvedResult}catch(error){if(hasHooks){const originalError=unwrapError(error);const sourceInfo={type:"after",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx);hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,void 0,true,[originalError],api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error}},error=>{if(hasHooks&&!error[ERROR_HOOK_PROCESSED]){const originalError=unwrapError(error);const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx)}if(hasHooks){const originalError=unwrapError(error);hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,void 0,true,[originalError],api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error})}finalResult=result;if(hasHooks){const afterResult=hookManager.executeAfterHooks(wrapper.____slothletInternal.apiPath,result,args,api,ctx);if(afterResult.modified){finalResult=afterResult.result}}return finalResult}catch(error){lastSyncError=error;if(hasHooks&&!error[ERROR_HOOK_PROCESSED]){const originalError=unwrapError(error);const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error}finally{if(hasHooks&&!isAsync){const syncError=lastSyncError;const resultValue=syncError?void 0:typeof finalResult!=="undefined"?finalResult:result;const errors=syncError?[unwrapError(syncError)]:[];hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,resultValue,!!syncError,errors,api,ctx)}}};const hasTrap=(target,prop)=>{if(prop==="_materialize"){return true}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){return true}if(!isInternal&&wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")&&prop in wrapper.____slothletInternal.impl){return true}return Object.prototype.hasOwnProperty.call(target,prop)};const getOwnPropertyDescriptorTrap=(target,prop)=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(prop==="____slothletInternal")return void 0;if(prop==="prototype"&&typeof target==="function"){const desc=Object.getOwnPropertyDescriptor(target,"prototype");if(desc){return desc}}const ownDesc=Object.getOwnPropertyDescriptor(target,prop);if((!ownDesc||ownDesc.configurable)&&runtime_isReadRedacted(wrapper,prop)){return void 0}if(Object.prototype.hasOwnProperty.call(target,prop)){return Object.getOwnPropertyDescriptor(target,prop)}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){const desc=Object.getOwnPropertyDescriptor(wrapper,prop);if(desc){return desc}}if(!isInternal&&wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")&&prop in wrapper.____slothletInternal.impl){return Object.getOwnPropertyDescriptor(wrapper.____slothletInternal.impl,prop)}return void 0};const ownKeysTrap=target=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const keys=new Set;if(typeof target==="function"||target&&target.__isCallable){keys.add("prototype");keys.add("length");keys.add("name")}for(const key of Reflect.ownKeys(target)){const descriptor=Object.getOwnPropertyDescriptor(target,key);if(!descriptor.configurable||descriptor.enumerable){keys.add(key)}}if(target!==wrapper){for(const key of Reflect.ownKeys(wrapper)){const descriptor=Object.getOwnPropertyDescriptor(wrapper,key);if(descriptor&&descriptor.enumerable){keys.add(key)}}}const implKeys=wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")?Reflect.ownKeys(wrapper.____slothletInternal.impl):[];for(const key of implKeys){if(key!=="prototype"&&!IMPL_METADATA_KEYS.has(key)){keys.add(key)}}for(const key of keys){const targetDesc=Object.getOwnPropertyDescriptor(target,key);if(targetDesc&&!targetDesc.configurable)continue;if(runtime_isReadRedacted(wrapper,key))keys.delete(key)}return Array.from(keys)};const setTrap=(target,prop,value)=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize()}if(UnifiedWrapper.INTERNAL_KEYS.has(prop)&&prop!=="_materialize")return true;const internalKeys=new Set(["_materialize"]);if(!internalKeys.has(prop)){const isObjectOrFunctionValue=value!==null&&(typeof value==="object"||typeof value==="function");if(!isObjectOrFunctionValue){const liveImpl=wrapper.____slothletInternal.impl;const isLiveIdentityWrapper=wrapper.____slothletInternal.deferChildAdopt||EventEmitter&&liveImpl instanceof EventEmitter;const hasLiveImpl=isLiveIdentityWrapper&&liveImpl!==null&&liveImpl!==void 0&&(typeof liveImpl==="object"||typeof liveImpl==="function");if(hasLiveImpl){const setSucceeded=Reflect.set(liveImpl,prop,value);if(!setSucceeded)return false;const existingDescriptor=Object.getOwnPropertyDescriptor(wrapper,prop);if(!existingDescriptor||typeof existingDescriptor.set!=="function"){Object.defineProperty(wrapper,prop,{get:()=>{const currentImpl=wrapper.____slothletInternal.impl;return currentImpl?currentImpl[prop]:void 0},set:newValue=>{const currentImpl=wrapper.____slothletInternal.impl;if(currentImpl)currentImpl[prop]=newValue},enumerable:true,configurable:true})}return true}}if(hasOwn(wrapper,prop)){delete wrapper[prop]}let stored=value;const inBuild=wrapper.slothlet.____buildDepth>0;if(!inBuild&&value!==null&&(typeof value==="object"||typeof value==="function")&&!util.types.isProxy(value)&&resolveWrapper(value)===null){const wrapped=wrapper.___createChildWrapper(prop,value,null,true);if(wrapped!==null&&wrapped!==void 0){const wrappedInternal=resolveWrapper(wrapped);if(wrappedInternal)wrappedInternal.____slothletInternal.userAssigned=true;stored=wrapped}}Object.defineProperty(wrapper,prop,{value:stored,writable:false,enumerable:true,configurable:true})}else{target[prop]=value}return true};const deletePropertyTrap=(target,prop)=>{const internalKeys=new Set(["____slothletInternal","__impl","___setImpl","___resetLazy","_materialize","___invalidate","_impl","___getState","__state","__mode","__apiPath","__slothletPath","__isCallable","__materializeOnCreate","__displayName","__type","__metadata","__invalid","__filePath","__sourceFolder","__moduleID","__materialized","__inFlight"]);if(internalKeys.has(prop)){return true}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){const childWrapper=wrapper[prop];const childWrapperRaw=resolveWrapper(childWrapper);if(childWrapperRaw){childWrapperRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(wrapper,prop);if(descriptor?.configurable){delete wrapper[prop]}}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&prop in wrapper.____slothletInternal.impl){delete wrapper.____slothletInternal.impl[prop]}delete target[prop];return true};const constructTrap=(target,args,newTarget)=>{if(wrapper.____slothletInternal.invalid){throw new TypeError(`${wrapper.____slothletInternal.apiPath||"api"} is invalidated`)}enforcePermission(wrapper);if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return Promise.resolve(wrapper.____slothletInternal.materializationPromise).then(()=>{if(!wrapper.____slothletInternal.state.materialized){throw new wrapper.slothlet.SlothletError("INVALID_CONFIG_LAZY_MATERIALIZATION_FAILED",{apiPath:wrapper.____slothletInternal.apiPath},null,{validationError:true})}const impl2=wrapper.____slothletInternal.impl;if(typeof impl2==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl2:newTarget;return Reflect.construct(impl2,args,effectiveNewTarget)}if(impl2&&typeof impl2==="object"&&typeof impl2.default==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl2.default:newTarget;return Reflect.construct(impl2.default,args,effectiveNewTarget)}throw new wrapper.slothlet.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl2},null,{validationError:true})})}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl:newTarget;return Reflect.construct(impl,args,effectiveNewTarget)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl.default:newTarget;return Reflect.construct(impl.default,args,effectiveNewTarget)}throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl},null,{validationError:true})};wrapper.____slothletInternal.proxy=new Proxy(proxyTarget,{get:(target,prop,receiver)=>runtime_bindCapturedIdentity(wrapper,prop,getTrap(target,prop,receiver)),apply:applyTrap,construct:constructTrap,has:hasTrap,getOwnPropertyDescriptor:getOwnPropertyDescriptorTrap,ownKeys:ownKeysTrap,set:setTrap,deleteProperty:deletePropertyTrap,getPrototypeOf:target=>{const internal=wrapper.____slothletInternal;const impl=internal.impl;if(Array.isArray(impl))return Array.prototype;if(!Reflect.isExtensible(target))return Reflect.getPrototypeOf(target);const isLiveIdentity=internal.deferChildAdopt||EventEmitter&&impl instanceof EventEmitter;if(isLiveIdentity&&impl&&typeof impl==="object")return Object.getPrototypeOf(impl);return null}});_proxyRegistry.set(wrapper.____slothletInternal.proxy,wrapper);genuineWrappers.add(wrapper);return wrapper.____slothletInternal.proxy}}Object.defineProperty(UnifiedWrapper.prototype,util.inspect.custom,{value:UnifiedWrapper.prototype.____inspectCustom,writable:true,enumerable:false,configurable:true});function resolveWrapper(value){if(!value)return null;const registered=_proxyRegistry.get(value);if(registered)return registered;if(value instanceof UnifiedWrapper&&value.____slothletInternal!=null)return value;return null}export{IMPL_METADATA_KEYS,TYPE_STATES,UnifiedWrapper,isFrameworkReservedKey,resolveWrapper};
package/dist/slothlet.mjs CHANGED
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{isNode,fs,fsp,path,url,createRequire}from"@cldmv/slothlet/helpers/platform";import{getContextManager}from"#factories/context";import{warnIfCoverageWithoutImporter}from"@cldmv/slothlet/processors/loader";import{SlothletError,SlothletWarning,SlothletDebug}from"@cldmv/slothlet/errors";import{registerInstance}from"#handlers/lifecycle-token";import{resolveWrapper}from"#handlers/unified-wrapper";import{isFrameworkInternal}from"#handlers/framework-internals";import{TRUSTED_ROOT}from"#handlers/trusted-root";import{initI18n}from"@cldmv/slothlet/i18n";import{enableEventEmitterPatching,disableEventEmitterPatching,cleanupEventEmitterResources,setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";import{enableSchedulerPatching,disableSchedulerPatching}from"@cldmv/slothlet/helpers/scheduler-context";import{enableEventTargetPatching,disableEventTargetPatching}from"@cldmv/slothlet/helpers/eventtarget-context";import{enableEventTargetPropertyPatching,disableEventTargetPropertyPatching}from"@cldmv/slothlet/helpers/eventtarget-property-context";import{enableObserverPatching,disableObserverPatching}from"@cldmv/slothlet/helpers/observer-context";import{DEFAULT_ROUTINES,RESERVED_EXPORTS}from"@cldmv/slothlet/helpers/defaults";const boundaryPatchHolders=new Set;class Slothlet{static RESERVED_ROOT_KEYS=["slothlet","shutdown","destroy"];static SKIP_PROPS=["__metadata","__type","_materialize","_impl","____slothletInternal"];constructor(){this.SlothletError=SlothletError;this.SlothletWarning=SlothletWarning;this.debugLogger=null;this.instanceID=null;this.config=null;this.envTarget="node";this.api=null;this.boundApi=null;this.contextManager=null;this.isLoaded=false;this.reference=null;this.context=null;this.envSnapshot=null;this._totalLazyCount=0;this._unmaterializedLazyCount=0;this._materializationComplete=false;this._materializationWaiters=[];this._materializationCompleteEmitted=false;this.componentCategories=["helpers","handlers","builders","processors","modes"];for(const category of this.componentCategories){this[category]={}}}async _initializeComponents(){if(this.envTarget==="browser"){await this._initializeComponentsBrowser();return}const baseDir=path.join(path.dirname(url.fileURLToPath(import.meta.url)),"lib");for(const category of this.componentCategories){const categoryDir=path.join(baseDir,category);const files=fs.readdirSync(categoryDir).filter(f=>f.endsWith(".mjs"));for(const file of files){const filePath=path.join(categoryDir,file);try{const module=await import(url.pathToFileURL(filePath).href);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this);if(this.config?.debug?.initialization){this.debug("initialization",{key:"DEBUG_MODE_COMPONENT_INITIALIZED",component:ClassExport.name,category,propertyName:propName})}}}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}}}async _initializeComponentsBrowser(){const BROWSER_COMPONENT_SPECIFIERS=["@cldmv/slothlet/builders/api-assignment","@cldmv/slothlet/builders/api_builder","@cldmv/slothlet/builders/builder","@cldmv/slothlet/builders/modes-processor","#handlers/api-cache-manager","#handlers/api-manager","#handlers/hook-manager","#handlers/lifecycle","#handlers/materialize-manager","#handlers/metadata","#handlers/module-manager","#handlers/ownership","#handlers/permission-manager","#handlers/routine-manager","#handlers/version-manager","@cldmv/slothlet/helpers/config","@cldmv/slothlet/helpers/hint-detector","@cldmv/slothlet/helpers/modes-utils","@cldmv/slothlet/helpers/resolve-from-caller","@cldmv/slothlet/helpers/sanitize","@cldmv/slothlet/helpers/utilities","@cldmv/slothlet/modes/eager","@cldmv/slothlet/modes/lazy","@cldmv/slothlet/processors/flatten","@cldmv/slothlet/processors/loader"];for(const specifier of BROWSER_COMPONENT_SPECIFIERS){const parts=specifier.split("/");const category=specifier.startsWith("#")?parts[0].slice(1):parts[2];const module=await import(specifier);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this)}}}_setupConfigLifecycleSubscribers(){const map=this.config.lifecycle;if(!map){return}const lifecycle=this.handlers.lifecycle;for(const[event,handler]of Object.entries(map)){const handlers=Array.isArray(handler)?handler:[handler];for(const fn of handlers){lifecycle.subscribe(event,fn)}}}_setupLifecycleSubscribers(){if(!this.handlers.lifecycle){return}if(this.handlers.metadata){this.handlers.lifecycle.subscribe("impl:created",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:changed",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:removed",data=>{if(data.apiPath){const rootSegment=data.apiPath.split(".")[0];this.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}})}if(this.handlers.routineManager){this.handlers.lifecycle.subscribe("impl:created",data=>{this.handlers.routineManager.onImplCreated(data)});this.handlers.lifecycle.subscribe("impl:changed",data=>{this.handlers.routineManager.onImplCreated(data)});this.handlers.lifecycle.subscribe("impl:removed",data=>{this.handlers.routineManager.onImplRemoved(data)})}if(this.handlers.ownership){this.handlers.lifecycle.subscribe("impl:created",data=>{const configCollisionMode=this.config?.collision?.api||"merge";const collisionMode=configCollisionMode==="replace"||configCollisionMode==="merge-replace"?configCollisionMode:"merge";const implValue=data.wrapper?.__impl??data.impl;if(typeof implValue==="function"&&implValue.__slothletRoutineStack===true){return}this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})});this.handlers.lifecycle.subscribe("impl:changed",data=>{const configCollisionMode=this.config?.collision?.api||"merge";const collisionMode=configCollisionMode==="replace"||configCollisionMode==="merge-replace"?configCollisionMode:"merge";const implValue=data.wrapper?.__impl??data.impl;if(typeof implValue==="function"&&implValue.__slothletRoutineStack===true){return}const currentOwner=this.handlers.ownership.getCurrentOwner(data.apiPath);if(currentOwner?.moduleID!==data.moduleID){this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})}})}}_registerLazyWrapper(){this._totalLazyCount++;this._unmaterializedLazyCount++;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_REGISTERED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount})}}_onWrapperMaterialized(){this._unmaterializedLazyCount--;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_MATERIALIZED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount,percentage:this._totalLazyCount>0?(this._totalLazyCount-this._unmaterializedLazyCount)/this._totalLazyCount*100:100})}if(this._unmaterializedLazyCount===0&&!this._materializationComplete){this._materializationComplete=true;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_ALL_LAZY_WRAPPERS_MATERIALIZED",total:this._totalLazyCount})}const waiters=this._materializationWaiters.splice(0);for(const resolve of waiters){resolve()}if(this.config?.tracking?.materialization&&!this._materializationCompleteEmitted){this._materializationCompleteEmitted=true;if(this.handlers?.lifecycle){this.handlers.lifecycle.emit("materialized:complete",{total:this._totalLazyCount,timestamp:Date.now()})}}}}_captureEnvSnapshot(envConfig){const rawInclude=envConfig?.include;const include=Array.isArray(rawInclude)?rawInclude.filter(key=>typeof key==="string"):null;const useAllowlist=include!==null&&include.length>0;const raw=useAllowlist?include.reduce((acc,key)=>{if(Object.prototype.hasOwnProperty.call(process.env,key)){acc[key]=process.env[key]}return acc},Object.create(null)):{...process.env};return Object.freeze(raw)}async load(config={},preservedInstanceID=null){this.config=config;this.envTarget=config.platform==="browser"||config.platform!=="node"&&config.manifest!=null?"browser":"node";if(!this.envSnapshot){this.envSnapshot=this.envTarget==="browser"?Object.freeze(Object.create(null)):this._captureEnvSnapshot(config.env)}this.debugLogger=new SlothletDebug(config);await this._initializeComponents();registerInstance(this);if(this.handlers.routineManager){this.handlers.routineManager.reset()}this._setupLifecycleSubscribers();this.config=this.helpers.config.transformConfig(config);if(this.envTarget==="node"){warnIfCoverageWithoutImporter(this.config)}this._setupConfigLifecycleSubscribers();if(this.config?.i18n?.language){initI18n({language:this.config.i18n.language})}this.debugLogger=new SlothletDebug(this.config);this.instanceID=preservedInstanceID||this.helpers.utilities.generateId();this.reference=this.config.reference;this.context=this.config.context;this.contextManager=getContextManager(this.envTarget==="browser"?"live":this.config.runtime);setApiContextChecker(()=>{const ctx=this.contextManager.tryGetContext();return!!(ctx&&ctx.self)});let store;if(preservedInstanceID&&this.contextManager.instances.has(preservedInstanceID)){this.contextManager.cleanup(preservedInstanceID);store=this.contextManager.initialize(this.instanceID,this.config)}else{store=this.contextManager.initialize(this.instanceID,this.config)}Object.defineProperty(store,TRUSTED_ROOT,{value:true,configurable:true});enableEventEmitterPatching();enableSchedulerPatching();enableEventTargetPatching();enableEventTargetPropertyPatching();enableObserverPatching();boundaryPatchHolders.add(this.instanceID);if(typeof this.contextManager.registerEventEmitterContextChecker==="function"){this.contextManager.registerEventEmitterContextChecker()}const baseModuleId=`base_${this.helpers.utilities.generateId().substring(0,8)}`;if(this.config.scanHiddenFolders!==void 0&&!this.config.silent){new this.SlothletWarning("CONFIG_SCAN_HIDDEN_FOLDERS_DEPRECATED",{option:"scanHiddenFolders"})}const baseApi=await this.builders.builder.buildAPI({dir:this.config.dir,mode:this.config.mode,moduleID:baseModuleId,hidden:this.config.hidden??null,scanHiddenFolders:this.config.scanHiddenFolders===true});this.api=baseApi;const apiWithBuiltins=await this.buildFinalAPI(this.api);if(this.handlers.apiCacheManager){this.handlers.apiCacheManager.set(baseModuleId,{endpoint:".",moduleID:baseModuleId,api:this.api,folderPath:this.config.dir,mode:this.config.mode,sanitizeOptions:this.config.sanitize||{},collisionMode:this.config.collision?.initial||"merge",config:{...this.config},timestamp:Date.now()})}this.injectRuntimeMetadataFunctions(apiWithBuiltins);if(this.config.metadata&&typeof this.config.metadata==="object"){for(const[key,value]of Object.entries(this.config.metadata)){this.handlers.metadata.setGlobalMetadata(key,value)}this.handlers.metadata.registerUserMetadata(baseModuleId,this.config.metadata)}if(this.handlers.ownership){this.handlers.ownership.registerSubtree(apiWithBuiltins,baseModuleId,"");this.handlers.ownership.setModuleEndpoint(baseModuleId,".")}if(!this.boundApi){const isCallable=typeof this.api==="function"||this.api&&typeof this.api.default==="function";const proxyTarget=isCallable?function(){}:{};this.boundApi=new Proxy(proxyTarget,{get:(target,prop)=>this.api?this.api[prop]:void 0,set:(target,prop,value)=>{if(this.api){this.api[prop]=value}return true},has:(target,prop)=>this.api?prop in this.api:false,ownKeys:____target=>this.api?Reflect.ownKeys(this.api):[],deleteProperty:(target,prop)=>this.api?delete this.api[prop]:true,apply:(target,thisArg,args)=>this.api?Reflect.apply(this.api,thisArg,args):void 0,construct:(target,args)=>this.api?Reflect.construct(this.api,args):{},getOwnPropertyDescriptor:(target,prop)=>{if(isCallable&&prop==="prototype"){return Object.getOwnPropertyDescriptor(target,prop)}if(this.api&&prop in this.api){const desc=Object.getOwnPropertyDescriptor(this.api,prop);if(desc){return{...desc,configurable:true}}}return void 0}})}store.self=this.boundApi;store.context=this.context||{};store.slothlet=this;if(this.reference&&typeof this.reference==="object"){Object.assign(this.boundApi,this.reference)}if(this.handlers.routineManager){await this.handlers.routineManager.rebuildStacks(this.boundApi);await this.handlers.routineManager.runStartupModeRoutines()}this.isLoaded=true;return this.boundApi}async reload(options={}){const{keepInstanceID=false}=options;if(!this.config?.dir){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"reload",validationError:true})}const operationHistory=this.handlers.apiManager?.state?.operationHistory?[...this.handlers.apiManager.state.operationHistory]:[];await this._clearModuleCaches();const oldInstanceID=this.instanceID;if(!keepInstanceID){this.instanceID=`${oldInstanceID}_reload_${Date.now()}`;if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}}const savedMetadataState=this.handlers.metadata?.exportUserState?.();const savedHooks=this.handlers.hookManager?.exportHooks?.();const wasSealed=this.handlers.permissionManager?.isSealed?.()===true;await this.load(this.config,this.instanceID);if(savedMetadataState&&this.handlers.metadata){this.handlers.metadata.importUserState(savedMetadataState)}if(savedHooks?.length&&this.handlers.hookManager){this.handlers.hookManager.importHooks(savedHooks)}for(const[,store]of this.contextManager.instances){if(store.parentInstanceID===oldInstanceID){store.parentInstanceID=this.instanceID}}if(oldInstanceID&&oldInstanceID!==this.instanceID&&this.contextManager.instances?.has(oldInstanceID)){this.contextManager.cleanup(oldInstanceID)}for(const operation of operationHistory){if(operation.type==="add"){await this.handlers.apiManager.addApiComponent({apiPath:operation.apiPath,folderPath:operation.folderPath,options:{...operation.options||{},recordHistory:false},versionConfig:operation.versionConfig||null})}else if(operation.type==="remove"){if(operation.scopedModuleID){await this.handlers.apiManager.removeApiComponent(operation.scopedModuleID,{scopedApiPath:operation.apiPath,recordHistory:false})}else{await this.handlers.apiManager.removeApiComponent(operation.apiPath,{recordHistory:false})}}else if(operation.type==="addPermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.addRule(operation.rule,operation.ownerModuleID,operation.ruleId)}}else{if(operation.type==="removePermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.removeRule(operation.ruleId,operation.callerModuleID)}}}}if(wasSealed)this.handlers.permissionManager?.seal?.();return this.boundApi}async _clearModuleCaches(){if(!isNode)return;const targetDir=this.config.dir;const require2=createRequire(import.meta.url);const absoluteTargetDir=path.resolve(targetDir);for(const key of Object.keys(require2.cache)){if(key.startsWith(absoluteTargetDir)){delete require2.cache[key]}}}injectRuntimeMetadataFunctions(api){if(!api.slothlet?.metadata){return}const metadataHandler=this.handlers.metadata;api.slothlet.metadata.get=async function slothlet_metadata_get_runtime(path2){return metadataHandler.get(path2)};api.slothlet.metadata.self=function slothlet_metadata_self_runtime(){return metadataHandler.self()};api.slothlet.metadata.caller=function slothlet_metadata_caller_runtime(){return metadataHandler.caller()}}async _drainInFlightLoads(){if(!this.api)return;const pending=[];const seen=new Set;const collect=(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>15||seen.has(obj))return;seen.add(obj);try{if(isFrameworkInternal(obj))return;const wrapper=resolveWrapper(obj);if(wrapper){const mat=wrapper.____slothletInternal.materializationPromise;if(mat)pending.push(mat);for(const key of Object.keys(wrapper)){if(!key.startsWith("____"))collect(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){collect(obj[key],depth+1)}}catch{}};for(const key of Object.keys(this.api)){collect(this.api[key])}if(pending.length>0){await Promise.allSettled(pending)}}async shutdown(){if(!this.isLoaded){return}await this._drainInFlightLoads();boundaryPatchHolders.delete(this.instanceID);if(boundaryPatchHolders.size===0){disableEventEmitterPatching();disableSchedulerPatching();disableEventTargetPatching();disableEventTargetPropertyPatching();disableObserverPatching();cleanupEventEmitterResources()}if(this.instanceID&&this.contextManager){this.contextManager.cleanup(this.instanceID)}if(this.handlers.ownership){this.handlers.ownership.clear()}this.handlers.versionManager?.shutdown();await this.handlers.permissionManager?.shutdown();if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}this.isLoaded=false}debug(code,context={}){if(this.debugLogger){this.debugLogger.log(code,context)}}getAPI(){if(!this.isLoaded){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"getAPI"},null,{validationError:true})}return this.boundApi}getDiagnostics(){return{instanceID:this.instanceID,isLoaded:this.isLoaded,config:this.config,context:this.contextManager?.getDiagnostics()||null,ownership:this.handlers.ownership?.getDiagnostics()||null}}getOwnership(){if(!this.handlers.ownership){return null}return this.handlers.ownership.getDiagnostics()}buildFinalAPI(userApi){return this.builders.apiBuilder.buildFinalAPI(userApi)}}async function slothlet(config){const instance=new Slothlet;const api=await instance.load(config);return api}slothlet.defaults=Object.freeze({routines:DEFAULT_ROUTINES,reservedExports:RESERVED_EXPORTS});var stdin_default=slothlet;export{stdin_default as default,slothlet};
17
+ import{isNode,fs,fsp,path,url,createRequire}from"@cldmv/slothlet/helpers/platform";import{getContextManager}from"#factories/context";import{warnIfCoverageWithoutImporter}from"@cldmv/slothlet/processors/loader";import{SlothletError,SlothletWarning,SlothletDebug}from"@cldmv/slothlet/errors";import{registerInstance}from"#handlers/lifecycle-token";import{resolveWrapper}from"#handlers/unified-wrapper";import{isFrameworkInternal}from"#handlers/framework-internals";import{TRUSTED_ROOT}from"#handlers/trusted-root";import{initI18n}from"@cldmv/slothlet/i18n";import{enableEventEmitterPatching,disableEventEmitterPatching,cleanupEventEmitterResources,setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";import{enableSchedulerPatching,disableSchedulerPatching}from"@cldmv/slothlet/helpers/scheduler-context";import{enableEventTargetPatching,disableEventTargetPatching}from"@cldmv/slothlet/helpers/eventtarget-context";import{enableEventTargetPropertyPatching,disableEventTargetPropertyPatching}from"@cldmv/slothlet/helpers/eventtarget-property-context";import{enableObserverPatching,disableObserverPatching}from"@cldmv/slothlet/helpers/observer-context";import{DEFAULT_ROUTINES,RESERVED_EXPORTS}from"@cldmv/slothlet/helpers/defaults";const boundaryPatchHolders=new Set;class Slothlet{static RESERVED_ROOT_KEYS=["slothlet","shutdown","destroy"];static SKIP_PROPS=["__metadata","__type","_materialize","_impl","____slothletInternal"];constructor(){this.SlothletError=SlothletError;this.SlothletWarning=SlothletWarning;this.debugLogger=null;this.instanceID=null;this.config=null;this.envTarget="node";this.api=null;this.boundApi=null;this.contextManager=null;this.isLoaded=false;this.reference=null;this.context=null;this.envSnapshot=null;this._totalLazyCount=0;this._unmaterializedLazyCount=0;this._materializationComplete=false;this._materializationWaiters=[];this._materializationCompleteEmitted=false;this.componentCategories=["helpers","handlers","builders","processors","modes"];for(const category of this.componentCategories){this[category]={}}}async _initializeComponents(){if(this.envTarget==="browser"){await this._initializeComponentsBrowser();return}const baseDir=path.join(path.dirname(url.fileURLToPath(import.meta.url)),"lib");for(const category of this.componentCategories){const categoryDir=path.join(baseDir,category);const files=fs.readdirSync(categoryDir).filter(f=>f.endsWith(".mjs"));for(const file of files){const filePath=path.join(categoryDir,file);try{const module=await import(url.pathToFileURL(filePath).href);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this);if(this.config?.debug?.initialization){this.debug("initialization",{key:"DEBUG_MODE_COMPONENT_INITIALIZED",component:ClassExport.name,category,propertyName:propName})}}}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}}}async _initializeComponentsBrowser(){const BROWSER_COMPONENT_SPECIFIERS=["@cldmv/slothlet/builders/api-assignment","@cldmv/slothlet/builders/api_builder","@cldmv/slothlet/builders/builder","@cldmv/slothlet/builders/modes-processor","#handlers/api-cache-manager","#handlers/api-manager","#handlers/hook-manager","#handlers/lifecycle","#handlers/materialize-manager","#handlers/metadata","#handlers/module-manager","#handlers/ownership","#handlers/permission-manager","#handlers/routine-manager","#handlers/version-manager","@cldmv/slothlet/helpers/config","@cldmv/slothlet/helpers/hint-detector","@cldmv/slothlet/helpers/modes-utils","@cldmv/slothlet/helpers/resolve-from-caller","@cldmv/slothlet/helpers/sanitize","@cldmv/slothlet/helpers/utilities","@cldmv/slothlet/modes/eager","@cldmv/slothlet/modes/lazy","@cldmv/slothlet/processors/flatten","@cldmv/slothlet/processors/loader"];for(const specifier of BROWSER_COMPONENT_SPECIFIERS){const parts=specifier.split("/");const category=specifier.startsWith("#")?parts[0].slice(1):parts[2];const module=await import(specifier);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this)}}}_setupConfigLifecycleSubscribers(){const map=this.config.lifecycle;if(!map){return}const lifecycle=this.handlers.lifecycle;for(const[event,handler]of Object.entries(map)){const handlers=Array.isArray(handler)?handler:[handler];for(const fn of handlers){lifecycle.subscribe(event,fn)}}}_setupLifecycleSubscribers(){if(!this.handlers.lifecycle){return}if(this.handlers.metadata){this.handlers.lifecycle.subscribeInternal("impl:created",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.__wrapperRef??data.wrapper?.__impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribeInternal("impl:changed",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.wrapper?.__impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:removed",data=>{if(data.apiPath){const rootSegment=data.apiPath.split(".")[0];this.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}})}if(this.handlers.routineManager){this.handlers.lifecycle.subscribeInternal("impl:created",data=>{this.handlers.routineManager.onImplCreated(data)});this.handlers.lifecycle.subscribeInternal("impl:changed",data=>{this.handlers.routineManager.onImplCreated(data)});this.handlers.lifecycle.subscribe("impl:removed",data=>{this.handlers.routineManager.onImplRemoved(data)})}if(this.handlers.ownership){this.handlers.lifecycle.subscribeInternal("impl:created",data=>{const configCollisionMode=this.config?.collision?.api||"merge";const collisionMode=configCollisionMode==="replace"||configCollisionMode==="merge-replace"?configCollisionMode:"merge";const implValue=data.wrapper?.__impl??data.__wrapperRef;if(typeof implValue==="function"&&implValue.__slothletRoutineStack===true){return}this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode});if(this.handlers.ownership.getCurrentOwner(data.apiPath)?.moduleID===data.moduleID){void this.handlers.lifecycle.emit("impl:created",{apiPath:data.apiPath,wrapper:data.wrapper,source:data.source,moduleID:data.moduleID,filePath:data.filePath,sourceFolder:data.sourceFolder})}});this.handlers.lifecycle.subscribeInternal("impl:changed",data=>{const configCollisionMode=this.config?.collision?.api||"merge";const collisionMode=configCollisionMode==="replace"||configCollisionMode==="merge-replace"?configCollisionMode:"merge";const implValue=data.wrapper?.__impl??data.__wrapperRef;if(typeof implValue==="function"&&implValue.__slothletRoutineStack===true){return}const currentOwner=this.handlers.ownership.getCurrentOwner(data.apiPath);if(currentOwner?.moduleID!==data.moduleID){this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})}if(this.handlers.ownership.getCurrentOwner(data.apiPath)?.moduleID===data.moduleID){void this.handlers.lifecycle.emit("impl:changed",{apiPath:data.apiPath,wrapper:data.wrapper,source:data.source,moduleID:data.moduleID,filePath:data.filePath,sourceFolder:data.sourceFolder})}})}}_registerLazyWrapper(){this._totalLazyCount++;this._unmaterializedLazyCount++;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_REGISTERED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount})}}_onWrapperMaterialized(){this._unmaterializedLazyCount--;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_MATERIALIZED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount,percentage:this._totalLazyCount>0?(this._totalLazyCount-this._unmaterializedLazyCount)/this._totalLazyCount*100:100})}if(this._unmaterializedLazyCount===0&&!this._materializationComplete){this._materializationComplete=true;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_ALL_LAZY_WRAPPERS_MATERIALIZED",total:this._totalLazyCount})}const waiters=this._materializationWaiters.splice(0);for(const resolve of waiters){resolve()}if(this.config?.tracking?.materialization&&!this._materializationCompleteEmitted){this._materializationCompleteEmitted=true;if(this.handlers?.lifecycle){this.handlers.lifecycle.emit("materialized:complete",{total:this._totalLazyCount,timestamp:Date.now()})}}}}_captureEnvSnapshot(envConfig){const rawInclude=envConfig?.include;const include=Array.isArray(rawInclude)?rawInclude.filter(key=>typeof key==="string"):null;const useAllowlist=include!==null&&include.length>0;const raw=useAllowlist?include.reduce((acc,key)=>{if(Object.prototype.hasOwnProperty.call(process.env,key)){acc[key]=process.env[key]}return acc},Object.create(null)):{...process.env};return Object.freeze(raw)}async load(config={},preservedInstanceID=null){this.config=config;this.envTarget=config.platform==="browser"||config.platform!=="node"&&config.manifest!=null?"browser":"node";if(!this.envSnapshot){this.envSnapshot=this.envTarget==="browser"?Object.freeze(Object.create(null)):this._captureEnvSnapshot(config.env)}this.debugLogger=new SlothletDebug(config);await this._initializeComponents();registerInstance(this);if(this.handlers.routineManager){this.handlers.routineManager.reset()}this._setupLifecycleSubscribers();this.config=this.helpers.config.transformConfig(config);if(this.envTarget==="node"){warnIfCoverageWithoutImporter(this.config)}this._setupConfigLifecycleSubscribers();if(this.config?.i18n?.language){initI18n({language:this.config.i18n.language})}this.debugLogger=new SlothletDebug(this.config);this.instanceID=preservedInstanceID||this.helpers.utilities.generateId();this.reference=this.config.reference;this.context=this.config.context;this.contextManager=getContextManager(this.envTarget==="browser"?"live":this.config.runtime);setApiContextChecker(()=>{const ctx=this.contextManager.tryGetContext();return!!(ctx&&ctx.self)});let store;if(preservedInstanceID&&this.contextManager.instances.has(preservedInstanceID)){this.contextManager.cleanup(preservedInstanceID);store=this.contextManager.initialize(this.instanceID,this.config)}else{store=this.contextManager.initialize(this.instanceID,this.config)}Object.defineProperty(store,TRUSTED_ROOT,{value:true,configurable:true});enableEventEmitterPatching();enableSchedulerPatching();enableEventTargetPatching();enableEventTargetPropertyPatching();enableObserverPatching();boundaryPatchHolders.add(this.instanceID);if(typeof this.contextManager.registerEventEmitterContextChecker==="function"){this.contextManager.registerEventEmitterContextChecker()}const baseModuleId=`base_${this.helpers.utilities.generateId().substring(0,8)}`;if(this.config.scanHiddenFolders!==void 0&&!this.config.silent){new this.SlothletWarning("CONFIG_SCAN_HIDDEN_FOLDERS_DEPRECATED",{option:"scanHiddenFolders"})}const baseApi=await this.builders.builder.buildAPI({dir:this.config.dir,mode:this.config.mode,moduleID:baseModuleId,hidden:this.config.hidden??null,scanHiddenFolders:this.config.scanHiddenFolders===true});this.api=baseApi;const apiWithBuiltins=await this.buildFinalAPI(this.api);if(this.handlers.apiCacheManager){this.handlers.apiCacheManager.set(baseModuleId,{endpoint:".",moduleID:baseModuleId,api:this.api,folderPath:this.config.dir,mode:this.config.mode,sanitizeOptions:this.config.sanitize||{},collisionMode:this.config.collision?.initial||"merge",config:{...this.config},timestamp:Date.now()})}this.injectRuntimeMetadataFunctions(apiWithBuiltins);if(this.config.metadata&&typeof this.config.metadata==="object"){for(const[key,value]of Object.entries(this.config.metadata)){this.handlers.metadata.setGlobalMetadata(key,value)}this.handlers.metadata.registerUserMetadata(baseModuleId,this.config.metadata)}if(this.handlers.ownership){this.handlers.ownership.registerSubtree(apiWithBuiltins,baseModuleId,"");this.handlers.ownership.setModuleEndpoint(baseModuleId,".")}if(!this.boundApi){const isCallable=typeof this.api==="function"||this.api&&typeof this.api.default==="function";const proxyTarget=isCallable?function(){}:{};this.boundApi=new Proxy(proxyTarget,{get:(target,prop)=>this.api?this.api[prop]:void 0,set:(target,prop,value)=>{if(this.api){this.api[prop]=value}return true},has:(target,prop)=>this.api?prop in this.api:false,ownKeys:____target=>this.api?Reflect.ownKeys(this.api):[],deleteProperty:(target,prop)=>this.api?delete this.api[prop]:true,apply:(target,thisArg,args)=>this.api?Reflect.apply(this.api,thisArg,args):void 0,construct:(target,args)=>this.api?Reflect.construct(this.api,args):{},getOwnPropertyDescriptor:(target,prop)=>{if(isCallable&&prop==="prototype"){return Object.getOwnPropertyDescriptor(target,prop)}if(this.api&&prop in this.api){const desc=Object.getOwnPropertyDescriptor(this.api,prop);if(desc){return{...desc,configurable:true}}}return void 0}})}store.self=this.boundApi;store.context=this.context||{};store.slothlet=this;if(this.reference&&typeof this.reference==="object"){Object.assign(this.boundApi,this.reference)}if(this.handlers.routineManager){await this.handlers.routineManager.rebuildStacks(this.boundApi);await this.handlers.routineManager.runStartupModeRoutines()}this.isLoaded=true;return this.boundApi}async reload(options={}){const{keepInstanceID=false}=options;if(!this.config?.dir){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"reload",validationError:true})}const operationHistory=this.handlers.apiManager?.state?.operationHistory?[...this.handlers.apiManager.state.operationHistory]:[];await this._clearModuleCaches();const oldInstanceID=this.instanceID;if(!keepInstanceID){this.instanceID=`${oldInstanceID}_reload_${Date.now()}`;if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}}const savedMetadataState=this.handlers.metadata?.exportUserState?.();const savedHooks=this.handlers.hookManager?.exportHooks?.();const wasSealed=this.handlers.permissionManager?.isSealed?.()===true;await this.load(this.config,this.instanceID);if(savedMetadataState&&this.handlers.metadata){this.handlers.metadata.importUserState(savedMetadataState)}if(savedHooks?.length&&this.handlers.hookManager){this.handlers.hookManager.importHooks(savedHooks)}for(const[,store]of this.contextManager.instances){if(store.parentInstanceID===oldInstanceID){store.parentInstanceID=this.instanceID}}if(oldInstanceID&&oldInstanceID!==this.instanceID&&this.contextManager.instances?.has(oldInstanceID)){this.contextManager.cleanup(oldInstanceID)}for(const operation of operationHistory){if(operation.type==="add"){await this.handlers.apiManager.addApiComponent({apiPath:operation.apiPath,folderPath:operation.folderPath,options:{...operation.options||{},recordHistory:false},versionConfig:operation.versionConfig||null})}else if(operation.type==="remove"){if(operation.scopedModuleID){await this.handlers.apiManager.removeApiComponent(operation.scopedModuleID,{scopedApiPath:operation.apiPath,recordHistory:false})}else{await this.handlers.apiManager.removeApiComponent(operation.apiPath,{recordHistory:false})}}else if(operation.type==="addPermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.addRule(operation.rule,operation.ownerModuleID,operation.ruleId)}}else{if(operation.type==="removePermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.removeRule(operation.ruleId,operation.callerModuleID)}}}}if(wasSealed)this.handlers.permissionManager?.seal?.();return this.boundApi}async _clearModuleCaches(){if(!isNode)return;const targetDir=this.config.dir;const require2=createRequire(import.meta.url);const absoluteTargetDir=path.resolve(targetDir);for(const key of Object.keys(require2.cache)){if(key.startsWith(absoluteTargetDir)){delete require2.cache[key]}}}injectRuntimeMetadataFunctions(api){if(!api.slothlet?.metadata){return}const metadataHandler=this.handlers.metadata;api.slothlet.metadata.get=async function slothlet_metadata_get_runtime(path2){return metadataHandler.get(path2)};api.slothlet.metadata.self=function slothlet_metadata_self_runtime(){return metadataHandler.self()};api.slothlet.metadata.caller=function slothlet_metadata_caller_runtime(){return metadataHandler.caller()}}async _drainInFlightLoads(){if(!this.api)return;const pending=[];const seen=new Set;const collect=(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>15||seen.has(obj))return;seen.add(obj);try{if(isFrameworkInternal(obj))return;const wrapper=resolveWrapper(obj);if(wrapper){const mat=wrapper.____slothletInternal.materializationPromise;if(mat)pending.push(mat);for(const key of Object.keys(wrapper)){if(!key.startsWith("____"))collect(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){collect(obj[key],depth+1)}}catch{}};for(const key of Object.keys(this.api)){collect(this.api[key])}if(pending.length>0){await Promise.allSettled(pending)}}async shutdown(){if(!this.isLoaded){return}await this._drainInFlightLoads();boundaryPatchHolders.delete(this.instanceID);if(boundaryPatchHolders.size===0){disableEventEmitterPatching();disableSchedulerPatching();disableEventTargetPatching();disableEventTargetPropertyPatching();disableObserverPatching();cleanupEventEmitterResources()}if(this.instanceID&&this.contextManager){this.contextManager.cleanup(this.instanceID)}if(this.handlers.ownership){this.handlers.ownership.clear()}this.handlers.versionManager?.shutdown();await this.handlers.permissionManager?.shutdown();if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}this.isLoaded=false}debug(code,context={}){if(this.debugLogger){this.debugLogger.log(code,context)}}getAPI(){if(!this.isLoaded){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"getAPI"},null,{validationError:true})}return this.boundApi}getDiagnostics(){return{instanceID:this.instanceID,isLoaded:this.isLoaded,config:this.config,context:this.contextManager?.getDiagnostics()||null,ownership:this.handlers.ownership?.getDiagnostics()||null}}getOwnership(){if(!this.handlers.ownership){return null}return this.handlers.ownership.getDiagnostics()}buildFinalAPI(userApi){return this.builders.apiBuilder.buildFinalAPI(userApi)}}async function slothlet(config){const instance=new Slothlet;const api=await instance.load(config);return api}slothlet.defaults=Object.freeze({routines:DEFAULT_ROUTINES,reservedExports:RESERVED_EXPORTS});var stdin_default=slothlet;export{stdin_default as default,slothlet};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cldmv/slothlet",
3
- "version": "3.16.2",
3
+ "version": "3.16.3",
4
4
  "moduleVersions": {
5
5
  "lazy": "3.0.0",
6
6
  "eager": "3.0.0",