@cldmv/slothlet 3.6.0 → 3.8.0
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 +150 -732
- package/REFERENCE.md +2 -0
- package/dist/lib/builders/api_builder.mjs +1 -1
- package/dist/lib/handlers/module-manager.mjs +17 -0
- package/dist/lib/handlers/permission-manager.mjs +1 -1
- package/dist/lib/handlers/unified-wrapper.mjs +1 -1
- package/dist/lib/helpers/config.mjs +1 -1
- package/dist/lib/helpers/eventemitter-context.mjs +1 -1
- package/dist/lib/helpers/module-discovery.mjs +17 -0
- package/dist/lib/helpers/module-manifest-validator.mjs +17 -0
- package/dist/lib/helpers/module-sort.mjs +17 -0
- package/dist/lib/i18n/languages/de-de.json +23 -1
- package/dist/lib/i18n/languages/en-gb.json +23 -1
- package/dist/lib/i18n/languages/en-us.json +23 -1
- package/dist/lib/i18n/languages/es-es.json +23 -1
- package/dist/lib/i18n/languages/es-mx.json +23 -1
- package/dist/lib/i18n/languages/fr-fr.json +23 -1
- package/dist/lib/i18n/languages/hi-in.json +23 -1
- package/dist/lib/i18n/languages/ja-jp.json +23 -1
- package/dist/lib/i18n/languages/ko-kr.json +23 -1
- package/dist/lib/i18n/languages/pt-br.json +23 -1
- package/dist/lib/i18n/languages/ru-ru.json +23 -1
- package/dist/lib/i18n/languages/zh-cn.json +23 -1
- package/package.json +5 -9
- package/schemas/slothlet.module.schema.json +98 -0
- package/types/dist/lib/builders/api_builder.d.mts.map +1 -1
- package/types/dist/lib/handlers/module-manager.d.mts +29 -0
- package/types/dist/lib/handlers/module-manager.d.mts.map +1 -0
- package/types/dist/lib/handlers/permission-manager.d.mts +2 -0
- package/types/dist/lib/handlers/permission-manager.d.mts.map +1 -1
- package/types/dist/lib/handlers/unified-wrapper.d.mts.map +1 -1
- package/types/dist/lib/helpers/config.d.mts +2 -0
- package/types/dist/lib/helpers/config.d.mts.map +1 -1
- package/types/dist/lib/helpers/eventemitter-context.d.mts.map +1 -1
- package/types/dist/lib/helpers/module-discovery.d.mts +8 -0
- package/types/dist/lib/helpers/module-discovery.d.mts.map +1 -0
- package/types/dist/lib/helpers/module-manifest-validator.d.mts +14 -0
- package/types/dist/lib/helpers/module-manifest-validator.d.mts.map +1 -0
- package/types/dist/lib/helpers/module-sort.d.mts +2 -0
- package/types/dist/lib/helpers/module-sort.d.mts.map +1 -0
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
const ____COLLISION_MERGED_PROPERTY=Symbol("collisionMergedProperty");import util from"node:util";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");const hasOwn=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);function unwrapError(error){if(error&&error.name==="SlothletError"&&error.originalError){return error.originalError}return error}const wrapperDebugEnabled=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 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}){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.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.proxy=null;internal.impl=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){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;const extractFullImpl_result={};for(const key of Object.keys(impl)){if(key.startsWith("__"))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);let extractedModuleId=moduleID||(wrapperMetadata?.moduleID?wrapperMetadata.moduleID.split(":")[0]:null);if(extractedModuleId&&typeof extractedModuleId!=="string"){extractedModuleId=extractedModuleId.moduleID||extractedModuleId.__moduleID||String(extractedModuleId)}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.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=>{this._applyNewImpl(value)};const result=await this.____slothletInternal.materializeFunc(lazy_setImpl);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});if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){return}if(util.types.isProxy(this.____slothletInternal.impl))return;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;const builtinKeys=new Set(["slothlet","shutdown","destroy"]);for(const key of ownKeys){if(internalKeys.has(key)){continue}if(typeof key==="string"&&metadataKeys.has(key)){continue}if(typeof key==="string"&&builtinKeys.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";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.slothlet,this.____slothletInternal.moduleID,this.____slothletInternal.filePath)}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.slothlet,this.____slothletInternal.moduleID,this.____slothletInternal.filePath);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);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){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){if(value===void 0){return void 0}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}let childImpl=value;if(this.____slothletInternal.mode==="eager"&&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?.moduleID){const colonIndex=parentMetadata.moduleID.indexOf(":");childModuleId=colonIndex>0?parentMetadata.moduleID.substring(0,colonIndex):parentMetadata.moduleID}}else{if(childExistingMetadata?.moduleID){const colonIndex=childExistingMetadata.moduleID.indexOf(":");childModuleId=colonIndex>0?childExistingMetadata.moduleID.substring(0,colonIndex):childExistingMetadata.moduleID}}const childSourceFolder=childExistingMetadata?.sourceFolder||parentMetadata?.sourceFolder||null;const 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});return nestedWrapper.createProxy()}___createWaitingProxy(propChain=[]){const wrapper=this;const cacheKey=propChain.join(".");if(!wrapper.____slothletInternal.waitingProxyCache){wrapper.____slothletInternal.waitingProxyCache=new Map}if(wrapper.____slothletInternal.waitingProxyCache.has(cacheKey)){return wrapper.____slothletInternal.waitingProxyCache.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;for(const chainProp of propChain){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;const idx=propChain.indexOf(chainProp);for(let i=idx;i<propChain.length;i++){result=result[propChain[i]]}return result}const isInternal2=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));if(!isInternal2&&hasOwn(current,chainProp)){const child=current[chainProp];const _childW=resolveWrapper(child);if(_childW){current=_childW;if(current.____slothletInternal.mode==="lazy"&&!current.____slothletInternal.state.materialized){await current._materialize()}continue}return child}if(current.____slothletInternal.impl&¤t.____slothletInternal.impl[chainProp]!==void 0){return current.____slothletInternal.impl[chainProp]}return void 0}if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl}return current.____slothletInternal.impl};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||current===null){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(current&¤tWrapper){const isInternal2=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));if(!isInternal2&&chainProp in currentWrapper){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"&¤tWrapper.____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"&¤t!==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=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));if(!isInternal2&¤t&&chainProp in current){const cached=current[chainProp];const _cachedW2=resolveWrapper(cached);if(_cachedW2){current=_cachedW2;remainingChain.shift()}else{return void 0}}else{return void 0}}if(current&¤t.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl[prop]}const isFinalInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isFinalInternal&¤t&&prop in current){return current[prop]}return void 0}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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 ___capturedCallerWrapper=wrapper.slothlet.contextManager?.tryGetContext?.()?.currentWrapper??null;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(current&¤tWrapper){lastWrapper=currentWrapper;const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&prop in currentWrapper){lastObject=current;current=currentWrapper[prop];continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&¤tWrapper.____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(___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)}}return Reflect.apply(current,lastObject,args)}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);wrapper.____slothletInternal.waitingProxyCache.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{proxyTarget=wrapper}if(!(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)=>{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=typeof prop==="string"&&UnifiedWrapper.INTERNAL_KEYS.has(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;if(prop==="then")return void 0;if(prop==="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()=>void 0}if(wrapper.____slothletInternal.invalid){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&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"){return cachedImpl}}if(_cachedWrapper){const cachedWrapper=_cachedWrapper;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}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]}const isInternal2=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal2&&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(()=>{})}}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}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 wrapped=wrapper.___createChildWrapper(prop,value);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 permissionManager=wrapper.slothlet.handlers?.permissionManager;if(permissionManager&&permissionManager.isEnabled()){const ctx2=wrapper.slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx2?.currentWrapper;if(callerWrapper){const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetPath=wrapper.____slothletInternal.apiPath;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=ctx2?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}}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||{};let result;let finalResult;let isAsync=false;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,thisArg,args,wrapper))}else{resolve(impl2.apply(thisArg,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))}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,thisArg,args,wrapper)}else{result=impl.apply(thisArg,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)}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){this.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=this.lastSyncError;this.lastSyncError=null;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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&hasOwn(wrapper,prop)){return true}if(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}}if(Object.prototype.hasOwnProperty.call(target,prop)){return Object.getOwnPropertyDescriptor(target,prop)}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&hasOwn(wrapper,prop)){const desc=Object.getOwnPropertyDescriptor(wrapper,prop);if(desc){return desc}}if(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"){keys.add(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)){if(hasOwn(wrapper,prop)){delete wrapper[prop]}Object.defineProperty(wrapper,prop,{value,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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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`)}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:getTrap,apply:applyTrap,construct:constructTrap,has:hasTrap,getOwnPropertyDescriptor:getOwnPropertyDescriptorTrap,ownKeys:ownKeysTrap,set:setTrap,deleteProperty:deletePropertyTrap,getPrototypeOf:()=>null});_proxyRegistry.set(wrapper.____slothletInternal.proxy,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{TYPE_STATES,UnifiedWrapper,resolveWrapper};
|
|
17
|
+
const ____COLLISION_MERGED_PROPERTY=Symbol("collisionMergedProperty");import util from"node:util";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");const hasOwn=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);function runtime_enforceReadGate(wrapper,prop,resolvedValue,callerOverride){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return;const isTerminal=resolvedValue!==Object(resolvedValue)||resolvedValue instanceof Map||resolvedValue instanceof Set||resolvedValue instanceof WeakMap||resolvedValue instanceof WeakSet||resolvedValue instanceof Date||resolvedValue instanceof RegExp||resolvedValue instanceof Promise||resolvedValue instanceof Error||ArrayBuffer.isView(resolvedValue)||resolvedValue instanceof ArrayBuffer;if(!isTerminal)return;const ctx=callerOverride!==void 0?callerOverride:wrapper.slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx?.currentWrapper;if(!callerWrapper)return;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);if(!pm.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,ctx.context??null)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}function unwrapError(error){if(error&&error.name==="SlothletError"&&error.originalError){return error.originalError}return error}const wrapperDebugEnabled=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 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}){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.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;internal.impl=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){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;const extractFullImpl_result={};for(const key of Object.keys(impl)){if(key.startsWith("__"))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);let extractedModuleId=moduleID||(wrapperMetadata?.moduleID?wrapperMetadata.moduleID.split(":")[0]:null);if(extractedModuleId&&typeof extractedModuleId!=="string"){extractedModuleId=extractedModuleId.moduleID||extractedModuleId.__moduleID||String(extractedModuleId)}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=>{this._applyNewImpl(value)};const result=await this.____slothletInternal.materializeFunc(lazy_setImpl);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});if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){return}if(util.types.isProxy(this.____slothletInternal.impl))return;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;const builtinKeys=new Set(["slothlet","shutdown","destroy"]);for(const key of ownKeys){if(internalKeys.has(key)){continue}if(typeof key==="string"&&metadataKeys.has(key)){continue}if(typeof key==="string"&&builtinKeys.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";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.slothlet,this.____slothletInternal.moduleID,this.____slothletInternal.filePath)}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.slothlet,this.____slothletInternal.moduleID,this.____slothletInternal.filePath);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);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){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){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}let childImpl=value;if(this.____slothletInternal.mode==="eager"&&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?.moduleID){const colonIndex=parentMetadata.moduleID.indexOf(":");childModuleId=colonIndex>0?parentMetadata.moduleID.substring(0,colonIndex):parentMetadata.moduleID}}else{if(childExistingMetadata?.moduleID){const colonIndex=childExistingMetadata.moduleID.indexOf(":");childModuleId=colonIndex>0?childExistingMetadata.moduleID.substring(0,colonIndex):childExistingMetadata.moduleID}}const childSourceFolder=childExistingMetadata?.sourceFolder||parentMetadata?.sourceFolder||null;const 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});return nestedWrapper.createProxy()}___createWaitingProxy(propChain=[]){const wrapper=this;const __readGateStore=wrapper.slothlet.contextManager?.tryGetContext?.();const __readGateCaller=__readGateStore?{currentWrapper:__readGateStore.currentWrapper,context:__readGateStore.context}: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;for(const chainProp of propChain){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;const idx=propChain.indexOf(chainProp);for(let i=idx;i<propChain.length;i++){result=result[propChain[i]]}return result}const isInternal2=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));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}runtime_enforceReadGate(current,chainProp,child,__readGateCaller);return child}if(current.____slothletInternal.impl&¤t.____slothletInternal.impl[chainProp]!==void 0){const implValue=current.____slothletInternal.impl[chainProp];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)}return current.____slothletInternal.impl};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||current===null){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(current&¤tWrapper){const isInternal2=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));if(!isInternal2&&chainProp in currentWrapper){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"&¤tWrapper.____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"&¤t!==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=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));if(!isInternal2&¤t&&chainProp in current){const cached=current[chainProp];const _cachedW2=resolveWrapper(cached);if(_cachedW2){current=_cachedW2;remainingChain.shift()}else{return void 0}}else{return void 0}}if(current&¤t.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl[prop]}const isFinalInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isFinalInternal&¤t&&prop in current){return current[prop]}return void 0}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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 ___capturedCallerWrapper=wrapper.slothlet.contextManager?.tryGetContext?.()?.currentWrapper??null;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(current&¤tWrapper){lastWrapper=currentWrapper;const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&prop in currentWrapper){lastObject=current;current=currentWrapper[prop];continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&¤tWrapper.____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(___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)}}return Reflect.apply(current,lastObject,args)}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{proxyTarget=wrapper}if(!(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=typeof prop==="string"&&UnifiedWrapper.INTERNAL_KEYS.has(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;if(prop==="then")return void 0;if(prop==="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()=>void 0}if(wrapper.____slothletInternal.invalid){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&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]}const isInternal2=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal2&&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 wrapped=wrapper.___createChildWrapper(prop,value);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 permissionManager=wrapper.slothlet.handlers?.permissionManager;if(permissionManager&&permissionManager.isEnabled()){const ctx2=wrapper.slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx2?.currentWrapper;if(callerWrapper){const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetPath=wrapper.____slothletInternal.apiPath;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=ctx2?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}}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||{};let result;let finalResult;let isAsync=false;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,thisArg,args,wrapper))}else{resolve(impl2.apply(thisArg,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))}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,thisArg,args,wrapper)}else{result=impl.apply(thisArg,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)}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){this.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=this.lastSyncError;this.lastSyncError=null;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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&hasOwn(wrapper,prop)){return true}if(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}}if(Object.prototype.hasOwnProperty.call(target,prop)){return Object.getOwnPropertyDescriptor(target,prop)}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&hasOwn(wrapper,prop)){const desc=Object.getOwnPropertyDescriptor(wrapper,prop);if(desc){return desc}}if(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"){keys.add(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)){if(hasOwn(wrapper,prop)){delete wrapper[prop]}Object.defineProperty(wrapper,prop,{value,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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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`)}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:getTrap,apply:applyTrap,construct:constructTrap,has:hasTrap,getOwnPropertyDescriptor:getOwnPropertyDescriptorTrap,ownKeys:ownKeysTrap,set:setTrap,deleteProperty:deletePropertyTrap,getPrototypeOf:()=>null});_proxyRegistry.set(wrapper.____slothletInternal.proxy,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{TYPE_STATES,UnifiedWrapper,resolveWrapper};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{SlothletError}from"@cldmv/slothlet/errors";class Config extends ComponentBase{static slothletProperty="config";normalizeCollision(collision){const validModes=["skip","warn","replace","merge","merge-replace","error"];const defaultMode="merge";if(typeof collision==="string"){const normalized=collision.toLowerCase();const mode=validModes.includes(normalized)?normalized:defaultMode;return{initial:mode,api:mode}}if(collision&&typeof collision==="object"){const validateMode=m=>{if(!m)return defaultMode;const normalized=String(m).toLowerCase();return validModes.includes(normalized)?normalized:defaultMode};return{initial:validateMode(collision.initial),api:validateMode(collision.api)}}return{initial:defaultMode,api:defaultMode}}normalizeRuntime(runtime){if(!runtime||typeof runtime!=="string"){return"async"}const normalized=runtime.toLowerCase().trim();if(normalized==="async"||normalized==="asynclocal"||normalized==="asynclocalstorage"){return"async"}if(normalized==="live"||normalized==="livebindings"||normalized==="experimental"){return"live"}return"async"}normalizeMode(mode){if(!mode||typeof mode!=="string"){return"eager"}const normalized=mode.toLowerCase().trim();if(normalized==="lazy"||normalized==="deferred"||normalized==="proxy"){return"lazy"}if(normalized==="eager"||normalized==="immediate"||normalized==="preload"){return"eager"}return"eager"}normalizeMutations(mutations){const defaults={add:true,remove:true,reload:true,permissions:true};if(!mutations||typeof mutations!=="object"){return defaults}return{add:mutations.add===false?false:true,remove:mutations.remove===false?false:true,reload:mutations.reload===false?false:true,permissions:mutations.permissions===false?false:true}}normalizeDebug(debug){if(!debug){return{builder:false,api:false,index:false,modes:false,wrapper:false,ownership:false,context:false,initialization:false,materialize:false,versioning:false,permissions:false}}if(debug===true){return{builder:true,api:true,index:true,modes:true,wrapper:true,ownership:true,context:true,initialization:true,materialize:true,versioning:true,permissions:true}}if(typeof debug==="object"){return{builder:debug.builder||false,api:debug.api||false,index:debug.index||false,modes:debug.modes||false,wrapper:debug.wrapper||false,ownership:debug.ownership||false,context:debug.context||false,initialization:debug.initialization||false,materialize:debug.materialize||false,versioning:debug.versioning||false,permissions:debug.permissions||false}}return{builder:false,api:false,index:false,modes:false,wrapper:false,ownership:false,context:false,initialization:false,materialize:false,versioning:false,permissions:false}}transformConfig(config={}){if(!config.dir){throw new this.SlothletError("INVALID_CONFIG_DIR_MISSING",{},null,{validationError:true})}const resolvedDir=this.slothlet.helpers.resolver.resolvePathFromCaller(config.dir);let mutations=null;if(config.allowMutation===false){mutations={add:false,remove:false,reload:false};if(!config.silent){new this.SlothletWarning("V2_CONFIG_UNSUPPORTED",{option:"allowMutation",replacement:"api.mutations: { add: false, remove: false, reload: false }",hint:"The allowMutation config option was part of v2. Use api.mutations for granular control in v3."})}}let collision=null;if(config.collision&&!config.api?.collision){collision=this.normalizeCollision(config.collision);if(!config.silent){new this.SlothletWarning("V2_CONFIG_UNSUPPORTED",{option:"collision",replacement:"api.collision",hint:"Root-level collision config was part of v2. Use api.collision in v3."})}}const apiConfig=config.api||{};const finalCollision=apiConfig.collision?this.normalizeCollision(apiConfig.collision):collision||this.normalizeCollision(null);const finalMutations=apiConfig.mutations?this.normalizeMutations(apiConfig.mutations):mutations||this.normalizeMutations(null);let scopeConfig=config.scope;if(scopeConfig&&typeof scopeConfig==="object"&&scopeConfig.merge){const validMergeStrategies=["shallow","deep"];if(!validMergeStrategies.includes(scopeConfig.merge)){throw new this.SlothletError("INVALID_CONFIG",{option:"scope.merge",value:scopeConfig.merge,expected:validMergeStrategies.join(" or "),hint:`Invalid merge strategy: "${scopeConfig.merge}". Must be "shallow" or "deep".`,validationError:true},null,{validationError:true})}}let hookConfig={enabled:false,pattern:"**",suppressErrors:false};if(config.hook===true||config.hook===false){hookConfig.enabled=config.hook;hookConfig.pattern=config.hook?"**":null}else if(typeof config.hook==="string"){hookConfig.enabled=true;hookConfig.pattern=config.hook}else if(config.hook&&typeof config.hook==="object"){hookConfig.enabled=config.hook.enabled!==false;hookConfig.pattern=config.hook.pattern||"**";hookConfig.suppressErrors=config.hook.suppressErrors||false}let trackingConfig={materialization:false};if(config.tracking===true||config.tracking===false){trackingConfig.materialization=config.tracking}else if(config.tracking&&typeof config.tracking==="object"){trackingConfig.materialization=config.tracking.materialization===true}if(config.backgroundMaterialize===true){trackingConfig.materialization=true}if(config.versionDispatcher!==void 0&&config.versionDispatcher!==null){if(typeof config.versionDispatcher!=="string"&&typeof config.versionDispatcher!=="function"){throw new this.SlothletError("INVALID_CONFIG_VERSION_DISPATCHER",{received:typeof config.versionDispatcher,validationError:true})}}const permissionsConfig=this.normalizePermissions(config.permissions);let i18nConfig=null;if(config.i18n&&typeof config.i18n==="object"){i18nConfig={language:typeof config.i18n.language==="string"?config.i18n.language:void 0}}return{...config,dir:resolvedDir,mode:this.normalizeMode(config.mode),runtime:this.normalizeRuntime(config.runtime),apiDepth:config.apiDepth!==void 0?config.apiDepth:Infinity,reference:config.reference||null,context:config.context||null,i18n:i18nConfig,debug:this.normalizeDebug(config.debug),diagnostics:config.diagnostics===true,hook:hookConfig,collision:finalCollision,api:{collision:finalCollision,mutations:finalMutations},scope:scopeConfig,tracking:trackingConfig,backgroundMaterialize:config.backgroundMaterialize===true,silent:config.silent===true,typescript:this.normalizeTypeScript(config.typescript),env:this.normalizeEnv(config.env),versionDispatcher:config.versionDispatcher??null,permissions:permissionsConfig}}normalizeTypeScript(typescript){if(!typescript){return null}if(typescript===true){return{enabled:true,mode:"fast"}}if(typeof typescript==="string"){const mode=typescript.toLowerCase();if(mode==="fast"||mode==="strict"){return{enabled:true,mode}}return{enabled:true,mode:"fast"}}if(typeof typescript==="object"){const mode=typescript.mode==="strict"?"strict":"fast";return{enabled:true,mode,types:typescript.types||null,target:typescript.target||"es2020",sourcemap:typescript.sourcemap||false}}return null}normalizeEnv(env){if(!env||typeof env!=="object"){return null}const include=Array.isArray(env.include)?env.include.filter(k=>typeof k==="string"):null;if(include&&include.length>0){return{include}}return null}normalizePermissions(permissions){if(!permissions||typeof permissions!=="object"){return null}let defaultPolicy;if(permissions.defaultPolicy==="deny"){defaultPolicy="deny"}else if(permissions.defaultPolicy==="allow"||permissions.defaultPolicy===void 0){defaultPolicy="allow"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.defaultPolicy",value:permissions.defaultPolicy,expected:'"allow" or "deny"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}const enabled=permissions.enabled!==false;let audit;if(permissions.audit==="verbose"){audit="verbose"}else if(permissions.audit==="default"||permissions.audit===void 0){audit="default"}else if(permissions.audit===true){audit="default"}else if(permissions.audit===false){audit="default"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.audit",value:permissions.audit,expected:'"default" or "verbose"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}if(permissions.rules!==void 0&&!Array.isArray(permissions.rules)){throw new SlothletError("INVALID_CONFIG",{option:"permissions.rules",value:permissions.rules,expected:"array",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}const rules=Array.isArray(permissions.rules)?permissions.rules:[];return{defaultPolicy,enabled,audit,rules}}}export{Config};
|
|
17
|
+
import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{SlothletError}from"@cldmv/slothlet/errors";class Config extends ComponentBase{static slothletProperty="config";normalizeCollision(collision){const validModes=["skip","warn","replace","merge","merge-replace","error"];const defaultMode="merge";if(typeof collision==="string"){const normalized=collision.toLowerCase();const mode=validModes.includes(normalized)?normalized:defaultMode;return{initial:mode,api:mode}}if(collision&&typeof collision==="object"){const validateMode=m=>{if(!m)return defaultMode;const normalized=String(m).toLowerCase();return validModes.includes(normalized)?normalized:defaultMode};return{initial:validateMode(collision.initial),api:validateMode(collision.api)}}return{initial:defaultMode,api:defaultMode}}normalizeRuntime(runtime){if(!runtime||typeof runtime!=="string"){return"async"}const normalized=runtime.toLowerCase().trim();if(normalized==="async"||normalized==="asynclocal"||normalized==="asynclocalstorage"){return"async"}if(normalized==="live"||normalized==="livebindings"||normalized==="experimental"){return"live"}return"async"}normalizeMode(mode){if(!mode||typeof mode!=="string"){return"eager"}const normalized=mode.toLowerCase().trim();if(normalized==="lazy"||normalized==="deferred"||normalized==="proxy"){return"lazy"}if(normalized==="eager"||normalized==="immediate"||normalized==="preload"){return"eager"}return"eager"}normalizeMutations(mutations){const defaults={add:true,remove:true,reload:true,permissions:true};if(!mutations||typeof mutations!=="object"){return defaults}return{add:mutations.add===false?false:true,remove:mutations.remove===false?false:true,reload:mutations.reload===false?false:true,permissions:mutations.permissions===false?false:true}}normalizeDebug(debug){if(!debug){return{builder:false,api:false,index:false,modes:false,wrapper:false,ownership:false,context:false,initialization:false,materialize:false,versioning:false,permissions:false}}if(debug===true){return{builder:true,api:true,index:true,modes:true,wrapper:true,ownership:true,context:true,initialization:true,materialize:true,versioning:true,permissions:true}}if(typeof debug==="object"){return{builder:debug.builder||false,api:debug.api||false,index:debug.index||false,modes:debug.modes||false,wrapper:debug.wrapper||false,ownership:debug.ownership||false,context:debug.context||false,initialization:debug.initialization||false,materialize:debug.materialize||false,versioning:debug.versioning||false,permissions:debug.permissions||false}}return{builder:false,api:false,index:false,modes:false,wrapper:false,ownership:false,context:false,initialization:false,materialize:false,versioning:false,permissions:false}}transformConfig(config={}){if(!config.dir){throw new this.SlothletError("INVALID_CONFIG_DIR_MISSING",{},null,{validationError:true})}const resolvedDir=this.slothlet.helpers.resolver.resolvePathFromCaller(config.dir);let mutations=null;if(config.allowMutation===false){mutations={add:false,remove:false,reload:false};if(!config.silent){new this.SlothletWarning("V2_CONFIG_UNSUPPORTED",{option:"allowMutation",replacement:"api.mutations: { add: false, remove: false, reload: false }",hint:"The allowMutation config option was part of v2. Use api.mutations for granular control in v3."})}}let collision=null;if(config.collision&&!config.api?.collision){collision=this.normalizeCollision(config.collision);if(!config.silent){new this.SlothletWarning("V2_CONFIG_UNSUPPORTED",{option:"collision",replacement:"api.collision",hint:"Root-level collision config was part of v2. Use api.collision in v3."})}}const apiConfig=config.api||{};const finalCollision=apiConfig.collision?this.normalizeCollision(apiConfig.collision):collision||this.normalizeCollision(null);const finalMutations=apiConfig.mutations?this.normalizeMutations(apiConfig.mutations):mutations||this.normalizeMutations(null);let scopeConfig=config.scope;if(scopeConfig&&typeof scopeConfig==="object"&&scopeConfig.merge){const validMergeStrategies=["shallow","deep"];if(!validMergeStrategies.includes(scopeConfig.merge)){throw new this.SlothletError("INVALID_CONFIG",{option:"scope.merge",value:scopeConfig.merge,expected:validMergeStrategies.join(" or "),hint:`Invalid merge strategy: "${scopeConfig.merge}". Must be "shallow" or "deep".`,validationError:true},null,{validationError:true})}}let hookConfig={enabled:false,pattern:"**",suppressErrors:false};if(config.hook===true||config.hook===false){hookConfig.enabled=config.hook;hookConfig.pattern=config.hook?"**":null}else if(typeof config.hook==="string"){hookConfig.enabled=true;hookConfig.pattern=config.hook}else if(config.hook&&typeof config.hook==="object"){hookConfig.enabled=config.hook.enabled!==false;hookConfig.pattern=config.hook.pattern||"**";hookConfig.suppressErrors=config.hook.suppressErrors||false}let trackingConfig={materialization:false};if(config.tracking===true||config.tracking===false){trackingConfig.materialization=config.tracking}else if(config.tracking&&typeof config.tracking==="object"){trackingConfig.materialization=config.tracking.materialization===true}if(config.backgroundMaterialize===true){trackingConfig.materialization=true}if(config.versionDispatcher!==void 0&&config.versionDispatcher!==null){if(typeof config.versionDispatcher!=="string"&&typeof config.versionDispatcher!=="function"){throw new this.SlothletError("INVALID_CONFIG_VERSION_DISPATCHER",{received:typeof config.versionDispatcher,validationError:true})}}const permissionsConfig=this.normalizePermissions(config.permissions);let i18nConfig=null;if(config.i18n&&typeof config.i18n==="object"){i18nConfig={language:typeof config.i18n.language==="string"?config.i18n.language:void 0}}return{...config,dir:resolvedDir,mode:this.normalizeMode(config.mode),runtime:this.normalizeRuntime(config.runtime),apiDepth:config.apiDepth!==void 0?config.apiDepth:Infinity,reference:config.reference||null,context:config.context||null,i18n:i18nConfig,debug:this.normalizeDebug(config.debug),diagnostics:config.diagnostics===true,hook:hookConfig,collision:finalCollision,api:{collision:finalCollision,mutations:finalMutations},scope:scopeConfig,tracking:trackingConfig,backgroundMaterialize:config.backgroundMaterialize===true,silent:config.silent===true,typescript:this.normalizeTypeScript(config.typescript),env:this.normalizeEnv(config.env),versionDispatcher:config.versionDispatcher??null,permissions:permissionsConfig}}normalizeTypeScript(typescript){if(!typescript){return null}if(typescript===true){return{enabled:true,mode:"fast"}}if(typeof typescript==="string"){const mode=typescript.toLowerCase();if(mode==="fast"||mode==="strict"){return{enabled:true,mode}}return{enabled:true,mode:"fast"}}if(typeof typescript==="object"){const mode=typescript.mode==="strict"?"strict":"fast";return{enabled:true,mode,types:typescript.types||null,target:typescript.target||"es2020",sourcemap:typescript.sourcemap||false}}return null}normalizeEnv(env){if(!env||typeof env!=="object"){return null}const include=Array.isArray(env.include)?env.include.filter(k=>typeof k==="string"):null;if(include&&include.length>0){return{include}}return null}normalizePermissions(permissions){if(!permissions||typeof permissions!=="object"){return null}let defaultPolicy;if(permissions.defaultPolicy==="deny"){defaultPolicy="deny"}else if(permissions.defaultPolicy==="allow"||permissions.defaultPolicy===void 0){defaultPolicy="allow"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.defaultPolicy",value:permissions.defaultPolicy,expected:'"allow" or "deny"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}const enabled=permissions.enabled!==false;let audit;if(permissions.audit==="verbose"){audit="verbose"}else if(permissions.audit==="default"||permissions.audit===void 0){audit="default"}else if(permissions.audit===true){audit="default"}else if(permissions.audit===false){audit="default"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.audit",value:permissions.audit,expected:'"default" or "verbose"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}let readGating;if(permissions.readGating===false){readGating=false}else if(permissions.readGating===true||permissions.readGating===void 0){readGating=true}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.readGating",value:permissions.readGating,expected:"boolean",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}if(permissions.rules!==void 0&&!Array.isArray(permissions.rules)){throw new SlothletError("INVALID_CONFIG",{option:"permissions.rules",value:permissions.rules,expected:"array",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}const rules=Array.isArray(permissions.rules)?permissions.rules:[];return{defaultPolicy,enabled,audit,readGating,rules}}}export{Config};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{EventEmitter}from"node:events";import{AsyncResource}from"node:async_hooks";let isInApiContext=null;function setApiContextChecker(checker){isInApiContext=checker}const originalMethods=new Map;const wrappedListeners=new Map;const trackedEmitters=new Set;let isPatchingEnabled=false;function runtime_wrapEventListener(listener){const resource=new AsyncResource("slothlet-event-listener");const runtime_wrappedListener=function(...args){return resource.runInAsyncScope(()=>{return listener.apply(this,args)},this)};runtime_wrappedListener._slothletOriginal=listener;runtime_wrappedListener._slothletResource=resource;return runtime_wrappedListener}function runtime_getListenerTracking(emitter){let emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking){emitterTracking=new Map;wrappedListeners.set(emitter,emitterTracking)}return emitterTracking}function runtime_trackListener(emitter,event,originalListener,wrappedListener){const emitterTracking=runtime_getListenerTracking(emitter);let eventTracking=emitterTracking.get(event);if(!eventTracking){eventTracking=new Map;emitterTracking.set(event,eventTracking)}eventTracking.set(originalListener,wrappedListener)}function runtime_getWrappedListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return void 0;const eventTracking=emitterTracking.get(event);if(!eventTracking)return void 0;
|
|
17
|
+
import{EventEmitter}from"node:events";import{AsyncResource}from"node:async_hooks";let isInApiContext=null;function setApiContextChecker(checker){isInApiContext=checker}const originalMethods=new Map;const wrappedListeners=new Map;const trackedEmitters=new Set;let isPatchingEnabled=false;function runtime_wrapEventListener(listener){const resource=new AsyncResource("slothlet-event-listener");const runtime_wrappedListener=function(...args){return resource.runInAsyncScope(()=>{return listener.apply(this,args)},this)};runtime_wrappedListener._slothletOriginal=listener;runtime_wrappedListener._slothletResource=resource;return runtime_wrappedListener}function runtime_getListenerTracking(emitter){let emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking){emitterTracking=new Map;wrappedListeners.set(emitter,emitterTracking)}return emitterTracking}function runtime_trackListener(emitter,event,originalListener,wrappedListener){const emitterTracking=runtime_getListenerTracking(emitter);let eventTracking=emitterTracking.get(event);if(!eventTracking){eventTracking=new Map;emitterTracking.set(event,eventTracking)}let wrappers=eventTracking.get(originalListener);if(!wrappers){wrappers=[];eventTracking.set(originalListener,wrappers)}wrappers.push(wrappedListener)}function runtime_getWrappedListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return void 0;const eventTracking=emitterTracking.get(event);if(!eventTracking)return void 0;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return void 0;return wrappers[wrappers.length-1]}function runtime_untrackListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const wrappedListener=wrappers.pop();wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_untrackSpecificWrapper(emitter,event,originalListener,wrappedListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const idx=wrappers.indexOf(wrappedListener);if(idx===-1)return;wrappers.splice(idx,1);wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_shouldWrapListener(listener){if(typeof listener!=="function")return false;if(listener._slothletOriginal)return false;return true}function runtime_maybeTrackEmitter(emitter){if(isInApiContext&&isInApiContext()){trackedEmitters.add(emitter)}}function runtime_patchOn(){const original=EventEmitter.prototype.on;originalMethods.set("on",original);EventEmitter.prototype.on=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)};EventEmitter.prototype.addListener=EventEmitter.prototype.on}function runtime_patchOnce(){const original=EventEmitter.prototype.once;originalMethods.set("once",original);const originalOn=originalMethods.get("on")??EventEmitter.prototype.on;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.once=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalOn.call(this,event,runtime_onceWrapper)}}function runtime_patchPrependListener(){const original=EventEmitter.prototype.prependListener;originalMethods.set("prependListener",original);EventEmitter.prototype.prependListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)}}function runtime_patchPrependOnceListener(){const original=EventEmitter.prototype.prependOnceListener;originalMethods.set("prependOnceListener",original);const originalPrepend=originalMethods.get("prependListener")??EventEmitter.prototype.prependListener;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.prependOnceListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalPrepend.call(this,event,runtime_onceWrapper)}}function runtime_patchRemoveListener(){const original=EventEmitter.prototype.removeListener;originalMethods.set("removeListener",original);EventEmitter.prototype.removeListener=function(event,listener){const wrapped=runtime_getWrappedListener(this,event,listener);if(wrapped){const result=original.call(this,event,wrapped);runtime_untrackListener(this,event,listener);return result}return original.call(this,event,listener)};EventEmitter.prototype.off=EventEmitter.prototype.removeListener}function runtime_patchRemoveAllListeners(){const original=EventEmitter.prototype.removeAllListeners;originalMethods.set("removeAllListeners",original);EventEmitter.prototype.removeAllListeners=function(event){const emitterTracking=wrappedListeners.get(this);if(emitterTracking){if(event===void 0){for(const[____evt,eventTracking]of emitterTracking.entries()){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}}wrappedListeners.delete(this)}else{const eventTracking=emitterTracking.get(event);if(eventTracking){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}emitterTracking.delete(event);if(emitterTracking.size===0){wrappedListeners.delete(this)}}}}return original.call(this,event)}}function enableEventEmitterPatching(){if(isPatchingEnabled){return}runtime_patchOn();runtime_patchOnce();runtime_patchPrependListener();runtime_patchPrependOnceListener();runtime_patchRemoveListener();runtime_patchRemoveAllListeners();isPatchingEnabled=true}function disableEventEmitterPatching(){if(!isPatchingEnabled){return}for(const[methodName,originalMethod]of originalMethods.entries()){EventEmitter.prototype[methodName]=originalMethod;if(methodName==="on"){EventEmitter.prototype.addListener=originalMethod}else if(methodName==="removeListener"){EventEmitter.prototype.off=originalMethod}}originalMethods.clear();isPatchingEnabled=false}function cleanupEventEmitterResources(){for(const emitter of trackedEmitters){try{emitter.removeAllListeners()}catch(____error){}}trackedEmitters.clear();wrappedListeners.clear()}export{cleanupEventEmitterResources,disableEventEmitterPatching,enableEventEmitterPatching,setApiContextChecker};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2026 CLDMV/Shinrai
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import{promises as fs}from"node:fs";import path from"node:path";import{SlothletError}from"@cldmv/slothlet/errors";import{validateModuleManifest}from"@cldmv/slothlet/helpers/module-manifest-validator";const DEFAULT_MANIFEST_FILE="slothlet.module.json";const UPWARD_WALK_CAP=20;async function discoverModules(options={}){const scanRoots=await resolveScanRoots(options.scanRoot);const manifestSource=parseManifestSource(options.manifest);const fieldSchema=options.schema??{};const filterFn=options.filter;const prefixes=normalizePrefixes(options.prefix);const candidates=[];for(const root of scanRoots){const mode=await detectScanMode(root);if(mode==="npm"){candidates.push(...await enumerateNpmPackages(root,prefixes))}else{candidates.push(...await enumerateFolderModules(root,prefixes))}}const results=[];const seenRealPaths=new Set;const realPathByNameVersion=new Map;for(const candidate of candidates){let realPath;try{realPath=await fs.realpath(candidate.path)}catch{continue}if(seenRealPaths.has(realPath))continue;seenRealPaths.add(realPath);const pkgJsonPath=path.join(realPath,"package.json");const pkg=await readJsonOrNull(pkgJsonPath);if(!pkg||typeof pkg.name!=="string"||typeof pkg.version!=="string"){continue}const manifestPath=path.join(realPath,manifestSource.file);const manifestRaw=await loadManifestRaw(manifestPath,manifestSource,pkg.name);if(manifestRaw===void 0)continue;const remapped=applySchemaRemap(manifestRaw,fieldSchema);if(manifestSource.isOverride&&remapped.schemaVersion===void 0){remapped.schemaVersion=1}const normalized=validateModuleManifest(remapped,{packageName:pkg.name,packageVersion:pkg.version,packageDescription:pkg.description,packageRoot:realPath,manifestPath});if(typeof filterFn==="function"&&!filterFn(normalized,pkg.name)){continue}const nameVersionKey=`${pkg.name}@${pkg.version}`;if(realPathByNameVersion.has(nameVersionKey)){const otherRealPath=realPathByNameVersion.get(nameVersionKey);if(otherRealPath!==realPath){throw new SlothletError("MODULE_DUPLICATE_NAME_VERSION_MISMATCH",{packageName:pkg.name,version:pkg.version,paths:[otherRealPath,realPath].join(", ")},null,{validationError:true})}}else{realPathByNameVersion.set(nameVersionKey,realPath)}const apiDirAbs=path.resolve(realPath,normalized.apiDir);results.push(Object.freeze({packageName:pkg.name,packageRoot:realPath,mountPath:Object.freeze([...normalized.mountPath]),apiDir:apiDirAbs,manifest:deepFreeze(normalized)}))}return results}async function resolveScanRoots(opt){if(opt===void 0){return[await defaultScanRoot()]}if(typeof opt==="string"){return[path.resolve(opt)]}if(Array.isArray(opt)){return opt.map(p=>path.resolve(p))}throw new SlothletError("INVALID_ARGUMENT",{argument:"scanRoot",expected:"string or string[]",received:typeof opt},null,{validationError:true})}async function defaultScanRoot(){let current=process.cwd();for(let i=0;i<UPWARD_WALK_CAP;i++){try{const stat=await fs.stat(path.join(current,"node_modules"));if(stat.isDirectory())return current}catch{}const parent=path.dirname(current);if(parent===current)break;current=parent}return process.cwd()}async function detectScanMode(root){try{const stat=await fs.stat(path.join(root,"node_modules"));if(stat.isDirectory())return"npm"}catch{}return"folder"}async function enumerateNpmPackages(root,prefixes){const nodeModules=path.join(root,"node_modules");const out=[];let entries;try{entries=await fs.readdir(nodeModules,{withFileTypes:true})}catch{return out}for(const entry of entries){if(!entry.isDirectory()&&!entry.isSymbolicLink())continue;if(entry.name.startsWith("."))continue;if(entry.name.startsWith("@")){const scopeDir=path.join(nodeModules,entry.name);let scopedEntries;try{scopedEntries=await fs.readdir(scopeDir,{withFileTypes:true})}catch{continue}for(const scoped of scopedEntries){if(!scoped.isDirectory()&&!scoped.isSymbolicLink())continue;const fullName=`${entry.name}/${scoped.name}`;if(!matchesPrefix(fullName,prefixes))continue;out.push({path:path.join(scopeDir,scoped.name),packageName:fullName})}}else{if(!matchesPrefix(entry.name,prefixes))continue;out.push({path:path.join(nodeModules,entry.name),packageName:entry.name})}}return out}async function enumerateFolderModules(root,prefixes){const out=[];let entries;try{entries=await fs.readdir(root,{withFileTypes:true})}catch{return out}for(const entry of entries){if(!entry.isDirectory()&&!entry.isSymbolicLink())continue;if(entry.name.startsWith("."))continue;if(!matchesPrefix(entry.name,prefixes))continue;out.push({path:path.join(root,entry.name),packageName:entry.name})}return out}function normalizePrefixes(opt){if(opt===void 0)return null;if(typeof opt==="string")return[opt];if(Array.isArray(opt)){if(opt.length===0)return null;return opt.slice()}throw new SlothletError("INVALID_ARGUMENT",{argument:"prefix",expected:"string or string[]",received:typeof opt},null,{validationError:true})}function matchesPrefix(name,prefixes){if(!prefixes)return true;for(const p of prefixes){if(name.startsWith(p))return true}return false}function parseManifestSource(opt){if(opt===void 0){return{file:DEFAULT_MANIFEST_FILE,subkey:null,isOverride:false}}if(typeof opt!=="string"||opt.length===0){throw new SlothletError("INVALID_ARGUMENT",{argument:"manifest",expected:"string",received:typeof opt},null,{validationError:true})}const hashIdx=opt.indexOf("#");if(hashIdx===-1){return{file:opt,subkey:null,isOverride:opt!==DEFAULT_MANIFEST_FILE}}const file=opt.slice(0,hashIdx);const subkey=opt.slice(hashIdx+1);if(file.length===0||subkey.length===0){throw new SlothletError("INVALID_ARGUMENT",{argument:"manifest",expected:"<file>#<dotted.key> with both parts non-empty",received:opt},null,{validationError:true})}return{file,subkey,isOverride:true}}async function readJsonOrNull(filePath){let content;try{content=await fs.readFile(filePath,"utf8")}catch{return null}try{return JSON.parse(content)}catch{return null}}async function loadManifestRaw(manifestPath,source,packageName){let content;try{content=await fs.readFile(manifestPath,"utf8")}catch{return void 0}let parsed;try{parsed=JSON.parse(content)}catch(err){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`JSON parse error: ${err.message}`},err,{validationError:true})}if(source.subkey===null){return parsed}const parts=source.subkey.split(".");let cur=parsed;for(const part of parts){if(cur===null||typeof cur!=="object"||!(part in cur)){return void 0}cur=cur[part]}if(cur===null||typeof cur!=="object"||Array.isArray(cur)){return void 0}return cur}function applySchemaRemap(raw,schemaMap){if(!schemaMap||Object.keys(schemaMap).length===0){return raw}const out={...raw};for(const[canonical,legacy]of Object.entries(schemaMap)){if(legacy===canonical)continue;if(out[canonical]!==void 0)continue;if(legacy in out){out[canonical]=out[legacy];delete out[legacy]}}return out}function deepFreeze(obj){if(obj===null||typeof obj!=="object"||Object.isFrozen(obj))return obj;Object.freeze(obj);for(const key of Object.keys(obj)){const value=obj[key];if(value!==null&&typeof value==="object"){deepFreeze(value)}}return obj}export{discoverModules};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2026 CLDMV/Shinrai
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import path from"node:path";import{SlothletError}from"@cldmv/slothlet/errors";const RESERVED_MOUNTPATH_ROOTS=Object.freeze(new Set(["slothlet","shutdown","destroy"]));const ALLOWED_TOP_LEVEL_FIELDS=Object.freeze(new Set(["schemaVersion","name","version","description","mountPath","apiDir","kind","priority","dependencies","permissions","metadata"]));const PERMISSION_EFFECT_VALUES=Object.freeze(new Set(["allow","deny"]));function validateModuleManifest(manifest,packageContext){if(!manifest||typeof manifest!=="object"||Array.isArray(manifest)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName:packageContext?.packageName??"<unknown>",manifestPath:packageContext?.manifestPath??"<unknown>",reason:"manifest must be a JSON object"},null,{validationError:true})}const{packageName,packageVersion,packageDescription,packageRoot,manifestPath}=packageContext;for(const key of Object.keys(manifest)){if(!ALLOWED_TOP_LEVEL_FIELDS.has(key)){throw new SlothletError("MODULE_MANIFEST_UNKNOWN_FIELD",{packageName,manifestPath,field:key},null,{validationError:true})}}if(manifest.schemaVersion===void 0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"missing required field 'schemaVersion'"},null,{validationError:true})}if(manifest.schemaVersion!==1){throw new SlothletError("MODULE_VERSION_UNSUPPORTED",{packageName,schemaVersion:String(manifest.schemaVersion)},null,{validationError:true})}if(manifest.mountPath===void 0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"missing required field 'mountPath'"},null,{validationError:true})}const mountPathSegments=normalizeMountPath(manifest.mountPath,packageName,manifestPath);if(RESERVED_MOUNTPATH_ROOTS.has(mountPathSegments[0])){throw new SlothletError("MODULE_RESERVED_MOUNTPATH",{packageName,mountPathRoot:mountPathSegments[0],mountPath:mountPathSegments.join(".")},null,{validationError:true})}if(manifest.apiDir===void 0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"missing required field 'apiDir'"},null,{validationError:true})}if(typeof manifest.apiDir!=="string"||manifest.apiDir.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'apiDir' must be a non-empty string"},null,{validationError:true})}validateApiDirContainment(manifest.apiDir,packageRoot,packageName);if(manifest.name!==void 0){if(typeof manifest.name!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'name' must be a string"},null,{validationError:true})}if(manifest.name!==packageName){throw new SlothletError("MODULE_MANIFEST_NAME_MISMATCH",{packageName,manifestName:manifest.name},null,{validationError:true})}}if(manifest.version!==void 0){if(typeof manifest.version!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'version' must be a string"},null,{validationError:true})}if(manifest.version!==packageVersion){throw new SlothletError("MODULE_MANIFEST_VERSION_MISMATCH",{packageName,manifestVersion:manifest.version,packageVersion},null,{validationError:true})}}if(manifest.description!==void 0&&typeof manifest.description!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'description' must be a string"},null,{validationError:true})}if(manifest.kind!==void 0&&typeof manifest.kind!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'kind' must be a string"},null,{validationError:true})}if(manifest.priority!==void 0&&(typeof manifest.priority!=="number"||!Number.isFinite(manifest.priority))){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'priority' must be a finite number"},null,{validationError:true})}if(manifest.dependencies!==void 0){if(typeof manifest.dependencies!=="object"||manifest.dependencies===null||Array.isArray(manifest.dependencies)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'dependencies' must be a plain object"},null,{validationError:true})}for(const[depName,depValue]of Object.entries(manifest.dependencies)){if(typeof depValue!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`dependency '${depName}' must be a string version range`},null,{validationError:true})}}}if(manifest.permissions!==void 0){validatePermissions(manifest.permissions,packageName,manifestPath)}if(manifest.metadata!==void 0){if(typeof manifest.metadata!=="object"||manifest.metadata===null||Array.isArray(manifest.metadata)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'metadata' must be a plain object"},null,{validationError:true})}}return{schemaVersion:1,name:packageName,version:packageVersion,description:manifest.description??packageDescription,mountPath:mountPathSegments,apiDir:manifest.apiDir,kind:manifest.kind,priority:manifest.priority??0,dependencies:manifest.dependencies,permissions:manifest.permissions,metadata:manifest.metadata}}function normalizeMountPath(mountPath,packageName,manifestPath){if(typeof mountPath==="string"){if(mountPath.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' must be a non-empty string or non-empty array of non-empty strings"},null,{validationError:true})}return mountPath.split(".")}if(Array.isArray(mountPath)){if(mountPath.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' must be a non-empty string or non-empty array of non-empty strings"},null,{validationError:true})}for(const segment of mountPath){if(typeof segment!=="string"||segment.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' array entries must all be non-empty strings"},null,{validationError:true})}}return mountPath.slice()}throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' must be a non-empty string or non-empty array of non-empty strings"},null,{validationError:true})}function validateApiDirContainment(apiDir,packageRoot,packageName){const resolved=path.resolve(packageRoot,apiDir);const rootWithSep=packageRoot.endsWith(path.sep)?packageRoot:packageRoot+path.sep;if(resolved!==packageRoot&&!resolved.startsWith(rootWithSep)){throw new SlothletError("MODULE_PATH_TRAVERSAL",{packageName,apiDir,resolvedPath:resolved,packageRoot},null,{validationError:true})}}function validatePermissions(permissions,packageName,manifestPath){if(!Array.isArray(permissions)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'permissions' must be an array of rule objects"},null,{validationError:true})}for(let i=0;i<permissions.length;i++){const rule=permissions[i];if(!rule||typeof rule!=="object"||Array.isArray(rule)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}] must be a rule object`},null,{validationError:true})}if(typeof rule.caller!=="string"||rule.caller.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}].caller must be a non-empty string`},null,{validationError:true})}if(typeof rule.target!=="string"||rule.target.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}].target must be a non-empty string`},null,{validationError:true})}if(!PERMISSION_EFFECT_VALUES.has(rule.effect)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}].effect must be "allow" or "deny"`},null,{validationError:true})}}}export{validateModuleManifest};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright 2026 CLDMV/Shinrai
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
function sortModules(results,comparator){const cmp=typeof comparator==="function"?comparator:defaultModuleComparator;return[...results].sort(cmp)}function defaultModuleComparator(a,b){const pa=typeof a?.manifest?.priority==="number"?a.manifest.priority:0;const pb=typeof b?.manifest?.priority==="number"?b.manifest.priority:0;if(pa!==pb)return pb-pa;const na=a?.packageName??"";const nb=b?.packageName??"";if(na<nb)return-1;if(na>nb)return 1;return 0}export{sortModules};
|
|
@@ -405,7 +405,29 @@
|
|
|
405
405
|
"PERM_RULE_CONDITION_INVALID": "rule.condition muss ein einfaches Objekt, eine Funktion oder ein Array sein, bei dem jeder Eintrag ein einfaches Objekt oder eine Funktion ist",
|
|
406
406
|
"BRACE_EXPANSION_MAX_DEPTH": "Klammerauflösung hat die maximale Tiefe von {maxDepth} überschritten",
|
|
407
407
|
"HINT_BRACE_EXPANSION_MAX_DEPTH": "Verringern Sie die Verschachtelung in Ihren Klammermustern oder erhöhen Sie die maxDepth-Option.",
|
|
408
|
-
"PERMISSION_MANAGER_NOT_AVAILABLE": "Berechtigungsmanager ist nicht in dieser Slothlet-Instanz verfügbar"
|
|
408
|
+
"PERMISSION_MANAGER_NOT_AVAILABLE": "Berechtigungsmanager ist nicht in dieser Slothlet-Instanz verfügbar",
|
|
409
|
+
"MODULE_MANIFEST_NOT_FOUND": "Modul-Manifest nicht gefunden für Paket '{packageName}': '{manifestPath}' erwartet, aber die Datei existiert nicht.",
|
|
410
|
+
"HINT_MODULE_MANIFEST_NOT_FOUND": "Plugin-Module müssen eine 'slothlet.module.json' im Paketwurzelverzeichnis ausliefern (oder die über die `manifest`-Überschreibung angegebene Datei/Schlüssel). Überprüfen Sie, ob die Datei im Paket existiert und der Override-Locator korrekt ist.",
|
|
411
|
+
"MODULE_MANIFEST_INVALID": "Modul-Manifest ist ungültig für Paket '{packageName}' unter '{manifestPath}': {reason}.",
|
|
412
|
+
"HINT_MODULE_MANIFEST_INVALID": "Öffnen Sie das Manifest und stellen Sie sicher, dass es gültiges JSON ist und dem Slothlet-Modul-Schema entspricht (siehe schemas/slothlet.module.schema.json). Erforderliche Felder: schemaVersion, mountPath, apiDir.",
|
|
413
|
+
"MODULE_MANIFEST_UNKNOWN_FIELD": "Modul-Manifest für Paket '{packageName}' enthält nicht erkanntes Feld auf oberster Ebene '{field}'. Unbekannte Felder werden abgelehnt; verwenden Sie den dedizierten 'metadata'-Block für entwicklerdefinierte Zusätze.",
|
|
414
|
+
"HINT_MODULE_MANIFEST_UNKNOWN_FIELD": "Wenn '{field}' ein Tippfehler ist, korrigieren Sie ihn. Wenn es sich um beabsichtigte Entwicklermetadaten handelt, verschieben Sie sie in das 'metadata'-Objekt.",
|
|
415
|
+
"MODULE_MANIFEST_NAME_MISMATCH": "Modul-Manifest für Paket '{packageName}' deklariert Namen '{manifestName}', der nicht mit dem Namen in package.json '{packageName}' übereinstimmt.",
|
|
416
|
+
"HINT_MODULE_MANIFEST_NAME_MISMATCH": "Das 'name'-Feld in slothlet.module.json ist optional, muss aber mit package.json übereinstimmen, wenn vorhanden. Entfernen Sie entweder das 'name'-Feld im Manifest oder gleichen Sie es mit package.json ab.",
|
|
417
|
+
"MODULE_MANIFEST_VERSION_MISMATCH": "Modul-Manifest für Paket '{packageName}' deklariert Version '{manifestVersion}', die nicht mit der Version in package.json '{packageVersion}' übereinstimmt.",
|
|
418
|
+
"HINT_MODULE_MANIFEST_VERSION_MISMATCH": "Das 'version'-Feld in slothlet.module.json ist optional, muss aber mit package.json übereinstimmen, wenn vorhanden. Entfernen Sie entweder das 'version'-Feld im Manifest oder gleichen Sie es mit package.json ab.",
|
|
419
|
+
"MODULE_PATH_TRAVERSAL": "Modul-Paket '{packageName}' hat apiDir '{apiDir}', das außerhalb des Paketwurzelverzeichnisses aufgelöst wird ('{resolvedPath}' liegt nicht unter '{packageRoot}').",
|
|
420
|
+
"HINT_MODULE_PATH_TRAVERSAL": "apiDir muss ein relativer Pfad sein, der innerhalb des Pakets bleibt. Entfernen Sie '..'-Segmente und absolute Pfade.",
|
|
421
|
+
"MODULE_VERSION_UNSUPPORTED": "Modul-Manifest für Paket '{packageName}' verwendet nicht unterstützte schemaVersion '{schemaVersion}'. Unterstützt: 1.",
|
|
422
|
+
"HINT_MODULE_VERSION_UNSUPPORTED": "Aktualisieren Sie slothlet auf eine Version, die schemaVersion {schemaVersion} unterstützt, oder aktualisieren Sie das Manifest auf schemaVersion 1.",
|
|
423
|
+
"MODULE_PACKAGE_NOT_FOUND": "Modul-Paket '{packageName}' wurde nicht im Discovery-Cache gefunden. {hint}",
|
|
424
|
+
"HINT_MODULE_PACKAGE_NOT_FOUND": "Entweder ist das Paket nicht installiert, der scanRoot deckt seinen Speicherort nicht ab, oder es wurde noch kein discover()-Aufruf durchgeführt. addModule(name) ruft discover() lazy mit scanRoot=process.cwd() auf, wenn der Cache leer ist.",
|
|
425
|
+
"MODULE_RESERVED_MOUNTPATH": "Modul-Paket '{packageName}' deklariert reservierte mountPath-Wurzel '{mountPathRoot}' (aus mountPath '{mountPath}'). Reservierte Wurzeln: slothlet, shutdown, destroy.",
|
|
426
|
+
"HINT_MODULE_RESERVED_MOUNTPATH": "Reservierte mountPath-Wurzeln werden von der integrierten Oberfläche von slothlet verwendet und können nicht von Modulen beansprucht werden. Wählen Sie ein anderes Wurzelsegment.",
|
|
427
|
+
"MODULE_DUPLICATE_NAME_VERSION_MISMATCH": "Modul-Paket '{packageName}' Version '{version}' wurde an mehreren verschiedenen tatsächlichen Pfaden gefunden: {paths}.",
|
|
428
|
+
"HINT_MODULE_DUPLICATE_NAME_VERSION_MISMATCH": "Dies ist mit ziemlicher Sicherheit eine Fehlkonfiguration — dasselbe Paket in derselben Version, das an zwei nicht verwandten Orten installiert ist. Untersuchen Sie, welche Installation gewünscht ist, und entfernen Sie die andere.",
|
|
429
|
+
"MODULE_MOUNT_COLLISION": "Modul-Paket '{packageName}' kann nicht unter '{mountPath}' eingebunden werden: Pfad ist bereits von Modul '{existingModuleID}' belegt und collisionMode ist '{collisionMode}'.",
|
|
430
|
+
"HINT_MODULE_MOUNT_COLLISION": "Ändern Sie entweder den mountPath des Manifests, übergeben Sie `collisionMode: \"merge\"` an `addModule()` / `addModules()` um Koexistenz zu erlauben, oder entfernen Sie zuerst das bestehende Modul mit `removeModule()`."
|
|
409
431
|
},
|
|
410
432
|
"metadata": {
|
|
411
433
|
"code": "de-de",
|
|
@@ -405,7 +405,29 @@
|
|
|
405
405
|
"PERM_RULE_CONDITION_INVALID": "rule.condition must be a plain object, a function, or an array where each entry is a plain object or function",
|
|
406
406
|
"BRACE_EXPANSION_MAX_DEPTH": "Brace expansion exceeded maximum depth of {maxDepth}",
|
|
407
407
|
"HINT_BRACE_EXPANSION_MAX_DEPTH": "Reduce nesting in your brace patterns or increase the maxDepth option.",
|
|
408
|
-
"PERMISSION_MANAGER_NOT_AVAILABLE": "Permission manager is not available in this Slothlet instance"
|
|
408
|
+
"PERMISSION_MANAGER_NOT_AVAILABLE": "Permission manager is not available in this Slothlet instance",
|
|
409
|
+
"MODULE_MANIFEST_NOT_FOUND": "Module manifest not found for package '{packageName}': expected '{manifestPath}' but the file does not exist.",
|
|
410
|
+
"HINT_MODULE_MANIFEST_NOT_FOUND": "Plugin modules must ship a 'slothlet.module.json' at the package root (or the file/key specified via the `manifest` override). Check that the file exists in the package and that the override locator is correct.",
|
|
411
|
+
"MODULE_MANIFEST_INVALID": "Module manifest is invalid for package '{packageName}' at '{manifestPath}': {reason}.",
|
|
412
|
+
"HINT_MODULE_MANIFEST_INVALID": "Open the manifest and ensure it is valid JSON and matches the slothlet module schema (see schemas/slothlet.module.schema.json). Required fields: schemaVersion, mountPath, apiDir.",
|
|
413
|
+
"MODULE_MANIFEST_UNKNOWN_FIELD": "Module manifest for package '{packageName}' contains unrecognised top-level field '{field}'. Unknown fields are rejected; use the dedicated 'metadata' block for developer-defined extras.",
|
|
414
|
+
"HINT_MODULE_MANIFEST_UNKNOWN_FIELD": "If '{field}' is a typo, fix it. If it is intentional developer metadata, move it inside the 'metadata' object.",
|
|
415
|
+
"MODULE_MANIFEST_NAME_MISMATCH": "Module manifest for package '{packageName}' declares name '{manifestName}' which does not match package.json name '{packageName}'.",
|
|
416
|
+
"HINT_MODULE_MANIFEST_NAME_MISMATCH": "The 'name' field in slothlet.module.json is optional but must match package.json when present. Either remove the manifest 'name' field or align it with package.json.",
|
|
417
|
+
"MODULE_MANIFEST_VERSION_MISMATCH": "Module manifest for package '{packageName}' declares version '{manifestVersion}' which does not match package.json version '{packageVersion}'.",
|
|
418
|
+
"HINT_MODULE_MANIFEST_VERSION_MISMATCH": "The 'version' field in slothlet.module.json is optional but must match package.json when present. Either remove the manifest 'version' field or align it with package.json.",
|
|
419
|
+
"MODULE_PATH_TRAVERSAL": "Module package '{packageName}' has apiDir '{apiDir}' that resolves outside the package root ('{resolvedPath}' is not under '{packageRoot}').",
|
|
420
|
+
"HINT_MODULE_PATH_TRAVERSAL": "apiDir must be a relative path that stays inside the package. Remove '..' segments and absolute paths.",
|
|
421
|
+
"MODULE_VERSION_UNSUPPORTED": "Module manifest for package '{packageName}' uses unsupported schemaVersion '{schemaVersion}'. Supported: 1.",
|
|
422
|
+
"HINT_MODULE_VERSION_UNSUPPORTED": "Upgrade slothlet to a version that supports schemaVersion {schemaVersion}, or update the manifest to use schemaVersion 1.",
|
|
423
|
+
"MODULE_PACKAGE_NOT_FOUND": "Module package '{packageName}' was not found in the discovery cache. {hint}",
|
|
424
|
+
"HINT_MODULE_PACKAGE_NOT_FOUND": "Either the package is not installed, the scanRoot does not cover its location, or no discover() call has been made yet. addModule(name) will lazily run discover() with scanRoot=process.cwd() if the cache is empty.",
|
|
425
|
+
"MODULE_RESERVED_MOUNTPATH": "Module package '{packageName}' declares reserved mountPath root '{mountPathRoot}' (from mountPath '{mountPath}'). Reserved roots: slothlet, shutdown, destroy.",
|
|
426
|
+
"HINT_MODULE_RESERVED_MOUNTPATH": "Reserved mountPath roots are used by slothlet's built-in surface and cannot be claimed by modules. Choose a different root segment.",
|
|
427
|
+
"MODULE_DUPLICATE_NAME_VERSION_MISMATCH": "Module package '{packageName}' version '{version}' was found at multiple distinct real paths: {paths}.",
|
|
428
|
+
"HINT_MODULE_DUPLICATE_NAME_VERSION_MISMATCH": "This is almost certainly a misconfiguration — the same package at the same version installed in two unrelated locations. Investigate which install is intended and remove the other.",
|
|
429
|
+
"MODULE_MOUNT_COLLISION": "Module package '{packageName}' cannot mount at '{mountPath}': path is already occupied by module '{existingModuleID}' and collisionMode is '{collisionMode}'.",
|
|
430
|
+
"HINT_MODULE_MOUNT_COLLISION": "Either change the manifest's mountPath, pass `collisionMode: \"merge\"` to `addModule()` / `addModules()` to allow coexistence, or call `removeModule()` on the existing module first."
|
|
409
431
|
},
|
|
410
432
|
"metadata": {
|
|
411
433
|
"code": "en-gb",
|