@cldmv/slothlet 3.15.2 → 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 +8 -6
- 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/hook-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 +17 -0
- 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/modes/lazy.mjs +1 -1
- package/dist/lib/processors/flatten.mjs +1 -1
- package/dist/lib/processors/loader.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 +42 -0
- 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
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";class EagerMode extends ComponentBase{static slothletProperty="eager";constructor(slothlet){super(slothlet)}async buildAPI({dir,apiPathPrefix="",collisionContext="initial",moduleID,apiDepth=
|
|
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};
|
package/dist/lib/modes/lazy.mjs
CHANGED
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{ComponentBase}from"#factories/component-base";class LazyMode extends ComponentBase{static slothletProperty="lazy";constructor(slothlet){super(slothlet)}createNamedMaterializeFunc(apiPath,handler){const safePath=String(apiPath||"api").replace(/\./g,"__").replace(/[^A-Za-z0-9_$]/g,"_");const normalized=/^[A-Za-z_$]/.test(safePath[0])?safePath:`_${safePath}`;const funcName=`${normalized}__lazy_materializeFunc`;return{[funcName]:async function(...args){return handler(...args)}}[funcName]}async buildAPI({dir,apiPathPrefix="",collisionContext="initial",collisionMode=null,moduleID,apiDepth=
|
|
17
|
+
import{ComponentBase}from"#factories/component-base";import{DEFAULT_API_DEPTH}from"@cldmv/slothlet/helpers/defaults";class LazyMode extends ComponentBase{static slothletProperty="lazy";constructor(slothlet){super(slothlet)}createNamedMaterializeFunc(apiPath,handler){const safePath=String(apiPath||"api").replace(/\./g,"__").replace(/[^A-Za-z0-9_$]/g,"_");const normalized=/^[A-Za-z_$]/.test(safePath[0])?safePath:`_${safePath}`;const funcName=`${normalized}__lazy_materializeFunc`;return{[funcName]:async function(...args){return handler(...args)}}[funcName]}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}){this.slothlet.debug("modes",{key:"DEBUG_MODE_BUILD_LAZY_API_CALLED",apiPathPrefix,collisionMode,collisionContext});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,"lazy",true,false,false,apiPathPrefix,collisionContext,moduleID,dir,cacheBust,collisionMode,rootUnwrap);return modesProcessor.applyRootContributor(api,rootDefaultFunction,"lazy")}}export{LazyMode};
|
|
@@ -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};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{ComponentBase}from"#factories/component-base";import{fsp,path,url,createRequire}from"@cldmv/slothlet/helpers/platform";import{compilePattern}from"@cldmv/slothlet/helpers/pattern-matcher";import{isFrameworkReservedKey}from"#handlers/unified-wrapper";import{SlothletWarning}from"@cldmv/slothlet/errors";const RUNTIME_EXTERNALIZED=!("env"in import.meta);function warnIfCoverageWithoutImporter(config,{worker=globalThis.__vitest_worker__,externalized=RUNTIME_EXTERNALIZED}={}){if(worker?.config?.coverage?.enabled!==true)return false;if(!externalized)return false;if(typeof config?.import==="function")return false;if(config?.silent)return false;new SlothletWarning("WARNING_COVERAGE_IMPORTER_UNSET",{});return true}function compileHidden(globs){if(!globs)return null;const list=Array.isArray(globs)?globs:[globs];const rules=[];for(const g of list){if(typeof g!=="string"||g.length===0)continue;const negated=g.startsWith("!");const body=(negated?g.slice(1):g).replace(/\//g,".");if(body.length===0)continue;rules.push({negated,match:compilePattern(body)})}if(!rules.length)return null;return relDotted=>{let hidden=false;for(const rule of rules){if(rule.match(relDotted))hidden=!rule.negated}return hidden}}class Loader extends ComponentBase{static slothletProperty="loader";constructor(slothlet){super(slothlet)}async loadModule(filePath,instanceID,moduleID,cacheBust=null){try{if(this.slothlet.envTarget==="browser"){return this.#loadModuleBrowser(filePath)}if(filePath.endsWith(".cjs")){return this.#loadCJSIsolated(filePath)}const isTypeScript=filePath.endsWith(".ts")||filePath.endsWith(".mts");const typescriptConfig=this.slothlet.config?.typescript;let moduleUrl;if(isTypeScript&&typescriptConfig?.enabled){const mode=typescriptConfig.mode;if(mode==="strict"){if(!typescriptConfig.types?.output){throw new this.SlothletError("TS_STRICT_REQUIRES_OUTPUT",{},null,{validationError:true})}if(!typescriptConfig.types?.interfaceName){throw new this.SlothletError("TS_STRICT_REQUIRES_INTERFACE_NAME",{},null,{validationError:true})}if(!this.slothlet._typesGenerated){const{fork}=await import("child_process");const path2=await import("path");const{fileURLToPath}=await import("url");const __dirname=path2.dirname(fileURLToPath(import.meta.url));const scriptPath=path2.resolve(__dirname,"../../../tools/build/generate-types-worker.mjs");const childConfig=JSON.stringify({dir:this.slothlet.config.root||this.slothlet.config.dir,mode:"eager",typescript:{enabled:true,mode:"fast"},types:typescriptConfig.types});await new Promise((resolve,reject)=>{const child=fork(scriptPath,[],{stdio:["pipe","pipe","pipe","ipc"],env:{...process.env,SLOTHLET_CONFIG:childConfig}});let errorOutput="";child.stderr?.on("data",data=>{errorOutput+=data.toString()});child.on("message",msg=>{if(msg.type==="success"){this.slothlet._typesGenerated=true;resolve()}else if(msg.type==="error"){reject(new this.SlothletError("TS_TYPE_GENERATION_FAILED",{},{message:msg.error}))}});child.on("error",error=>{reject(new this.SlothletError("TS_TYPE_GENERATION_FORK_FAILED",{},error))});child.on("exit",code=>{if(code!==0&&!this.slothlet._typesGenerated){reject(new this.SlothletError("TS_TYPE_GENERATION_PROCESS_EXITED",{code,output:errorOutput},null,{validationError:true}))}})})}const{transformTypeScriptStrict,writeTransformedToCache,formatDiagnostics}=await import("@cldmv/slothlet/processors/typescript");const strictTransform=async tsPath=>{const result=await transformTypeScriptStrict(tsPath,{target:typescriptConfig.target,module:typescriptConfig.module,strict:typescriptConfig.strict,typeDefinitionPath:typescriptConfig.types.output,compilerOptions:typescriptConfig.compilerOptions});if(result.diagnostics&&result.diagnostics.length>0){const ts=await import("typescript");const errors=formatDiagnostics(result.diagnostics,ts.default);const error=new this.SlothletError("TS_TYPE_CHECK_ERRORS",{filePath:tsPath,errors:errors.join("\n")},null,{validationError:true});error.diagnostics=result.diagnostics;throw error}return result.code};const entryCode=await strictTransform(filePath);moduleUrl=await this.#buildTypescriptModuleUrl(writeTransformedToCache,filePath,entryCode,instanceID,moduleID,cacheBust,strictTransform)}else{const{transformTypeScript,writeTransformedToCache}=await import("@cldmv/slothlet/processors/typescript");const transformOptions={target:typescriptConfig.target,sourcemap:typescriptConfig.sourcemap};const transformedCode=await transformTypeScript(filePath,transformOptions);const transform=tsPath=>transformTypeScript(tsPath,transformOptions);moduleUrl=await this.#buildTypescriptModuleUrl(writeTransformedToCache,filePath,transformedCode,instanceID,moduleID,cacheBust,transform)}}else{const fileUrl=url.pathToFileURL(filePath).href;moduleUrl=`${fileUrl}?slothlet_instance=${instanceID}`;if(moduleID){moduleUrl+=`&module=${moduleID}`}if(cacheBust){moduleUrl+=`&_reload=${cacheBust}`}}const customImport=this.slothlet?.config?.import;const module=customImport?await customImport(moduleUrl):await import(moduleUrl);return module}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}#loadCJSIsolated(filePath){const requireFn=createRequire(filePath);const resolved=requireFn.resolve(filePath);delete requireFn.cache[resolved];const exports=requireFn(resolved);delete requireFn.cache[resolved];const namespace={default:exports};if(exports!==null&&typeof exports==="object"){for(const key of Object.keys(exports)){if(key!=="default"){namespace[key]=exports[key]}}}return namespace}async#buildTypescriptModuleUrl(writeTransformedToCache,filePath,code,instanceID,moduleID,cacheBust,transform){const{url:url2,cacheDir}=await writeTransformedToCache(filePath,code,instanceID,transform);(this.slothlet._typescriptCacheDirs??=new Set).add(cacheDir);let moduleUrl=`${url2}?slothlet_instance=${instanceID}`;if(moduleID){moduleUrl+=`&module=${moduleID}`}if(cacheBust){moduleUrl+=`&_reload=${cacheBust}`}return moduleUrl}async scanDirectory(dir,options={}){if(this.slothlet.envTarget==="browser"){return this.#scanDirectoryBrowser(dir,options)}const typescriptConfig=this.slothlet.config?.typescript;const defaultExtensions=[".mjs",".cjs",".js"];const typescriptExtensions=typescriptConfig?.enabled?[".ts",".mts"]:[];const allExtensions=[...defaultExtensions,...typescriptExtensions];const{recursive=true,extensions=allExtensions,isRootScan=true,currentDepth=0,maxDepth=Infinity,fileFilter=null,hidden=null,scanHiddenFolders=false,rootDir=dir}=options;const hiddenMatcher=typeof hidden==="function"?hidden:compileHidden(hidden);const apiRel=p=>path.relative(rootDir,p).split(path.sep).join(".");const hasHiddenPrefix=name=>name.startsWith(".")||name.startsWith("__");try{await fsp.stat(dir)}catch(error){throw new this.SlothletError("INVALID_DIRECTORY",{dir},error)}const structure={files:[],directories:[]};const entries=await fsp.readdir(dir,{withFileTypes:true});for(const entry of entries){const fullPath=path.join(dir,entry.name);if(entry.isDirectory()){if(fileFilter){continue}if(!scanHiddenFolders&&hasHiddenPrefix(entry.name)){continue}if(hiddenMatcher&&hiddenMatcher(apiRel(fullPath))){continue}if(recursive&¤tDepth<maxDepth){const subStructure=await this.scanDirectory(fullPath,{...options,isRootScan:false,currentDepth:currentDepth+1,hidden:hiddenMatcher,scanHiddenFolders,rootDir});if(subStructure.files.length===0&&subStructure.directories.length===0){continue}structure.directories.push({path:fullPath,name:entry.name,children:subStructure})}}else if(entry.isFile()){const ext=path.extname(entry.name);if(extensions.includes(ext)){if(hasHiddenPrefix(entry.name)){continue}if(fileFilter&&!fileFilter(entry.name)){continue}const nameWithoutExt=path.basename(entry.name,ext);if(hiddenMatcher&&hiddenMatcher(apiRel(path.join(dir,nameWithoutExt)))){continue}if(isFrameworkReservedKey(nameWithoutExt)){throw new this.SlothletError("MODULE_RESERVED_FILENAME",{file:entry.name,dir},null,{validationError:true})}structure.files.push({path:fullPath,name:nameWithoutExt,fullName:entry.name,moduleID:this.slothlet.helpers.sanitize.getModuleId(fullPath,dir)})}}}if(isRootScan&&structure.files.length===0&&structure.directories.length===0&&!this.____config?.silent){new this.SlothletWarning("WARN_DIRECTORY_EMPTY",{dir,resolvedPath:path.resolve(dir)})}return structure}#scanDirectoryBrowser(dir,options={}){const manifest=this.slothlet.config?.manifest;if(!manifest){throw new this.SlothletError("INVALID_CONFIG_BROWSER_REQUIRES_MANIFEST",{},null,{validationError:true})}const configBase=(this.slothlet.config?.dir||"").replace(/\/$/,"");let relativePath=(dir||"").replace(/\/$/,"");if(configBase&&relativePath.startsWith(configBase)){relativePath=relativePath.slice(configBase.length).replace(/^\/|\/$/g,"")}const isRoot=!relativePath||relativePath==="/"||relativePath===".";const node=isRoot?manifest:this.#findManifestNode(manifest,relativePath);if(!node){throw new this.SlothletError("INVALID_DIRECTORY",{dir},null)}return this.#manifestNodeToStructure(node,dir,options)}#findManifestNode(node,targetPath){const normalised=targetPath.replace(/\\/g,"/").replace(/^\/|\/$/g,"");for(const dir of node.directories||[]){const dirPath=(dir.path||dir.name||"").replace(/\\/g,"/").replace(/^\/|\/$/g,"");if(dirPath===normalised)return dir.children||dir;const found=this.#findManifestNode(dir.children||dir,normalised);if(found)return found}return null}#manifestNodeToStructure(node,rootPath,options={}){const{fileFilter=null}=options;const ALLOWED_EXTS=[".mjs",".cjs",".js"];const structure={files:[],directories:[]};for(const file of node.files||[]){const filePath=file.path||file.relativePath||"";const fullName=file.fullName||filePath.split("/").pop();const lastDot=fullName.lastIndexOf(".");const ext=lastDot>=0?fullName.slice(lastDot):"";if(!ALLOWED_EXTS.includes(ext))continue;if(fullName.startsWith("__"))continue;if(fileFilter&&!fileFilter(fullName))continue;const name=file.name||(lastDot>=0?fullName.slice(0,lastDot):fullName);if(isFrameworkReservedKey(name)){throw new this.SlothletError("MODULE_RESERVED_FILENAME",{file:fullName,dir:rootPath},null,{validationError:true})}structure.files.push({path:filePath,name,fullName,moduleID:this.slothlet.helpers.sanitize.getModuleId(filePath,rootPath)})}if(!fileFilter){for(const dir of node.directories||[]){const dirPath=dir.path||dir.name||"";structure.directories.push({path:dirPath,name:dir.name||dirPath.split("/").pop(),children:this.#manifestNodeToStructure(dir.children||dir,dirPath,options)})}}return structure}async#loadModuleBrowser(filePath){const resolveModuleSpecifier=this.slothlet.config?.resolveModuleSpecifier??(({path:p})=>{const base=this.slothlet.config?.base??this.slothlet.config?.dir??"";const leadingSlash=base.startsWith("/")?"":"/";const baseUrl=/^[a-zA-Z][\w+\-.]*:\/\//.test(base)?base.endsWith("/")?base:base+"/":"file://"+leadingSlash+base.replace(/\/?$/,"/");return new URL(p,baseUrl).href});const fullName=filePath.split("/").pop();const lastDot=fullName.lastIndexOf(".");const name=lastDot>=0?fullName.slice(0,lastDot):fullName;const specifier=resolveModuleSpecifier({path:filePath,name,fullName});const module=await import(specifier);return module}extractExports(module){const exports={};if(module.default!==void 0){exports.default=module.default}for(const key of Object.keys(module)){if(key!=="default"&&key!=="module.exports"&&typeof key==="string"){if(isFrameworkReservedKey(key)){throw new this.SlothletError("MODULE_RESERVED_EXPORT",{name:key},null,{validationError:true})}exports[key]=module[key]}}if(exports.default&&typeof exports.default==="object"&&exports.default!==null&&"default"in exports.default){const rootNamedKeys=Object.keys(exports).filter(k=>k!=="default"&&k!=="module.exports");const defaultKeys=Object.keys(exports.default).filter(k=>k!=="default");const isCJSPattern=rootNamedKeys.every(k=>k in exports.default);if(isCJSPattern&&defaultKeys.length>0){exports.default=exports.default.default}}return exports}}export{Loader,warnIfCoverageWithoutImporter};
|
|
17
|
+
import{ComponentBase}from"#factories/component-base";import{DEFAULT_API_DEPTH}from"@cldmv/slothlet/helpers/defaults";import{fsp,path,url,createRequire}from"@cldmv/slothlet/helpers/platform";import{compilePattern}from"@cldmv/slothlet/helpers/pattern-matcher";import{isFrameworkReservedKey}from"#handlers/unified-wrapper";import{SlothletWarning}from"@cldmv/slothlet/errors";const RUNTIME_EXTERNALIZED=!("env"in import.meta);function warnIfCoverageWithoutImporter(config,{worker=globalThis.__vitest_worker__,externalized=RUNTIME_EXTERNALIZED}={}){if(worker?.config?.coverage?.enabled!==true)return false;if(!externalized)return false;if(typeof config?.import==="function")return false;if(config?.silent)return false;new SlothletWarning("WARNING_COVERAGE_IMPORTER_UNSET",{});return true}function compileHidden(globs){if(!globs)return null;const list=Array.isArray(globs)?globs:[globs];const rules=[];for(const g of list){if(typeof g!=="string"||g.length===0)continue;const negated=g.startsWith("!");const body=(negated?g.slice(1):g).replace(/\//g,".");if(body.length===0)continue;rules.push({negated,match:compilePattern(body)})}if(!rules.length)return null;return relDotted=>{let hidden=false;for(const rule of rules){if(rule.match(relDotted))hidden=!rule.negated}return hidden}}class Loader extends ComponentBase{static slothletProperty="loader";constructor(slothlet){super(slothlet)}async loadModule(filePath,instanceID,moduleID,cacheBust=null){try{if(this.slothlet.envTarget==="browser"){return this.#loadModuleBrowser(filePath)}if(filePath.endsWith(".cjs")){return this.#loadCJSIsolated(filePath)}const isTypeScript=filePath.endsWith(".ts")||filePath.endsWith(".mts");const typescriptConfig=this.slothlet.config?.typescript;let moduleUrl;if(isTypeScript&&typescriptConfig?.enabled){const mode=typescriptConfig.mode;if(mode==="strict"){if(!typescriptConfig.types?.output){throw new this.SlothletError("TS_STRICT_REQUIRES_OUTPUT",{},null,{validationError:true})}if(!typescriptConfig.types?.interfaceName){throw new this.SlothletError("TS_STRICT_REQUIRES_INTERFACE_NAME",{},null,{validationError:true})}if(!this.slothlet._typesGenerated){const{fork}=await import("child_process");const path2=await import("path");const{fileURLToPath}=await import("url");const __dirname=path2.dirname(fileURLToPath(import.meta.url));const scriptPath=path2.resolve(__dirname,"../../../tools/build/generate-types-worker.mjs");const childConfig=JSON.stringify({dir:this.slothlet.config.root||this.slothlet.config.dir,mode:"eager",typescript:{enabled:true,mode:"fast"},types:typescriptConfig.types});await new Promise((resolve,reject)=>{const child=fork(scriptPath,[],{stdio:["pipe","pipe","pipe","ipc"],env:{...process.env,SLOTHLET_CONFIG:childConfig}});let errorOutput="";child.stderr?.on("data",data=>{errorOutput+=data.toString()});child.on("message",msg=>{if(msg.type==="success"){this.slothlet._typesGenerated=true;resolve()}else if(msg.type==="error"){reject(new this.SlothletError("TS_TYPE_GENERATION_FAILED",{},{message:msg.error}))}});child.on("error",error=>{reject(new this.SlothletError("TS_TYPE_GENERATION_FORK_FAILED",{},error))});child.on("exit",code=>{if(code!==0&&!this.slothlet._typesGenerated){reject(new this.SlothletError("TS_TYPE_GENERATION_PROCESS_EXITED",{code,output:errorOutput},null,{validationError:true}))}})})}const{transformTypeScriptStrict,writeTransformedToCache,formatDiagnostics}=await import("@cldmv/slothlet/processors/typescript");const strictTransform=async tsPath=>{const result=await transformTypeScriptStrict(tsPath,{target:typescriptConfig.target,module:typescriptConfig.module,strict:typescriptConfig.strict,typeDefinitionPath:typescriptConfig.types.output,compilerOptions:typescriptConfig.compilerOptions});if(result.diagnostics&&result.diagnostics.length>0){const ts=await import("typescript");const errors=formatDiagnostics(result.diagnostics,ts.default);const error=new this.SlothletError("TS_TYPE_CHECK_ERRORS",{filePath:tsPath,errors:errors.join("\n")},null,{validationError:true});error.diagnostics=result.diagnostics;throw error}return result.code};const entryCode=await strictTransform(filePath);moduleUrl=await this.#buildTypescriptModuleUrl(writeTransformedToCache,filePath,entryCode,instanceID,moduleID,cacheBust,strictTransform)}else{const{transformTypeScript,writeTransformedToCache}=await import("@cldmv/slothlet/processors/typescript");const transformOptions={target:typescriptConfig.target,sourcemap:typescriptConfig.sourcemap};const transformedCode=await transformTypeScript(filePath,transformOptions);const transform=tsPath=>transformTypeScript(tsPath,transformOptions);moduleUrl=await this.#buildTypescriptModuleUrl(writeTransformedToCache,filePath,transformedCode,instanceID,moduleID,cacheBust,transform)}}else{const fileUrl=url.pathToFileURL(filePath).href;moduleUrl=`${fileUrl}?slothlet_instance=${instanceID}`;if(moduleID){moduleUrl+=`&module=${moduleID}`}if(cacheBust){moduleUrl+=`&_reload=${cacheBust}`}}const customImport=this.slothlet?.config?.import;const module=customImport?await customImport(moduleUrl):await import(moduleUrl);return module}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}#loadCJSIsolated(filePath){const requireFn=createRequire(filePath);const resolved=requireFn.resolve(filePath);delete requireFn.cache[resolved];const exports=requireFn(resolved);delete requireFn.cache[resolved];const namespace={default:exports};if(exports!==null&&typeof exports==="object"){for(const key of Object.keys(exports)){if(key!=="default"){namespace[key]=exports[key]}}}return namespace}async#buildTypescriptModuleUrl(writeTransformedToCache,filePath,code,instanceID,moduleID,cacheBust,transform){const{url:url2,cacheDir}=await writeTransformedToCache(filePath,code,instanceID,transform);(this.slothlet._typescriptCacheDirs??=new Set).add(cacheDir);let moduleUrl=`${url2}?slothlet_instance=${instanceID}`;if(moduleID){moduleUrl+=`&module=${moduleID}`}if(cacheBust){moduleUrl+=`&_reload=${cacheBust}`}return moduleUrl}async scanDirectory(dir,options={}){if(this.slothlet.envTarget==="browser"){return this.#scanDirectoryBrowser(dir,options)}const typescriptConfig=this.slothlet.config?.typescript;const defaultExtensions=[".mjs",".cjs",".js"];const typescriptExtensions=typescriptConfig?.enabled?[".ts",".mts"]:[];const allExtensions=[...defaultExtensions,...typescriptExtensions];const{recursive=true,extensions=allExtensions,isRootScan=true,currentDepth=0,maxDepth=DEFAULT_API_DEPTH,fileFilter=null,hidden=null,scanHiddenFolders=false,rootDir=dir}=options;const hiddenMatcher=typeof hidden==="function"?hidden:compileHidden(hidden);const apiRel=p=>path.relative(rootDir,p).split(path.sep).join(".");const hasHiddenPrefix=name=>name.startsWith(".")||name.startsWith("__");try{await fsp.stat(dir)}catch(error){throw new this.SlothletError("INVALID_DIRECTORY",{dir},error)}const structure={files:[],directories:[]};const entries=await fsp.readdir(dir,{withFileTypes:true});for(const entry of entries){const fullPath=path.join(dir,entry.name);if(entry.isDirectory()){if(fileFilter){continue}if(!scanHiddenFolders&&hasHiddenPrefix(entry.name)){continue}if(hiddenMatcher&&hiddenMatcher(apiRel(fullPath))){continue}if(recursive&¤tDepth<maxDepth){const subStructure=await this.scanDirectory(fullPath,{...options,isRootScan:false,currentDepth:currentDepth+1,hidden:hiddenMatcher,scanHiddenFolders,rootDir});if(subStructure.files.length===0&&subStructure.directories.length===0){continue}structure.directories.push({path:fullPath,name:entry.name,children:subStructure})}}else if(entry.isFile()){const ext=path.extname(entry.name);if(extensions.includes(ext)){if(hasHiddenPrefix(entry.name)){continue}if(fileFilter&&!fileFilter(entry.name)){continue}const nameWithoutExt=path.basename(entry.name,ext);if(hiddenMatcher&&hiddenMatcher(apiRel(path.join(dir,nameWithoutExt)))){continue}if(isFrameworkReservedKey(nameWithoutExt)){throw new this.SlothletError("MODULE_RESERVED_FILENAME",{file:entry.name,dir},null,{validationError:true})}structure.files.push({path:fullPath,name:nameWithoutExt,fullName:entry.name,moduleID:this.slothlet.helpers.sanitize.getModuleId(fullPath,dir)})}}}if(isRootScan&&structure.files.length===0&&structure.directories.length===0&&!this.____config?.silent){new this.SlothletWarning("WARN_DIRECTORY_EMPTY",{dir,resolvedPath:path.resolve(dir)})}return structure}#scanDirectoryBrowser(dir,options={}){const manifest=this.slothlet.config?.manifest;if(!manifest){throw new this.SlothletError("INVALID_CONFIG_BROWSER_REQUIRES_MANIFEST",{},null,{validationError:true})}const configBase=(this.slothlet.config?.dir||"").replace(/\/$/,"");let relativePath=(dir||"").replace(/\/$/,"");if(configBase&&relativePath.startsWith(configBase)){relativePath=relativePath.slice(configBase.length).replace(/^\/|\/$/g,"")}const isRoot=!relativePath||relativePath==="/"||relativePath===".";const node=isRoot?manifest:this.#findManifestNode(manifest,relativePath);if(!node){throw new this.SlothletError("INVALID_DIRECTORY",{dir},null)}return this.#manifestNodeToStructure(node,dir,options)}#findManifestNode(node,targetPath){const normalised=targetPath.replace(/\\/g,"/").replace(/^\/|\/$/g,"");for(const dir of node.directories||[]){const dirPath=(dir.path||dir.name||"").replace(/\\/g,"/").replace(/^\/|\/$/g,"");if(dirPath===normalised)return dir.children||dir;const found=this.#findManifestNode(dir.children||dir,normalised);if(found)return found}return null}#manifestNodeToStructure(node,rootPath,options={}){const{fileFilter=null}=options;const ALLOWED_EXTS=[".mjs",".cjs",".js"];const structure={files:[],directories:[]};for(const file of node.files||[]){const filePath=file.path||file.relativePath||"";const fullName=file.fullName||filePath.split("/").pop();const lastDot=fullName.lastIndexOf(".");const ext=lastDot>=0?fullName.slice(lastDot):"";if(!ALLOWED_EXTS.includes(ext))continue;if(fullName.startsWith("__"))continue;if(fileFilter&&!fileFilter(fullName))continue;const name=file.name||(lastDot>=0?fullName.slice(0,lastDot):fullName);if(isFrameworkReservedKey(name)){throw new this.SlothletError("MODULE_RESERVED_FILENAME",{file:fullName,dir:rootPath},null,{validationError:true})}structure.files.push({path:filePath,name,fullName,moduleID:this.slothlet.helpers.sanitize.getModuleId(filePath,rootPath)})}if(!fileFilter){for(const dir of node.directories||[]){const dirPath=dir.path||dir.name||"";structure.directories.push({path:dirPath,name:dir.name||dirPath.split("/").pop(),children:this.#manifestNodeToStructure(dir.children||dir,dirPath,options)})}}return structure}async#loadModuleBrowser(filePath){const resolveModuleSpecifier=this.slothlet.config?.resolveModuleSpecifier??(({path:p})=>{const base=this.slothlet.config?.base??this.slothlet.config?.dir??"";const leadingSlash=base.startsWith("/")?"":"/";const baseUrl=/^[a-zA-Z][\w+\-.]*:\/\//.test(base)?base.endsWith("/")?base:base+"/":"file://"+leadingSlash+base.replace(/\/?$/,"/");return new URL(p,baseUrl).href});const fullName=filePath.split("/").pop();const lastDot=fullName.lastIndexOf(".");const name=lastDot>=0?fullName.slice(0,lastDot):fullName;const specifier=resolveModuleSpecifier({path:filePath,name,fullName});const module=await import(specifier);return module}extractExports(module){const exports={};if(module.default!==void 0){exports.default=module.default}for(const key of Object.keys(module)){if(key!=="default"&&key!=="module.exports"&&typeof key==="string"){if(isFrameworkReservedKey(key)){throw new this.SlothletError("MODULE_RESERVED_EXPORT",{name:key},null,{validationError:true})}exports[key]=module[key]}}if(exports.default&&typeof exports.default==="object"&&exports.default!==null&&"default"in exports.default){const rootNamedKeys=Object.keys(exports).filter(k=>k!=="default"&&k!=="module.exports");const defaultKeys=Object.keys(exports.default).filter(k=>k!=="default");const isCJSPattern=rootNamedKeys.every(k=>k in exports.default);if(isCJSPattern&&defaultKeys.length>0){exports.default=exports.default.default}}return exports}}export{Loader,warnIfCoverageWithoutImporter};
|
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";
|
|
@@ -1,3 +1,110 @@
|
|
|
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
|
+
* Builds final API with built-in methods attached
|
|
5
|
+
* @class ApiBuilder
|
|
6
|
+
* @extends ComponentBase
|
|
7
|
+
* @package
|
|
8
|
+
*
|
|
9
|
+
* @description
|
|
10
|
+
* Class-based builder for final API construction with built-in namespace attachment.
|
|
11
|
+
* Extends ComponentBase for common Slothlet property access.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* const builder = new ApiBuilder(slothlet);
|
|
15
|
+
* const api = await builder.buildFinalAPI(userApi);
|
|
16
|
+
*/
|
|
17
|
+
export class ApiBuilder extends ComponentBase {
|
|
18
|
+
static slothletProperty: string;
|
|
19
|
+
/**
|
|
20
|
+
* Create an ApiBuilder instance.
|
|
21
|
+
* @param {object} slothlet - Slothlet class instance.
|
|
22
|
+
* @package
|
|
23
|
+
*
|
|
24
|
+
* @description
|
|
25
|
+
* Creates ApiBuilder with ComponentBase support for config, debug, instanceID access.
|
|
26
|
+
*/
|
|
27
|
+
constructor(slothlet: object);
|
|
28
|
+
/**
|
|
29
|
+
* Build final API with built-in methods attached
|
|
30
|
+
* @param {Object} userApi - User API object from mode builder
|
|
31
|
+
* @returns {Promise<Object>} Final API with built-ins attached
|
|
32
|
+
* @public
|
|
33
|
+
*/
|
|
34
|
+
public buildFinalAPI(userApi: Object): Promise<Object>;
|
|
35
|
+
/**
|
|
36
|
+
* @param {object} userApi - User API object (for diagnostics).
|
|
37
|
+
* @returns {Promise<object>} Slothlet namespace object.
|
|
38
|
+
* @private
|
|
39
|
+
*
|
|
40
|
+
* @description
|
|
41
|
+
* Builds the slothlet namespace with version metadata, API controls, and lifecycle
|
|
42
|
+
* helpers for the current instance.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* const namespace = await this.createSlothletNamespace(api);
|
|
46
|
+
*/
|
|
47
|
+
private createSlothletNamespace;
|
|
48
|
+
/**
|
|
49
|
+
* Create root-level shutdown function (convenience)
|
|
50
|
+
* @returns {Function} Shutdown function that dynamically calls user hooks
|
|
51
|
+
* @private
|
|
52
|
+
*/
|
|
53
|
+
private createShutdownFunction;
|
|
54
|
+
/**
|
|
55
|
+
* Create root-level run function (per-request context isolation)
|
|
56
|
+
* @returns {Function} Run function that executes callbacks with isolated context
|
|
57
|
+
* @private
|
|
58
|
+
*/
|
|
59
|
+
private createRunFunction;
|
|
60
|
+
/**
|
|
61
|
+
* Create root-level scope function (structured per-request context with options)
|
|
62
|
+
* @returns {Function} Scope function that executes functions with isolated context
|
|
63
|
+
* @private
|
|
64
|
+
*/
|
|
65
|
+
private createScopeFunction;
|
|
66
|
+
/**
|
|
67
|
+
* Create root-level destroy function (permanent destruction)
|
|
68
|
+
* @param {Object} api - Full API object
|
|
69
|
+
* @returns {Function} Destroy function that dynamically calls user hooks
|
|
70
|
+
* @private
|
|
71
|
+
*/
|
|
72
|
+
private createDestroyFunction;
|
|
73
|
+
/**
|
|
74
|
+
* Attach built-in methods to user API
|
|
75
|
+
* @param {Object} userApi - User API object
|
|
76
|
+
* @param {Object} builtins - Built-in methods to attach
|
|
77
|
+
* @private
|
|
78
|
+
*/
|
|
79
|
+
private attachBuiltins;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* i18n translation helpers exposed on every Slothlet namespace.
|
|
83
|
+
*/
|
|
84
|
+
export type I18nNamespace = {
|
|
85
|
+
/**
|
|
86
|
+
* - Set the active locale (e.g. "en-us"). Synchronous; in a browser, non-default locales load in the background.
|
|
87
|
+
*/
|
|
88
|
+
setLanguage: Function;
|
|
89
|
+
/**
|
|
90
|
+
* - Set the active locale and await its load. Browser-capable (resolves once the locale module is fetched).
|
|
91
|
+
*/
|
|
92
|
+
setLanguageAsync: Function;
|
|
93
|
+
/**
|
|
94
|
+
* - Return the current active locale string.
|
|
95
|
+
*/
|
|
96
|
+
getLanguage: Function;
|
|
97
|
+
/**
|
|
98
|
+
* - Translate an error code with optional params.
|
|
99
|
+
*/
|
|
100
|
+
translate: Function;
|
|
101
|
+
/**
|
|
102
|
+
* - Alias for translate.
|
|
103
|
+
*/
|
|
104
|
+
t: Function;
|
|
105
|
+
/**
|
|
106
|
+
* - Initialise the i18n system with options.
|
|
107
|
+
*/
|
|
108
|
+
initI18n: Function;
|
|
109
|
+
};
|
|
110
|
+
import { ComponentBase } from "#factories/component-base";
|