@cldmv/slothlet 3.15.3 → 3.16.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 +7 -5
- package/dist/lib/builders/api-assignment.mjs +1 -1
- package/dist/lib/builders/api_builder.mjs +1 -1
- package/dist/lib/builders/builder.mjs +1 -1
- package/dist/lib/builders/modes-processor.mjs +1 -1
- package/dist/lib/handlers/api-cache-manager.mjs +1 -1
- package/dist/lib/handlers/api-manager.mjs +1 -1
- package/dist/lib/handlers/module-manager.mjs +1 -1
- package/dist/lib/handlers/ownership.mjs +1 -1
- package/dist/lib/handlers/routine-manager.mjs +17 -0
- package/dist/lib/handlers/unified-wrapper.mjs +1 -1
- package/dist/lib/helpers/config.mjs +1 -1
- package/dist/lib/helpers/defaults.mjs +1 -1
- package/dist/lib/helpers/eventtarget-property-context.mjs +17 -0
- package/dist/lib/helpers/observer-context.mjs +17 -0
- package/dist/lib/helpers/scheduler-context.mjs +1 -1
- package/dist/lib/i18n/languages/en-us.json +2 -0
- package/dist/lib/modes/eager.mjs +1 -1
- package/dist/lib/processors/flatten.mjs +1 -1
- package/dist/slothlet.mjs +1 -1
- package/index.cjs +20 -0
- package/index.mjs +14 -0
- package/package.json +8 -7
- package/types/stub/devcheck.d.mts +1 -1
- package/types/stub/lib/builders/api-assignment.d.mts +130 -2
- package/types/stub/lib/builders/api_builder.d.mts +109 -2
- package/types/stub/lib/builders/builder.d.mts +87 -2
- package/types/stub/lib/builders/modes-processor.d.mts +71 -2
- package/types/stub/lib/factories/component-base.d.mts +177 -0
- package/types/stub/lib/helpers/caller-pinning.d.mts +22 -2
- package/types/stub/lib/helpers/class-instance-wrapper.d.mts +58 -2
- package/types/stub/lib/helpers/config.d.mts +321 -2
- package/types/stub/lib/helpers/defaults.d.mts +41 -2
- package/types/stub/lib/helpers/eventemitter-context.d.mts +31 -2
- package/types/stub/lib/helpers/eventtarget-context.d.mts +21 -2
- package/types/stub/lib/helpers/eventtarget-property-context.d.mts +23 -0
- package/types/stub/lib/helpers/generate-manifest.d.mts +180 -2
- package/types/stub/lib/helpers/hint-detector.d.mts +27 -2
- package/types/stub/lib/helpers/manifest-resolver.d.mts +101 -2
- package/types/stub/lib/helpers/modes-utils.d.mts +35 -2
- package/types/stub/lib/helpers/module-discovery.d.mts +81 -2
- package/types/stub/lib/helpers/module-manifest-validator.d.mts +37 -2
- package/types/stub/lib/helpers/module-sort.d.mts +65 -2
- package/types/stub/lib/helpers/observer-context.d.mts +23 -0
- package/types/stub/lib/helpers/pattern-matcher.d.mts +44 -2
- package/types/stub/lib/helpers/platform.d.mts +111 -2
- package/types/stub/lib/helpers/resolve-from-caller.d.mts +33 -2
- package/types/stub/lib/helpers/scheduler-context.d.mts +23 -2
- package/types/stub/lib/helpers/utilities.d.mts +57 -2
- package/types/stub/lib/i18n/translations.d.mts +52 -2
- package/types/stub/lib/modes/eager.d.mts +56 -2
- package/types/stub/lib/modes/lazy.d.mts +67 -2
- package/types/stub/lib/processors/flatten.d.mts +123 -2
- package/types/stub/lib/processors/loader.d.mts +83 -2
- package/types/stub/lib/processors/type-generator.d.mts +19 -2
- package/types/stub/lib/processors/typescript.d.mts +174 -2
- package/types/stub/lib/runtime/runtime-asynclocalstorage.d.mts +72 -2
- package/types/stub/lib/runtime/runtime-livebindings.d.mts +38 -2
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{ComponentBase}from"#factories/component-base";import{SlothletError}from"@cldmv/slothlet/errors";import{isNode as IS_NODE}from"@cldmv/slothlet/helpers/platform";import{DEFAULT_API_DEPTH}from"@cldmv/slothlet/helpers/defaults";function normalizeHookConfig(hook){const hookConfig={enabled:false,pattern:"**",suppressErrors:false,pin:true};if(hook===true||hook===false){hookConfig.enabled=hook;hookConfig.pattern=hook?"**":null}else if(typeof hook==="string"){hookConfig.enabled=true;hookConfig.pattern=hook}else if(hook&&typeof hook==="object"){hookConfig.enabled=hook.enabled!==false;hookConfig.pattern=hook.pattern||"**";hookConfig.suppressErrors=hook.suppressErrors||false;hookConfig.pin=hook.pin!==false}return hookConfig}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}}normalizeEnvTarget(platform,hasManifest=false){if(platform==="browser")return"browser";if(platform==="node")return"node";if(hasManifest)return"browser";return IS_NODE?"node":"browser"}normalizeHook(hook){return normalizeHookConfig(hook)}transformConfig(config={}){const hasManifest=config.manifest!=null;const envTarget=this.normalizeEnvTarget(config.platform,hasManifest);const rawBase=config.base??config.dir;if(config.dir!==void 0&&config.base===void 0&&!config.silent){new this.SlothletWarning("V3_CONFIG_DEPRECATED",{option:"dir",replacement:"base"})}if(!rawBase){throw new this.SlothletError("INVALID_CONFIG_DIR_MISSING",{},null,{validationError:true})}if(envTarget==="browser"){if(!config.manifest||typeof config.manifest!=="object"||Array.isArray(config.manifest)){throw new this.SlothletError("INVALID_CONFIG_BROWSER_REQUIRES_MANIFEST",{},null,{validationError:true})}if(!Array.isArray(config.manifest.files)||!Array.isArray(config.manifest.directories)){throw new this.SlothletError("INVALID_CONFIG_BROWSER_MANIFEST_INVALID",{received:typeof config.manifest},null,{validationError:true})}if(config.resolveModuleSpecifier!==void 0&&config.resolveModuleSpecifier!==null&&typeof config.resolveModuleSpecifier!=="function"){throw new this.SlothletError("INVALID_CONFIG_BROWSER_RESOLVE_SPECIFIER_INVALID",{received:typeof config.resolveModuleSpecifier},null,{validationError:true})}}const resolvedDir=envTarget==="browser"?rawBase:this.slothlet.helpers.resolver.resolvePathFromCaller(rawBase);let mutations=null;if(config.allowMutation===false){mutations={add:false,remove:false,reload:false};if(!config.silent){new this.SlothletWarning("V3_CONFIG_DEPRECATED",{option:"allowMutation",replacement:"api.mutations: { add: false, remove: false, reload: false }"})}}let collision=null;if(config.collision&&!config.api?.collision){collision=this.normalizeCollision(config.collision);if(!config.silent){new this.SlothletWarning("V3_CONFIG_DEPRECATED",{option:"collision",replacement:"api.collision"})}}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})}}const hookConfig=this.normalizeHook(config.hook);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.import!==void 0&&config.import!==null&&typeof config.import!=="function"){throw new this.SlothletError("INVALID_CONFIG_IMPORT",{received:typeof config.import,validationError: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);const suppressFixes=this.normalizeSuppressFixes(config.suppressFixes,config.silent);let i18nConfig=null;if(config.i18n&&typeof config.i18n==="object"){i18nConfig={language:typeof config.i18n.language==="string"?config.i18n.language:void 0}}const lifecycleConfig=this.normalizeLifecycle(config.lifecycle);return{...config,base:resolvedDir,dir:resolvedDir,manifest:config.manifest??null,resolveModuleSpecifier:config.resolveModuleSpecifier??null,envTarget,mode:this.normalizeMode(config.mode),runtime:this.normalizeRuntime(config.runtime),apiDepth:config.apiDepth!==void 0?config.apiDepth:DEFAULT_API_DEPTH,reference:config.reference||null,context:config.context||null,i18n:i18nConfig,lifecycle:lifecycleConfig,debug:this.normalizeDebug(config.debug),diagnostics:config.diagnostics===true,collectLifecycleHooks:config.collectLifecycleHooks===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,import:config.import??null,permissions:permissionsConfig,suppressFixes}}normalizeSuppressFixes(suppressFixes,silent){const KNOWN_FIX_IDS=new Set(["C03_116"]);const REPO_PR_BASE="https://github.com/CLDMV/slothlet/pull/";if(!Array.isArray(suppressFixes)||suppressFixes.length===0){return new Set}const result=new Set;for(const rule of suppressFixes){if(typeof rule!=="string"||!KNOWN_FIX_IDS.has(rule)){continue}result.add(rule);if(!silent){const prNumber=rule.split("_").pop();const url=`${REPO_PR_BASE}${prNumber}`;new this.SlothletWarning("WARN_SUPPRESS_FIX_ACTIVE",{rule,url})}}return result}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}normalizeLifecycle(lifecycle){if(lifecycle===void 0||lifecycle===null){return null}if(typeof lifecycle!=="object"||Array.isArray(lifecycle)){throw new this.SlothletError("INVALID_CONFIG",{option:"lifecycle",value:Array.isArray(lifecycle)?"array":typeof lifecycle,expected:"a plain object mapping event names to functions or arrays of functions",hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}const lifecycleProto=Object.getPrototypeOf(lifecycle);if(lifecycleProto!==null&&lifecycleProto!==Object.prototype){throw new this.SlothletError("INVALID_CONFIG",{option:"lifecycle",value:lifecycle?.constructor?.name?`${lifecycle.constructor.name} instance`:"non-plain object",expected:"a plain object mapping event names to functions or arrays of functions",hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}for(const[event,handler]of Object.entries(lifecycle)){const handlers=Array.isArray(handler)?handler:[handler];for(const fn of handlers){if(typeof fn!=="function"){throw new this.SlothletError("INVALID_CONFIG",{option:`lifecycle["${event}"]`,value:typeof fn,expected:"a function or an array of functions",hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}}}return lifecycle}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})}let failOpenOnAbsentCaller;if(permissions.failOpenOnAbsentCaller===true){failOpenOnAbsentCaller=true}else if(permissions.failOpenOnAbsentCaller===false||permissions.failOpenOnAbsentCaller===void 0){failOpenOnAbsentCaller=false}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.failOpenOnAbsentCaller",value:permissions.failOpenOnAbsentCaller,expected:"boolean",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}if(permissions.references!==void 0&&(typeof permissions.references!=="object"||permissions.references===null||Array.isArray(permissions.references))){throw new SlothletError("INVALID_CONFIG",{option:"permissions.references",value:permissions.references,expected:"object",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}let capture;if(permissions.references?.capture===false){capture=false}else if(permissions.references?.capture===true||permissions.references?.capture===void 0){capture=true}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.references.capture",value:permissions.references.capture,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:[];if(permissions.private!==void 0&&(typeof permissions.private!=="object"||permissions.private===null||Array.isArray(permissions.private))){throw new SlothletError("INVALID_CONFIG",{option:"permissions.private",value:permissions.private,expected:"object",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}let privateHost;if(permissions.private?.host==="allow"){privateHost="allow"}else if(permissions.private?.host==="deny"||permissions.private?.host===void 0){privateHost="deny"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.private.host",value:permissions.private.host,expected:'"deny" or "allow"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}return{defaultPolicy,enabled,audit,readGating,failOpenOnAbsentCaller,references:{capture},private:{host:privateHost},rules}}}export{Config,normalizeHookConfig};
|
|
17
|
+
import{ComponentBase}from"#factories/component-base";import{SlothletError}from"@cldmv/slothlet/errors";import{isNode as IS_NODE}from"@cldmv/slothlet/helpers/platform";import{DEFAULT_API_DEPTH,DEFAULT_ROUTINES}from"@cldmv/slothlet/helpers/defaults";import{compilePattern}from"@cldmv/slothlet/helpers/pattern-matcher";const VALID_ROUTINE_MODES=new Set(["manual","startup","shutdown","destroy"]);const VALID_ROUTINE_ORDERS=new Set(["mount","depth"]);const DEFAULT_ROUTINE_ORDER_BY_MODE=Object.freeze({startup:"mount",shutdown:"depth",destroy:"depth",manual:"mount"});const COLLECT_LIFECYCLE_HOOKS_IMPLICIT_ROUTINES=Object.freeze([Object.freeze({name:"^**.shutdown",mode:"shutdown",order:"depth"}),Object.freeze({name:"^**.destroy",mode:"destroy",order:"depth"})]);const ROUTINE_NAME_RESERVED=new Set(["slothlet","__proto__","constructor","prototype"]);function normalizeHookConfig(hook){const hookConfig={enabled:false,pattern:"**",suppressErrors:false,pin:true};if(hook===true||hook===false){hookConfig.enabled=hook;hookConfig.pattern=hook?"**":null}else if(typeof hook==="string"){hookConfig.enabled=true;hookConfig.pattern=hook}else if(hook&&typeof hook==="object"){hookConfig.enabled=hook.enabled!==false;hookConfig.pattern=hook.pattern||"**";hookConfig.suppressErrors=hook.suppressErrors||false;hookConfig.pin=hook.pin!==false}return hookConfig}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}}normalizeEnvTarget(platform,hasManifest=false){if(platform==="browser")return"browser";if(platform==="node")return"node";if(hasManifest)return"browser";return IS_NODE?"node":"browser"}normalizeHook(hook){return normalizeHookConfig(hook)}transformConfig(config={}){const hasManifest=config.manifest!=null;const envTarget=this.normalizeEnvTarget(config.platform,hasManifest);const rawBase=config.base??config.dir;if(config.dir!==void 0&&config.base===void 0&&!config.silent){new this.SlothletWarning("V3_CONFIG_DEPRECATED",{option:"dir",replacement:"base"})}if(!rawBase){throw new this.SlothletError("INVALID_CONFIG_DIR_MISSING",{},null,{validationError:true})}if(envTarget==="browser"){if(!config.manifest||typeof config.manifest!=="object"||Array.isArray(config.manifest)){throw new this.SlothletError("INVALID_CONFIG_BROWSER_REQUIRES_MANIFEST",{},null,{validationError:true})}if(!Array.isArray(config.manifest.files)||!Array.isArray(config.manifest.directories)){throw new this.SlothletError("INVALID_CONFIG_BROWSER_MANIFEST_INVALID",{received:typeof config.manifest},null,{validationError:true})}if(config.resolveModuleSpecifier!==void 0&&config.resolveModuleSpecifier!==null&&typeof config.resolveModuleSpecifier!=="function"){throw new this.SlothletError("INVALID_CONFIG_BROWSER_RESOLVE_SPECIFIER_INVALID",{received:typeof config.resolveModuleSpecifier},null,{validationError:true})}}const resolvedDir=envTarget==="browser"?rawBase:this.slothlet.helpers.resolver.resolvePathFromCaller(rawBase);let mutations=null;if(config.allowMutation===false){mutations={add:false,remove:false,reload:false};if(!config.silent){new this.SlothletWarning("V3_CONFIG_DEPRECATED",{option:"allowMutation",replacement:"api.mutations: { add: false, remove: false, reload: false }"})}}let collision=null;if(config.collision&&!config.api?.collision){collision=this.normalizeCollision(config.collision);if(!config.silent){new this.SlothletWarning("V3_CONFIG_DEPRECATED",{option:"collision",replacement:"api.collision"})}}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})}}const hookConfig=this.normalizeHook(config.hook);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.import!==void 0&&config.import!==null&&typeof config.import!=="function"){throw new this.SlothletError("INVALID_CONFIG_IMPORT",{received:typeof config.import,validationError: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);const suppressFixes=this.normalizeSuppressFixes(config.suppressFixes,config.silent);let i18nConfig=null;if(config.i18n&&typeof config.i18n==="object"){i18nConfig={language:typeof config.i18n.language==="string"?config.i18n.language:void 0}}const lifecycleConfig=this.normalizeLifecycle(config.lifecycle);if(config.collectLifecycleHooks!==void 0&&config.autoRoutines===void 0&&!config.silent){new this.SlothletWarning("V3_CONFIG_DEPRECATED",{option:"collectLifecycleHooks",replacement:"autoRoutines"})}const autoRoutines=config.autoRoutines!==void 0?config.autoRoutines===true:config.collectLifecycleHooks===true;const normalizedRoutines=this.normalizeRoutines(config.routines);const routines=config.collectLifecycleHooks===true?[...normalizedRoutines.filter(routine=>routine.mode!=="shutdown"&&routine.mode!=="destroy"),...COLLECT_LIFECYCLE_HOOKS_IMPLICIT_ROUTINES.filter(implicit=>!normalizedRoutines.some(routine=>routine.name===implicit.name)).map(implicit=>({...implicit,recursive:false}))]:normalizedRoutines;return{...config,base:resolvedDir,dir:resolvedDir,manifest:config.manifest??null,resolveModuleSpecifier:config.resolveModuleSpecifier??null,envTarget,mode:this.normalizeMode(config.mode),runtime:this.normalizeRuntime(config.runtime),apiDepth:config.apiDepth!==void 0?config.apiDepth:DEFAULT_API_DEPTH,reference:config.reference||null,context:config.context||null,i18n:i18nConfig,lifecycle:lifecycleConfig,routines,debug:this.normalizeDebug(config.debug),diagnostics:config.diagnostics===true,collectLifecycleHooks:config.collectLifecycleHooks===true,autoRoutines,stackRoutines:config.stackRoutines===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,import:config.import??null,permissions:permissionsConfig,suppressFixes}}normalizeSuppressFixes(suppressFixes,silent){const KNOWN_FIX_IDS=new Set(["C03_116"]);const REPO_PR_BASE="https://github.com/CLDMV/slothlet/pull/";if(!Array.isArray(suppressFixes)||suppressFixes.length===0){return new Set}const result=new Set;for(const rule of suppressFixes){if(typeof rule!=="string"||!KNOWN_FIX_IDS.has(rule)){continue}result.add(rule);if(!silent){const prNumber=rule.split("_").pop();const url=`${REPO_PR_BASE}${prNumber}`;new this.SlothletWarning("WARN_SUPPRESS_FIX_ACTIVE",{rule,url})}}return result}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}normalizeLifecycle(lifecycle){if(lifecycle===void 0||lifecycle===null){return null}if(typeof lifecycle!=="object"||Array.isArray(lifecycle)){throw new this.SlothletError("INVALID_CONFIG",{option:"lifecycle",value:Array.isArray(lifecycle)?"array":typeof lifecycle,expected:"a plain object mapping event names to functions or arrays of functions",hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}const lifecycleProto=Object.getPrototypeOf(lifecycle);if(lifecycleProto!==null&&lifecycleProto!==Object.prototype){throw new this.SlothletError("INVALID_CONFIG",{option:"lifecycle",value:lifecycle?.constructor?.name?`${lifecycle.constructor.name} instance`:"non-plain object",expected:"a plain object mapping event names to functions or arrays of functions",hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}for(const[event,handler]of Object.entries(lifecycle)){const handlers=Array.isArray(handler)?handler:[handler];for(const fn of handlers){if(typeof fn!=="function"){throw new this.SlothletError("INVALID_CONFIG",{option:`lifecycle["${event}"]`,value:typeof fn,expected:"a function or an array of functions",hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}}}return lifecycle}normalizeRoutines(routines){if(routines===void 0){return DEFAULT_ROUTINES.map(entry=>({name:entry.name,mode:entry.mode,recursive:entry.recursive??false,order:entry.order??DEFAULT_ROUTINE_ORDER_BY_MODE[entry.mode]}))}if(routines===null){return[]}if(!Array.isArray(routines)){throw new this.SlothletError("INVALID_CONFIG",{option:"routines",value:typeof routines,expected:'an array of routine names/objects, e.g. ["initialize", "shutdown:shutdown", { name: "warmup" }]',hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}return routines.map((entry,index)=>{let name;let mode;if(typeof entry==="string"){const sepIndex=entry.indexOf(":");if(sepIndex===-1){name=entry;mode="manual"}else{name=entry.slice(0,sepIndex);mode=entry.slice(sepIndex+1)}}else if(entry&&typeof entry==="object"&&!Array.isArray(entry)){name=entry.name;mode=entry.mode??"manual"}else{throw new this.SlothletError("INVALID_CONFIG",{option:`routines[${index}]`,value:Array.isArray(entry)?"array":typeof entry,expected:'a string ("name" or "name:mode") or an object ({ name, mode? })',hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}if(typeof name!=="string"||name.length===0){throw new this.SlothletError("INVALID_CONFIG",{option:`routines[${index}].name`,value:typeof name,expected:"a non-empty string",hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}if(ROUTINE_NAME_RESERVED.has(name)){throw new this.SlothletError("INVALID_CONFIG",{option:`routines[${index}].name`,value:name,expected:`a name other than the reserved: ${[...ROUTINE_NAME_RESERVED].join(", ")}`,hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}if(!VALID_ROUTINE_MODES.has(mode)){throw new this.SlothletError("INVALID_CONFIG",{option:`routines[${index}].mode`,value:String(mode),expected:`one of: ${[...VALID_ROUTINE_MODES].join(", ")}`,hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}const recursive=typeof entry==="object"?entry.recursive??false:false;if(typeof recursive!=="boolean"){throw new this.SlothletError("INVALID_CONFIG",{option:`routines[${index}].recursive`,value:typeof recursive,expected:"a boolean",hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}const pattern=name.startsWith("^")?name.slice(1):name;if(pattern.length===0){throw new this.SlothletError("INVALID_CONFIG",{option:`routines[${index}].name`,value:name,expected:'a root-anchored name with a pattern after the `^` (a bare "^" matches nothing)',hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}try{compilePattern(pattern)}catch(error){throw new this.SlothletError("INVALID_CONFIG",{option:`routines[${index}].name`,value:name,expected:`a name that compiles as a valid glob pattern (see helpers/pattern-matcher.mjs): ${error.message}`,hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}const order=typeof entry==="object"&&entry.order!==void 0?entry.order:DEFAULT_ROUTINE_ORDER_BY_MODE[mode];if(!VALID_ROUTINE_ORDERS.has(order)){throw new this.SlothletError("INVALID_CONFIG",{option:`routines[${index}].order`,value:String(order),expected:`one of: ${[...VALID_ROUTINE_ORDERS].join(", ")}`,hint:"HINT_INVALID_CONFIG",validationError:true},null,{validationError:true})}return{name,mode,recursive,order}})}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})}let failOpenOnAbsentCaller;if(permissions.failOpenOnAbsentCaller===true){failOpenOnAbsentCaller=true}else if(permissions.failOpenOnAbsentCaller===false||permissions.failOpenOnAbsentCaller===void 0){failOpenOnAbsentCaller=false}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.failOpenOnAbsentCaller",value:permissions.failOpenOnAbsentCaller,expected:"boolean",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}if(permissions.references!==void 0&&(typeof permissions.references!=="object"||permissions.references===null||Array.isArray(permissions.references))){throw new SlothletError("INVALID_CONFIG",{option:"permissions.references",value:permissions.references,expected:"object",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}let capture;if(permissions.references?.capture===false){capture=false}else if(permissions.references?.capture===true||permissions.references?.capture===void 0){capture=true}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.references.capture",value:permissions.references.capture,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:[];if(permissions.private!==void 0&&(typeof permissions.private!=="object"||permissions.private===null||Array.isArray(permissions.private))){throw new SlothletError("INVALID_CONFIG",{option:"permissions.private",value:permissions.private,expected:"object",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}let privateHost;if(permissions.private?.host==="allow"){privateHost="allow"}else if(permissions.private?.host==="deny"||permissions.private?.host===void 0){privateHost="deny"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.private.host",value:permissions.private.host,expected:'"deny" or "allow"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}return{defaultPolicy,enabled,audit,readGating,failOpenOnAbsentCaller,references:{capture},private:{host:privateHost},rules}}}export{Config,normalizeHookConfig};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
const DEFAULT_API_DEPTH=Infinity;export{DEFAULT_API_DEPTH};
|
|
17
|
+
import{ComponentBase}from"#factories/component-base";import{IMPL_METADATA_KEYS}from"#handlers/unified-wrapper";const DEFAULT_API_DEPTH=Infinity;const DEFAULT_ROUTINES=Object.freeze([Object.freeze({name:"initialize",mode:"startup"}),Object.freeze({name:"shutdown",mode:"shutdown"})]);function freezeSet(set){Object.freeze(set);return new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear"){return()=>{throw new TypeError("This Set is frozen and cannot be mutated.")}}const value=Reflect.get(target,prop,target);return typeof value==="function"?value.bind(target):value}})}const RESERVED_EXPORTS=freezeSet(new Set([...ComponentBase.INTERNAL_KEYS,...IMPL_METADATA_KEYS]));export{DEFAULT_API_DEPTH,DEFAULT_ROUTINES,RESERVED_EXPORTS};
|
|
@@ -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{pinToCurrentCaller}from"@cldmv/slothlet/helpers/caller-pinning";const PATCHED_INTERFACES=[["EventSource",["onopen","onmessage","onerror"]],["WebSocket",["onopen","onmessage","onerror","onclose"]],["Worker",["onmessage","onmessageerror","onerror"]],["MessagePort",["onmessage","onmessageerror"]],["FileReader",["onloadstart","onprogress","onabort","onerror","onload","onloadend"]],["XMLHttpRequest",["onreadystatechange","onloadstart","onprogress","onabort","onerror","onload","ontimeout","onloadend"]]];const patched=[];let isPatchingEnabled=false;function runtime_patchHandlerProperty(ctor,propName){const proto=ctor?.prototype;const descriptor=proto&&Object.getOwnPropertyDescriptor(proto,propName);if(!descriptor||typeof descriptor.get!=="function"||typeof descriptor.set!=="function"||!descriptor.configurable)return;const{get:originalGet,set:originalSet}=descriptor;const tracked=new WeakMap;const wrapperGet=function(){const entry=tracked.get(this);const current=originalGet.call(this);if(entry){if(current===entry.wrapper)return entry.original;tracked.delete(this)}return current};const wrapperSet=function(value){if(typeof value!=="function"){const result2=originalSet.call(this,value);tracked.delete(this);return result2}const wrapper=pinToCurrentCaller(value);const result=originalSet.call(this,wrapper);tracked.set(this,{original:value,wrapper});return result};Object.defineProperty(proto,propName,{configurable:descriptor.configurable,enumerable:descriptor.enumerable,get:wrapperGet,set:wrapperSet});patched.push({proto,propName,descriptor,wrapperGet,wrapperSet})}function enableEventTargetPropertyPatching(){if(isPatchingEnabled)return;for(const[ctorName,propNames]of PATCHED_INTERFACES){const ctor=globalThis[ctorName];if(typeof ctor!=="function")continue;for(const propName of propNames)runtime_patchHandlerProperty(ctor,propName)}isPatchingEnabled=true}function disableEventTargetPropertyPatching(){if(!isPatchingEnabled)return;for(const{proto,propName,descriptor,wrapperGet,wrapperSet}of patched){const current=Object.getOwnPropertyDescriptor(proto,propName);if(current&¤t.get===wrapperGet&¤t.set===wrapperSet){Object.defineProperty(proto,propName,descriptor)}}patched.length=0;isPatchingEnabled=false}export{disableEventTargetPropertyPatching,enableEventTargetPropertyPatching};
|
|
@@ -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{pinToCurrentCaller}from"@cldmv/slothlet/helpers/caller-pinning";const PATCHED_CONSTRUCTORS=["MutationObserver","ResizeObserver","IntersectionObserver"];const patched=[];let isPatchingEnabled=false;function runtime_carryOwnExtras(wrapper,original){for(const key of Object.getOwnPropertySymbols(original)){const descriptor=Object.getOwnPropertyDescriptor(original,key);if(!descriptor)continue;Object.defineProperty(wrapper,key,descriptor)}for(const key of Object.keys(original)){wrapper[key]=original[key]}}function runtime_patchObserverConstructor(name){const original=globalThis[name];if(typeof original!=="function")return;const wrapper=function(callback,...rest){if(!new.target)throw new TypeError(`Failed to construct '${name}': Please use the 'new' operator.`);const pinned=typeof callback==="function"?pinToCurrentCaller(callback):callback;return Reflect.construct(original,[pinned,...rest],new.target)};wrapper.prototype=Object.create(original.prototype,{constructor:{value:wrapper,writable:true,configurable:true}});runtime_carryOwnExtras(wrapper,original);globalThis[name]=wrapper;patched.push({name,original,wrapper})}function enableObserverPatching(){if(isPatchingEnabled)return;for(const name of PATCHED_CONSTRUCTORS)runtime_patchObserverConstructor(name);isPatchingEnabled=true}function disableObserverPatching(){if(!isPatchingEnabled)return;for(const{name,original,wrapper}of patched){if(globalThis[name]===wrapper)globalThis[name]=original}patched.length=0;isPatchingEnabled=false}export{disableObserverPatching,enableObserverPatching};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{pinToCurrentCaller}from"@cldmv/slothlet/helpers/caller-pinning";const patched=[];let isPatchingEnabled=false;function runtime_carryOwnExtras(wrapper,original){for(const key of Object.getOwnPropertySymbols(original)){const descriptor=Object.getOwnPropertyDescriptor(original,key);if(!descriptor)continue;Object.defineProperty(wrapper,key,descriptor)}for(const key of Object.keys(original)){wrapper[key]=original[key]}}function runtime_patchScheduler(host,name){const original=host?.[name];if(typeof original!=="function")return;const wrapper=function(callback,...rest){if(typeof callback!=="function")return original.call(host,callback,...rest);return original.call(host,pinToCurrentCaller(callback),...rest)};runtime_carryOwnExtras(wrapper,original);host[name]=wrapper;patched.push({host,name,original,wrapper})}function enableSchedulerPatching(){if(isPatchingEnabled)return;runtime_patchScheduler(globalThis,"setTimeout");runtime_patchScheduler(globalThis,"setInterval");runtime_patchScheduler(globalThis,"setImmediate");runtime_patchScheduler(globalThis,"queueMicrotask");runtime_patchScheduler(globalThis.process,"nextTick");isPatchingEnabled=true}function disableSchedulerPatching(){if(!isPatchingEnabled)return;for(const{host,name,original,wrapper}of patched){if(host[name]===wrapper)host[name]=original}patched.length=0;isPatchingEnabled=false}export{disableSchedulerPatching,enableSchedulerPatching};
|
|
17
|
+
import{pinToCurrentCaller}from"@cldmv/slothlet/helpers/caller-pinning";const patched=[];let isPatchingEnabled=false;function runtime_carryOwnExtras(wrapper,original){for(const key of Object.getOwnPropertySymbols(original)){const descriptor=Object.getOwnPropertyDescriptor(original,key);if(!descriptor)continue;Object.defineProperty(wrapper,key,descriptor)}for(const key of Object.keys(original)){wrapper[key]=original[key]}}function runtime_patchScheduler(host,name){const original=host?.[name];if(typeof original!=="function")return;const wrapper=function(callback,...rest){if(typeof callback!=="function")return original.call(host,callback,...rest);return original.call(host,pinToCurrentCaller(callback),...rest)};runtime_carryOwnExtras(wrapper,original);host[name]=wrapper;patched.push({host,name,original,wrapper})}function enableSchedulerPatching(){if(isPatchingEnabled)return;runtime_patchScheduler(globalThis,"setTimeout");runtime_patchScheduler(globalThis,"setInterval");runtime_patchScheduler(globalThis,"setImmediate");runtime_patchScheduler(globalThis,"queueMicrotask");runtime_patchScheduler(globalThis.process,"nextTick");runtime_patchScheduler(globalThis,"requestAnimationFrame");runtime_patchScheduler(globalThis,"requestIdleCallback");isPatchingEnabled=true}function disableSchedulerPatching(){if(!isPatchingEnabled)return;for(const{host,name,original,wrapper}of patched){if(host[name]===wrapper)host[name]=original}patched.length=0;isPatchingEnabled=false}export{disableSchedulerPatching,enableSchedulerPatching};
|
|
@@ -473,6 +473,8 @@
|
|
|
473
473
|
"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.",
|
|
474
474
|
"MODULE_MOUNT_COLLISION": "Module package '{packageName}' cannot mount at '{mountPath}': path is already occupied by module '{existingModuleID}' and collisionMode is '{collisionMode}'.",
|
|
475
475
|
"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.",
|
|
476
|
+
"ROUTINE_FAILED": "Routine contributor from module '{moduleID}' at '{apiPath}' failed: {error} ({count} failure(s) total: {failures}).",
|
|
477
|
+
"HINT_ROUTINE_FAILED": "Fix the throwing contributor, or catch and handle the failure inside it — every contributor in the routine's chain still runs even after one throws, and a single aggregated error listing every failure is thrown afterward (see `context.failures`).",
|
|
476
478
|
"HOOK_TYPEPATTERN_PREFIX_DEPRECATED": "Hook registration form '{given}' is deprecated and will be removed in v4. Use the path-first form '{suggested}' instead (e.g. 'math.*:before').",
|
|
477
479
|
"HINT_HOOK_TYPEPATTERN_PREFIX_DEPRECATED": "Move the hook type to the end as a suffix: rewrite a type-first selector like 'before:math.add' as the path-first form 'math.add:before'.",
|
|
478
480
|
"HOOK_UNPINNED_IGNORED": "lockCaller:false was ignored for hook '{pattern}'; hooks are pinned to their registering module. Set hook.pin:false (init) or call api.slothlet.hook.pin.disable() to permit unpinned hooks.",
|
package/dist/lib/modes/eager.mjs
CHANGED
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{ComponentBase}from"#factories/component-base";import{DEFAULT_API_DEPTH}from"@cldmv/slothlet/helpers/defaults";class EagerMode extends ComponentBase{static slothletProperty="eager";constructor(slothlet){super(slothlet)}async buildAPI({dir,apiPathPrefix="",collisionContext="initial",moduleID,apiDepth=DEFAULT_API_DEPTH,cacheBust=null,fileFilter=null,hidden=null,scanHiddenFolders=false,preloadedStructure=null,rootUnwrap=false}){const api={};const{modesProcessor}=this.slothlet.builders;const{loader}=this.slothlet.processors;if(preloadedStructure!=null&&(!Array.isArray(preloadedStructure.files)||!Array.isArray(preloadedStructure.directories))){const filesType=Array.isArray(preloadedStructure.files)?"array":typeof preloadedStructure.files;const directoriesType=Array.isArray(preloadedStructure.directories)?"array":typeof preloadedStructure.directories;const received=`{ files: ${filesType}, directories: ${directoriesType} }`;throw new this.SlothletError("INVALID_CONFIG_PRELOADED_STRUCTURE",{received},null,{validationError:true})}const structure=preloadedStructure??await loader.scanDirectory(dir,{maxDepth:apiDepth,fileFilter,hidden,scanHiddenFolders});const rootDirectory={name:".",path:dir,children:{files:structure.files,directories:structure.directories}};const rootDefaultFunction=await modesProcessor.processFiles(api,structure.files,rootDirectory,0,"eager",true,true,false,apiPathPrefix,collisionContext,moduleID,dir,cacheBust,
|
|
17
|
+
import{ComponentBase}from"#factories/component-base";import{DEFAULT_API_DEPTH}from"@cldmv/slothlet/helpers/defaults";class EagerMode extends ComponentBase{static slothletProperty="eager";constructor(slothlet){super(slothlet)}async buildAPI({dir,apiPathPrefix="",collisionContext="initial",collisionMode=null,moduleID,apiDepth=DEFAULT_API_DEPTH,cacheBust=null,fileFilter=null,hidden=null,scanHiddenFolders=false,preloadedStructure=null,rootUnwrap=false}){const api={};const{modesProcessor}=this.slothlet.builders;const{loader}=this.slothlet.processors;if(preloadedStructure!=null&&(!Array.isArray(preloadedStructure.files)||!Array.isArray(preloadedStructure.directories))){const filesType=Array.isArray(preloadedStructure.files)?"array":typeof preloadedStructure.files;const directoriesType=Array.isArray(preloadedStructure.directories)?"array":typeof preloadedStructure.directories;const received=`{ files: ${filesType}, directories: ${directoriesType} }`;throw new this.SlothletError("INVALID_CONFIG_PRELOADED_STRUCTURE",{received},null,{validationError:true})}const structure=preloadedStructure??await loader.scanDirectory(dir,{maxDepth:apiDepth,fileFilter,hidden,scanHiddenFolders});const rootDirectory={name:".",path:dir,children:{files:structure.files,directories:structure.directories}};const rootDefaultFunction=await modesProcessor.processFiles(api,structure.files,rootDirectory,0,"eager",true,true,false,apiPathPrefix,collisionContext,moduleID,dir,cacheBust,collisionMode,rootUnwrap);return modesProcessor.applyRootContributor(api,rootDefaultFunction,"eager")}}export{EagerMode};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{ComponentBase}from"#factories/component-base";class Flatten extends ComponentBase{static slothletProperty="flatten";constructor(slothlet){super(slothlet)}#checkSelfReferential(mod,moduleName){if(!mod||typeof mod!=="object")return false;return mod[moduleName]===mod}async#checkMultiDefault(analysis,hasMultipleDefaults,t){if(!hasMultipleDefaults)return null;if(analysis.hasDefault){return{preserveAsNamespace:true,reason:await t("FLATTEN_REASON_MULTI_DEFAULT_WITH_DEFAULT")}}return{flattenToRoot:true,reason:await t("FLATTEN_REASON_MULTI_DEFAULT_WITHOUT_DEFAULT")}}#checkAutoFlatten(mod,moduleName,moduleKeys){if(moduleKeys.length!==1)return false;return moduleKeys[0]===moduleName}async getFlatteningDecision(options){const{mod,moduleName,categoryName,analysis,hasMultipleDefaults,moduleKeys,t}=options;const isAddapiFile=moduleName==="addapi";if(isAddapiFile){if(analysis.hasDefault&&analysis.defaultExportType==="object"&&moduleKeys.length>0){return{flattenToCategory:true,flattenType:"addapi-metadata-default",reason:await t("FLATTEN_REASON_ADDAPI_METADATA_DEFAULT")}}return{flattenToCategory:true,flattenType:"addapi-special-file",reason:await t("FLATTEN_REASON_ADDAPI_SPECIAL_FILE")}}if(this.#checkSelfReferential(mod,moduleName)){return{preserveAsNamespace:true,reason:await t("FLATTEN_REASON_SELF_REFERENTIAL")}}const multiDefaultDecision=await this.#checkMultiDefault(analysis,hasMultipleDefaults,t);if(multiDefaultDecision){if(multiDefaultDecision.preserveAsNamespace){const exportToCheck2=typeof mod==="function"?mod:mod?.default&&typeof mod.default==="function"?mod.default:null;if(exportToCheck2&&exportToCheck2.name&&exportToCheck2.name!=="default"){const normalizedFunctionName=exportToCheck2.name.toLowerCase().replace(/[-_]/g,"");const normalizedModuleName=moduleName.toLowerCase().replace(/[-_]/g,"");if(normalizedFunctionName===normalizedModuleName){multiDefaultDecision.preferredName=exportToCheck2.name}}}return multiDefaultDecision}if(this.#checkAutoFlatten(mod,moduleName,moduleKeys)){return{useAutoFlattening:true,reason:await t("FLATTEN_REASON_SINGLE_EXPORT_MATCHES_FILENAME")}}if(moduleName===categoryName){return{flattenToCategory:true,reason:await t("FLATTEN_REASON_FILENAME_MATCHES_CATEGORY")}}const exportToCheck=typeof mod==="function"?mod:mod?.default&&typeof mod.default==="function"?mod.default:null;if(exportToCheck&&exportToCheck.name&&exportToCheck.name!=="default"){const normalizedFunctionName=exportToCheck.name.toLowerCase().replace(/[-_]/g,"");const normalizedModuleName=moduleName.toLowerCase().replace(/[-_]/g,"");const functionNameMatchesFilename=normalizedFunctionName===normalizedModuleName;if(functionNameMatchesFilename){return{preserveAsNamespace:true,preferredName:exportToCheck.name,reason:await t("FLATTEN_REASON_PRESERVING_FUNCTION_NAME")}}}return{preserveAsNamespace:true,reason:await t("FLATTEN_REASON_DEFAULT_PRESERVE_NAMESPACE")}}processModuleForAPI(options){const{mod,decision,moduleName,propertyName,moduleKeys,analysis,file=null,collisionContext="initial",apiPathPrefix="",isSelfReferential=false}=options;const isAddapiFile=moduleName==="addapi"||file&&file.name==="addapi"||file&&file.fullName&&["addapi.mjs","addapi.cjs","addapi.js","addapi.ts"].includes(file.fullName.toLowerCase());if(isAddapiFile&&analysis.hasDefault&&moduleKeys.length>0){const moduleContent2=mod.default;for(const key of moduleKeys){moduleContent2[key]=mod[key]}return{moduleContent:moduleContent2}}if(decision.useAutoFlattening){return{moduleContent:mod[moduleName]}}if(decision.flattenToRoot||decision.flattenToCategory){if(mod.default&&moduleKeys.length===0){return{moduleContent:mod.default}}if(mod.default&&moduleKeys.length>0){const moduleContent3=typeof mod.default==="function"?mod.default:{...mod.default};for(const key of moduleKeys){moduleContent3[key]=mod[key]}return{moduleContent:moduleContent3}}const moduleContent2={};for(const key of moduleKeys){moduleContent2[key]=mod[key]}return{moduleContent:moduleContent2}}if(isSelfReferential){return{moduleContent:mod[moduleName]||mod}}if(mod.default&&moduleKeys.length>0){if(typeof mod.default==="function"){const moduleContent3=this.slothlet.helpers.modesUtils.ensureNamedExportFunction(mod.default,propertyName);const collisionConfig=this.slothlet.config.api?.collision||this.slothlet.config.collision;const collisionMode=collisionContext==="initial"?collisionConfig.initial:collisionConfig.api;for(const key of moduleKeys){if(!this.shouldAttachNamedExport(key,mod[key],moduleContent3,mod.default)){continue}const hasExisting=Object.prototype.hasOwnProperty.call(moduleContent3,key);if(hasExisting){if(collisionMode==="merge"||collisionMode==="skip"){continue}else if(collisionMode==="error"){throw new this.slothlet.SlothletError("COLLISION_DEFAULT_EXPORT_ERROR",{key,apiPath:`${apiPathPrefix}.${propertyName}`},null,{validationError:true})}else if(collisionMode==="warn"){new this.slothlet.SlothletWarning("WARNING_COLLISION_DEFAULT_EXPORT_OVERWRITE",{key,apiPath:`${apiPathPrefix}.${propertyName}`})}}moduleContent3[key]=mod[key]}return{moduleContent:moduleContent3}}if(typeof mod.default==="object"&&mod.default!==null){const moduleContent3=mod.default;for(const key of moduleKeys){if(key in mod.default){continue}if(!this.shouldAttachNamedExport(key,mod[key],moduleContent3,mod.default)){continue}moduleContent3[key]=mod[key]}return{moduleContent:moduleContent3}}const moduleContent2={default:mod.default};for(const key of moduleKeys){moduleContent2[key]=mod[key]}return{moduleContent:moduleContent2}}if(mod.default&&moduleKeys.length===0){return{moduleContent:this.slothlet.helpers.modesUtils.ensureNamedExportFunction(mod.default,propertyName)}}const moduleContent={};for(const key of moduleKeys){moduleContent[key]=mod[key]}return{moduleContent}}async buildCategoryDecisions(options){const{categoryName,mod,moduleName,fileBaseName,analysis,moduleKeys,currentDepth,moduleFiles=[],t}=options;const decision={shouldFlatten:false,flattenType:"preserve",preferredName:null,reason:await t("FLATTEN_REASON_NO_CONDITIONS_MET")};const isAddapiFile=moduleName==="addapi"||fileBaseName==="addapi"||fileBaseName&&["addapi.mjs","addapi.cjs","addapi.js","addapi.ts"].includes(fileBaseName.toLowerCase());if(isAddapiFile){if(analysis.hasDefault&&analysis.defaultExportType==="object"&&moduleKeys.length>0){return{shouldFlatten:true,flattenType:"addapi-metadata-default",reason:await t("FLATTEN_REASON_ADDAPI_SPECIAL_FILE_PARENT")}}return{shouldFlatten:true,flattenType:"addapi-special-file",reason:await t("FLATTEN_REASON_ADDAPI_SPECIAL_FILE")}}if(moduleName===categoryName&&typeof mod==="function"&¤tDepth>0){return{shouldFlatten:true,flattenType:"function-folder-match",reason:await t("FLATTEN_REASON_FUNCTION_FOLDER_MATCH")}}if(analysis.hasDefault&&analysis.defaultExportType==="object"&&moduleName===categoryName&¤tDepth>0){return{shouldFlatten:true,flattenType:"default-export-flatten",reason:await t("FLATTEN_REASON_DEFAULT_OBJECT_EXPORT_FLATTEN")}}if(moduleName===categoryName&&mod&&typeof mod==="object"&&!Array.isArray(mod)&¤tDepth>0){if(moduleKeys.length===1&&moduleKeys[0]===moduleName){return{shouldFlatten:true,flattenType:"object-auto-flatten",reason:await t("FLATTEN_REASON_SINGLE_EXPORT_MATCHES_FILENAME")}}}if(fileBaseName===categoryName&&moduleKeys.length>0){return{shouldFlatten:true,flattenType:"filename-folder-match-flatten",reason:await t("FLATTEN_REASON_BASENAME_MATCHES_CATEGORY")}}if(moduleFiles.length===1&¤tDepth>0&&mod&&typeof mod==="object"&&!Array.isArray(mod)){const genericFilenames=["singlefile","index","main","default"];const isGenericFilename=genericFilenames.includes(moduleName.toLowerCase());if(moduleKeys.length===1&&isGenericFilename){return{shouldFlatten:true,flattenType:"parent-level-flatten",reason:await t("FLATTEN_REASON_GENERIC_FILENAME_SINGLE_EXPORT")}}}if(typeof mod==="function"&&mod.name&¤tDepth>0){const functionNameMatchesFolder=mod.name.toLowerCase()===categoryName.toLowerCase()||mod.name.toLowerCase().replace(/[-_]/g,"")===categoryName.toLowerCase().replace(/[-_]/g,"");if(functionNameMatchesFolder){return{shouldFlatten:true,flattenType:"function-folder-match",preferredName:mod.name,reason:await t("FLATTEN_REASON_FUNCTION_FOLDER_MATCH")}}}const exportToCheck=typeof mod==="function"?mod:mod?.default&&typeof mod.default==="function"?mod.default:null;if(exportToCheck&&exportToCheck.name&&exportToCheck.name!=="default"){const normalizedFunctionName=exportToCheck.name.toLowerCase().replace(/[-_]/g,"");const normalizedModuleName=moduleName.toLowerCase().replace(/[-_]/g,"");const functionNameMatchesFilename=normalizedFunctionName===normalizedModuleName;if(functionNameMatchesFilename){return{shouldFlatten:false,preferredName:exportToCheck.name,reason:await t("FLATTEN_REASON_PRESERVING_FUNCTION_NAME")}}}if(typeof mod==="function"&&(!mod.name||mod.name==="default"||mod.__slothletDefault===true)&¤tDepth>0){return{shouldFlatten:true,flattenType:"default-function",preferredName:categoryName,reason:await t("FLATTEN_REASON_DEFAULT_FUNCTION_EXPORT")}}if(moduleKeys.length===1&&moduleKeys[0]===moduleName){return{shouldFlatten:true,flattenType:"object-auto-flatten",preferredName:moduleName,reason:await t("FLATTEN_REASON_SINGLE_EXPORT_MATCHES_MODULE")}}return decision}shouldAttachNamedExport(key,value,defaultFunc,originalDefault){if(!key||key==="default"){return false}if(value===defaultFunc||value===originalDefault){return false}if(typeof defaultFunc==="function"&&key===defaultFunc.name){return false}if(typeof originalDefault==="function"&&key===originalDefault.name){return false}return true}}export{Flatten};
|
|
17
|
+
import{ComponentBase}from"#factories/component-base";class Flatten extends ComponentBase{static slothletProperty="flatten";constructor(slothlet){super(slothlet)}#checkSelfReferential(mod,moduleName){if(!mod||typeof mod!=="object")return false;return mod[moduleName]===mod}async#checkMultiDefault(analysis,hasMultipleDefaults,t){if(!hasMultipleDefaults)return null;if(analysis.hasDefault){return{preserveAsNamespace:true,reason:await t("FLATTEN_REASON_MULTI_DEFAULT_WITH_DEFAULT")}}return{flattenToRoot:true,reason:await t("FLATTEN_REASON_MULTI_DEFAULT_WITHOUT_DEFAULT")}}#checkAutoFlatten(mod,moduleName,moduleKeys){if(moduleKeys.length!==1)return false;return moduleKeys[0]===moduleName}async getFlatteningDecision(options){const{mod,moduleName,categoryName,analysis,hasMultipleDefaults,moduleKeys,t}=options;const isAddapiFile=moduleName==="addapi";if(isAddapiFile){if(analysis.hasDefault&&analysis.defaultExportType==="object"&&moduleKeys.length>0){return{flattenToCategory:true,flattenType:"addapi-metadata-default",reason:await t("FLATTEN_REASON_ADDAPI_METADATA_DEFAULT")}}return{flattenToCategory:true,flattenType:"addapi-special-file",reason:await t("FLATTEN_REASON_ADDAPI_SPECIAL_FILE")}}if(this.#checkSelfReferential(mod,moduleName)){return{preserveAsNamespace:true,reason:await t("FLATTEN_REASON_SELF_REFERENTIAL")}}const multiDefaultDecision=await this.#checkMultiDefault(analysis,hasMultipleDefaults,t);if(multiDefaultDecision){if(multiDefaultDecision.preserveAsNamespace){const exportToCheck2=typeof mod==="function"?mod:mod?.default&&typeof mod.default==="function"?mod.default:null;if(exportToCheck2&&exportToCheck2.name&&exportToCheck2.name!=="default"){const normalizedFunctionName=exportToCheck2.name.toLowerCase().replace(/[-_]/g,"");const normalizedModuleName=moduleName.toLowerCase().replace(/[-_]/g,"");if(normalizedFunctionName===normalizedModuleName){multiDefaultDecision.preferredName=exportToCheck2.name}}}return multiDefaultDecision}if(this.#checkAutoFlatten(mod,moduleName,moduleKeys)){return{useAutoFlattening:true,reason:await t("FLATTEN_REASON_SINGLE_EXPORT_MATCHES_FILENAME")}}if(moduleName===categoryName){return{flattenToCategory:true,reason:await t("FLATTEN_REASON_FILENAME_MATCHES_CATEGORY")}}const exportToCheck=typeof mod==="function"?mod:mod?.default&&typeof mod.default==="function"?mod.default:null;if(exportToCheck&&exportToCheck.name&&exportToCheck.name!=="default"){const normalizedFunctionName=exportToCheck.name.toLowerCase().replace(/[-_]/g,"");const normalizedModuleName=moduleName.toLowerCase().replace(/[-_]/g,"");const functionNameMatchesFilename=normalizedFunctionName===normalizedModuleName;if(functionNameMatchesFilename){return{preserveAsNamespace:true,preferredName:exportToCheck.name,reason:await t("FLATTEN_REASON_PRESERVING_FUNCTION_NAME")}}}return{preserveAsNamespace:true,reason:await t("FLATTEN_REASON_DEFAULT_PRESERVE_NAMESPACE")}}processModuleForAPI(options){const{mod,decision,moduleName,propertyName,moduleKeys,analysis,file=null,collisionContext="initial",apiPathPrefix="",isSelfReferential=false,collisionModeOverride=null}=options;const isAddapiFile=moduleName==="addapi"||file&&file.name==="addapi"||file&&file.fullName&&["addapi.mjs","addapi.cjs","addapi.js","addapi.ts"].includes(file.fullName.toLowerCase());if(isAddapiFile&&analysis.hasDefault&&moduleKeys.length>0){const moduleContent2=mod.default;for(const key of moduleKeys){moduleContent2[key]=mod[key]}return{moduleContent:moduleContent2}}if(decision.useAutoFlattening){return{moduleContent:mod[moduleName]}}if(decision.flattenToRoot||decision.flattenToCategory){if(mod.default&&moduleKeys.length===0){return{moduleContent:mod.default}}if(mod.default&&moduleKeys.length>0){const moduleContent3=typeof mod.default==="function"?mod.default:{...mod.default};for(const key of moduleKeys){moduleContent3[key]=mod[key]}return{moduleContent:moduleContent3}}const moduleContent2={};for(const key of moduleKeys){moduleContent2[key]=mod[key]}return{moduleContent:moduleContent2}}if(isSelfReferential){return{moduleContent:mod[moduleName]||mod}}if(mod.default&&moduleKeys.length>0){if(typeof mod.default==="function"){const moduleContent3=this.slothlet.helpers.modesUtils.ensureNamedExportFunction(mod.default,propertyName);const collisionConfig=this.slothlet.config.api?.collision||this.slothlet.config.collision;const collisionMode=collisionModeOverride||(collisionContext==="initial"?collisionConfig.initial:collisionConfig.api);for(const key of moduleKeys){if(!this.shouldAttachNamedExport(key,mod[key],moduleContent3,mod.default)){continue}const hasExisting=Object.prototype.hasOwnProperty.call(moduleContent3,key);if(hasExisting){if(collisionMode==="merge"||collisionMode==="skip"){continue}else if(collisionMode==="error"){throw new this.slothlet.SlothletError("COLLISION_DEFAULT_EXPORT_ERROR",{key,apiPath:`${apiPathPrefix}.${propertyName}`},null,{validationError:true})}else if(collisionMode==="warn"){new this.slothlet.SlothletWarning("WARNING_COLLISION_DEFAULT_EXPORT_OVERWRITE",{key,apiPath:`${apiPathPrefix}.${propertyName}`})}}moduleContent3[key]=mod[key]}return{moduleContent:moduleContent3}}if(typeof mod.default==="object"&&mod.default!==null){const moduleContent3=mod.default;for(const key of moduleKeys){if(key in mod.default){continue}if(!this.shouldAttachNamedExport(key,mod[key],moduleContent3,mod.default)){continue}moduleContent3[key]=mod[key]}return{moduleContent:moduleContent3}}const moduleContent2={default:mod.default};for(const key of moduleKeys){moduleContent2[key]=mod[key]}return{moduleContent:moduleContent2}}if(mod.default&&moduleKeys.length===0){return{moduleContent:this.slothlet.helpers.modesUtils.ensureNamedExportFunction(mod.default,propertyName)}}const moduleContent={};for(const key of moduleKeys){moduleContent[key]=mod[key]}return{moduleContent}}async buildCategoryDecisions(options){const{categoryName,mod,moduleName,fileBaseName,analysis,moduleKeys,currentDepth,moduleFiles=[],t}=options;const decision={shouldFlatten:false,flattenType:"preserve",preferredName:null,reason:await t("FLATTEN_REASON_NO_CONDITIONS_MET")};const isAddapiFile=moduleName==="addapi"||fileBaseName==="addapi"||fileBaseName&&["addapi.mjs","addapi.cjs","addapi.js","addapi.ts"].includes(fileBaseName.toLowerCase());if(isAddapiFile){if(analysis.hasDefault&&analysis.defaultExportType==="object"&&moduleKeys.length>0){return{shouldFlatten:true,flattenType:"addapi-metadata-default",reason:await t("FLATTEN_REASON_ADDAPI_SPECIAL_FILE_PARENT")}}return{shouldFlatten:true,flattenType:"addapi-special-file",reason:await t("FLATTEN_REASON_ADDAPI_SPECIAL_FILE")}}if(moduleName===categoryName&&typeof mod==="function"&¤tDepth>0){return{shouldFlatten:true,flattenType:"function-folder-match",reason:await t("FLATTEN_REASON_FUNCTION_FOLDER_MATCH")}}if(analysis.hasDefault&&analysis.defaultExportType==="object"&&moduleName===categoryName&¤tDepth>0){return{shouldFlatten:true,flattenType:"default-export-flatten",reason:await t("FLATTEN_REASON_DEFAULT_OBJECT_EXPORT_FLATTEN")}}if(moduleName===categoryName&&mod&&typeof mod==="object"&&!Array.isArray(mod)&¤tDepth>0){if(moduleKeys.length===1&&moduleKeys[0]===moduleName){return{shouldFlatten:true,flattenType:"object-auto-flatten",reason:await t("FLATTEN_REASON_SINGLE_EXPORT_MATCHES_FILENAME")}}}if(fileBaseName===categoryName&&moduleKeys.length>0){return{shouldFlatten:true,flattenType:"filename-folder-match-flatten",reason:await t("FLATTEN_REASON_BASENAME_MATCHES_CATEGORY")}}if(moduleFiles.length===1&¤tDepth>0&&mod&&typeof mod==="object"&&!Array.isArray(mod)){const genericFilenames=["singlefile","index","main","default"];const isGenericFilename=genericFilenames.includes(moduleName.toLowerCase());if(moduleKeys.length===1&&isGenericFilename){return{shouldFlatten:true,flattenType:"parent-level-flatten",reason:await t("FLATTEN_REASON_GENERIC_FILENAME_SINGLE_EXPORT")}}}if(typeof mod==="function"&&mod.name&¤tDepth>0){const functionNameMatchesFolder=mod.name.toLowerCase()===categoryName.toLowerCase()||mod.name.toLowerCase().replace(/[-_]/g,"")===categoryName.toLowerCase().replace(/[-_]/g,"");if(functionNameMatchesFolder){return{shouldFlatten:true,flattenType:"function-folder-match",preferredName:mod.name,reason:await t("FLATTEN_REASON_FUNCTION_FOLDER_MATCH")}}}const exportToCheck=typeof mod==="function"?mod:mod?.default&&typeof mod.default==="function"?mod.default:null;if(exportToCheck&&exportToCheck.name&&exportToCheck.name!=="default"){const normalizedFunctionName=exportToCheck.name.toLowerCase().replace(/[-_]/g,"");const normalizedModuleName=moduleName.toLowerCase().replace(/[-_]/g,"");const functionNameMatchesFilename=normalizedFunctionName===normalizedModuleName;if(functionNameMatchesFilename){return{shouldFlatten:false,preferredName:exportToCheck.name,reason:await t("FLATTEN_REASON_PRESERVING_FUNCTION_NAME")}}}if(typeof mod==="function"&&(!mod.name||mod.name==="default"||mod.__slothletDefault===true)&¤tDepth>0){return{shouldFlatten:true,flattenType:"default-function",preferredName:categoryName,reason:await t("FLATTEN_REASON_DEFAULT_FUNCTION_EXPORT")}}if(moduleKeys.length===1&&moduleKeys[0]===moduleName){return{shouldFlatten:true,flattenType:"object-auto-flatten",preferredName:moduleName,reason:await t("FLATTEN_REASON_SINGLE_EXPORT_MATCHES_MODULE")}}return decision}shouldAttachNamedExport(key,value,defaultFunc,originalDefault){if(!key||key==="default"){return false}if(value===defaultFunc||value===originalDefault){return false}if(typeof defaultFunc==="function"&&key===defaultFunc.name){return false}if(typeof originalDefault==="function"&&key===originalDefault.name){return false}return true}}export{Flatten};
|
package/dist/slothlet.mjs
CHANGED
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{isNode,fs,fsp,path,url,createRequire}from"@cldmv/slothlet/helpers/platform";import{getContextManager}from"#factories/context";import{warnIfCoverageWithoutImporter}from"@cldmv/slothlet/processors/loader";import{SlothletError,SlothletWarning,SlothletDebug}from"@cldmv/slothlet/errors";import{registerInstance}from"#handlers/lifecycle-token";import{resolveWrapper}from"#handlers/unified-wrapper";import{isFrameworkInternal}from"#handlers/framework-internals";import{TRUSTED_ROOT}from"#handlers/trusted-root";import{initI18n}from"@cldmv/slothlet/i18n";import{enableEventEmitterPatching,disableEventEmitterPatching,cleanupEventEmitterResources,setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";import{enableSchedulerPatching,disableSchedulerPatching}from"@cldmv/slothlet/helpers/scheduler-context";import{enableEventTargetPatching,disableEventTargetPatching}from"@cldmv/slothlet/helpers/eventtarget-context";const boundaryPatchHolders=new Set;class Slothlet{static RESERVED_ROOT_KEYS=["slothlet","shutdown","destroy"];static SKIP_PROPS=["__metadata","__type","_materialize","_impl","____slothletInternal"];constructor(){this.SlothletError=SlothletError;this.SlothletWarning=SlothletWarning;this.debugLogger=null;this.instanceID=null;this.config=null;this.envTarget="node";this.api=null;this.boundApi=null;this.contextManager=null;this.isLoaded=false;this.reference=null;this.context=null;this.envSnapshot=null;this._totalLazyCount=0;this._unmaterializedLazyCount=0;this._materializationComplete=false;this._materializationWaiters=[];this._materializationCompleteEmitted=false;this.componentCategories=["helpers","handlers","builders","processors","modes"];for(const category of this.componentCategories){this[category]={}}}async _initializeComponents(){if(this.envTarget==="browser"){await this._initializeComponentsBrowser();return}const baseDir=path.join(path.dirname(url.fileURLToPath(import.meta.url)),"lib");for(const category of this.componentCategories){const categoryDir=path.join(baseDir,category);const files=fs.readdirSync(categoryDir).filter(f=>f.endsWith(".mjs"));for(const file of files){const filePath=path.join(categoryDir,file);try{const module=await import(url.pathToFileURL(filePath).href);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this);if(this.config?.debug?.initialization){this.debug("initialization",{key:"DEBUG_MODE_COMPONENT_INITIALIZED",component:ClassExport.name,category,propertyName:propName})}}}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}}}async _initializeComponentsBrowser(){const BROWSER_COMPONENT_SPECIFIERS=["@cldmv/slothlet/builders/api-assignment","@cldmv/slothlet/builders/api_builder","@cldmv/slothlet/builders/builder","@cldmv/slothlet/builders/modes-processor","#handlers/api-cache-manager","#handlers/api-manager","#handlers/hook-manager","#handlers/lifecycle","#handlers/materialize-manager","#handlers/metadata","#handlers/module-manager","#handlers/ownership","#handlers/permission-manager","#handlers/version-manager","@cldmv/slothlet/helpers/config","@cldmv/slothlet/helpers/hint-detector","@cldmv/slothlet/helpers/modes-utils","@cldmv/slothlet/helpers/resolve-from-caller","@cldmv/slothlet/helpers/sanitize","@cldmv/slothlet/helpers/utilities","@cldmv/slothlet/modes/eager","@cldmv/slothlet/modes/lazy","@cldmv/slothlet/processors/flatten","@cldmv/slothlet/processors/loader"];for(const specifier of BROWSER_COMPONENT_SPECIFIERS){const parts=specifier.split("/");const category=specifier.startsWith("#")?parts[0].slice(1):parts[2];const module=await import(specifier);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this)}}}_setupConfigLifecycleSubscribers(){const map=this.config.lifecycle;if(!map){return}const lifecycle=this.handlers.lifecycle;for(const[event,handler]of Object.entries(map)){const handlers=Array.isArray(handler)?handler:[handler];for(const fn of handlers){lifecycle.subscribe(event,fn)}}}_setupLifecycleSubscribers(){if(!this.handlers.lifecycle){return}if(this.handlers.metadata){this.handlers.lifecycle.subscribe("impl:created",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:changed",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:removed",data=>{if(data.apiPath){const rootSegment=data.apiPath.split(".")[0];this.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}})}if(this.handlers.ownership){this.handlers.lifecycle.subscribe("impl:created",data=>{const collisionMode=this.config?.collision?.api||"merge";const implValue=data.wrapper?.__impl??data.impl;this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})});this.handlers.lifecycle.subscribe("impl:changed",data=>{const collisionMode=this.config?.collision?.api||"merge";const implValue=data.wrapper?.__impl??data.impl;const currentOwner=this.handlers.ownership.getCurrentOwner(data.apiPath);if(currentOwner?.moduleID!==data.moduleID){this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})}})}}_registerLazyWrapper(){this._totalLazyCount++;this._unmaterializedLazyCount++;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_REGISTERED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount})}}_onWrapperMaterialized(){this._unmaterializedLazyCount--;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_MATERIALIZED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount,percentage:this._totalLazyCount>0?(this._totalLazyCount-this._unmaterializedLazyCount)/this._totalLazyCount*100:100})}if(this._unmaterializedLazyCount===0&&!this._materializationComplete){this._materializationComplete=true;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_ALL_LAZY_WRAPPERS_MATERIALIZED",total:this._totalLazyCount})}const waiters=this._materializationWaiters.splice(0);for(const resolve of waiters){resolve()}if(this.config?.tracking?.materialization&&!this._materializationCompleteEmitted){this._materializationCompleteEmitted=true;if(this.handlers?.lifecycle){this.handlers.lifecycle.emit("materialized:complete",{total:this._totalLazyCount,timestamp:Date.now()})}}}}_captureEnvSnapshot(envConfig){const rawInclude=envConfig?.include;const include=Array.isArray(rawInclude)?rawInclude.filter(key=>typeof key==="string"):null;const useAllowlist=include!==null&&include.length>0;const raw=useAllowlist?include.reduce((acc,key)=>{if(Object.prototype.hasOwnProperty.call(process.env,key)){acc[key]=process.env[key]}return acc},Object.create(null)):{...process.env};return Object.freeze(raw)}async load(config={},preservedInstanceID=null){this.config=config;this.envTarget=config.platform==="browser"||config.platform!=="node"&&config.manifest!=null?"browser":"node";if(!this.envSnapshot){this.envSnapshot=this.envTarget==="browser"?Object.freeze(Object.create(null)):this._captureEnvSnapshot(config.env)}this.debugLogger=new SlothletDebug(config);await this._initializeComponents();registerInstance(this);this._setupLifecycleSubscribers();this.config=this.helpers.config.transformConfig(config);if(this.envTarget==="node"){warnIfCoverageWithoutImporter(this.config)}this._setupConfigLifecycleSubscribers();if(this.config?.i18n?.language){initI18n({language:this.config.i18n.language})}this.debugLogger=new SlothletDebug(this.config);this.instanceID=preservedInstanceID||this.helpers.utilities.generateId();this.reference=this.config.reference;this.context=this.config.context;this.contextManager=getContextManager(this.envTarget==="browser"?"live":this.config.runtime);setApiContextChecker(()=>{const ctx=this.contextManager.tryGetContext();return!!(ctx&&ctx.self)});let store;if(preservedInstanceID&&this.contextManager.instances.has(preservedInstanceID)){this.contextManager.cleanup(preservedInstanceID);store=this.contextManager.initialize(this.instanceID,this.config)}else{store=this.contextManager.initialize(this.instanceID,this.config)}Object.defineProperty(store,TRUSTED_ROOT,{value:true,configurable:true});enableEventEmitterPatching();enableSchedulerPatching();enableEventTargetPatching();boundaryPatchHolders.add(this.instanceID);if(typeof this.contextManager.registerEventEmitterContextChecker==="function"){this.contextManager.registerEventEmitterContextChecker()}const baseModuleId=`base_${this.helpers.utilities.generateId().substring(0,8)}`;if(this.config.scanHiddenFolders!==void 0&&!this.config.silent){new this.SlothletWarning("CONFIG_SCAN_HIDDEN_FOLDERS_DEPRECATED",{option:"scanHiddenFolders"})}const baseApi=await this.builders.builder.buildAPI({dir:this.config.dir,mode:this.config.mode,moduleID:baseModuleId,hidden:this.config.hidden??null,scanHiddenFolders:this.config.scanHiddenFolders===true});this.api=baseApi;const apiWithBuiltins=await this.buildFinalAPI(this.api);if(this.handlers.apiCacheManager){this.handlers.apiCacheManager.set(baseModuleId,{endpoint:".",moduleID:baseModuleId,api:this.api,folderPath:this.config.dir,mode:this.config.mode,sanitizeOptions:this.config.sanitize||{},collisionMode:this.config.collision?.api||"merge",config:{...this.config},timestamp:Date.now()})}this.injectRuntimeMetadataFunctions(apiWithBuiltins);if(this.config.metadata&&typeof this.config.metadata==="object"){for(const[key,value]of Object.entries(this.config.metadata)){this.handlers.metadata.setGlobalMetadata(key,value)}this.handlers.metadata.registerUserMetadata(baseModuleId,this.config.metadata)}if(this.handlers.ownership){this.handlers.ownership.registerSubtree(apiWithBuiltins,baseModuleId,"");this.handlers.ownership.setModuleEndpoint(baseModuleId,".")}if(!this.boundApi){const isCallable=typeof this.api==="function"||this.api&&typeof this.api.default==="function";const proxyTarget=isCallable?function(){}:{};this.boundApi=new Proxy(proxyTarget,{get:(target,prop)=>this.api?this.api[prop]:void 0,set:(target,prop,value)=>{if(this.api){this.api[prop]=value}return true},has:(target,prop)=>this.api?prop in this.api:false,ownKeys:____target=>this.api?Reflect.ownKeys(this.api):[],deleteProperty:(target,prop)=>this.api?delete this.api[prop]:true,apply:(target,thisArg,args)=>this.api?Reflect.apply(this.api,thisArg,args):void 0,construct:(target,args)=>this.api?Reflect.construct(this.api,args):{},getOwnPropertyDescriptor:(target,prop)=>{if(isCallable&&prop==="prototype"){return Object.getOwnPropertyDescriptor(target,prop)}if(this.api&&prop in this.api){const desc=Object.getOwnPropertyDescriptor(this.api,prop);if(desc){return{...desc,configurable:true}}}return void 0}})}store.self=this.boundApi;store.context=this.context||{};store.slothlet=this;if(this.reference&&typeof this.reference==="object"){Object.assign(this.boundApi,this.reference)}this.isLoaded=true;return this.boundApi}async reload(options={}){const{keepInstanceID=false}=options;if(!this.config?.dir){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"reload",validationError:true})}const operationHistory=this.handlers.apiManager?.state?.operationHistory?[...this.handlers.apiManager.state.operationHistory]:[];await this._clearModuleCaches();const oldInstanceID=this.instanceID;if(!keepInstanceID){this.instanceID=`${oldInstanceID}_reload_${Date.now()}`;if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}}const savedMetadataState=this.handlers.metadata?.exportUserState?.();const savedHooks=this.handlers.hookManager?.exportHooks?.();const wasSealed=this.handlers.permissionManager?.isSealed?.()===true;await this.load(this.config,this.instanceID);if(savedMetadataState&&this.handlers.metadata){this.handlers.metadata.importUserState(savedMetadataState)}if(savedHooks?.length&&this.handlers.hookManager){this.handlers.hookManager.importHooks(savedHooks)}for(const[,store]of this.contextManager.instances){if(store.parentInstanceID===oldInstanceID){store.parentInstanceID=this.instanceID}}if(oldInstanceID&&oldInstanceID!==this.instanceID&&this.contextManager.instances?.has(oldInstanceID)){this.contextManager.cleanup(oldInstanceID)}for(const operation of operationHistory){if(operation.type==="add"){await this.handlers.apiManager.addApiComponent({apiPath:operation.apiPath,folderPath:operation.folderPath,options:{...operation.options||{},recordHistory:false},versionConfig:operation.versionConfig||null})}else if(operation.type==="remove"){if(operation.scopedModuleID){await this.handlers.apiManager.removeApiComponent(operation.scopedModuleID,{scopedApiPath:operation.apiPath,recordHistory:false})}else{await this.handlers.apiManager.removeApiComponent(operation.apiPath,{recordHistory:false})}}else if(operation.type==="addPermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.addRule(operation.rule,operation.ownerModuleID,operation.ruleId)}}else{if(operation.type==="removePermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.removeRule(operation.ruleId,operation.callerModuleID)}}}}if(wasSealed)this.handlers.permissionManager?.seal?.();return this.boundApi}async _clearModuleCaches(){if(!isNode)return;const targetDir=this.config.dir;const require2=createRequire(import.meta.url);const absoluteTargetDir=path.resolve(targetDir);for(const key of Object.keys(require2.cache)){if(key.startsWith(absoluteTargetDir)){delete require2.cache[key]}}}injectRuntimeMetadataFunctions(api){if(!api.slothlet?.metadata){return}const metadataHandler=this.handlers.metadata;api.slothlet.metadata.get=async function slothlet_metadata_get_runtime(path2){return metadataHandler.get(path2)};api.slothlet.metadata.self=function slothlet_metadata_self_runtime(){return metadataHandler.self()};api.slothlet.metadata.caller=function slothlet_metadata_caller_runtime(){return metadataHandler.caller()}}async _drainInFlightLoads(){if(!this.api)return;const pending=[];const seen=new Set;const collect=(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>15||seen.has(obj))return;seen.add(obj);try{if(isFrameworkInternal(obj))return;const wrapper=resolveWrapper(obj);if(wrapper){const mat=wrapper.____slothletInternal.materializationPromise;if(mat)pending.push(mat);for(const key of Object.keys(wrapper)){if(!key.startsWith("____"))collect(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){collect(obj[key],depth+1)}}catch{}};for(const key of Object.keys(this.api)){collect(this.api[key])}if(pending.length>0){await Promise.allSettled(pending)}}async _collectLifecycleHooks(kind){if(!this.api)return[];const hooks=[];const seen=new Set;const collect=async(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>15||seen.has(obj))return;seen.add(obj);try{if(isFrameworkInternal(obj))return;const wrapper=resolveWrapper(obj);if(wrapper){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){try{await wrapper._materialize()}catch{return}}if(wrapper.____slothletInternal.mode!=="lazy"||wrapper.____slothletInternal.state.materialized){const hook=obj[kind];if(typeof hook==="function"){hooks.push({apiPath:wrapper.____slothletInternal.apiPath,fn:hook,receiver:obj})}}for(const key of Object.keys(wrapper)){if(!key.startsWith("____"))await collect(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){await collect(obj[key],depth+1)}}catch{}};for(const key of Object.keys(this.api)){if(key==="slothlet"||key==="shutdown"||key==="destroy"||key.startsWith("____"))continue;await collect(this.api[key])}return hooks}async shutdown(){if(!this.isLoaded){return}await this._drainInFlightLoads();boundaryPatchHolders.delete(this.instanceID);if(boundaryPatchHolders.size===0){disableEventEmitterPatching();disableSchedulerPatching();disableEventTargetPatching();cleanupEventEmitterResources()}if(this.instanceID&&this.contextManager){this.contextManager.cleanup(this.instanceID)}if(this.handlers.ownership){this.handlers.ownership.clear()}this.handlers.versionManager?.shutdown();await this.handlers.permissionManager?.shutdown();if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}this.isLoaded=false}debug(code,context={}){if(this.debugLogger){this.debugLogger.log(code,context)}}getAPI(){if(!this.isLoaded){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"getAPI"},null,{validationError:true})}return this.boundApi}getDiagnostics(){return{instanceID:this.instanceID,isLoaded:this.isLoaded,config:this.config,context:this.contextManager?.getDiagnostics()||null,ownership:this.handlers.ownership?.getDiagnostics()||null}}getOwnership(){if(!this.handlers.ownership){return null}return this.handlers.ownership.getDiagnostics()}buildFinalAPI(userApi){return this.builders.apiBuilder.buildFinalAPI(userApi)}}async function slothlet(config){const instance=new Slothlet;const api=await instance.load(config);return api}var stdin_default=slothlet;export{stdin_default as default,slothlet};
|
|
17
|
+
import{isNode,fs,fsp,path,url,createRequire}from"@cldmv/slothlet/helpers/platform";import{getContextManager}from"#factories/context";import{warnIfCoverageWithoutImporter}from"@cldmv/slothlet/processors/loader";import{SlothletError,SlothletWarning,SlothletDebug}from"@cldmv/slothlet/errors";import{registerInstance}from"#handlers/lifecycle-token";import{resolveWrapper}from"#handlers/unified-wrapper";import{isFrameworkInternal}from"#handlers/framework-internals";import{TRUSTED_ROOT}from"#handlers/trusted-root";import{initI18n}from"@cldmv/slothlet/i18n";import{enableEventEmitterPatching,disableEventEmitterPatching,cleanupEventEmitterResources,setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";import{enableSchedulerPatching,disableSchedulerPatching}from"@cldmv/slothlet/helpers/scheduler-context";import{enableEventTargetPatching,disableEventTargetPatching}from"@cldmv/slothlet/helpers/eventtarget-context";import{enableEventTargetPropertyPatching,disableEventTargetPropertyPatching}from"@cldmv/slothlet/helpers/eventtarget-property-context";import{enableObserverPatching,disableObserverPatching}from"@cldmv/slothlet/helpers/observer-context";import{DEFAULT_ROUTINES,RESERVED_EXPORTS}from"@cldmv/slothlet/helpers/defaults";const boundaryPatchHolders=new Set;class Slothlet{static RESERVED_ROOT_KEYS=["slothlet","shutdown","destroy"];static SKIP_PROPS=["__metadata","__type","_materialize","_impl","____slothletInternal"];constructor(){this.SlothletError=SlothletError;this.SlothletWarning=SlothletWarning;this.debugLogger=null;this.instanceID=null;this.config=null;this.envTarget="node";this.api=null;this.boundApi=null;this.contextManager=null;this.isLoaded=false;this.reference=null;this.context=null;this.envSnapshot=null;this._totalLazyCount=0;this._unmaterializedLazyCount=0;this._materializationComplete=false;this._materializationWaiters=[];this._materializationCompleteEmitted=false;this.componentCategories=["helpers","handlers","builders","processors","modes"];for(const category of this.componentCategories){this[category]={}}}async _initializeComponents(){if(this.envTarget==="browser"){await this._initializeComponentsBrowser();return}const baseDir=path.join(path.dirname(url.fileURLToPath(import.meta.url)),"lib");for(const category of this.componentCategories){const categoryDir=path.join(baseDir,category);const files=fs.readdirSync(categoryDir).filter(f=>f.endsWith(".mjs"));for(const file of files){const filePath=path.join(categoryDir,file);try{const module=await import(url.pathToFileURL(filePath).href);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this);if(this.config?.debug?.initialization){this.debug("initialization",{key:"DEBUG_MODE_COMPONENT_INITIALIZED",component:ClassExport.name,category,propertyName:propName})}}}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}}}async _initializeComponentsBrowser(){const BROWSER_COMPONENT_SPECIFIERS=["@cldmv/slothlet/builders/api-assignment","@cldmv/slothlet/builders/api_builder","@cldmv/slothlet/builders/builder","@cldmv/slothlet/builders/modes-processor","#handlers/api-cache-manager","#handlers/api-manager","#handlers/hook-manager","#handlers/lifecycle","#handlers/materialize-manager","#handlers/metadata","#handlers/module-manager","#handlers/ownership","#handlers/permission-manager","#handlers/routine-manager","#handlers/version-manager","@cldmv/slothlet/helpers/config","@cldmv/slothlet/helpers/hint-detector","@cldmv/slothlet/helpers/modes-utils","@cldmv/slothlet/helpers/resolve-from-caller","@cldmv/slothlet/helpers/sanitize","@cldmv/slothlet/helpers/utilities","@cldmv/slothlet/modes/eager","@cldmv/slothlet/modes/lazy","@cldmv/slothlet/processors/flatten","@cldmv/slothlet/processors/loader"];for(const specifier of BROWSER_COMPONENT_SPECIFIERS){const parts=specifier.split("/");const category=specifier.startsWith("#")?parts[0].slice(1):parts[2];const module=await import(specifier);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this)}}}_setupConfigLifecycleSubscribers(){const map=this.config.lifecycle;if(!map){return}const lifecycle=this.handlers.lifecycle;for(const[event,handler]of Object.entries(map)){const handlers=Array.isArray(handler)?handler:[handler];for(const fn of handlers){lifecycle.subscribe(event,fn)}}}_setupLifecycleSubscribers(){if(!this.handlers.lifecycle){return}if(this.handlers.metadata){this.handlers.lifecycle.subscribe("impl:created",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:changed",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:removed",data=>{if(data.apiPath){const rootSegment=data.apiPath.split(".")[0];this.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}})}if(this.handlers.routineManager){this.handlers.lifecycle.subscribe("impl:created",data=>{this.handlers.routineManager.onImplCreated(data)});this.handlers.lifecycle.subscribe("impl:changed",data=>{this.handlers.routineManager.onImplCreated(data)});this.handlers.lifecycle.subscribe("impl:removed",data=>{this.handlers.routineManager.onImplRemoved(data)})}if(this.handlers.ownership){this.handlers.lifecycle.subscribe("impl:created",data=>{const configCollisionMode=this.config?.collision?.api||"merge";const collisionMode=configCollisionMode==="replace"||configCollisionMode==="merge-replace"?configCollisionMode:"merge";const implValue=data.wrapper?.__impl??data.impl;if(typeof implValue==="function"&&implValue.__slothletRoutineStack===true){return}this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})});this.handlers.lifecycle.subscribe("impl:changed",data=>{const configCollisionMode=this.config?.collision?.api||"merge";const collisionMode=configCollisionMode==="replace"||configCollisionMode==="merge-replace"?configCollisionMode:"merge";const implValue=data.wrapper?.__impl??data.impl;if(typeof implValue==="function"&&implValue.__slothletRoutineStack===true){return}const currentOwner=this.handlers.ownership.getCurrentOwner(data.apiPath);if(currentOwner?.moduleID!==data.moduleID){this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})}})}}_registerLazyWrapper(){this._totalLazyCount++;this._unmaterializedLazyCount++;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_REGISTERED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount})}}_onWrapperMaterialized(){this._unmaterializedLazyCount--;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_MATERIALIZED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount,percentage:this._totalLazyCount>0?(this._totalLazyCount-this._unmaterializedLazyCount)/this._totalLazyCount*100:100})}if(this._unmaterializedLazyCount===0&&!this._materializationComplete){this._materializationComplete=true;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_ALL_LAZY_WRAPPERS_MATERIALIZED",total:this._totalLazyCount})}const waiters=this._materializationWaiters.splice(0);for(const resolve of waiters){resolve()}if(this.config?.tracking?.materialization&&!this._materializationCompleteEmitted){this._materializationCompleteEmitted=true;if(this.handlers?.lifecycle){this.handlers.lifecycle.emit("materialized:complete",{total:this._totalLazyCount,timestamp:Date.now()})}}}}_captureEnvSnapshot(envConfig){const rawInclude=envConfig?.include;const include=Array.isArray(rawInclude)?rawInclude.filter(key=>typeof key==="string"):null;const useAllowlist=include!==null&&include.length>0;const raw=useAllowlist?include.reduce((acc,key)=>{if(Object.prototype.hasOwnProperty.call(process.env,key)){acc[key]=process.env[key]}return acc},Object.create(null)):{...process.env};return Object.freeze(raw)}async load(config={},preservedInstanceID=null){this.config=config;this.envTarget=config.platform==="browser"||config.platform!=="node"&&config.manifest!=null?"browser":"node";if(!this.envSnapshot){this.envSnapshot=this.envTarget==="browser"?Object.freeze(Object.create(null)):this._captureEnvSnapshot(config.env)}this.debugLogger=new SlothletDebug(config);await this._initializeComponents();registerInstance(this);if(this.handlers.routineManager){this.handlers.routineManager.reset()}this._setupLifecycleSubscribers();this.config=this.helpers.config.transformConfig(config);if(this.envTarget==="node"){warnIfCoverageWithoutImporter(this.config)}this._setupConfigLifecycleSubscribers();if(this.config?.i18n?.language){initI18n({language:this.config.i18n.language})}this.debugLogger=new SlothletDebug(this.config);this.instanceID=preservedInstanceID||this.helpers.utilities.generateId();this.reference=this.config.reference;this.context=this.config.context;this.contextManager=getContextManager(this.envTarget==="browser"?"live":this.config.runtime);setApiContextChecker(()=>{const ctx=this.contextManager.tryGetContext();return!!(ctx&&ctx.self)});let store;if(preservedInstanceID&&this.contextManager.instances.has(preservedInstanceID)){this.contextManager.cleanup(preservedInstanceID);store=this.contextManager.initialize(this.instanceID,this.config)}else{store=this.contextManager.initialize(this.instanceID,this.config)}Object.defineProperty(store,TRUSTED_ROOT,{value:true,configurable:true});enableEventEmitterPatching();enableSchedulerPatching();enableEventTargetPatching();enableEventTargetPropertyPatching();enableObserverPatching();boundaryPatchHolders.add(this.instanceID);if(typeof this.contextManager.registerEventEmitterContextChecker==="function"){this.contextManager.registerEventEmitterContextChecker()}const baseModuleId=`base_${this.helpers.utilities.generateId().substring(0,8)}`;if(this.config.scanHiddenFolders!==void 0&&!this.config.silent){new this.SlothletWarning("CONFIG_SCAN_HIDDEN_FOLDERS_DEPRECATED",{option:"scanHiddenFolders"})}const baseApi=await this.builders.builder.buildAPI({dir:this.config.dir,mode:this.config.mode,moduleID:baseModuleId,hidden:this.config.hidden??null,scanHiddenFolders:this.config.scanHiddenFolders===true});this.api=baseApi;const apiWithBuiltins=await this.buildFinalAPI(this.api);if(this.handlers.apiCacheManager){this.handlers.apiCacheManager.set(baseModuleId,{endpoint:".",moduleID:baseModuleId,api:this.api,folderPath:this.config.dir,mode:this.config.mode,sanitizeOptions:this.config.sanitize||{},collisionMode:this.config.collision?.initial||"merge",config:{...this.config},timestamp:Date.now()})}this.injectRuntimeMetadataFunctions(apiWithBuiltins);if(this.config.metadata&&typeof this.config.metadata==="object"){for(const[key,value]of Object.entries(this.config.metadata)){this.handlers.metadata.setGlobalMetadata(key,value)}this.handlers.metadata.registerUserMetadata(baseModuleId,this.config.metadata)}if(this.handlers.ownership){this.handlers.ownership.registerSubtree(apiWithBuiltins,baseModuleId,"");this.handlers.ownership.setModuleEndpoint(baseModuleId,".")}if(!this.boundApi){const isCallable=typeof this.api==="function"||this.api&&typeof this.api.default==="function";const proxyTarget=isCallable?function(){}:{};this.boundApi=new Proxy(proxyTarget,{get:(target,prop)=>this.api?this.api[prop]:void 0,set:(target,prop,value)=>{if(this.api){this.api[prop]=value}return true},has:(target,prop)=>this.api?prop in this.api:false,ownKeys:____target=>this.api?Reflect.ownKeys(this.api):[],deleteProperty:(target,prop)=>this.api?delete this.api[prop]:true,apply:(target,thisArg,args)=>this.api?Reflect.apply(this.api,thisArg,args):void 0,construct:(target,args)=>this.api?Reflect.construct(this.api,args):{},getOwnPropertyDescriptor:(target,prop)=>{if(isCallable&&prop==="prototype"){return Object.getOwnPropertyDescriptor(target,prop)}if(this.api&&prop in this.api){const desc=Object.getOwnPropertyDescriptor(this.api,prop);if(desc){return{...desc,configurable:true}}}return void 0}})}store.self=this.boundApi;store.context=this.context||{};store.slothlet=this;if(this.reference&&typeof this.reference==="object"){Object.assign(this.boundApi,this.reference)}if(this.handlers.routineManager){await this.handlers.routineManager.rebuildStacks(this.boundApi);await this.handlers.routineManager.runStartupModeRoutines()}this.isLoaded=true;return this.boundApi}async reload(options={}){const{keepInstanceID=false}=options;if(!this.config?.dir){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"reload",validationError:true})}const operationHistory=this.handlers.apiManager?.state?.operationHistory?[...this.handlers.apiManager.state.operationHistory]:[];await this._clearModuleCaches();const oldInstanceID=this.instanceID;if(!keepInstanceID){this.instanceID=`${oldInstanceID}_reload_${Date.now()}`;if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}}const savedMetadataState=this.handlers.metadata?.exportUserState?.();const savedHooks=this.handlers.hookManager?.exportHooks?.();const wasSealed=this.handlers.permissionManager?.isSealed?.()===true;await this.load(this.config,this.instanceID);if(savedMetadataState&&this.handlers.metadata){this.handlers.metadata.importUserState(savedMetadataState)}if(savedHooks?.length&&this.handlers.hookManager){this.handlers.hookManager.importHooks(savedHooks)}for(const[,store]of this.contextManager.instances){if(store.parentInstanceID===oldInstanceID){store.parentInstanceID=this.instanceID}}if(oldInstanceID&&oldInstanceID!==this.instanceID&&this.contextManager.instances?.has(oldInstanceID)){this.contextManager.cleanup(oldInstanceID)}for(const operation of operationHistory){if(operation.type==="add"){await this.handlers.apiManager.addApiComponent({apiPath:operation.apiPath,folderPath:operation.folderPath,options:{...operation.options||{},recordHistory:false},versionConfig:operation.versionConfig||null})}else if(operation.type==="remove"){if(operation.scopedModuleID){await this.handlers.apiManager.removeApiComponent(operation.scopedModuleID,{scopedApiPath:operation.apiPath,recordHistory:false})}else{await this.handlers.apiManager.removeApiComponent(operation.apiPath,{recordHistory:false})}}else if(operation.type==="addPermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.addRule(operation.rule,operation.ownerModuleID,operation.ruleId)}}else{if(operation.type==="removePermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.removeRule(operation.ruleId,operation.callerModuleID)}}}}if(wasSealed)this.handlers.permissionManager?.seal?.();return this.boundApi}async _clearModuleCaches(){if(!isNode)return;const targetDir=this.config.dir;const require2=createRequire(import.meta.url);const absoluteTargetDir=path.resolve(targetDir);for(const key of Object.keys(require2.cache)){if(key.startsWith(absoluteTargetDir)){delete require2.cache[key]}}}injectRuntimeMetadataFunctions(api){if(!api.slothlet?.metadata){return}const metadataHandler=this.handlers.metadata;api.slothlet.metadata.get=async function slothlet_metadata_get_runtime(path2){return metadataHandler.get(path2)};api.slothlet.metadata.self=function slothlet_metadata_self_runtime(){return metadataHandler.self()};api.slothlet.metadata.caller=function slothlet_metadata_caller_runtime(){return metadataHandler.caller()}}async _drainInFlightLoads(){if(!this.api)return;const pending=[];const seen=new Set;const collect=(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>15||seen.has(obj))return;seen.add(obj);try{if(isFrameworkInternal(obj))return;const wrapper=resolveWrapper(obj);if(wrapper){const mat=wrapper.____slothletInternal.materializationPromise;if(mat)pending.push(mat);for(const key of Object.keys(wrapper)){if(!key.startsWith("____"))collect(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){collect(obj[key],depth+1)}}catch{}};for(const key of Object.keys(this.api)){collect(this.api[key])}if(pending.length>0){await Promise.allSettled(pending)}}async shutdown(){if(!this.isLoaded){return}await this._drainInFlightLoads();boundaryPatchHolders.delete(this.instanceID);if(boundaryPatchHolders.size===0){disableEventEmitterPatching();disableSchedulerPatching();disableEventTargetPatching();disableEventTargetPropertyPatching();disableObserverPatching();cleanupEventEmitterResources()}if(this.instanceID&&this.contextManager){this.contextManager.cleanup(this.instanceID)}if(this.handlers.ownership){this.handlers.ownership.clear()}this.handlers.versionManager?.shutdown();await this.handlers.permissionManager?.shutdown();if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}this.isLoaded=false}debug(code,context={}){if(this.debugLogger){this.debugLogger.log(code,context)}}getAPI(){if(!this.isLoaded){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"getAPI"},null,{validationError:true})}return this.boundApi}getDiagnostics(){return{instanceID:this.instanceID,isLoaded:this.isLoaded,config:this.config,context:this.contextManager?.getDiagnostics()||null,ownership:this.handlers.ownership?.getDiagnostics()||null}}getOwnership(){if(!this.handlers.ownership){return null}return this.handlers.ownership.getDiagnostics()}buildFinalAPI(userApi){return this.builders.apiBuilder.buildFinalAPI(userApi)}}async function slothlet(config){const instance=new Slothlet;const api=await instance.load(config);return api}slothlet.defaults=Object.freeze({routines:DEFAULT_ROUTINES,reservedExports:RESERVED_EXPORTS});var stdin_default=slothlet;export{stdin_default as default,slothlet};
|
package/index.cjs
CHANGED
|
@@ -61,3 +61,23 @@ module.exports = slothlet;
|
|
|
61
61
|
* const api = await slothlet({ dir: "./api" });
|
|
62
62
|
*/
|
|
63
63
|
module.exports.slothlet = slothlet; // optional named alias
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* `slothlet.defaults` (#341), attached best-effort for CJS consumers.
|
|
67
|
+
*
|
|
68
|
+
* @description
|
|
69
|
+
* The ESM entry (`index.mjs`) attaches `slothlet.defaults` via a static import, so it is set
|
|
70
|
+
* before any `import`'s continuation runs. A CJS `require()` cannot await a promise before
|
|
71
|
+
* returning, so this assignment resolves on the microtask queue shortly after `require()`
|
|
72
|
+
* returns rather than synchronously within it — every realistic use (inside an async function,
|
|
73
|
+
* after any `await`, or building a `routines` array to pass to a later `slothlet({...})` call)
|
|
74
|
+
* observes it populated; only code reading `require("@cldmv/slothlet").defaults` in the same
|
|
75
|
+
* synchronous tick as the `require()` call itself would see `undefined` first. Best-effort: a
|
|
76
|
+
* failed re-import (an unsupported environment, a resolution error) is swallowed rather than left
|
|
77
|
+
* as an unhandled rejection — `.defaults` simply stays unset in that case.
|
|
78
|
+
*/
|
|
79
|
+
import("./index.mjs")
|
|
80
|
+
.then((mod) => {
|
|
81
|
+
module.exports.defaults = mod.default.defaults;
|
|
82
|
+
})
|
|
83
|
+
.catch(() => {});
|
package/index.mjs
CHANGED
|
@@ -16,6 +16,10 @@
|
|
|
16
16
|
* @module @cldmv/slothlet
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
+
// Single source of truth for the `slothlet.defaults` namespace (#341) — a helper module with no
|
|
20
|
+
// node:* specifiers, safe for the browser bundle's static-import graph (#123).
|
|
21
|
+
import { DEFAULT_ROUTINES, RESERVED_EXPORTS } from "@cldmv/slothlet/helpers/defaults";
|
|
22
|
+
|
|
19
23
|
// Custom uncaught exception handler for SlothletError
|
|
20
24
|
// `process` is undefined in a browser, so define the handler unconditionally but
|
|
21
25
|
// only register it under Node — keeps this entry module loadable in a browser (#123).
|
|
@@ -142,3 +146,13 @@ const slothlet = async (options = {}) => {
|
|
|
142
146
|
// emits the named `export { slothlet }` alongside the default export.
|
|
143
147
|
export default slothlet;
|
|
144
148
|
export { slothlet };
|
|
149
|
+
|
|
150
|
+
// `slothlet.defaults` (#341) is attached on the REAL implementation (`src/slothlet.mjs`'s own
|
|
151
|
+
// exported function), but this file's `slothlet` is a distinct wrapper that only imports that
|
|
152
|
+
// implementation lazily, inside the call — so it carries none of the inner function's static
|
|
153
|
+
// properties. Attach the identical, single-sourced value here too (see the static import above),
|
|
154
|
+
// so `slothlet.defaults` is available synchronously through every entry point.
|
|
155
|
+
slothlet.defaults = Object.freeze({
|
|
156
|
+
routines: DEFAULT_ROUTINES,
|
|
157
|
+
reservedExports: RESERVED_EXPORTS
|
|
158
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cldmv/slothlet",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.16.0",
|
|
4
4
|
"moduleVersions": {
|
|
5
5
|
"lazy": "3.0.0",
|
|
6
6
|
"eager": "3.0.0",
|
|
@@ -271,7 +271,7 @@
|
|
|
271
271
|
"zero-dependencies"
|
|
272
272
|
],
|
|
273
273
|
"engines": {
|
|
274
|
-
"node": ">=22.
|
|
274
|
+
"node": ">=22.12.0"
|
|
275
275
|
},
|
|
276
276
|
"author": {
|
|
277
277
|
"name": "Shinrai",
|
|
@@ -314,14 +314,15 @@
|
|
|
314
314
|
"devDependencies": {
|
|
315
315
|
"@cldmv/fix-headers": "^1.3.10",
|
|
316
316
|
"@cldmv/vitest-runner": "^1.2.0",
|
|
317
|
-
"@eslint/css": "^
|
|
317
|
+
"@eslint/css": "^2.0.0",
|
|
318
318
|
"@eslint/js": "^10.0.1",
|
|
319
319
|
"@eslint/json": "^2.0.1",
|
|
320
320
|
"@eslint/markdown": "^8.0.3",
|
|
321
321
|
"@types/node": "^26.1.1",
|
|
322
|
-
"@vitest/browser": "^
|
|
323
|
-
"@vitest/browser-playwright": "^
|
|
324
|
-
"@vitest/coverage-v8": "^
|
|
322
|
+
"@vitest/browser": "^5.0.0",
|
|
323
|
+
"@vitest/browser-playwright": "^5.0.0",
|
|
324
|
+
"@vitest/coverage-v8": "^5.0.0",
|
|
325
|
+
"@vitest/istanbul-lib-coverage": "^1.0.1",
|
|
325
326
|
"acorn": "^8.18.0",
|
|
326
327
|
"chalk": "^6.0.0",
|
|
327
328
|
"chokidar": "^5.0.0",
|
|
@@ -338,7 +339,7 @@
|
|
|
338
339
|
"prettier": "^3.9.5",
|
|
339
340
|
"shx": "^0.4.0",
|
|
340
341
|
"typescript": "^6.0.3",
|
|
341
|
-
"vitest": "^
|
|
342
|
+
"vitest": "^5.0.0"
|
|
342
343
|
},
|
|
343
344
|
"optionalDependencies": {
|
|
344
345
|
"@rolldown/binding-linux-x64-gnu": "1.1.3"
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// AUTO-GENERATED by tools/build/build-typestubs.mjs — do not edit.
|
|
2
|
-
//
|
|
2
|
+
// Self-contained copy: this subpath is internal and not published by @cldmv/slothlet-types.
|
|
3
3
|
export {};
|
|
@@ -1,3 +1,131 @@
|
|
|
1
1
|
// AUTO-GENERATED by tools/build/build-typestubs.mjs — do not edit.
|
|
2
|
-
//
|
|
3
|
-
|
|
2
|
+
// Self-contained copy: this subpath is internal and not published by @cldmv/slothlet-types.
|
|
3
|
+
/**
|
|
4
|
+
* Manages unified API assignment logic
|
|
5
|
+
* @class ApiAssignment
|
|
6
|
+
* @extends ComponentBase
|
|
7
|
+
* @package
|
|
8
|
+
*
|
|
9
|
+
* @description
|
|
10
|
+
* Class-based utility for assigning values to API paths with collision detection,
|
|
11
|
+
* wrapper sync, and merge operations. Extends ComponentBase for Slothlet property access.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* const assignment = new ApiAssignment(slothlet);
|
|
15
|
+
* assignment.assignToApiPath(api, "math", mathWrapper, {});
|
|
16
|
+
*/
|
|
17
|
+
export class ApiAssignment extends ComponentBase {
|
|
18
|
+
static slothletProperty: string;
|
|
19
|
+
/**
|
|
20
|
+
* Create an ApiAssignment instance.
|
|
21
|
+
* @param {object} slothlet - Slothlet class instance.
|
|
22
|
+
* @package
|
|
23
|
+
*
|
|
24
|
+
* @description
|
|
25
|
+
* Creates ApiAssignment with ComponentBase support for config access.
|
|
26
|
+
*/
|
|
27
|
+
constructor(slothlet: object);
|
|
28
|
+
/**
|
|
29
|
+
* Check if a value is a UnifiedWrapper proxy
|
|
30
|
+
* @param {unknown} value - Value to check
|
|
31
|
+
* @returns {boolean} True if value is a wrapper proxy
|
|
32
|
+
* @private
|
|
33
|
+
*/
|
|
34
|
+
private isWrapperProxy;
|
|
35
|
+
/**
|
|
36
|
+
* Merge a callable-vs-callable collision's off-slot folder into the callable that kept the slot.
|
|
37
|
+
*
|
|
38
|
+
* Under the documented `merge` row the first-loaded callable holds the slot, so the folder
|
|
39
|
+
* composes off-slot; its members still belong on the surface — everything the survivor does not
|
|
40
|
+
* already define (first loaded wins conflicts). Idempotent: the handle is cleared on the first
|
|
41
|
+
* run, so a later settle pass over the same wrapper is a no-op.
|
|
42
|
+
*
|
|
43
|
+
* @param {object} keptWrapper - The surviving callable's wrapper (holds the off-slot handle).
|
|
44
|
+
* @returns {void}
|
|
45
|
+
* @package
|
|
46
|
+
*/
|
|
47
|
+
mergeOffSlotCollisionFolder(keptWrapper: object): void;
|
|
48
|
+
/**
|
|
49
|
+
* Assign a value to an API object at a given property key.
|
|
50
|
+
* Handles wrapper sync, collision detection, and proper proxy preservation.
|
|
51
|
+
*
|
|
52
|
+
* @param {Object} targetApi - Target object to assign to (may be a UnifiedWrapper proxy)
|
|
53
|
+
* @param {string|symbol} key - Property name to assign
|
|
54
|
+
* @param {unknown} value - Value to assign (may be UnifiedWrapper proxy, raw value, etc.)
|
|
55
|
+
* @param {Object} options - Assignment options
|
|
56
|
+
* @param {boolean} [options.allowOverwrite=false] - Allow overwriting existing non-wrapper values
|
|
57
|
+
* @param {boolean} [options.mutateExisting=false] - Sync existing wrappers instead of replacing
|
|
58
|
+
* @param {boolean} [options.useCollisionDetection=false] - Enable collision detection using config.collision mode
|
|
59
|
+
* @param {Object} [options.config] - Slothlet config (uses config.collision.initial or config.collision.api)
|
|
60
|
+
* @param {string} [options.collisionContext="initial"] - Collision context: "initial" or "api"
|
|
61
|
+
* @param {Function} [options.syncWrapper] - Function to sync two wrapper proxies
|
|
62
|
+
* @param {string} [options.collisionMode="merge"] - Mode used by the mutateExisting/hot-reload path (Case 1) when syncing two existing wrappers
|
|
63
|
+
* @param {string|null} [options.collisionModeOverride=null] - Per-call override (e.g. `api.add()`'s `forceOverwrite`) for the collision-detection branch (Case 2); takes precedence over `config.collision[collisionContext]`
|
|
64
|
+
* @param {string|null} [options.moduleID=null] - Module id to associate with this assignment, forwarded to `syncWrapper`
|
|
65
|
+
* @returns {Promise<boolean>} True if assignment succeeded, false if blocked by collision or other constraint
|
|
66
|
+
*
|
|
67
|
+
* @description
|
|
68
|
+
* This function encapsulates all assignment patterns from processFiles:
|
|
69
|
+
* - Direct assignment when no collision
|
|
70
|
+
* - Wrapper sync when both existing and new are wrappers
|
|
71
|
+
* - Collision detection using config.collision[context] mode (merge/replace/error/skip/warn)
|
|
72
|
+
* - Proper handling of UnifiedWrapper proxies (preserves them, doesn't unwrap)
|
|
73
|
+
*
|
|
74
|
+
* Async (#369) because Case 1 awaits `syncWrapper` — itself async since it force-materializes
|
|
75
|
+
* both sides of a collision (#364). Every caller must await this call: a caller that captures
|
|
76
|
+
* the return value in an `if (assigned)`/truthy check and does NOT await first sees a Promise
|
|
77
|
+
* object, which is always truthy regardless of what it resolves to.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* // Direct assignment
|
|
81
|
+
* await assignment.assignToApiPath(api, "math", mathWrapper, {});
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* // Sync existing wrapper with new data
|
|
85
|
+
* await assignment.assignToApiPath(api, "config", newConfigWrapper, { mutateExisting: true, syncWrapper });
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* // With collision detection
|
|
89
|
+
* await assignment.assignToApiPath(api.math, "add", addFunction, {
|
|
90
|
+
* useCollisionDetection: true,
|
|
91
|
+
* config,
|
|
92
|
+
* collisionContext: "initial"
|
|
93
|
+
* });
|
|
94
|
+
*/
|
|
95
|
+
assignToApiPath(targetApi: Object, key: string | symbol, value: unknown, options?: {
|
|
96
|
+
allowOverwrite?: boolean | undefined;
|
|
97
|
+
mutateExisting?: boolean | undefined;
|
|
98
|
+
useCollisionDetection?: boolean | undefined;
|
|
99
|
+
config?: Object | undefined;
|
|
100
|
+
collisionContext?: string | undefined;
|
|
101
|
+
syncWrapper?: Function | undefined;
|
|
102
|
+
collisionMode?: string | undefined;
|
|
103
|
+
collisionModeOverride?: string | null | undefined;
|
|
104
|
+
moduleID?: string | null | undefined;
|
|
105
|
+
}): Promise<boolean>;
|
|
106
|
+
/**
|
|
107
|
+
* Recursively merge a source object into a target object using assignToApiPath logic.
|
|
108
|
+
*
|
|
109
|
+
* @param {Object} targetApi - Target object
|
|
110
|
+
* @param {Object} sourceApi - Source object to merge from
|
|
111
|
+
* @param {Object} options - Assignment options (passed to assignToApiPath)
|
|
112
|
+
* @param {boolean} [options.removeMissing=false] - Remove keys from target that don't exist in source
|
|
113
|
+
* @returns {Promise<void>}
|
|
114
|
+
*
|
|
115
|
+
* @description
|
|
116
|
+
* Recursively walks the source object and assigns each value to the target using
|
|
117
|
+
* assignToApiPath. This provides consistent merge behavior for both initial build
|
|
118
|
+
* and hot reload operations.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* await assignment.mergeApiObjects(api.config, newConfigApi, {
|
|
122
|
+
* mutateExisting: true,
|
|
123
|
+
* syncWrapper,
|
|
124
|
+
* removeMissing: false
|
|
125
|
+
* });
|
|
126
|
+
*/
|
|
127
|
+
mergeApiObjects(targetApi: Object, sourceApi: Object, options?: {
|
|
128
|
+
removeMissing?: boolean | undefined;
|
|
129
|
+
}): Promise<void>;
|
|
130
|
+
}
|
|
131
|
+
import { ComponentBase } from "#factories/component-base";
|