@kosdev-code/kos-ui-plugin 2.1.18 → 2.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/documentation-generator-CAlVz5vA.cjs +266 -0
  2. package/documentation-generator-CAlVz5vA.cjs.map +1 -0
  3. package/documentation-generator-Di4c9D9P.js +2337 -0
  4. package/documentation-generator-Di4c9D9P.js.map +1 -0
  5. package/index.cjs +69 -69
  6. package/index.cjs.map +1 -1
  7. package/index.d.ts +1 -0
  8. package/index.d.ts.map +1 -1
  9. package/index.js +817 -753
  10. package/index.js.map +1 -1
  11. package/lib/components/dynamic-component/dynamic-component.d.ts +69 -0
  12. package/lib/components/dynamic-component/dynamic-component.d.ts.map +1 -1
  13. package/lib/contexts/index.d.ts +1 -0
  14. package/lib/contexts/index.d.ts.map +1 -1
  15. package/lib/contexts/plugins-provider/plugins-provider.d.ts.map +1 -1
  16. package/lib/contexts/reactive-extension-registry-context.d.ts +10 -0
  17. package/lib/contexts/reactive-extension-registry-context.d.ts.map +1 -0
  18. package/lib/hooks/index.d.ts +4 -2
  19. package/lib/hooks/index.d.ts.map +1 -1
  20. package/lib/hooks/use-dynamic-component.d.ts +12 -1
  21. package/lib/hooks/use-dynamic-component.d.ts.map +1 -1
  22. package/lib/hooks/use-extension-point.d.ts +95 -0
  23. package/lib/hooks/use-extension-point.d.ts.map +1 -0
  24. package/lib/hooks/use-reactive-extension-registry.d.ts +20 -0
  25. package/lib/hooks/use-reactive-extension-registry.d.ts.map +1 -0
  26. package/lib/hooks/use-typed-extensions.d.ts.map +1 -1
  27. package/lib/utils/contribution-registry.d.ts +170 -0
  28. package/lib/utils/contribution-registry.d.ts.map +1 -0
  29. package/lib/utils/extension-points/extension-point-registry.d.ts.map +1 -1
  30. package/lib/utils/extension-points/extension-point-schemas.d.ts +4 -4
  31. package/lib/utils/index.d.ts +3 -0
  32. package/lib/utils/index.d.ts.map +1 -1
  33. package/lib/utils/plugin-system/plugin-extension-manager.d.ts.map +1 -1
  34. package/lib/utils/processors/initialize-plugins.d.ts.map +1 -1
  35. package/lib/utils/reactive-extension-registry.d.ts +140 -0
  36. package/lib/utils/reactive-extension-registry.d.ts.map +1 -0
  37. package/lib/webpack/index.d.ts +2 -0
  38. package/lib/webpack/index.d.ts.map +1 -1
  39. package/lib/webpack/with-plugin-dev-aggregator.d.ts +94 -0
  40. package/lib/webpack/with-plugin-dev-aggregator.d.ts.map +1 -0
  41. package/lib/webpack/with-plugin-dev-server.d.ts +113 -0
  42. package/lib/webpack/with-plugin-dev-server.d.ts.map +1 -0
  43. package/package.json +2 -2
  44. package/types/contribution-enablement.d.ts +293 -0
  45. package/types/contribution-enablement.d.ts.map +1 -0
  46. package/types/plugins.d.ts +8 -0
  47. package/utils.cjs +1 -1
  48. package/utils.cjs.map +1 -1
  49. package/utils.js +29 -291
  50. package/utils.js.map +1 -1
  51. package/webpack.cjs +3 -12
  52. package/webpack.cjs.map +1 -1
  53. package/webpack.js +455 -727
  54. package/webpack.js.map +1 -1
  55. package/documentation-generator-DFaIDo0E.cjs +0 -266
  56. package/documentation-generator-DFaIDo0E.cjs.map +0 -1
  57. package/documentation-generator-auruIa_o.js +0 -1560
  58. package/documentation-generator-auruIa_o.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documentation-generator-Di4c9D9P.js","sources":["../../../../node_modules/@nx/react/mf/dynamic-federation.js","../../../../node_modules/@nx/react/mf/index.js","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/plugin-system/resolve-best-extension.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/contribution-registry.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/plugin-system/plugin-extension-registry.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/extension-points/extension-point-schema.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/extension-points/extension-point-validation.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/extension-points/extension-point-registry.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/extension-points/extension-point-transforms.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/extension-points/define-extension-point.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/extension-points/json-extension-parser.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/processors/contribution-reducer.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/plugin-system/plugin-extension-manager.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/processors/initialize-plugins.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/reactive-extension-registry.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/processors/process-kos-config.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/extension-points/extension-point-schemas.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/discovery/plugin-discovery-service.ts","../../../../packages/sdk/kos-ui-plugin/src/lib/utils/discovery/documentation-generator.ts"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.loadRemoteModule = exports.setRemoteDefinitions = exports.setRemoteUrlResolver = void 0;\nlet remoteUrlDefinitions;\nlet resolveRemoteUrl;\nconst remoteModuleMap = new Map();\nconst remoteContainerMap = new Map();\nlet initialSharingScopeCreated = false;\nfunction setRemoteUrlResolver(_resolveRemoteUrl) {\n resolveRemoteUrl = _resolveRemoteUrl;\n}\nexports.setRemoteUrlResolver = setRemoteUrlResolver;\nfunction setRemoteDefinitions(definitions) {\n remoteUrlDefinitions = definitions;\n}\nexports.setRemoteDefinitions = setRemoteDefinitions;\nasync function loadRemoteModule(remoteName, moduleName) {\n const remoteModuleKey = `${remoteName}:${moduleName}`;\n if (remoteModuleMap.has(remoteModuleKey)) {\n return remoteModuleMap.get(remoteModuleKey);\n }\n const container = remoteContainerMap.has(remoteName)\n ? remoteContainerMap.get(remoteName)\n : await loadRemoteContainer(remoteName);\n const factory = await container.get(moduleName);\n const Module = factory();\n remoteModuleMap.set(remoteModuleKey, Module);\n return Module;\n}\nexports.loadRemoteModule = loadRemoteModule;\nconst fetchRemoteModule = (url, remoteName) => {\n return new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = url;\n script.type = 'text/javascript';\n script.async = true;\n script.onload = () => {\n const proxy = {\n get: (request) => window[remoteName].get(request),\n init: (arg) => {\n try {\n window[remoteName].init(arg);\n }\n catch (e) {\n console.error(`Failed to initialize remote ${remoteName}`, e);\n reject(e);\n }\n },\n };\n resolve(proxy);\n };\n script.onerror = () => reject(new Error(`Remote ${remoteName} not found`));\n document.head.appendChild(script);\n });\n};\nasync function loadRemoteContainer(remoteName) {\n if (!resolveRemoteUrl && !remoteUrlDefinitions) {\n throw new Error('Call setRemoteDefinitions or setRemoteUrlResolver to allow Dynamic Federation to find the remote apps correctly.');\n }\n if (!initialSharingScopeCreated) {\n initialSharingScopeCreated = true;\n await __webpack_init_sharing__('default');\n }\n const remoteUrl = remoteUrlDefinitions\n ? remoteUrlDefinitions[remoteName]\n : await resolveRemoteUrl(remoteName);\n let containerUrl = remoteUrl;\n if (!remoteUrl.endsWith('.mjs') && !remoteUrl.endsWith('.js')) {\n containerUrl = `${remoteUrl}${remoteUrl.endsWith('/') ? '' : '/'}remoteEntry.js`;\n }\n const container = await fetchRemoteModule(containerUrl, remoteName);\n await container.init(__webpack_share_scopes__.default);\n remoteContainerMap.set(remoteName, container);\n return container;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.setRemoteUrlResolver = exports.setRemoteDefinitions = exports.loadRemoteModule = void 0;\nvar dynamic_federation_1 = require(\"./dynamic-federation\");\nObject.defineProperty(exports, \"loadRemoteModule\", { enumerable: true, get: function () { return dynamic_federation_1.loadRemoteModule; } });\nObject.defineProperty(exports, \"setRemoteDefinitions\", { enumerable: true, get: function () { return dynamic_federation_1.setRemoteDefinitions; } });\nObject.defineProperty(exports, \"setRemoteUrlResolver\", { enumerable: true, get: function () { return dynamic_federation_1.setRemoteUrlResolver; } });\n","import type { PluginExtension } from \"../../../types/plugins\";\n\n/**\n * Resolves the best plugin extension for a given extension point.\n *\n * @param extensions A map of plugin extensions keyed by module/plugin ID\n * @param module Optional module ID to resolve\n * @param exact If true, only returns a plugin if the given `module` matches exactly. If false (default), falls back to the best-ranked plugin if no match is found.\n * @returns The resolved PluginExtension or null\n */\nexport function resolveBestExtension<T extends PluginExtension>(\n extensions: Record<string, T> | undefined,\n module?: string,\n exact = false\n): T | null {\n if (!extensions || Object.keys(extensions).length === 0) {\n return null;\n }\n\n // Exact mode: must match the module ID\n if (exact) {\n return module && extensions[module] ? extensions[module] : null;\n }\n\n // Prefer exact match if available\n if (module && extensions[module]) {\n return extensions[module];\n }\n\n // Fallback: pick the best-ranked plugin\n const sorted = Object.values(extensions)\n .filter((ext) => typeof ext.id === \"string\")\n .sort((a, b) => {\n const aRank = typeof a.rank === \"number\" ? a.rank : Infinity;\n const bRank = typeof b.rank === \"number\" ? b.rank : Infinity;\n\n if (aRank === bRank) {\n const aId = a.id ?? \"\";\n const bId = b.id ?? \"\";\n return aId.localeCompare(bId);\n }\n\n return aRank - bRank;\n });\n\n return sorted[0] ?? null;\n}\n","import type {\n ContributionStateChangeEvent,\n DynamicContribution,\n EnablementContext,\n IContributionRegistry,\n} from \"../../types/contribution-enablement\";\n\n/**\n * Centralized contribution enablement registry\n *\n * Manages the enabled/disabled state of all plugin contributions in the system.\n * Provides subscription mechanism for reactive updates when contribution state changes.\n *\n * This is a singleton that maintains runtime state for contribution enablement.\n * State is ephemeral and resets on page reload.\n *\n * @example\n * ```typescript\n * // Enable/disable a contribution\n * ContributionRegistry.setEnabled('advanced-settings', false, 'Basic mode active');\n *\n * // Check if contribution is enabled\n * if (ContributionRegistry.isEnabled('advanced-settings')) {\n * // Show advanced settings\n * }\n *\n * // Subscribe to changes\n * const unsubscribe = ContributionRegistry.subscribe((event) => {\n * console.log(`${event.contributionId} is now ${event.enabled ? 'enabled' : 'disabled'}`);\n * });\n * ```\n */\nclass ContributionRegistryImpl implements IContributionRegistry {\n /**\n * Map of contribution ID to its dynamic contribution state\n */\n private contributions: Map<string, DynamicContribution> = new Map();\n\n /**\n * Map of extension point to contribution IDs\n * Allows efficient lookup of contributions by extension point\n */\n private extensionPointIndex: Map<string, Set<string>> = new Map();\n\n /**\n * Global listeners for all state changes\n */\n private globalListeners: Set<(event: ContributionStateChangeEvent) => void> =\n new Set();\n\n /**\n * Extension point-scoped listeners\n * Map of extension point to listeners\n */\n private extensionPointListeners: Map<\n string,\n Set<(event: ContributionStateChangeEvent) => void>\n > = new Map();\n\n /**\n * Current enablement context for conditional evaluation\n */\n private enablementContext: EnablementContext = {\n extensions: {},\n contributions: {\n controlPourDefinitions: {},\n experiences: {},\n },\n context: {},\n };\n\n /**\n * Register a contribution in the registry\n *\n * This is called during plugin initialization to register all contributions\n * with their default enabled state (true).\n *\n * @param contributionId - Unique identifier for the contribution\n * @param extensionPoint - Extension point this contribution belongs to\n * @param contribution - The contribution object\n * @internal\n */\n register(\n contributionId: string,\n extensionPoint: string,\n contribution: Omit<DynamicContribution, \"enabled\">\n ): void {\n // Create dynamic contribution with default enabled: true\n const dynamicContribution: DynamicContribution = {\n ...contribution,\n enabled: true,\n lastStateChange: Date.now(),\n };\n\n this.contributions.set(contributionId, dynamicContribution);\n\n // Update extension point index\n if (!this.extensionPointIndex.has(extensionPoint)) {\n this.extensionPointIndex.set(extensionPoint, new Set());\n }\n this.extensionPointIndex.get(extensionPoint)!.add(contributionId);\n }\n\n /**\n * Update the enablement context\n *\n * The context is used when evaluating conditional enablement functions.\n *\n * @param context - New enablement context\n * @internal\n */\n setContext(context: Partial<EnablementContext>): void {\n this.enablementContext = {\n ...this.enablementContext,\n ...context,\n };\n }\n\n /**\n * Set enabled state for a contribution\n *\n * Updates the contribution's enabled state and emits a\n * ContributionStateChangeEvent to all subscribers.\n *\n * @param contributionId - Unique identifier of the contribution\n * @param enabled - New enabled state (true = enabled, false = disabled)\n * @param reason - Optional human-readable reason for the change\n */\n setEnabled(contributionId: string, enabled: boolean, reason?: string): void {\n const contribution = this.contributions.get(contributionId);\n\n if (!contribution) {\n console.warn(\n `ContributionRegistry.setEnabled: Contribution '${contributionId}' not found. Ignoring.`\n );\n return;\n }\n\n // Check if state actually changed\n const previousState = contribution.enabled;\n if (previousState === enabled) {\n // State unchanged, skip event emission (optimization)\n return;\n }\n\n // Update contribution state\n contribution.enabled = enabled;\n contribution.disabledReason = enabled ? undefined : reason;\n contribution.lastStateChange = Date.now();\n\n // Emit event to subscribers\n this.emitStateChange({\n contributionId,\n extensionPoint: this.findExtensionPoint(contributionId),\n enabled,\n previousState,\n reason,\n timestamp: contribution.lastStateChange,\n });\n }\n\n /**\n * Get enabled state for a contribution\n *\n * Checks both the enabled boolean field and evaluates any\n * enabledCondition function if present. Returns true only if\n * both checks pass.\n *\n * @param contributionId - Unique identifier of the contribution\n * @returns true if contribution is enabled, false otherwise\n */\n isEnabled(contributionId: string): boolean {\n const contribution = this.contributions.get(contributionId);\n\n if (!contribution) {\n // Default to true if contribution not found (backward compatibility)\n return true;\n }\n\n // Check enabled flag\n if (!contribution.enabled) {\n return false;\n }\n\n // Evaluate conditional enablement if present\n if (contribution.enabledCondition) {\n try {\n return contribution.enabledCondition(this.enablementContext);\n } catch (error) {\n console.error(\n `ContributionRegistry.isEnabled: Error evaluating enabledCondition for '${contributionId}':`,\n error\n );\n // Fail closed - if condition throws, consider disabled\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Subscribe to all contribution state changes\n *\n * Registers a listener that will be called whenever any contribution's\n * enabled state changes. The listener receives a ContributionStateChangeEvent.\n *\n * @param listener - Callback function to handle state change events\n * @returns Unsubscribe function to stop receiving events\n */\n subscribe(\n listener: (event: ContributionStateChangeEvent) => void\n ): () => void {\n if (typeof listener !== \"function\") {\n throw new TypeError(\n \"ContributionRegistry.subscribe: listener must be a function\"\n );\n }\n\n this.globalListeners.add(listener);\n\n // Return unsubscribe function\n return () => {\n this.globalListeners.delete(listener);\n };\n }\n\n /**\n * Subscribe to changes for a specific extension point\n *\n * Like subscribe(), but only emits events for contributions\n * belonging to the specified extension point.\n *\n * @param extensionPoint - Extension point identifier to monitor\n * @param listener - Callback function to handle state change events\n * @returns Unsubscribe function to stop receiving events\n */\n subscribeToExtensionPoint(\n extensionPoint: string,\n listener: (event: ContributionStateChangeEvent) => void\n ): () => void {\n if (typeof listener !== \"function\") {\n throw new TypeError(\n \"ContributionRegistry.subscribeToExtensionPoint: listener must be a function\"\n );\n }\n\n if (!this.extensionPointListeners.has(extensionPoint)) {\n this.extensionPointListeners.set(extensionPoint, new Set());\n }\n\n this.extensionPointListeners.get(extensionPoint)!.add(listener);\n\n // Return unsubscribe function\n return () => {\n this.extensionPointListeners.get(extensionPoint)?.delete(listener);\n\n // Cleanup empty sets\n if (this.extensionPointListeners.get(extensionPoint)?.size === 0) {\n this.extensionPointListeners.delete(extensionPoint);\n }\n };\n }\n\n /**\n * Batch update multiple contributions atomically\n *\n * Updates multiple contribution states in a single atomic operation.\n * All updates succeed or all fail together. Emits one event per\n * contribution that changed state.\n *\n * @param updates - Array of contribution updates to apply\n */\n batchUpdate(\n updates: Array<{\n contributionId: string;\n enabled: boolean;\n reason?: string;\n }>\n ): void {\n if (!Array.isArray(updates)) {\n throw new TypeError(\n \"ContributionRegistry.batchUpdate: updates must be an array\"\n );\n }\n\n // Validate all updates first (atomic semantics - all or nothing)\n const validatedUpdates = updates.map((update) => {\n const contribution = this.contributions.get(update.contributionId);\n if (!contribution) {\n console.warn(\n `ContributionRegistry.batchUpdate: Contribution '${update.contributionId}' not found. Skipping.`\n );\n return null;\n }\n\n // Check if state actually changes\n if (contribution.enabled === update.enabled) {\n return null; // No change needed\n }\n\n return {\n contribution,\n update,\n previousState: contribution.enabled,\n };\n });\n\n // Apply all updates\n const timestamp = Date.now();\n validatedUpdates.forEach((validated) => {\n if (!validated) return;\n\n const { contribution, update } = validated;\n\n contribution.enabled = update.enabled;\n contribution.disabledReason = update.enabled ? undefined : update.reason;\n contribution.lastStateChange = timestamp;\n });\n\n // Emit events for all changes\n validatedUpdates.forEach((validated) => {\n if (!validated) return;\n\n const { update, previousState } = validated;\n\n this.emitStateChange({\n contributionId: update.contributionId,\n extensionPoint: this.findExtensionPoint(update.contributionId),\n enabled: update.enabled,\n previousState,\n reason: update.reason,\n timestamp,\n });\n });\n }\n\n /**\n * Get all contributions for an extension point\n *\n * Returns an array of DynamicContribution objects for the specified\n * extension point. By default, only returns enabled contributions.\n *\n * @param extensionPoint - Extension point identifier\n * @param includeDisabled - If true, include disabled contributions in results\n * @returns Array of contributions for the extension point\n */\n getContributions(\n extensionPoint: string,\n includeDisabled = false\n ): DynamicContribution[] {\n const contributionIds = this.extensionPointIndex.get(extensionPoint);\n\n if (!contributionIds || contributionIds.size === 0) {\n return [];\n }\n\n const contributions: DynamicContribution[] = [];\n\n contributionIds.forEach((id) => {\n const contribution = this.contributions.get(id);\n if (!contribution) return;\n\n // Filter by enabled state unless includeDisabled is true\n if (includeDisabled || this.isEnabled(id)) {\n contributions.push(contribution);\n }\n });\n\n return contributions;\n }\n\n /**\n * Find the extension point for a contribution ID\n * @internal\n */\n private findExtensionPoint(contributionId: string): string {\n for (const [extensionPoint, ids] of this.extensionPointIndex.entries()) {\n if (ids.has(contributionId)) {\n return extensionPoint;\n }\n }\n return \"\"; // Unknown extension point\n }\n\n /**\n * Emit state change event to all relevant listeners\n * @internal\n */\n private emitStateChange(event: ContributionStateChangeEvent): void {\n // Notify global listeners\n this.globalListeners.forEach((listener) => {\n try {\n listener(event);\n } catch (error) {\n console.error(\"ContributionRegistry: Error in global listener:\", error);\n }\n });\n\n // Notify extension point-scoped listeners\n const listeners = this.extensionPointListeners.get(event.extensionPoint);\n if (listeners) {\n listeners.forEach((listener) => {\n try {\n listener(event);\n } catch (error) {\n console.error(\n `ContributionRegistry: Error in extension point listener for '${event.extensionPoint}':`,\n error\n );\n }\n });\n }\n }\n\n /**\n * Clear all state (useful for testing or cleanup)\n * @internal\n */\n reset(): void {\n this.contributions.clear();\n this.extensionPointIndex.clear();\n this.globalListeners.clear();\n this.extensionPointListeners.clear();\n this.enablementContext = {\n extensions: {},\n contributions: {\n controlPourDefinitions: {},\n experiences: {},\n },\n context: {},\n };\n }\n}\n\n/**\n * Singleton instance of ContributionRegistry\n *\n * Use this instance throughout the application to manage contribution state.\n *\n * @example\n * ```typescript\n * import { ContributionRegistry } from '@kosdev-code/kos-ui-plugin';\n *\n * ContributionRegistry.setEnabled('my-contribution', false);\n * ```\n */\nexport const ContributionRegistry = new ContributionRegistryImpl();\n","// plugin-extension-registry.ts\n\nimport type {\n PluginExtensionsType,\n ProcessedContributions,\n} from \"../../../types/plugins\";\n\nexport type ExtensionReducer = (\n extensions: PluginExtensionsType,\n contributions: ProcessedContributions,\n experiences: any\n) => PluginExtensionsType;\n\nconst extensionPointRegistry: ExtensionReducer[] = [];\n\nexport function registerExtensionReducer(reducer: ExtensionReducer) {\n extensionPointRegistry.push(reducer);\n}\n\nexport function applyExtensionReducers(\n base: PluginExtensionsType,\n contributions: ProcessedContributions,\n experiences: any\n): PluginExtensionsType {\n return extensionPointRegistry.reduce(\n (acc, reducer) => reducer(acc, contributions, experiences),\n base\n );\n}\n","/**\n * Schema utilities for extension points\n */\n\nimport type { z } from \"zod\";\nimport type { SchemaFieldInfo } from \"./extension-point-types\";\n\n/**\n * Extract field information from a Zod schema for documentation purposes\n * Returns field information that is safe to display in Plugin Explorer\n */\nexport function extractSchemaFieldInfo(schema: z.ZodSchema): SchemaFieldInfo[] {\n try {\n // Check if schema is a ZodObject by checking for shape property\n if (\"shape\" in schema) {\n const objectSchema = schema as z.ZodObject<any>;\n const fields: SchemaFieldInfo[] = [];\n\n for (const [fieldName, fieldSchema] of Object.entries(\n objectSchema.shape\n )) {\n const zodField = fieldSchema as z.ZodTypeAny;\n const fieldInfo: SchemaFieldInfo = {\n name: fieldName,\n required: !zodField.isOptional(),\n };\n\n // Extract description if available\n if (zodField._def && zodField._def.description) {\n fieldInfo.description = zodField._def.description;\n }\n\n // Extract type information\n if (zodField._def) {\n // Get the base type name (handles optional types)\n let typeName = zodField._def.typeName || \"unknown\";\n if (typeName === \"ZodOptional\" && zodField._def.innerType) {\n typeName = zodField._def.innerType._def?.typeName || \"unknown\";\n }\n // Simplify type names for display\n fieldInfo.type = typeName.replace(\"Zod\", \"\").toLowerCase();\n }\n\n fields.push(fieldInfo);\n }\n\n return fields;\n }\n\n // For other schema types, we can't safely extract fields\n return [];\n } catch (error) {\n console.warn(\"Failed to extract schema field info:\", error);\n return [];\n }\n}\n","/**\n * Validation utilities for extension points\n */\n\nimport type { ValidationContext } from \"./extension-point-types\";\n\n/**\n * Implementation of ValidationContext for collecting validation issues\n */\nexport class ValidationContextImpl implements ValidationContext {\n private issues: { type: \"error\" | \"warning\" | \"info\"; message: string }[] =\n [];\n\n addError(message: string): void {\n this.issues.push({ type: \"error\", message });\n }\n\n addWarning(message: string): void {\n this.issues.push({ type: \"warning\", message });\n }\n\n addInfo(message: string): void {\n this.issues.push({ type: \"info\", message });\n }\n\n hasErrors(): boolean {\n return this.issues.some((issue) => issue.type === \"error\");\n }\n\n hasIssues(): boolean {\n return this.issues.length > 0;\n }\n\n getIssues(): { type: \"error\" | \"warning\" | \"info\"; message: string }[] {\n return [...this.issues];\n }\n}\n\n/**\n * Validation results cache\n * Stores validation results by plugin ID to avoid re-running validation\n */\nexport class ValidationResultsCache {\n private cache: Map<\n string,\n { type: \"error\" | \"warning\" | \"info\"; message: string }[]\n > = new Map();\n\n set(\n pluginId: string,\n results: { type: \"error\" | \"warning\" | \"info\"; message: string }[]\n ) {\n this.cache.set(pluginId, results);\n }\n\n get(\n pluginId: string\n ): { type: \"error\" | \"warning\" | \"info\"; message: string }[] {\n return this.cache.get(pluginId) || [];\n }\n\n clear() {\n this.cache.clear();\n }\n}\n\n// Create singleton validation cache\nexport const validationCache = new ValidationResultsCache();\n\n/**\n * Get validation results for a plugin from the cache\n * Returns validation results that were stored during plugin processing\n */\nexport function getValidationResults(\n pluginId: string\n): { type: \"error\" | \"warning\" | \"info\"; message: string }[] {\n return validationCache.get(pluginId);\n}\n","/**\n * Registry management for extension points\n */\n\nimport type {\n BasePluginExtension,\n PluginExtensionsType,\n ProcessedContributions,\n} from \"../../../types/plugins\";\nimport { ContributionRegistry } from \"../contribution-registry\";\nimport { registerExtensionReducer } from \"../plugin-system/plugin-extension-registry\";\nimport { extractSchemaFieldInfo } from \"./extension-point-schema\";\nimport type {\n ExtensionPointConfig,\n ExtensionPointDefinition,\n TransformContext,\n} from \"./extension-point-types\";\nimport {\n ValidationContextImpl,\n validationCache,\n} from \"./extension-point-validation\";\n\n/**\n * Registry for simplified extension points\n * Keeps track of all extension points defined via this API\n */\nexport class SimplifiedExtensionPointRegistry {\n private extensionPoints: Map<string, ExtensionPointDefinition> = new Map();\n\n define<TData = any, TProcessed = TData, TProps = any>(\n config: ExtensionPointConfig<TData, TProcessed, TProps>\n ): ExtensionPointDefinition<TData, TProcessed, TProps> {\n // Check if already defined\n if (this.extensionPoints.has(config.id)) {\n console.warn(`Extension point ${config.id} is already defined`);\n return this.extensionPoints.get(config.id) as ExtensionPointDefinition<\n TData,\n TProcessed,\n TProps\n >;\n }\n\n // Create the definition\n const definition: ExtensionPointDefinition<TData, TProcessed, TProps> = {\n config,\n id: config.id,\n isRegistered: false,\n getExtensions: (extensions: PluginExtensionsType) =>\n (extensions[config.id] || {}) as Record<\n string,\n BasePluginExtension & { data: TProcessed }\n >,\n register: () => {\n if (definition.isRegistered) {\n console.warn(`Extension point ${config.id} is already registered`);\n return;\n }\n\n // Create and register the reducer\n const reducer = this.createReducer(config);\n registerExtensionReducer(reducer);\n\n definition.isRegistered = true;\n },\n };\n\n // Add schema field extraction if schema is provided\n if (config.schema) {\n definition.getSchemaFieldInfo = () =>\n extractSchemaFieldInfo(config.schema!);\n }\n\n // Component creation is handled at runtime via useExtensionComponent hook or createExtensionComponent factory\n\n // Store the definition\n this.extensionPoints.set(config.id, definition);\n\n return definition;\n }\n\n private createReducer<TData = any, TProcessed = TData>(\n config: ExtensionPointConfig<TData, TProcessed>\n ) {\n return (\n extensions: PluginExtensionsType,\n contributions: ProcessedContributions,\n experiences: any\n ): PluginExtensionsType => {\n // Check if contributions exist for this extension point\n const contributionData = (contributions as any)[config.contributionKey];\n if (!contributionData || typeof contributionData !== \"object\") {\n return extensions;\n }\n\n // Process each contribution\n Object.entries(contributionData).forEach(\n ([key, rawData]: [string, any]) => {\n // Skip if no data\n if (!rawData) return;\n\n // Create transform context\n const context: TransformContext = {\n remote: rawData.remote || \"\",\n sectionId: rawData.sectionId || key,\n experiences,\n contributions,\n };\n\n // Validate if validator provided\n if (config.validate) {\n const validationContext = new ValidationContextImpl();\n const validationResult = config.validate(\n rawData,\n validationContext\n );\n\n // Handle skip result\n if (validationResult === \"skip\") {\n validationCache.set(key, [\n {\n type: \"warning\",\n message: \"Plugin marked to skip processing\",\n },\n ]);\n return; // Skip processing this contribution\n }\n\n // Store validation issues in cache\n if (validationContext.hasIssues()) {\n const issues = validationContext.getIssues().map((issue) => {\n return {\n ...issue,\n message: `Extension point validation: ${issue.message}`,\n };\n });\n\n validationCache.set(key, issues);\n\n if (validationContext.hasErrors()) {\n console.error(\n `Validation failed for ${config.id} contribution \"${key}\":`,\n issues\n .filter((i) => i.type === \"error\")\n .map((i) => i.message)\n .join(\", \")\n );\n return; // Skip processing on errors\n }\n } else {\n // Clear any previous validation errors for successful validation\n validationCache.set(key, []);\n }\n }\n\n // Transform data if transformer provided\n const processedData = config.transform\n ? config.transform(rawData, context)\n : rawData;\n\n // Initialize extension point if needed\n if (!extensions[config.id]) {\n extensions[config.id] = {};\n }\n\n // Create the base extension\n const extension: BasePluginExtension = {\n id: key,\n type: config.contributionKey,\n data: processedData,\n remote: context.remote,\n sectionId: context.sectionId,\n };\n\n // Add rank if rankable\n if (config.isRankable && typeof rawData.rank === \"number\") {\n extension.rank = rawData.rank;\n }\n\n // Copy component-related properties to root level for useDynamicComponent compatibility\n if (processedData && typeof processedData === \"object\") {\n // Copy component properties from processed data to extension root\n if (\"component\" in processedData) {\n (extension as any).component = processedData.component;\n }\n if (\"view\" in processedData) {\n (extension as any).view = processedData.view;\n }\n if (\"location\" in processedData) {\n (extension as any).location = processedData.location;\n }\n }\n\n // Store the extension\n extensions[config.id][key] = extension;\n\n // Register contribution in ContributionRegistry with default enabled: true\n // This allows runtime control of contribution visibility\n ContributionRegistry.register(key, config.id, {\n id: key,\n remote: context.remote,\n sectionId: context.sectionId,\n });\n\n // Handle view-based extensions if configured\n if (config.hasView && config.relatedPoints?.view) {\n const experienceId = rawData.experienceId;\n const view = experiences?.[experienceId];\n\n if (view) {\n // Initialize view extension point if needed\n if (!extensions[config.relatedPoints.view]) {\n extensions[config.relatedPoints.view] = {};\n }\n\n // Create view extension\n extensions[config.relatedPoints.view][key] = {\n id: key,\n type: `${config.contributionKey}.view`,\n data: view,\n remote: context.remote,\n sectionId: context.sectionId,\n };\n\n // Register view contribution in ContributionRegistry\n ContributionRegistry.register(key, config.relatedPoints.view, {\n id: key,\n remote: context.remote,\n sectionId: context.sectionId,\n });\n }\n }\n\n // Handle definition extension point if configured\n if (config.relatedPoints?.definition) {\n // Initialize definition extension point if needed\n if (!extensions[config.relatedPoints.definition]) {\n extensions[config.relatedPoints.definition] = {};\n }\n\n // Create definition extension\n extensions[config.relatedPoints.definition][key] = {\n id: key,\n type: `${config.contributionKey}.definition`,\n data: processedData,\n remote: context.remote,\n sectionId: context.sectionId,\n };\n\n // Register definition contribution in ContributionRegistry\n ContributionRegistry.register(\n key,\n config.relatedPoints.definition,\n {\n id: key,\n remote: context.remote,\n sectionId: context.sectionId,\n }\n );\n }\n }\n );\n\n return extensions;\n };\n }\n\n /**\n * Get all registered extension points (for discovery/documentation)\n */\n getAllExtensionPoints(): ExtensionPointDefinition[] {\n return Array.from(this.extensionPoints.values()).filter(\n (definition) => definition.isRegistered\n );\n }\n\n /**\n * Get all defined extension points (registered and unregistered)\n */\n getAllDefinedExtensionPoints(): ExtensionPointDefinition[] {\n return Array.from(this.extensionPoints.values());\n }\n\n /**\n * Get a specific extension point definition\n */\n getExtensionPoint(id: string): ExtensionPointDefinition | undefined {\n return this.extensionPoints.get(id);\n }\n\n /**\n * Check if an extension point is registered\n */\n hasExtensionPoint(id: string): boolean {\n return this.extensionPoints.has(id);\n }\n\n /**\n * Get the Zod schema for an extension point\n * Returns undefined if the extension point doesn't have a schema\n */\n getExtensionPointSchema(id: string): any | undefined {\n const definition = this.extensionPoints.get(id);\n return definition?.config.schema;\n }\n}\n\n// Create singleton registry instance\nexport const registry = new SimplifiedExtensionPointRegistry();\n\n/**\n * Get the simplified extension point registry\n * Useful for discovery tools and documentation generation\n */\nexport function getExtensionPointRegistry(): SimplifiedExtensionPointRegistry {\n return registry;\n}\n\n/**\n * Get the Zod schema for an extension point by ID\n * Useful for inferring TypeScript types from JSON-defined extension points\n *\n * @example\n * ```typescript\n * import { getExtensionPointSchema } from '@kosdev-code/kos-ui-plugin';\n * import { z } from 'zod';\n *\n * // Get the schema\n * const schema = getExtensionPointSchema('app.navigation.link');\n *\n * // Infer the TypeScript type\n * type NavLinkData = z.infer<typeof schema>;\n *\n * // Use it with hooks\n * const { extensions, t } = useExtensionI18n<NavLinkData>(EXTENSION_ID_NAV_LINK);\n * ```\n */\nexport function getExtensionPointSchema(id: string): any | undefined {\n return registry.getExtensionPointSchema(id);\n}\n","/**\n * Transform utilities for extension points\n */\n\nimport type { TransformContext } from \"./extension-point-types\";\n\n/**\n * Generic transform helper for extension points that use the experience/view pattern\n * Handles mapping experience IDs to experience data and flattening component properties\n */\nexport function createViewAwareTransform<TData extends Record<string, any>>(\n options: {\n /**\n * Property name that contains the experience ID (default: \"experienceId\")\n */\n experienceIdProperty?: keyof TData;\n /**\n * Whether to flatten component properties to root level for useDynamicComponent compatibility (default: true)\n */\n flattenComponentProperties?: boolean;\n /**\n * Additional transform logic to apply after view mapping\n */\n customTransform?: (\n data: TData,\n view: any,\n context: TransformContext\n ) => any;\n } = {}\n) {\n const {\n experienceIdProperty = \"experienceId\",\n flattenComponentProperties = true,\n customTransform,\n } = options;\n\n return (data: TData, context: TransformContext) => {\n // Map experience ID to experience data\n const experienceId = data[experienceIdProperty] as string;\n const view = experienceId ? context.experiences?.[experienceId] || {} : {};\n\n // Start with base data - use any to allow dynamic property addition\n let result: any = {\n ...data,\n view: view,\n };\n\n // Flatten component properties for useDynamicComponent compatibility\n if (flattenComponentProperties && view) {\n if (view.component) {\n result.component = view.component;\n }\n if (view.location) {\n result.location = view.location;\n }\n }\n\n // Apply custom transform if provided\n if (customTransform) {\n result = customTransform(data, view, context) || result;\n }\n\n return result;\n };\n}\n","/**\n * Simplified Extension Point Definition API\n *\n * This utility provides a streamlined way to define new extension points\n * without modifying multiple files. It maintains full backward compatibility\n * with existing extension points which continue to use the legacy reducer system.\n */\n\nimport { registry } from \"./extension-point-registry\";\nimport type {\n ExtensionPointConfig,\n ExtensionPointDefinition,\n ViewExtensionPointDefinition,\n} from \"./extension-point-types\";\n\n// Re-export types and interfaces\nexport type {\n ExtensionComponentProps,\n ExtensionPointConfig,\n ExtensionPointDefinition,\n SchemaFieldInfo,\n TransformContext,\n ValidationContext,\n ViewExtensionPointDefinition,\n} from \"./extension-point-types\";\n\n// Re-export utilities\nexport {\n getExtensionPointRegistry,\n getExtensionPointSchema,\n registry,\n} from \"./extension-point-registry\";\nexport { createViewAwareTransform } from \"./extension-point-transforms\";\nexport { extensionPointId } from \"./extension-point-types\";\nexport { getValidationResults } from \"./extension-point-validation\";\n\n/**\n * Define a new extension point with simplified API\n *\n * Returns an extension point definition that must be explicitly registered\n * by calling the register() method. This prevents automatic registration\n * and circular dependency issues.\n *\n * @example\n * ```typescript\n * // Simple extension point\n * export const MyFeatureExtension = defineExtensionPoint({\n * id: 'ddk.myFeature',\n * contributionKey: 'myFeature',\n * displayName: 'My Feature',\n * description: 'Extension point for custom features'\n * });\n *\n * // Register it explicitly in your app initialization\n * MyFeatureExtension.register();\n *\n * // Extension point with view support\n * export const MyViewExtension = defineExtensionPoint({\n * id: 'ddk.myView.config',\n * contributionKey: 'myView',\n * hasView: true,\n * relatedPoints: {\n * view: 'ddk.myView.view',\n * definition: 'ddk.myView'\n * },\n * transform: (data, context) => ({\n * ...data,\n * processedAt: Date.now()\n * })\n * });\n *\n * // Register it explicitly in your app initialization\n * MyViewExtension.register();\n *\n * // Use the pre-configured component (for view-based extensions)\n * <MyViewExtension.Component\n * module=\"specific-module-id\"\n * fallback={<div>Loading...</div>}\n * customProp=\"value\"\n * />\n * ```\n */\n\n// Overload for hasView: true - guarantees Component property exists\nexport function defineExtensionPoint<\n TData = any,\n TProcessed = TData,\n TProps = any\n>(\n config: ExtensionPointConfig<TData, TProcessed, TProps> & { hasView: true }\n): ViewExtensionPointDefinition<TData, TProcessed, TProps>;\n\n// Overload for hasView: false/undefined - Component might not exist\nexport function defineExtensionPoint<\n TData = any,\n TProcessed = TData,\n TProps = any\n>(\n config: ExtensionPointConfig<TData, TProcessed, TProps>\n): ExtensionPointDefinition<TData, TProcessed, TProps>;\n\n// Implementation\nexport function defineExtensionPoint<\n TData = any,\n TProcessed = TData,\n TProps = any\n>(\n config: ExtensionPointConfig<TData, TProcessed, TProps>\n): ExtensionPointDefinition<TData, TProcessed, TProps> {\n return registry.define(config);\n}\n","/**\n * JSON Extension Point Parser\n *\n * Parses extension point definitions from JSON and converts them to\n * ExtensionPointConfig objects that can be registered with the system.\n */\n\nimport type {\n ExtensionPointConfig,\n TransformContext,\n ValidationContext,\n} from \"./extension-point-types\";\nimport { createViewAwareTransform } from \"./extension-point-transforms\";\n\n/**\n * JSON representation of an extension point definition\n */\nexport interface JsonExtensionPointDefinition {\n id: string;\n displayName?: string;\n description?: string;\n contributionKey: string;\n hasView?: boolean;\n isRankable?: boolean;\n relatedPoints?: Record<string, string>;\n schema?: JsonContributionSchema;\n validation?: JsonValidationRules;\n transform?: JsonTransformOperations;\n metadata?: JsonExtensionPointMetadata;\n}\n\ninterface JsonContributionSchema {\n type?: string;\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n}\n\ninterface JsonValidationRules {\n rules?: JsonValidationRule[];\n module?: string;\n}\n\ninterface JsonValidationRule {\n type: \"required\" | \"range\" | \"pattern\" | \"custom\" | \"dependency\";\n field?: string;\n min?: number;\n max?: number;\n pattern?: string;\n message?: string;\n dependsOn?: string;\n expression?: string;\n}\n\ninterface JsonTransformOperations {\n addFields?: Record<string, unknown>;\n removeFields?: string[];\n renameFields?: Record<string, string>;\n normalizeFields?: Array<{\n field: string;\n operation: \"trim\" | \"lowercase\" | \"uppercase\" | \"camelCase\" | \"kebabCase\";\n }>;\n module?: string;\n}\n\ninterface JsonExtensionPointMetadata {\n category?: string;\n tags?: string[];\n owner?: string;\n since?: string;\n deprecated?: boolean;\n deprecatedSince?: string;\n replacedBy?: string;\n exportName?: string;\n}\n\n/**\n * Special variables that can be used in transform operations\n */\nconst SPECIAL_VARIABLES: Record<string, () => unknown> = {\n $timestamp: () => Date.now(),\n $date: () => new Date().toISOString(),\n $packageVersion: () => process.env.npm_package_version || \"0.0.0\",\n $env: () => process.env.NODE_ENV || \"development\",\n};\n\n/**\n * Parse a JSON extension point definition into an ExtensionPointConfig\n */\nexport function parseJsonExtensionPoint<TData = any, TProcessed = TData>(\n jsonDef: JsonExtensionPointDefinition\n): ExtensionPointConfig<TData, TProcessed> {\n const config: ExtensionPointConfig<TData, TProcessed> = {\n id: jsonDef.id,\n displayName: jsonDef.displayName,\n description: jsonDef.description,\n contributionKey: jsonDef.contributionKey,\n hasView: jsonDef.hasView,\n isRankable: jsonDef.isRankable,\n relatedPoints: jsonDef.relatedPoints,\n metadata: jsonDef.metadata\n ? {\n ...jsonDef.metadata,\n exportName:\n jsonDef.metadata.exportName || generateExportName(jsonDef.id),\n }\n : undefined,\n };\n\n // Convert JSON schema to Zod schema if provided\n if (jsonDef.schema) {\n config.schema = createZodSchemaFromJson(jsonDef.schema, {\n hasView: jsonDef.hasView,\n isRankable: jsonDef.isRankable,\n });\n }\n\n // Create validation function from JSON rules\n if (jsonDef.validation) {\n config.validate = createValidationFunction(jsonDef.validation);\n }\n\n // Create transform function from JSON operations\n if (jsonDef.transform) {\n config.transform = createTransformFunction(jsonDef.transform);\n } else if (jsonDef.hasView) {\n // Auto-apply view-aware transform for view-enabled extension points\n config.transform = createViewAwareTransform() as any;\n }\n\n return config;\n}\n\n/**\n * Generate an export name from an extension point ID\n */\nfunction generateExportName(id: string): string {\n // Convert dot-separated ID to PascalCase\n // e.g., \"app.dashboard.widgets\" -> \"AppDashboardWidgets\"\n return (\n id\n .split(\".\")\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\"\") + \"Extension\"\n );\n}\n\n/**\n * Create a Zod schema from JSON schema definition\n */\nfunction createZodSchemaFromJson(\n jsonSchema: JsonContributionSchema,\n options?: { hasView?: boolean; isRankable?: boolean }\n): any {\n // This is a simplified implementation - in production, use a library like json-schema-to-zod\n // For now, we'll import zod dynamically to avoid adding it as a required dependency\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { z } = require(\"zod\");\n\n // If jsonSchema has properties, treat it as an object schema even if type is not specified\n if (jsonSchema.properties) {\n const shape: Record<string, any> = {};\n\n // Add base fields automatically\n shape.id = z.string().min(1);\n shape.title = z.string().min(1);\n shape.namespace = z.string().min(1);\n\n // Add view field if hasView is true\n if (options?.hasView) {\n shape.experienceId = z.string().min(1);\n }\n\n // Add rank field if isRankable is true\n if (options?.isRankable) {\n shape.rank = z.number().min(0).max(1000).optional();\n }\n\n // Add user-defined fields from schema\n for (const [key, propSchema] of Object.entries(jsonSchema.properties)) {\n shape[key] = createZodPropertyFromJson(propSchema, z);\n }\n\n let schema = z.object(shape);\n\n if (!jsonSchema.additionalProperties) {\n schema = schema.strict();\n }\n\n return schema;\n }\n\n return z.any();\n } catch (error) {\n console.warn(\"Zod not available for JSON schema conversion:\", error);\n return undefined;\n }\n}\n\n/**\n * Create a Zod property schema from JSON property definition\n */\nfunction createZodPropertyFromJson(propSchema: any, z: any): any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let schema: any;\n\n switch (propSchema.type) {\n case \"string\":\n schema = z.string();\n if (propSchema.minLength) schema = schema.min(propSchema.minLength);\n if (propSchema.maxLength) schema = schema.max(propSchema.maxLength);\n if (propSchema.pattern)\n schema = schema.regex(new RegExp(propSchema.pattern));\n if (propSchema.enum) schema = z.enum(propSchema.enum);\n break;\n\n case \"number\":\n schema = z.number();\n if (propSchema.minimum !== undefined)\n schema = schema.min(propSchema.minimum);\n if (propSchema.maximum !== undefined)\n schema = schema.max(propSchema.maximum);\n break;\n\n case \"boolean\":\n schema = z.boolean();\n break;\n\n case \"array\":\n schema = z.array(z.any());\n break;\n\n case \"object\":\n schema = z.object({});\n break;\n\n default:\n schema = z.any();\n }\n\n if (propSchema.description) {\n schema = schema.describe(propSchema.description);\n }\n\n if (propSchema.default !== undefined) {\n schema = schema.default(propSchema.default);\n }\n\n return schema;\n}\n\n/**\n * Create a validation function from JSON validation rules\n */\nfunction createValidationFunction(\n validationRules: JsonValidationRules\n): (data: any, context: ValidationContext) => \"skip\" | void {\n // If a module is specified, we'll need to load it dynamically\n if (validationRules.module) {\n return createModuleValidationFunction(validationRules.module);\n }\n\n // Create validation function from rules\n return (data: unknown, context: ValidationContext) => {\n if (!validationRules.rules) return;\n\n const dataRecord = data as Record<string, unknown>;\n for (const rule of validationRules.rules) {\n validateRule(rule, dataRecord, context);\n }\n };\n}\n\n/**\n * Validate a single rule against data\n */\nfunction validateRule(\n rule: JsonValidationRule,\n data: Record<string, unknown>,\n context: ValidationContext\n): void {\n switch (rule.type) {\n case \"required\":\n validateRequiredRule(rule, data, context);\n break;\n case \"range\":\n validateRangeRule(rule, data, context);\n break;\n case \"pattern\":\n validatePatternRule(rule, data, context);\n break;\n case \"dependency\":\n validateDependencyRule(rule, data, context);\n break;\n case \"custom\":\n validateCustomRule(rule, data, context);\n break;\n }\n}\n\nfunction validateRequiredRule(\n rule: JsonValidationRule,\n data: Record<string, unknown>,\n context: ValidationContext\n): void {\n if (rule.field && !data[rule.field]) {\n context.addError(rule.message || `Field '${rule.field}' is required`);\n }\n}\n\nfunction validateRangeRule(\n rule: JsonValidationRule,\n data: Record<string, unknown>,\n context: ValidationContext\n): void {\n if (rule.field && typeof data[rule.field] === \"number\") {\n const value = data[rule.field] as number;\n if (rule.min !== undefined && value < rule.min) {\n context.addError(\n rule.message || `Field '${rule.field}' must be at least ${rule.min}`\n );\n }\n if (rule.max !== undefined && value > rule.max) {\n context.addError(\n rule.message || `Field '${rule.field}' must be at most ${rule.max}`\n );\n }\n }\n}\n\nfunction validatePatternRule(\n rule: JsonValidationRule,\n data: Record<string, unknown>,\n context: ValidationContext\n): void {\n if (rule.field && rule.pattern && typeof data[rule.field] === \"string\") {\n const regex = new RegExp(rule.pattern);\n if (!regex.test(data[rule.field] as string)) {\n context.addError(\n rule.message ||\n `Field '${rule.field}' does not match pattern ${rule.pattern}`\n );\n }\n }\n}\n\nfunction validateDependencyRule(\n rule: JsonValidationRule,\n data: Record<string, unknown>,\n context: ValidationContext\n): void {\n if (rule.field && rule.dependsOn && rule.expression) {\n try {\n const result = evaluateSimpleExpression(rule.expression, data);\n if (!result) {\n context.addError(\n rule.message || `Field '${rule.field}' dependency validation failed`\n );\n }\n } catch (error) {\n context.addWarning(`Failed to evaluate dependency expression: ${error}`);\n }\n }\n}\n\nfunction validateCustomRule(\n rule: JsonValidationRule,\n data: Record<string, unknown>,\n context: ValidationContext\n): void {\n if (rule.expression) {\n try {\n const result = evaluateSimpleExpression(rule.expression, data);\n if (!result) {\n context.addError(rule.message || \"Custom validation failed\");\n }\n } catch (error) {\n context.addWarning(`Failed to evaluate custom expression: ${error}`);\n }\n }\n}\n\n/**\n * Create a validation function that loads an external module\n */\nfunction createModuleValidationFunction(\n modulePath: string\n): (data: unknown, context: ValidationContext) => \"skip\" | void {\n return (_data: unknown, context: ValidationContext) => {\n // In a real implementation, this would use dynamic import or require\n // For now, we'll just log a warning and add it to context\n console.warn(`External validation module not implemented: ${modulePath}`);\n context.addWarning(\n `External validation module not yet supported: ${modulePath}`\n );\n };\n}\n\n/**\n * Create a transform function from JSON transform operations\n */\nfunction createTransformFunction<TData = unknown, TProcessed = TData>(\n transformOps: JsonTransformOperations\n): (data: TData, context: TransformContext) => TProcessed {\n // If a module is specified, we'll need to load it dynamically\n if (transformOps.module) {\n return createModuleTransformFunction(transformOps.module);\n }\n\n return (data: TData, _context: TransformContext): TProcessed => {\n const result: Record<string, unknown> = { ...data } as Record<\n string,\n unknown\n >;\n\n // Add fields\n if (transformOps.addFields) {\n for (const [key, value] of Object.entries(transformOps.addFields)) {\n result[key] = resolveSpecialVariable(value);\n }\n }\n\n // Remove fields\n if (transformOps.removeFields) {\n for (const field of transformOps.removeFields) {\n delete result[field];\n }\n }\n\n // Rename fields\n if (transformOps.renameFields) {\n for (const [oldName, newName] of Object.entries(\n transformOps.renameFields\n )) {\n if (oldName in result) {\n result[newName] = result[oldName];\n delete result[oldName];\n }\n }\n }\n\n // Normalize fields\n if (transformOps.normalizeFields) {\n for (const { field, operation } of transformOps.normalizeFields) {\n if (field in result && typeof result[field] === \"string\") {\n result[field] = applyStringOperation(\n result[field] as string,\n operation\n );\n }\n }\n }\n\n return result as unknown as TProcessed;\n };\n}\n\n/**\n * Create a transform function that loads an external module\n */\nfunction createModuleTransformFunction<TData = any, TProcessed = TData>(\n modulePath: string\n): (data: TData, context: TransformContext) => TProcessed {\n return (data: TData, _context: TransformContext): TProcessed => {\n // In a real implementation, this would use dynamic import or require\n // For now, we'll just return the data unchanged and log a warning\n console.warn(`External transform module not implemented: ${modulePath}`);\n return data as unknown as TProcessed;\n };\n}\n\n/**\n * Resolve special variables in transform operations\n */\nfunction resolveSpecialVariable(value: unknown): unknown {\n if (typeof value === \"string\" && value.startsWith(\"$\")) {\n const resolver = SPECIAL_VARIABLES[value];\n if (resolver) {\n return resolver();\n }\n }\n return value;\n}\n\n/**\n * Apply string normalization operations\n */\nfunction applyStringOperation(value: string, operation: string): string {\n switch (operation) {\n case \"trim\":\n return value.trim();\n case \"lowercase\":\n return value.toLowerCase();\n case \"uppercase\":\n return value.toUpperCase();\n case \"camelCase\":\n return toCamelCase(value);\n case \"kebabCase\":\n return toKebabCase(value);\n default:\n return value;\n }\n}\n\n/**\n * Convert string to camelCase\n */\nfunction toCamelCase(str: string): string {\n return str\n .replace(/[-_\\s]+(.)?/g, (_, char) => (char ? char.toUpperCase() : \"\"))\n .replace(/^./, (char) => char.toLowerCase());\n}\n\n/**\n * Convert string to kebab-case\n */\nfunction toKebabCase(str: string): string {\n return str\n .replace(/([a-z])([A-Z])/g, \"$1-$2\")\n .replace(/[\\s_]+/g, \"-\")\n .toLowerCase();\n}\n\n/**\n * Simple expression evaluator for validation rules\n * In production, use a proper sandboxed expression evaluator\n */\nfunction evaluateSimpleExpression(\n expression: string,\n data: Record<string, unknown>\n): boolean {\n try {\n // This is a simplified implementation - in production, use a safe expression evaluator\n // For now, we'll just support basic comparisons\n\n // Replace field references with actual values\n let evalExpression = expression;\n for (const [key, value] of Object.entries(data)) {\n const quotedValue =\n typeof value === \"string\" ? `\"${value}\"` : String(value);\n evalExpression = evalExpression.replace(\n new RegExp(`\\\\b${key}\\\\b`, \"g\"),\n quotedValue\n );\n }\n\n // Very basic and LIMITED evaluation - only for demo purposes\n // In production, use a proper expression parser/evaluator\n if (evalExpression.includes(\"!==\")) {\n const [left, right] = evalExpression.split(\"!==\").map((s) => s.trim());\n return left !== right;\n }\n if (evalExpression.includes(\"===\")) {\n const [left, right] = evalExpression.split(\"===\").map((s) => s.trim());\n return left === right;\n }\n if (evalExpression.includes(\"||\")) {\n const parts = evalExpression.split(\"||\").map((s) => s.trim());\n return parts.some((part) => evaluateSimpleExpression(part, data));\n }\n if (evalExpression.includes(\"&&\")) {\n const parts = evalExpression.split(\"&&\").map((s) => s.trim());\n return parts.every((part) => evaluateSimpleExpression(part, data));\n }\n\n return false;\n } catch (error) {\n console.error(\"Expression evaluation failed:\", error);\n return false;\n }\n}\n\n/**\n * Parse all extension points from a .kos.json configuration\n */\nexport function parseExtensionPointsFromConfig(\n kosConfig: Record<string, unknown>\n): Array<ExtensionPointConfig<unknown, unknown>> {\n if (!kosConfig.extensionPoints || !Array.isArray(kosConfig.extensionPoints)) {\n return [];\n }\n\n const configs: Array<ExtensionPointConfig<unknown, unknown>> = [];\n\n for (const jsonDef of kosConfig.extensionPoints) {\n try {\n const config = parseJsonExtensionPoint(jsonDef);\n configs.push(config);\n } catch (error) {\n console.error(`Failed to parse extension point '${jsonDef.id}':`, error);\n }\n }\n\n return configs;\n}\n","import type { DynamicRemotes } from \"../../../types/global\";\nimport type { ProcessedContributions } from \"../../../types/plugins\";\nimport { getExtensionPointRegistry } from \"../extension-points/define-extension-point\";\n\nexport const contributionReducer =\n (remotes: DynamicRemotes) => (acc: ProcessedContributions, key: string) => {\n const remote = remotes[key].remote;\n const sectionId = remotes[key].section || \"default\";\n\n const experiences = remotes[key].contributes?.experiences ?? {};\n Object.keys(experiences).forEach((key) => {\n const experience = experiences[key];\n acc.experiences[key] = {\n ...experience,\n remote,\n sectionId,\n };\n });\n\n // Process contributions for simplified extension points\n const registry = getExtensionPointRegistry();\n const extensionPoints = registry.getAllExtensionPoints();\n\n extensionPoints.forEach((extensionPoint) => {\n const { contributionKey } = extensionPoint.config;\n\n // Check if this remote has contributions for this extension point\n const contributions = remotes[key].contributes?.[contributionKey];\n if (!contributions) return;\n\n // Initialize the contribution storage if needed\n if (!acc[contributionKey]) {\n acc[contributionKey] = {};\n }\n\n // Process each contribution\n if (Array.isArray(contributions)) {\n // Handle array-based contributions\n contributions.forEach((contribution) => {\n if (contribution && contribution.id) {\n acc[contributionKey][contribution.id] = {\n ...contribution,\n remote,\n sectionId,\n };\n }\n });\n } else if (typeof contributions === \"object\") {\n // Handle object-based contributions\n Object.entries(contributions).forEach(([contribId, contribution]) => {\n acc[contributionKey][contribId] = {\n ...(contribution as Record<string, any>),\n id: contribId,\n remote,\n sectionId,\n };\n });\n }\n });\n\n return acc;\n };\n","// plugin-extension-manager.ts\n\nimport { loadRemoteModule } from \"@nx/react/mf\";\nimport type { DynamicRemotes } from \"../../../types/global\";\nimport type {\n PluginExtension,\n PluginExtensionsType,\n ProcessedContributions,\n} from \"../../../types/plugins\";\n\nimport { defineExtensionPoint } from \"../extension-points/define-extension-point\";\nimport { parseJsonExtensionPoint } from \"../extension-points/json-extension-parser\";\nimport { contributionReducer } from \"../processors/contribution-reducer\";\nimport { applyExtensionReducers } from \"./plugin-extension-registry\";\nimport { ContributionRegistry } from \"../contribution-registry\";\n\ninterface PluginsType {\n remotes?: DynamicRemotes;\n extensions?: PluginExtensionsType;\n extensionPoints?: Record<string, PluginExtension[]>;\n getExtensions: (extensionPointId: string) => PluginExtension[];\n}\n\nexport async function initPluginManager(\n remotesOverride?: DynamicRemotes\n): Promise<PluginsType> {\n const remotes = remotesOverride ?? window.KosPlugins.__dynamicRemotes;\n\n if (window.KosPlugins.extensions) {\n const extensionPoints = window.KosPlugins.extensions;\n return {\n extensionPoints,\n getExtensions: (extensionPointId: string) =>\n extensionPoints[extensionPointId] || [],\n remotes,\n extensions: window.KosPlugins.__extensions,\n };\n }\n\n const extensions =\n window.KosPlugins.__extensions ?? (await loadExtensions(remotes));\n\n const extensionPoints: Record<string, PluginExtension[]> = {};\n if (extensions) {\n for (const extensionPointId of Object.keys(extensions)) {\n extensionPoints[extensionPointId] = Object.values(\n extensions[extensionPointId] || {}\n );\n }\n }\n\n window.KosPlugins.extensions = extensionPoints;\n\n const getExtensions = (extensionPointId: string) =>\n extensionPoints[extensionPointId] || [];\n\n return { extensionPoints, getExtensions, remotes, extensions };\n}\n\nconst DEFAULT_CONTRIBUTIONS: ProcessedContributions = {\n controlPourDefinitions: {},\n experiences: {},\n};\n\nexport function getContributions(\n remotes?: DynamicRemotes\n): ProcessedContributions {\n if (!remotes) {\n return DEFAULT_CONTRIBUTIONS;\n }\n return Object.keys(remotes).reduce(contributionReducer(remotes), {\n ...DEFAULT_CONTRIBUTIONS,\n });\n}\n\nexport async function loadExtensions(remotes?: DynamicRemotes) {\n if (!remotes) {\n window.KosPlugins = window.KosPlugins || {};\n return {};\n }\n\n // First pass: Parse JSON extension points and load InitPlugin modules\n // This ensures that any extension points (both JSON and TypeScript) are available\n // before we process contributions in the second pass\n for (const remote of Object.values(remotes)) {\n // Parse and register JSON-defined extension points\n try {\n if (remote.extensions && Array.isArray(remote.extensions)) {\n const jsonExtensionPoints = remote.extensions\n .filter((ext) => ext && typeof ext === \"object\" && \"id\" in ext)\n .map((epDef) => parseJsonExtensionPoint(epDef as unknown as any));\n\n if (jsonExtensionPoints.length > 0) {\n console.info(\n `Registering ${jsonExtensionPoints.length} JSON extension point(s) from ${remote.remote}`\n );\n\n for (const config of jsonExtensionPoints) {\n try {\n const extensionPoint = defineExtensionPoint(config);\n extensionPoint.register();\n console.debug(`Registered JSON extension point: ${config.id}`);\n } catch (error) {\n console.error(\n `Failed to register JSON extension point '${config.id}' from ${remote.remote}:`,\n error\n );\n }\n }\n }\n }\n } catch (error) {\n console.warn(\n `Failed to parse JSON extension points from ${remote.remote}:`,\n error\n );\n }\n\n // Then load TypeScript InitPlugin modules\n if (remote.init) {\n try {\n const InitPlugin = await loadRemoteModule(\n remote.remote,\n \"./InitPlugin\"\n );\n if (InitPlugin.default) {\n const initPlugin = new InitPlugin.default();\n initPlugin?.register();\n }\n } catch (error) {\n console.warn(`Failed to load InitPlugin from ${remote.remote}:`, error);\n }\n }\n }\n\n // Second pass: Now process contributions with full knowledge of all extension points\n const contributions = getContributions(remotes);\n const experiences = contributions.experiences;\n\n const baseExtensions: PluginExtensionsType = {};\n const reducedExtensions = applyExtensionReducers(\n baseExtensions,\n contributions,\n experiences\n );\n\n // Initialize ContributionRegistry context\n // This provides extensions and contributions for conditional enablement evaluation\n ContributionRegistry.setContext({\n extensions: reducedExtensions,\n contributions\n });\n\n window.KosPlugins = window.KosPlugins || {};\n window.KosPlugins.__extensions = reducedExtensions;\n return reducedExtensions;\n}\n\nexport async function getExtensions(extensionPointId: string) {\n const { getExtensions } = await initPluginManager();\n return getExtensions(extensionPointId);\n}\n","import { setRemoteDefinitions } from \"@nx/react/mf\";\nimport type { Contributions, DynamicRemotes } from \"../../../types/global\";\nimport type {\n PluginExtension,\n PluginExtensionsType,\n} from \"../../../types/plugins\";\nimport \"../plugin-system/plugin-extension-registry-init\";\n\ndeclare interface KosPluginsType {\n __dynamicRemotes: DynamicRemotes;\n __extensions?: PluginExtensionsType;\n extensions?: Record<string, PluginExtension[]>;\n}\ndeclare global {\n interface Window {\n KosPlugins: KosPluginsType;\n }\n}\n\nexport interface Extensions {\n extensionPointId: string;\n id: string;\n component: string;\n}\n\nexport interface Descriptor {\n id: string;\n baseUrl: string;\n descriptor: {\n id: string;\n extensions: Extensions[];\n contributes: Contributions;\n };\n}\n\ninterface KosPluginsProps {\n pluginBaseUrl?: string;\n pluginApiPath?: string;\n pluginContext?: {\n context?: string | string[];\n group?: string;\n };\n overrides?: Record<string, string>;\n}\n\n/**\n * Parses the query string from the URL or a provided string and returns an object\n * representing the key-value pairs in the query string.\n *\n * @param query - An optional query string to parse. If not provided, the function\n * will use the current window's `location.search` string.\n * The query string should not include the leading \"?\" character.\n *\n * @returns An object where each key is a parameter name from the query string,\n * and each value is the corresponding decoded parameter value.\n *\n * @example\n * // Assuming the URL is: https://example.com/?name=John&age=30\n * getQueryParams();\n * // Returns: { name: \"John\", age: \"30\" }\n *\n * @example\n * getQueryParams(\"foo=bar&baz=qux\");\n * // Returns: { foo: \"bar\", baz: \"qux\" }\n */\nexport const getQueryParams = (query = null) =>\n (query || window.location.search.replace(\"?\", \"\"))\n\n // get array of KeyValue pairs\n .split(\"&\")\n\n // Decode values\n .map((pair) => {\n const [key, val] = pair.split(\"=\");\n\n return [key, decodeURIComponent(val || \"\")];\n })\n\n // array to object\n .reduce((result, [key, val]) => {\n result[key] = val;\n return result;\n }, {});\n\nconst getDefaultHost = () => {\n const defaultHost = window.location.origin;\n const params = getQueryParams();\n const hostUrl = (params as Record<string, string>)?.host;\n const result = hostUrl || defaultHost;\n return result;\n};\n// eslint-disable-next-line no-restricted-globals\n\n/**\n * Initializes KOS plugins by fetching plugin metadata and configuring dynamic remotes.\n *\n * @param props - Optional properties to configure the plugin initialization.\n * @param props.pluginBaseUrl - The base URL for the plugins. Defaults to the result of `getDefaultHost()`.\n * @param props.pluginApiPath - The API path to fetch plugin metadata. Defaults to `\"/api/app/kosdev.ddk/ncui/plugins\"`.\n * @param props.overrides - An object containing overrides for plugin base URLs, keyed by plugin ID.\n * @param props.pluginContext - An optional context object that specifies the plugin context and group.\n * If provided, the function will fetch plugins from the UI plugins endpoint. Otherwise,\n * it will fetch from the DDK pluging endpoint.\n *\n * @returns A promise that resolves to a record of remote definitions, where the keys are remote IDs\n * and the values are the corresponding base paths for the remote entries.\n *\n * @remarks\n * - This function fetches plugin metadata from the specified API endpoint and processes the data\n * to configure dynamic remotes for the KOS plugin system.\n * - If a plugin does not have a descriptor, an error is logged to the console.\n * - The remote definitions are also set using the `setRemoteDefinitions` function.\n *\n * @throws Will throw an error if the fetch request fails or if the response cannot be parsed as JSON.\n */\nexport const initializeKosPlugins = async (props?: KosPluginsProps) => {\n const defaultHost = getDefaultHost();\n const data = props ?? {};\n const {\n pluginBaseUrl = defaultHost,\n pluginApiPath,\n overrides = {},\n pluginContext,\n } = data;\n\n console.log(\"[initialize-plugins] Config received:\", {\n propsPluginBaseUrl: props?.pluginBaseUrl,\n defaultHost,\n resolvedPluginBaseUrl: pluginBaseUrl,\n pluginApiPath,\n });\n\n const url = pluginApiPath\n ? `${pluginBaseUrl}${pluginApiPath}`\n : `${pluginBaseUrl}/api/kos/ui/plugins/contexts`;\n\n console.log(\n `initialize-plugins: Using Plugin Framework. Fetching plugins from ${url}`\n );\n const plugins = await fetch(url);\n const remotes = await plugins.json();\n\n // Check for third-party plugin dev servers in query parameters\n // Format: ?pluginDevServers=http://dev-machine:4201,http://dev-machine:4202\n const queryParams = getQueryParams() as Record<string, string>;\n const pluginDevServers = queryParams[\"pluginDevServers\"]\n ? queryParams[\"pluginDevServers\"]\n .split(\",\")\n .map((url: string) => url.trim())\n : [];\n\n if (pluginDevServers.length > 0) {\n console.log(\n \"[initialize-plugins] Detected third-party plugin dev servers:\",\n pluginDevServers\n );\n\n // Fetch from each dev server and merge plugins\n const devServerResponses = await Promise.all(\n pluginDevServers.map(async (serverUrl: string) => {\n try {\n console.log(\n `[initialize-plugins] Fetching from dev server: ${serverUrl}`\n );\n const response = await fetch(\n `${serverUrl}/api/kos/ui/plugins/contexts`\n );\n if (!response.ok) {\n console.warn(\n `[initialize-plugins] Dev server ${serverUrl} returned ${response.status}`\n );\n return null;\n }\n const data = await response.json();\n return { serverUrl, data };\n } catch (error) {\n console.warn(\n `[initialize-plugins] Failed to fetch from dev server ${serverUrl}:`,\n error\n );\n return null;\n }\n })\n );\n\n // Merge dev server plugins into remotes.data\n // Type guard to filter out null responses\n const validDevResponses = devServerResponses.filter(\n (r): r is { serverUrl: string; data: any } =>\n r !== null && r.data && r.data.status === 200\n );\n\n if (validDevResponses.length > 0) {\n console.log(\n `[initialize-plugins] Merging ${validDevResponses.length} dev server plugin(s)`\n );\n\n // Track overrides for dev server plugins\n const devServerOverrides: Record<string, string> = {};\n\n validDevResponses.forEach(({ serverUrl, data: devResponse }) => {\n devResponse.data?.forEach((contextGroup: any) => {\n // Find or create context in remotes.data\n let existingContext = remotes.data?.find(\n (ctx: any) => ctx.name === contextGroup.name\n );\n\n if (!existingContext) {\n existingContext = { name: contextGroup.name, plugins: [] };\n remotes.data = remotes.data || [];\n remotes.data.push(existingContext);\n }\n\n // Add dev server plugins with overrides\n contextGroup.plugins.forEach((plugin: any) => {\n existingContext.plugins.push(plugin);\n // Map plugin ID to dev server URL for override\n devServerOverrides[plugin.id] = `${serverUrl}/`;\n console.log(\n `[initialize-plugins] Added dev plugin: ${plugin.descriptor?.id} from ${serverUrl}`\n );\n });\n });\n });\n\n // Merge dev server overrides\n remotes.overrides = {\n ...(remotes.overrides || {}),\n ...devServerOverrides,\n };\n\n console.log(\n \"[initialize-plugins] Dev server overrides:\",\n devServerOverrides\n );\n }\n }\n\n // Merge overrides from props with overrides from response (dev mode aggregator)\n // Response overrides take precedence for dev mode compatibility\n const mergedOverrides = {\n ...overrides,\n ...(remotes.overrides || {}),\n };\n\n if (remotes.overrides) {\n console.log(\n \"[initialize-plugins] Using overrides from response:\",\n remotes.overrides\n );\n }\n if (Object.keys(mergedOverrides).length > 0) {\n console.log(\"[initialize-plugins] Merged overrides:\", mergedOverrides);\n }\n\n const context =\n typeof pluginContext?.context === \"string\"\n ? [pluginContext.context]\n : pluginContext?.context || [];\n const pluginData = remotes.data\n ?.filter((item) => context.length === 0 || context.includes(item.name))\n .flatMap(\n (i) =>\n i.plugins.map((p) => {\n return { ...p, name: i.name };\n }) ?? []\n );\n\n const pluginGroup = pluginContext?.group;\n const allRemotes = pluginData?.reduce((acc: DynamicRemotes, item: any) => {\n const baseUrl =\n mergedOverrides?.[item.id] ?? `${pluginBaseUrl}${item.path}`;\n\n if (item.descriptor) {\n const extensions = item.descriptor.extensions || [];\n const filteredExtensions = extensions.reduce((acc, ext) => {\n const groups = ext.groups || [];\n if (!pluginGroup || groups.includes(pluginGroup)) {\n acc.push(ext);\n }\n return acc;\n }, [] as Extensions[]);\n const contributes = item.descriptor.contributes || {};\n let hasContributes = false;\n const filteredContributes = Object.keys(contributes).reduce(\n (acc, key) => {\n if (Array.isArray(contributes[key])) {\n const contributions = (contributes[key] || []).filter((c) => {\n const groups = c.groups || [];\n return !pluginGroup || groups.includes(pluginGroup);\n });\n hasContributes = hasContributes || contributions.length > 0;\n acc[key] = contributions;\n } else {\n acc[key] = contributes[key];\n hasContributes = Object.keys(contributes[key]).length > 0;\n }\n return acc;\n },\n {} as Contributions\n );\n\n const init =\n !!item.descriptor.init &&\n (filteredExtensions.length > 0 || hasContributes);\n acc[item.id] = {\n section: item.name,\n basePath: `${baseUrl}remoteEntry.js`,\n extensions: filteredExtensions,\n contributes: filteredContributes,\n remote: item.descriptor.id,\n init,\n };\n } else {\n console.error(\n `initialize-plugins: Plugin ${item.id} does not have a descriptor`\n );\n }\n return acc;\n }, {} as DynamicRemotes);\n window.KosPlugins = window.KosPlugins || {};\n window.KosPlugins.__dynamicRemotes = allRemotes;\n const definitions = Object.keys(allRemotes).reduce((acc, item) => {\n const remote = allRemotes[item].remote;\n acc[remote] = allRemotes[item].basePath;\n return acc;\n }, {} as Record<string, string>);\n setRemoteDefinitions(definitions);\n return definitions;\n};\n","import type { ContributionStateChangeEvent } from \"../../types/contribution-enablement\";\nimport type {\n PluginExtension,\n PluginExtensionsType,\n} from \"../../types/plugins\";\nimport { ContributionRegistry } from \"./contribution-registry\";\nimport { resolveBestExtension } from \"./plugin-system/resolve-best-extension\";\n\n/**\n * Event emitted when extension point changes\n */\nexport interface ExtensionPointChangeEvent {\n extensionPoint: string;\n changeType: \"contribution-enabled\" | \"contribution-disabled\" | \"best-changed\";\n affectedContribution: string;\n newBest?: string;\n timestamp: number;\n}\n\n/**\n * Reactive extension registry that monitors contribution state\n *\n * Bridges the gap between ContributionRegistry (state management) and\n * React components by providing filtered extension lists and change notifications.\n *\n * This registry:\n * - Filters extensions based on enabled state\n * - Subscribes to ContributionRegistry for state changes\n * - Emits ExtensionPointChangeEvent when contributions change\n * - Manages extension point-scoped subscriptions\n * - Handles cleanup to prevent memory leaks\n *\n * @example\n * ```typescript\n * const registry = new ReactiveExtensionRegistry(extensions);\n *\n * // Get only enabled extensions\n * const enabledExtensions = registry.getExtensions('ddk.settings.view');\n *\n * // Subscribe to changes\n * const unsubscribe = registry.subscribe('ddk.settings.view', (event) => {\n * console.log('Extension point changed:', event);\n * });\n *\n * // Cleanup when done\n * registry.destroy();\n * ```\n */\nexport class ReactiveExtensionRegistry {\n /**\n * Reference to all plugin extensions (unfiltered)\n */\n private extensions: PluginExtensionsType;\n\n /**\n * Map of extension point to listeners\n * Each extension point can have multiple components listening for changes\n */\n private listeners: Map<\n string,\n Set<(event: ExtensionPointChangeEvent) => void>\n >;\n\n /**\n * Unsubscribe function for ContributionRegistry subscription\n * Used during cleanup to remove listener\n */\n private contributionUnsubscribe: (() => void) | null = null;\n\n constructor(extensions: PluginExtensionsType) {\n this.extensions = extensions;\n this.listeners = new Map();\n this.subscribeToContributionChanges();\n }\n\n /**\n * Get extensions for an extension point (filtered by enabled state)\n *\n * By default, only returns enabled contributions. Use `includeDisabled: true`\n * to get all contributions regardless of state.\n *\n * @param extensionPoint - Extension point identifier\n * @param includeDisabled - If true, include disabled contributions (default: false)\n * @returns Record of extension ID to extension object\n *\n * @example\n * ```typescript\n * // Get only enabled settings extensions\n * const enabled = registry.getExtensions('ddk.settings.view');\n *\n * // Get all settings extensions (including disabled)\n * const all = registry.getExtensions('ddk.settings.view', true);\n * ```\n */\n getExtensions(\n extensionPoint: string,\n includeDisabled = false\n ): Record<string, PluginExtension> {\n const allExtensions = this.extensions[extensionPoint] || {};\n\n if (includeDisabled) {\n return allExtensions;\n }\n\n // Filter to only enabled contributions\n return Object.entries(allExtensions).reduce((acc, [id, ext]) => {\n if (ContributionRegistry.isEnabled(id)) {\n acc[id] = ext;\n }\n return acc;\n }, {} as Record<string, PluginExtension>);\n }\n\n /**\n * Subscribe to changes for a specific extension point\n *\n * Registers a listener that will be called whenever contributions for\n * the specified extension point change state (enabled/disabled) or when\n * the best contribution for that point changes.\n *\n * @param extensionPoint - Extension point identifier to monitor\n * @param listener - Callback function to handle change events\n * @returns Unsubscribe function to stop receiving events\n *\n * @example\n * ```typescript\n * const unsubscribe = registry.subscribe('ddk.settings.view', (event) => {\n * if (event.changeType === 'best-changed') {\n * console.log('New best contribution:', event.newBest);\n * }\n * });\n *\n * // Later...\n * unsubscribe();\n * ```\n */\n subscribe(\n extensionPoint: string,\n listener: (event: ExtensionPointChangeEvent) => void\n ): () => void {\n if (typeof listener !== \"function\") {\n throw new TypeError(\n \"ReactiveExtensionRegistry.subscribe: listener must be a function\"\n );\n }\n\n if (!this.listeners.has(extensionPoint)) {\n this.listeners.set(extensionPoint, new Set());\n }\n this.listeners.get(extensionPoint)!.add(listener);\n\n // Return unsubscribe function\n return () => {\n this.listeners.get(extensionPoint)?.delete(listener);\n\n // Cleanup empty sets to prevent memory leaks\n if (this.listeners.get(extensionPoint)?.size === 0) {\n this.listeners.delete(extensionPoint);\n }\n };\n }\n\n /**\n * Internal: Subscribe to contribution state changes\n *\n * Sets up subscription to ContributionRegistry to receive notifications\n * when any contribution's enabled state changes. Routes these events to\n * extension point-specific listeners.\n *\n * @private\n */\n private subscribeToContributionChanges(): void {\n this.contributionUnsubscribe = ContributionRegistry.subscribe((event) =>\n this.handleContributionChange(event)\n );\n }\n\n /**\n * Internal: Handle contribution state change\n *\n * Called when ContributionRegistry emits a state change event.\n * Determines if the \"best\" contribution has changed and emits\n * ExtensionPointChangeEvent to all listeners for that extension point.\n *\n * @param event - Contribution state change event from ContributionRegistry\n * @private\n */\n private handleContributionChange(event: ContributionStateChangeEvent): void {\n const { contributionId, extensionPoint, enabled } = event;\n\n // Skip if no listeners for this extension point (optimization)\n if (!this.listeners.has(extensionPoint)) {\n return;\n }\n\n // Get current and previous best to detect if best changed\n const extensionsBeforeFilter = this.extensions[extensionPoint] || {};\n\n // Calculate best contribution before the change\n // We need to temporarily revert the state to get \"previous best\"\n const currentBest = resolveBestExtension(\n this.getExtensions(extensionPoint)\n );\n\n const changeType = enabled\n ? \"contribution-enabled\"\n : \"contribution-disabled\";\n\n // Emit event to subscribers\n const listeners = this.listeners.get(extensionPoint);\n if (listeners) {\n const changeEvent: ExtensionPointChangeEvent = {\n extensionPoint,\n changeType,\n affectedContribution: contributionId,\n newBest: currentBest?.id,\n timestamp: event.timestamp,\n };\n\n listeners.forEach((listener) => {\n try {\n listener(changeEvent);\n } catch (error) {\n console.error(\n `ReactiveExtensionRegistry: Error in listener for '${extensionPoint}':`,\n error\n );\n }\n });\n }\n }\n\n /**\n * Cleanup subscriptions and listeners\n *\n * Call this when the registry is no longer needed to prevent memory leaks.\n * Typically called when the PluginsProvider is unmounted.\n *\n * @example\n * ```typescript\n * useEffect(() => {\n * const registry = new ReactiveExtensionRegistry(extensions);\n * // Use registry...\n * return () => registry.destroy();\n * }, []);\n * ```\n */\n destroy(): void {\n // Unsubscribe from ContributionRegistry\n this.contributionUnsubscribe?.();\n this.contributionUnsubscribe = null;\n\n // Clear all listeners to prevent memory leaks\n this.listeners.clear();\n }\n}\n","/* eslint-disable max-lines-per-function */\nimport type { Contributions } from \"../../../types/global\";\n\ninterface KosConfigView {\n id: string;\n title: string;\n component: string;\n location: string;\n}\n\ninterface KosPluginConfig {\n id: string;\n init?: boolean;\n contributes: Contributions;\n}\n\ninterface DDKConfig {\n name: string;\n kosdev: {\n ddk: {\n ncui: {\n plugin: KosPluginConfig;\n };\n };\n };\n}\n\ninterface CoreKosConfig {\n name: string;\n kos: {\n ui: {\n plugin: KosPluginConfig;\n };\n };\n}\n\nexport type KosConfig = DDKConfig | CoreKosConfig;\n\nfunction normalizeVersion(version: string): string {\n const match = version.match(/^(\\d+)\\.(\\d+)\\.\\d+(?:-\\S+)?$/);\n if (!match) {\n throw new Error(`Invalid version format: ${version}`);\n }\n const [_, major, minor] = match;\n return `${major}.${minor}.0`;\n}\n\nexport interface PluginOptions {\n sdkVersion?: string;\n ddkVersion?: string;\n pluginPath?: string;\n}\nexport function generatePluginConfiguration(\n config: KosConfig,\n options?: PluginOptions\n): any {\n if (options?.sdkVersion) {\n console.log(\"sdkVersion\", options.sdkVersion);\n }\n if (options?.ddkVersion) {\n console.log(\"ddkVersion\", options.ddkVersion);\n }\n const sdkVersion = normalizeVersion(options?.sdkVersion || \"0.2.0\");\n const ddkVersion = normalizeVersion(options?.ddkVersion || \"0.2.0\");\n\n console.log(`Using DDK version: ${ddkVersion}`);\n console.log(`Using SDK version: ${sdkVersion}`);\n const projectId = config?.name;\n if (!projectId) {\n throw new Error(\n \"KOS Configuration should be added. Project name not found in config\"\n );\n }\n const pluginPath = options?.pluginPath || \"kos.ui.plugin\";\n const pluginObj = pluginPath\n .split(\".\")\n .reduce<KosPluginConfig>((obj, key) => {\n console.log(`Accessing key: ${key}`);\n return obj && obj[key] ? obj[key] : undefined;\n }, config as unknown as KosPluginConfig);\n\n const pluginId = pluginObj?.id;\n if (!pluginId) {\n throw new Error(\n \"KOS Configuration should be added. Plugin ID not found in config\"\n );\n }\n const mfConfig = Object.keys(pluginObj?.contributes?.views || {}).reduce(\n (acc, key) => {\n const views = pluginObj.contributes.views[key];\n\n views.forEach((view) => {\n acc[`./${view.component}`] = view.location;\n });\n return acc;\n },\n {}\n );\n\n Object.values(pluginObj?.contributes?.experiences || {}).forEach(\n (experience) => {\n mfConfig[`./${experience.component}`] = experience.location;\n }\n );\n\n if (pluginObj?.init) {\n mfConfig[\"./InitPlugin\"] = \"./src/app/init.ts\";\n }\n\n return {\n name: projectId,\n exposes: mfConfig,\n library: { type: \"var\", name: pluginId },\n additionalShared: [\n {\n libraryName: \"@kosdev-code/kos-ui-plugin\",\n sharedConfig: {\n singleton: true,\n eager: false,\n requiredVersion: `~${ddkVersion}`,\n },\n },\n {\n libraryName: \"react\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: true,\n requiredVersion: \"18.2.0\",\n },\n },\n\n {\n libraryName: \"react-dom\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: true,\n requiredVersion: \"18.2.0\",\n },\n },\n {\n libraryName: \"@kosdev-code/kos-ui-sdk\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: `~${sdkVersion}`,\n },\n },\n {\n libraryName: \"@kosdev-code/kos-dispense-sdk\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: `~${sdkVersion}`,\n },\n },\n\n {\n libraryName: \"@kosdev-code/kos-freestyle-sdk\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: `~${sdkVersion}`,\n },\n },\n {\n libraryName: \"@kosdev-code/kos-ddk-components\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: `~${ddkVersion}`,\n },\n },\n {\n libraryName: \"@kosdev-code/kos-ddk-model-components\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: `~${ddkVersion}`,\n },\n },\n {\n libraryName: \"@kosdev-code/kos-ddk-models\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: `~${ddkVersion}`,\n },\n },\n {\n libraryName: \"@kosdev-code/kos-ddk\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: `~${ddkVersion}`,\n },\n },\n {\n libraryName: \"@kosdev-code/kos-ddk-styles\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: `~${ddkVersion}`,\n },\n },\n {\n libraryName: \"@emotion/styled\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"~11.11.0\",\n },\n },\n {\n libraryName: \"@emotion/react\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"~11.11.0\",\n },\n },\n {\n libraryName: \"reflect-metadata\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^0.2.2\",\n },\n },\n {\n libraryName: \"mobx\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^6.9.0\",\n },\n },\n\n {\n libraryName: \"loglevel\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^1.8.1\",\n },\n },\n {\n libraryName: \"robot3\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^0.4.0\",\n },\n },\n {\n libraryName: \"mobx-react-lite\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^3.4.3\",\n },\n },\n {\n libraryName: \"react-router-dom\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^6.11.2\",\n },\n },\n {\n libraryName: \"date-fns\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^2.30.0\",\n },\n },\n {\n libraryName: \"@use-gesture/react\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^10.3.0\",\n },\n },\n {\n libraryName: \"@react-spring/web\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^9.7.3\",\n },\n },\n {\n libraryName: \"react-simple-keyboard\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^3.6.13\",\n },\n },\n {\n libraryName: \"expr-eval\",\n sharedConfig: {\n singleton: true,\n eager: false,\n strictVersion: false,\n requiredVersion: \"^2.0.2\",\n },\n },\n {\n libraryName: \"zod\",\n sharedConfig: {\n singleton: true,\n eager: true,\n strictVersion: false,\n requiredVersion: \"^3.25.0\",\n },\n },\n ],\n };\n}\n","/**\n * Common Zod schemas and validation helpers for extension points\n *\n * Provides reusable base schemas and validation functions to reduce\n * duplication across extension point definitions.\n */\n\nimport { z } from \"zod\";\nimport type { ValidationContext } from \"./define-extension-point\";\n\n/**\n * Base schema for view-based DDK extension points\n * Contains common fields that all DDK extension points share\n */\nexport const BaseViewExtensionSchema = z.object({\n id: z\n .string()\n .min(1, \"ID is required\")\n .describe(\"Unique identifier for this extension\"),\n title: z\n .string()\n .min(1, \"Title is required\")\n .describe(\"Display title shown in the interface\"),\n namespace: z\n .string()\n .min(1, \"Namespace is required\")\n .describe(\"Namespace for organizing related extensions\"),\n experienceId: z\n .string()\n .min(1, \"Experience ID is required\")\n .describe(\"Reference to the UI component experience for rendering\"),\n});\n\n/**\n * Base schema with optional ranking support\n */\nexport const RankableViewExtensionSchema = BaseViewExtensionSchema.extend({\n rank: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Optional ranking for ordering (higher = preferred)\"),\n});\n\n/**\n * Performs standard Zod validation and adds errors to the validation context\n *\n * @param schema The Zod schema to validate against\n * @param data The data to validate\n * @param context The validation context to add errors to\n * @returns true if validation passed, false if errors were added\n */\nexport function validateWithSchema<T>(\n schema: z.ZodSchema<T>,\n data: unknown,\n context: ValidationContext\n): boolean {\n const result = schema.safeParse(data);\n if (!result.success) {\n result.error.errors.forEach((error) => {\n context.addError(`${error.path.join(\".\")}: ${error.message}`);\n });\n return false;\n }\n return true;\n}\n\n/**\n * Common validation for descriptor fields that should use dot notation\n *\n * @param descriptorField The name of the descriptor field (e.g., \"setupDescriptor\", \"cuiDescriptor\")\n * @param descriptorValue The value of the descriptor field\n * @param context The validation context to add warnings to\n */\nexport function validateDescriptorFormat(\n descriptorField: string,\n descriptorValue: string | undefined,\n context: ValidationContext\n): void {\n if (descriptorValue && !descriptorValue.includes(\".\")) {\n context.addWarning(\n `${descriptorField} '${descriptorValue}' should typically include dot notation (e.g., 'category.item')`\n );\n }\n}\n\n/**\n * Common validation for rank values to ensure they're reasonable\n *\n * @param rank The rank value to validate\n * @param context The validation context to add warnings to\n * @param maxReasonableRank The maximum reasonable rank value (default 1000)\n */\nexport function validateRank(\n rank: number | undefined,\n context: ValidationContext,\n maxReasonableRank = 1000\n): void {\n if (rank !== undefined && rank > maxReasonableRank) {\n context.addWarning(\n `Rank ${rank} seems unusually high - consider using lower values for better ordering`\n );\n }\n}\n\n/**\n * Helper to create extension-specific schemas by extending the base\n * and adding custom fields\n *\n * @param additionalFields Additional fields specific to this extension point\n * @param options Options for schema creation\n * @returns Extended schema with base fields and additional fields\n */\nexport function createExtensionSchema<T extends z.ZodRawShape>(\n additionalFields: T,\n options: { rankable?: boolean } = {}\n): z.ZodObject<\n z.objectUtil.extendShape<\n | (typeof BaseViewExtensionSchema)[\"shape\"]\n | (typeof RankableViewExtensionSchema)[\"shape\"],\n T\n >\n> {\n const baseSchema = options.rankable\n ? RankableViewExtensionSchema\n : BaseViewExtensionSchema;\n return baseSchema.extend(additionalFields);\n}\n\n/**\n * Type-safe validation for rankable extensions\n * Only validates rank if the data has a rank property\n */\nexport function validateRankIfPresent(\n data: unknown,\n context: ValidationContext,\n maxReasonableRank = 1000\n): void {\n if (typeof data === \"object\" && data !== null && \"rank\" in data) {\n const typedData = data as { rank?: number };\n validateRank(typedData.rank, context, maxReasonableRank);\n }\n}\n\n/**\n * Type helper for inferring types from extension schemas\n */\nexport type InferExtensionSchema<T extends z.ZodTypeAny> = z.infer<T>;\n","/**\n * Plugin Discovery Service\n *\n * Pure business logic for discovering and analyzing plugins and extension points.\n * No UI dependencies - can be used by CLI tools, tests, or any consumer.\n */\n\nimport type {\n PluginExtension,\n PluginExtensionsType,\n} from \"../../../types/plugins\";\nimport { getExtensionPointRegistry } from \"../extension-points/define-extension-point\";\n\nexport interface ExtensionPointInfo {\n id: string;\n displayName?: string;\n description?: string;\n source: \"simplified\" | \"legacy\";\n metadata?: {\n category?: string;\n tags?: string[];\n since?: string;\n deprecated?: boolean;\n owner?: string;\n };\n pluginCount: number;\n plugins: PluginExtension[];\n}\n\nexport interface PluginHealthStats {\n totalExtensionPoints: number;\n extensionPointsWithPlugins: number;\n totalPlugins: number;\n simplifiedExtensionPoints: number;\n legacyExtensionPoints: number;\n deprecatedExtensionPoints: number;\n}\n\nexport interface PluginDiscoveryOptions {\n includeLegacyExtensions?: boolean;\n includeEmptyExtensionPoints?: boolean;\n}\n\nexport interface PluginDescriptorValidationResult {\n isValid: boolean;\n errors: string[];\n warnings: string[];\n missingRequired: string[];\n suggestions: string[];\n}\n\nexport interface CompatibilityCheckResult {\n isCompatible: boolean;\n issues: string[];\n missingExtensionPoints: string[];\n incompatibleTypes: string[];\n suggestions: string[];\n}\n\nexport interface PluginDescriptor {\n id: string;\n init?: boolean;\n contributes?: {\n [key: string]: any[];\n };\n}\n\n/**\n * Plugin Discovery Service - Core business logic for plugin analysis\n */\nexport class PluginDiscoveryService {\n /**\n * Get all extension points with their plugin information\n */\n static getExtensionPoints(\n extensions: PluginExtensionsType | undefined,\n options: PluginDiscoveryOptions = {}\n ): ExtensionPointInfo[] {\n const {\n includeLegacyExtensions = true,\n includeEmptyExtensionPoints = true,\n } = options;\n const registry = getExtensionPointRegistry();\n const simplifiedExtensionPoints = registry.getAllExtensionPoints();\n const result: ExtensionPointInfo[] = [];\n\n // Add simplified extension points\n simplifiedExtensionPoints.forEach((point) => {\n const plugins = Object.values(extensions?.[point.id] || {});\n\n if (!includeEmptyExtensionPoints && plugins.length === 0) {\n return;\n }\n\n result.push({\n id: point.id,\n displayName: point.config.displayName,\n description: point.config.description,\n source: \"simplified\",\n metadata: point.config.metadata,\n pluginCount: plugins.length,\n plugins,\n });\n });\n\n // Add legacy extension points (if enabled)\n if (includeLegacyExtensions && extensions) {\n Object.entries(extensions).forEach(([extensionId, extensionPlugins]) => {\n // Skip if already added as simplified extension point\n if (result.some((item) => item.id === extensionId)) {\n return;\n }\n\n const plugins = Object.values(extensionPlugins || {});\n\n if (!includeEmptyExtensionPoints && plugins.length === 0) {\n return;\n }\n\n result.push({\n id: extensionId,\n source: \"legacy\",\n pluginCount: plugins.length,\n plugins,\n });\n });\n }\n\n return result.sort((a, b) => a.id.localeCompare(b.id));\n }\n\n /**\n * Filter extension points based on search criteria\n */\n static filterExtensionPoints(\n extensionPoints: ExtensionPointInfo[],\n searchTerm: string\n ): ExtensionPointInfo[] {\n if (!searchTerm.trim()) {\n return extensionPoints;\n }\n\n const term = searchTerm.toLowerCase();\n return extensionPoints.filter(\n (point) =>\n point.id.toLowerCase().includes(term) ||\n point.displayName?.toLowerCase().includes(term) ||\n point.description?.toLowerCase().includes(term) ||\n point.metadata?.category?.toLowerCase().includes(term) ||\n point.metadata?.tags?.some((tag) => tag.toLowerCase().includes(term))\n );\n }\n\n /**\n * Calculate health statistics for the plugin system\n */\n static calculateHealthStats(\n extensionPoints: ExtensionPointInfo[]\n ): PluginHealthStats {\n const totalExtensionPoints = extensionPoints.length;\n const extensionPointsWithPlugins = extensionPoints.filter(\n (point) => point.pluginCount > 0\n ).length;\n const totalPlugins = extensionPoints.reduce(\n (sum, point) => sum + point.pluginCount,\n 0\n );\n const simplifiedExtensionPoints = extensionPoints.filter(\n (point) => point.source === \"simplified\"\n ).length;\n const legacyExtensionPoints = extensionPoints.filter(\n (point) => point.source === \"legacy\"\n ).length;\n const deprecatedExtensionPoints = extensionPoints.filter(\n (point) => point.metadata?.deprecated\n ).length;\n\n return {\n totalExtensionPoints,\n extensionPointsWithPlugins,\n totalPlugins,\n simplifiedExtensionPoints,\n legacyExtensionPoints,\n deprecatedExtensionPoints,\n };\n }\n\n /**\n * Analyze a specific plugin for health and capabilities\n */\n static analyzePlugin(plugin: PluginExtension): {\n hasComponent: boolean;\n hasRank: boolean;\n healthStatus: \"healthy\" | \"warning\" | \"error\";\n capabilities: string[];\n } {\n const hasComponent = !!(plugin as any).component;\n const hasRank = typeof (plugin as any).rank === \"number\";\n const rank = (plugin as any).rank || 0;\n const capabilities: string[] = [];\n\n // Add meaningful capabilities for developers\n if (hasComponent) {\n capabilities.push(\"UI Component\");\n } else {\n capabilities.push(\"Background Service\");\n }\n\n if (hasRank) capabilities.push(`Rank: ${rank}`);\n\n // Add more meaningful plugin characteristics\n if ((plugin as any).namespace) {\n const namespace = (plugin as any).namespace;\n if (namespace.includes(\"kos\") || namespace.includes(\"ddk\")) {\n capabilities.push(\"First-party\");\n } else {\n capabilities.push(\"Third-party\");\n }\n }\n\n // Check for modal mode (CUI plugins)\n if ((plugin as any).modalMode) {\n capabilities.push(`Modal: ${(plugin as any).modalMode}`);\n }\n\n // Simple health analysis - could be more sophisticated\n let healthStatus: \"healthy\" | \"warning\" | \"error\" = \"healthy\";\n\n if (!plugin.remote) {\n healthStatus = \"warning\";\n }\n\n // Could add more health checks:\n // - Check if module actually loads\n // - Validate plugin descriptor schema\n // - Check for required properties\n\n return {\n hasComponent,\n hasRank,\n healthStatus,\n capabilities,\n };\n }\n\n /**\n * Get extension point by ID with detailed information\n */\n static getExtensionPointById(\n extensionPoints: ExtensionPointInfo[],\n id: string\n ): ExtensionPointInfo | undefined {\n return extensionPoints.find((point) => point.id === id);\n }\n\n /**\n * Validate if an extension point ID follows conventions\n */\n static validateExtensionPointId(id: string): {\n isValid: boolean;\n issues: string[];\n suggestions: string[];\n } {\n const issues: string[] = [];\n const suggestions: string[] = [];\n\n // Check basic format\n if (!id.includes(\".\")) {\n issues.push(\n \"Extension point ID should contain at least one dot (namespace.feature)\"\n );\n suggestions.push('Use format like \"ddk.myFeature\" or \"app.myFeature\"');\n }\n\n // Check namespace conventions\n const parts = id.split(\".\");\n if (parts.length < 2) {\n issues.push(\n \"Extension point ID should have at least 2 parts (namespace.feature)\"\n );\n }\n\n const namespace = parts[0];\n if (\n namespace &&\n ![\"ddk\", \"cui\", \"app\"].includes(namespace) &&\n !namespace.endsWith(\"app\")\n ) {\n suggestions.push(\n \"Consider using standard namespaces: ddk, cui, or [appname]app\"\n );\n }\n\n // Check for camelCase in parts\n const hasCamelCase = parts.some((part) => /[A-Z]/.test(part));\n if (hasCamelCase) {\n issues.push(\"Extension point ID parts should be lowercase\");\n suggestions.push(\n 'Use kebab-case or dot notation: \"my.feature\" not \"my.myFeature\"'\n );\n }\n\n return {\n isValid: issues.length === 0,\n issues,\n suggestions,\n };\n }\n\n /**\n * Validate a plugin descriptor structure and content\n */\n static validatePluginDescriptor(\n descriptor: PluginDescriptor\n ): PluginDescriptorValidationResult {\n const errors: string[] = [];\n const warnings: string[] = [];\n const missingRequired: string[] = [];\n const suggestions: string[] = [];\n\n // Required fields validation\n if (!descriptor.id) {\n missingRequired.push(\"id\");\n errors.push(\"Plugin descriptor must have an 'id' field\");\n } else {\n // Validate ID format (informational only)\n if (!descriptor.id.match(/^[a-z0-9-]+$/)) {\n suggestions.push(\n \"Plugin ID convention: use lowercase letters, numbers, and hyphens (e.g., 'my-awesome-plugin')\"\n );\n }\n }\n\n // Contributions validation\n if (!descriptor.contributes) {\n warnings.push(\n \"Plugin has no contributions - it won't extend any functionality\"\n );\n suggestions.push(\"Add a 'contributes' section with plugin contributions\");\n } else {\n const contributionKeys = Object.keys(descriptor.contributes);\n if (contributionKeys.length === 0) {\n warnings.push(\"Plugin contributes section is empty\");\n }\n\n // Validate each contribution type\n contributionKeys.forEach((key) => {\n const contributions = descriptor.contributes![key];\n if (!Array.isArray(contributions)) {\n errors.push(`Contribution '${key}' must be an array`);\n return;\n }\n\n contributions.forEach((contrib, index) => {\n if (!contrib.id) {\n errors.push(\n `Contribution ${key}[${index}] missing required 'id' field`\n );\n }\n\n // Validate view contributions\n if (key === \"experiences\" && contrib.component && !contrib.location) {\n errors.push(\n `Experience '${contrib.id}' has component but no location`\n );\n suggestions.push(\n \"Add 'location' field pointing to the component file\"\n );\n }\n\n // Validate common required fields based on contribution type\n if ([\"cui\", \"utilities\", \"settings\", \"setup\"].includes(key)) {\n if (!contrib.title) {\n warnings.push(\n `${key} contribution '${contrib.id}' missing 'title' field`\n );\n }\n if (!contrib.namespace) {\n warnings.push(\n `${key} contribution '${contrib.id}' missing 'namespace' field`\n );\n }\n if (!contrib.experienceId) {\n errors.push(\n `${key} contribution '${contrib.id}' missing required 'experienceId' field`\n );\n }\n }\n });\n });\n }\n\n // Init flag validation\n if (descriptor.init !== undefined && typeof descriptor.init !== \"boolean\") {\n errors.push(\"'init' field must be a boolean value\");\n }\n\n return {\n isValid: errors.length === 0 && missingRequired.length === 0,\n errors,\n warnings,\n missingRequired,\n suggestions,\n };\n }\n\n /**\n * Check compatibility between plugin contributions and available extension points\n */\n static checkPluginCompatibility(\n pluginDescriptor: PluginDescriptor,\n availableExtensionPoints: ExtensionPointInfo[]\n ): CompatibilityCheckResult {\n const issues: string[] = [];\n const missingExtensionPoints: string[] = [];\n const incompatibleTypes: string[] = [];\n const suggestions: string[] = [];\n\n if (!pluginDescriptor.contributes) {\n return {\n isCompatible: true,\n issues: [\"Plugin has no contributions to check\"],\n missingExtensionPoints: [],\n incompatibleTypes: [],\n suggestions: [],\n };\n }\n\n const registry = getExtensionPointRegistry();\n const availableIds = new Set(\n availableExtensionPoints.map((point) => point.id)\n );\n\n // Check each contribution type\n Object.entries(pluginDescriptor.contributes).forEach(\n ([contributionKey, contributions]) => {\n // Map contribution keys to expected extension point IDs\n const expectedExtensionPoints =\n this.getExpectedExtensionPoints(contributionKey);\n\n expectedExtensionPoints.forEach((extensionPointId) => {\n if (!availableIds.has(extensionPointId)) {\n missingExtensionPoints.push(extensionPointId);\n issues.push(\n `Extension point '${extensionPointId}' not available for '${contributionKey}' contributions`\n );\n suggestions.push(\n `Ensure the extension point '${extensionPointId}' is registered`\n );\n }\n });\n\n // Check simplified extension point compatibility\n const simplifiedPoints = registry.getAllExtensionPoints();\n const matchingPoint = simplifiedPoints.find(\n (point) => point.config.contributionKey === contributionKey\n );\n\n if (matchingPoint && contributions.length > 0) {\n // Validate contribution structure matches extension point expectations\n contributions.forEach((contrib: any, index) => {\n if (\n matchingPoint.config.isRankable &&\n typeof contrib.rank !== \"number\"\n ) {\n issues.push(\n `${contributionKey}[${index}]: Extension point '${matchingPoint.id}' expects 'rank' property`\n );\n suggestions.push(\n \"Add 'rank' property with numeric value for ordering\"\n );\n }\n\n if (matchingPoint.config.hasView && !contrib.experienceId) {\n issues.push(\n `${contributionKey}[${index}]: Extension point '${matchingPoint.id}' expects 'experienceId' for view-based contributions`\n );\n suggestions.push(\n \"Add 'experienceId' property linking to an experience definition\"\n );\n }\n });\n }\n }\n );\n\n return {\n isCompatible: issues.length === 0,\n issues,\n missingExtensionPoints,\n incompatibleTypes,\n suggestions,\n };\n }\n\n /**\n * Map contribution keys to their expected extension point IDs\n */\n private static getExpectedExtensionPoints(contributionKey: string): string[] {\n // Known mappings from existing system\n const mappings: Record<string, string[]> = {\n cui: [\"ddk.cui\", \"ddk.cui.view\", \"ddk.cui.settings.config\"],\n utilities: [\"ddk.utility\", \"ddk.utility.view\", \"ddk.utilities\"],\n setup: [\"ddk.setup\", \"ddk.setup.view\"],\n settings: [\"ddk.settings\", \"ddk.settings.view\"],\n troubleActions: [\"ddk.troubleAction\", \"ddk.troubleAction.view\"],\n navViews: [\"ddk.nav\", \"ddk.nav.view\"],\n controlPour: [\"ddk.controlPour\", \"ddk.controlPour.view\"],\n experiences: [], // Experiences don't directly map to extension points\n views: [], // Views are mapped by their extension point ID keys\n };\n\n return mappings[contributionKey] || [];\n }\n\n /**\n * Get comprehensive plugin analysis including validation and compatibility\n */\n static analyzePluginDescriptor(\n descriptor: PluginDescriptor,\n availableExtensionPoints: ExtensionPointInfo[]\n ): {\n validation: PluginDescriptorValidationResult;\n compatibility: CompatibilityCheckResult;\n recommendations: string[];\n } {\n const validation = this.validatePluginDescriptor(descriptor);\n const compatibility = this.checkPluginCompatibility(\n descriptor,\n availableExtensionPoints\n );\n const recommendations: string[] = [];\n\n // Generate recommendations based on analysis\n if (validation.warnings.length > 0) {\n recommendations.push(\n \"Address validation warnings to improve plugin quality\"\n );\n }\n\n if (!compatibility.isCompatible) {\n recommendations.push(\n \"Resolve compatibility issues before deploying plugin\"\n );\n }\n\n if (\n descriptor.contributes &&\n Object.keys(descriptor.contributes).length === 1\n ) {\n recommendations.push(\n \"Consider adding more contribution types to increase plugin value\"\n );\n }\n\n return {\n validation,\n compatibility,\n recommendations,\n };\n }\n}\n","/**\n * Documentation Generator Service\n *\n * Auto-generates markdown documentation from registered extension points,\n * including usage examples and TypeScript definitions.\n */\n\nimport type {\n PluginExtension,\n PluginExtensionsType,\n} from \"../../../types/plugins\";\nimport { getExtensionPointRegistry } from \"../extension-points/extension-point-registry\";\nimport type { SchemaFieldInfo } from \"../extension-points/extension-point-types\";\nimport type { ExtensionPointInfo } from \"./plugin-discovery-service\";\nimport { PluginDiscoveryService } from \"./plugin-discovery-service\";\n\nexport interface DocumentationOptions {\n includeUsageExamples?: boolean;\n includeTypeDefinitions?: boolean;\n includeLegacyExtensions?: boolean;\n includePluginHealth?: boolean;\n format?: \"markdown\" | \"html\";\n}\n\nexport interface GeneratedDocumentation {\n content: string;\n metadata: {\n generatedAt: string;\n totalExtensionPoints: number;\n totalPlugins: number;\n simplifiedExtensionPoints: number;\n legacyExtensionPoints: number;\n };\n}\n\n/**\n * Documentation Generator - Creates comprehensive documentation from extension points\n */\nexport class DocumentationGenerator {\n /**\n * Generate complete documentation for all extension points\n */\n static generateFullDocumentation(\n extensions: PluginExtensionsType | undefined,\n options: DocumentationOptions = {}\n ): GeneratedDocumentation {\n const {\n includeUsageExamples = true,\n includeTypeDefinitions = true,\n includeLegacyExtensions = true,\n includePluginHealth = true,\n } = options;\n\n const extensionPoints = PluginDiscoveryService.getExtensionPoints(\n extensions,\n {\n includeLegacyExtensions,\n includeEmptyExtensionPoints: true,\n }\n );\n\n const healthStats =\n PluginDiscoveryService.calculateHealthStats(extensionPoints);\n\n let content = this.generateHeader(healthStats);\n content += this.generateTableOfContents(extensionPoints);\n content += this.generateOverviewSection(extensionPoints, healthStats);\n\n // Generate documentation for each extension point\n extensionPoints.forEach((point) => {\n content += this.generateExtensionPointSection(point, {\n includeUsageExamples,\n includePluginHealth,\n });\n });\n\n if (includeTypeDefinitions) {\n content += this.generateTypeDefinitionsSection(extensionPoints);\n }\n\n content += this.generateContributionGuide();\n content += this.generateTroubleshootingSection();\n\n return {\n content,\n metadata: {\n generatedAt: new Date().toISOString(),\n totalExtensionPoints: healthStats.totalExtensionPoints,\n totalPlugins: healthStats.totalPlugins,\n simplifiedExtensionPoints: healthStats.simplifiedExtensionPoints,\n legacyExtensionPoints: healthStats.legacyExtensionPoints,\n },\n };\n }\n\n /**\n * Generate documentation header with metadata\n */\n private static generateHeader(healthStats: any): string {\n return `# KOS Plugin Extension Points Reference\n\n**Generated**: ${new Date().toLocaleString()}\n\n## System Overview\n\n- **Total Extension Points**: ${healthStats.totalExtensionPoints}\n- **Extension Points with Plugins**: ${healthStats.extensionPointsWithPlugins}\n- **Total Active Plugins**: ${healthStats.totalPlugins}\n- **Simplified Extension Points**: ${healthStats.simplifiedExtensionPoints}\n- **Legacy Extension Points**: ${healthStats.legacyExtensionPoints}\n\n---\n\n`;\n }\n\n /**\n * Generate table of contents\n */\n private static generateTableOfContents(\n extensionPoints: ExtensionPointInfo[]\n ): string {\n let toc = \"## Table of Contents\\n\\n\";\n\n toc += \"- [Overview](#overview)\\n\";\n toc += \"- [Extension Points](#extension-points)\\n\";\n\n extensionPoints.forEach((point) => {\n const anchor = point.id.toLowerCase().replace(/\\./g, \"\");\n\n toc += ` - [${point.id}](#${anchor}) (${point.pluginCount} plugins)\\n`;\n });\n\n toc += \"- [Type Definitions](#type-definitions)\\n\";\n toc += \"- [Contribution Guide](#contribution-guide)\\n\";\n toc += \"- [Troubleshooting](#troubleshooting)\\n\\n\";\n\n return toc;\n }\n\n /**\n * Generate overview section with health statistics\n */\n private static generateOverviewSection(\n _extensionPoints: ExtensionPointInfo[],\n healthStats: any\n ): string {\n let overview = \"## Overview\\n\\n\";\n\n overview +=\n \"This document provides a comprehensive reference for all available extension points in the KOS plugin system. \";\n overview +=\n \"Extension points allow plugins to contribute functionality to the application.\\n\\n\";\n\n overview += \"### Extension Point Types\\n\\n\";\n overview +=\n \"- ** Simplified Extension Points**: Use the new simplified API from `defineExtensionPoint`\\n\";\n overview +=\n \"- ** Legacy Extension Points**: Use the traditional reducer-based system\\n\\n\";\n\n if (healthStats.deprecatedExtensionPoints > 0) {\n overview += `### ⚠️ Deprecated Extension Points\\n\\n`;\n overview += `${healthStats.deprecatedExtensionPoints} extension points are marked as deprecated. `;\n overview += `Consider migrating to newer alternatives.\\n\\n`;\n }\n\n return overview + \"---\\n\\n\";\n }\n\n /**\n * Generate documentation section for a single extension point\n */\n private static generateExtensionPointSection(\n extensionPoint: ExtensionPointInfo,\n options: { includeUsageExamples?: boolean; includePluginHealth?: boolean }\n ): string {\n const { includeUsageExamples = true, includePluginHealth = true } = options;\n\n let section = `## ${extensionPoint.id}\\n\\n`;\n\n // Basic information\n if (extensionPoint.displayName) {\n section += `**Display Name**: ${extensionPoint.displayName}\\n\\n`;\n }\n\n if (extensionPoint.description) {\n section += `**Description**: ${extensionPoint.description}\\n\\n`;\n }\n\n section += `**Source**: ${extensionPoint.source}\\n`;\n section += `**Active Plugins**: ${extensionPoint.pluginCount}\\n\\n`;\n\n // Metadata\n if (extensionPoint.metadata) {\n section += \"### Metadata\\n\\n\";\n const metadata = extensionPoint.metadata;\n\n if (metadata.category)\n section += `- **Category**: ${metadata.category}\\n`;\n if (metadata.owner) section += `- **Owner**: ${metadata.owner}\\n`;\n if (metadata.since) section += `- **Since**: ${metadata.since}\\n`;\n if (metadata.tags?.length)\n section += `- **Tags**: ${metadata.tags.join(\", \")}\\n`;\n if (metadata.deprecated) section += `- **⚠️ Status**: Deprecated\\n`;\n\n section += \"\\n\";\n }\n\n // Usage examples\n if (includeUsageExamples) {\n section += this.generateUsageExamples(extensionPoint);\n }\n\n // Plugin list\n if (extensionPoint.plugins.length > 0) {\n section += this.generatePluginList(\n extensionPoint.plugins,\n includePluginHealth\n );\n } else {\n section +=\n \"### Plugins\\n\\nNo plugins currently registered for this extension point.\\n\\n\";\n }\n\n // Schema fields (if available)\n section += this.generateSchemaFieldsSection(extensionPoint);\n\n // Contribution structure\n section += this.generateContributionStructure(extensionPoint);\n\n return section + \"---\\n\\n\";\n }\n\n /**\n * Generate usage examples for an extension point\n */\n static generateUsageExamples(extensionPoint: ExtensionPointInfo): string {\n let examples = \"### Usage Examples\\n\\n\";\n\n if (extensionPoint.source === \"simplified\") {\n examples += \"#### Using Simplified API\\n\\n\";\n examples += \"```typescript\\n\";\n examples += `// Import the extension point\\n`;\n examples += `import { ${this.getExtensionPointImportName(\n extensionPoint.id\n )} } from './extension-points';\\n\\n`;\n examples += `// Use extension component hook\\n`;\n examples += `import { useExtensionComponent } from '@kosdev-code/kos-ui-plugin';\\n\\n`;\n examples += `const Component = useExtensionComponent(${this.getExtensionPointImportName(\n extensionPoint.id\n )});\\n\\n`;\n examples += `if (Component) {\\n`;\n examples += ` return (\\n`;\n examples += ` <Component \\n`;\n examples += ` customProp=\"value\"\\n`;\n examples += ` onComplete={handleComplete}\\n`;\n examples += ` />\\n`;\n examples += ` );\\n`;\n examples += `}\\n\\n`;\n examples += `// Or use with dynamic component\\n`;\n examples += `const [Component] = useDynamicComponent({\\n`;\n examples += ` extension: ${this.getExtensionPointImportName(\n extensionPoint.id\n )}.id\\n`;\n examples += `});\\n`;\n examples += \"```\\n\\n\";\n\n examples += \"#### Using Typed Hooks\\n\\n\";\n examples += \"```typescript\\n\";\n examples += `// Get all extensions with type safety\\n`;\n examples += `const extensions = useExtensions(${this.getExtensionPointImportName(\n extensionPoint.id\n )});\\n\\n`;\n examples += `// Get best extension\\n`;\n examples += `const bestExtension = useBest(${this.getExtensionPointImportName(\n extensionPoint.id\n )});\\n\\n`;\n examples += `// Check availability\\n`;\n examples += `const hasExtensions = useHasExtensions(${this.getExtensionPointImportName(\n extensionPoint.id\n )});\\n`;\n examples += \"```\\n\\n\";\n }\n\n examples += \"#### Using DynamicComponent\\n\\n\";\n examples += \"```typescript\\n\";\n examples += `import { DynamicComponent } from '@kosdev-code/kos-ui-plugin';\\n`;\n examples += `import { ${this.getExtensionPointImportName(\n extensionPoint.id\n )} } from './extension-points';\\n\\n`;\n examples += `<DynamicComponent\\n`;\n examples += ` extension={${this.getExtensionPointImportName(\n extensionPoint.id\n )}.id}\\n`;\n examples += ` props={{ customData: \"value\" }}\\n`;\n examples += ` fallback={<div>Loading...</div>}\\n`;\n examples += `/>\\n`;\n examples += \"```\\n\\n\";\n\n examples += \"#### Using Context\\n\\n\";\n examples += \"```typescript\\n\";\n examples += `import { useKosPluginsContext } from '@kosdev-code/kos-ui-plugin';\\n`;\n examples += `import { ${this.getExtensionPointImportName(\n extensionPoint.id\n )} } from './extension-points';\\n\\n`;\n examples += `const { getExtensions } = useKosPluginsContext();\\n`;\n examples += `const extensions = getExtensions(${this.getExtensionPointImportName(\n extensionPoint.id\n )}.id);\\n`;\n examples += \"```\\n\\n\";\n\n return examples;\n }\n\n /**\n * Generate plugin list with health information\n */\n private static generatePluginList(\n plugins: PluginExtension[],\n includeHealth: boolean\n ): string {\n let list = \"### Active Plugins\\n\\n\";\n\n plugins.forEach((plugin) => {\n list += `#### ${plugin.id}\\n\\n`;\n\n if (plugin.remote) {\n list += `- **Remote**: ${plugin.remote}\\n`;\n }\n\n if (plugin.sectionId) {\n list += `- **Section**: ${plugin.sectionId}\\n`;\n }\n\n if ((plugin as any).rank !== undefined) {\n list += `- **Rank**: ${(plugin as any).rank}\\n`;\n }\n\n if (includeHealth) {\n const analysis = PluginDiscoveryService.analyzePlugin(plugin);\n list += `- **Health**: ${this.getHealthEmoji(analysis.healthStatus)} ${\n analysis.healthStatus\n }\\n`;\n\n if (analysis.capabilities.length > 0) {\n list += `- **Capabilities**: ${analysis.capabilities.join(\", \")}\\n`;\n }\n }\n\n list += \"\\n\";\n });\n\n return list;\n }\n\n /**\n * Generate schema fields documentation\n */\n private static generateSchemaFieldsSection(\n extensionPoint: ExtensionPointInfo\n ): string {\n // Only generate for simplified extension points with schemas\n if (extensionPoint.source !== \"simplified\") {\n return \"\";\n }\n\n const registry = getExtensionPointRegistry();\n const point = registry.getExtensionPoint(extensionPoint.id);\n\n if (!point?.getSchemaFieldInfo) {\n return \"\";\n }\n\n const fieldInfo = point.getSchemaFieldInfo();\n if (fieldInfo.length === 0) {\n return \"\";\n }\n\n let section = \"### Schema Fields\\n\\n\";\n section +=\n \"The following fields are defined in the schema for this extension point:\\n\\n\";\n section += \"| Field | Type | Required | Description |\\n\";\n section += \"|-------|------|----------|-------------|\\n\";\n\n fieldInfo.forEach((field) => {\n const name = field.name;\n const type = field.type || \"unknown\";\n const required = field.required ? \"✅\" : \"⭕\";\n const description = field.description || \"-\";\n\n section += `| \\`${name}\\` | ${type} | ${required} | ${description} |\\n`;\n });\n\n section += \"\\n\";\n\n return section;\n }\n\n /**\n * Generate contribution structure documentation\n */\n private static generateContributionStructure(\n extensionPoint: ExtensionPointInfo\n ): string {\n let structure = \"### Contribution Structure\\n\\n\";\n\n structure +=\n \"To contribute to this extension point, add the following to your plugin descriptor:\\n\\n\";\n structure += \"```json\\n\";\n structure += `{\\n`;\n structure += ` \"id\": \"your-plugin-id\",\\n`;\n structure += ` \"contributes\": {\\n`;\n\n // Try to infer contribution key from extension point ID or metadata\n const contributionKey = this.inferContributionKey(extensionPoint);\n\n structure += ` \"${contributionKey}\": [\\n`;\n structure += ` {\\n`;\n\n // Get schema fields if available (for simplified extension points)\n const schemaFields = this.getSchemaFieldsForContribution(extensionPoint);\n\n if (schemaFields.length > 0) {\n // Use schema-defined fields for the example\n const fieldExamples: string[] = [];\n\n schemaFields.forEach((field) => {\n let value: string;\n\n // Generate appropriate example values based on field type and name\n if (field.name === \"id\") {\n value = '\"your-contribution-id\"';\n } else if (field.name === \"title\") {\n value = '\"Your Contribution Title\"';\n } else if (field.name === \"namespace\") {\n value = '\"your-namespace\"';\n } else if (field.name === \"experienceId\") {\n value = '\"your-experience-id\"';\n } else if (field.name === \"dashboardKey\") {\n value = '\"your-dashboard-key\"';\n } else if (field.name === \"rank\") {\n value = \"10\";\n } else if (field.type === \"string\") {\n value = `\"your-${field.name}\"`;\n } else if (field.type === \"number\") {\n value = \"0\";\n } else if (field.type === \"boolean\") {\n value = \"false\";\n } else {\n value = `\"your-${field.name}\"`;\n }\n\n // Only include required fields and important optional ones\n if (\n field.required ||\n [\"experienceId\", \"rank\", \"dashboardKey\"].includes(field.name)\n ) {\n fieldExamples.push(` \"${field.name}\": ${value}`);\n }\n });\n\n structure += fieldExamples.join(\",\\n\");\n } else {\n // Fallback to old logic for legacy extension points\n structure += ` \"id\": \"your-contribution-id\",\\n`;\n structure += ` \"title\": \"Your Contribution Title\",\\n`;\n structure += ` \"namespace\": \"your-namespace\"`;\n\n // Add common fields based on patterns\n if (this.isViewBasedExtensionPoint(extensionPoint)) {\n structure += `,\\n \"experienceId\": \"your-experience-id\"`;\n }\n\n if (this.isRankableExtensionPoint(extensionPoint)) {\n structure += `,\\n \"rank\": 10`;\n }\n\n // Add specific fields based on extension point type\n const specificFields = this.getSpecificFields(extensionPoint);\n if (specificFields.length > 0) {\n structure += `,\\n ${specificFields.join(\",\\n \")}`;\n }\n }\n\n structure += `\\n }\\n`;\n structure += ` ]`;\n\n // Only add experiences section if it's a view-based extension point\n const hasExperienceId =\n schemaFields.some((f) => f.name === \"experienceId\") ||\n this.isViewBasedExtensionPoint(extensionPoint);\n\n if (hasExperienceId) {\n structure += `,\\n \"experiences\": {\\n`;\n structure += ` \"your-experience-id\": {\\n`;\n structure += ` \"id\": \"your-experience-id\",\\n`;\n structure += ` \"component\": \"YourComponent\",\\n`;\n structure += ` \"location\": \"./src/components/YourComponent.tsx\"\\n`;\n structure += ` }\\n`;\n structure += ` }`;\n }\n\n structure += `\\n }\\n`;\n structure += `}\\n`;\n structure += \"```\\n\\n\";\n\n return structure;\n }\n\n /**\n * Generate TypeScript definitions section\n */\n private static generateTypeDefinitionsSection(\n extensionPoints: ExtensionPointInfo[]\n ): string {\n let section = \"## Type Definitions\\n\\n\";\n\n section += \"### Extension Point Types\\n\\n\";\n section += \"```typescript\\n\";\n\n extensionPoints.forEach((point) => {\n if (point.source === \"simplified\") {\n section += `// ${point.id}\\n`;\n section += `interface ${this.getExtensionPointTypeName(point.id)} {\\n`;\n section += ` id: \"${point.id}\";\\n`;\n section += ` displayName?: \"${point.displayName || \"\"}\";\\n`;\n section += ` description?: \"${point.description || \"\"}\";\\n`;\n section += `}\\n\\n`;\n }\n });\n\n section += \"```\\n\\n\";\n\n section += \"### Plugin Contribution Types\\n\\n\";\n section += \"```typescript\\n\";\n section += \"interface BaseContribution {\\n\";\n section += \" id: string;\\n\";\n section += \" title: string;\\n\";\n section += \" namespace: string;\\n\";\n section += \"}\\n\\n\";\n section += \"interface ViewBasedContribution extends BaseContribution {\\n\";\n section += \" experienceId: string;\\n\";\n section += \"}\\n\\n\";\n section += \"interface RankableContribution extends BaseContribution {\\n\";\n section += \" rank: number;\\n\";\n section += \"}\\n\";\n section += \"```\\n\\n\";\n\n return section;\n }\n\n /**\n * Generate contribution guide\n */\n private static generateContributionGuide(): string {\n return `## Contribution Guide\n\n### Creating a Plugin\n\n1. **Create Plugin Project**\n \\`\\`\\`bash\n kosui plugin-project --name my-plugin\n \\`\\`\\`\n\n2. **Add Components**\n \\`\\`\\`bash\n kosui component --name MyComponent --pluginType utility --project my-plugin\n \\`\\`\\`\n\n3. **Update Plugin Descriptor**\n Add contributions to your \\`kosdev-plugin.json\\` file following the structure examples above.\n\n4. **Test Integration**\n Use the Plugin Explorer (Ctrl+Shift+P) to validate your plugin registration.\n\n### Best Practices\n\n- **Use descriptive IDs**: Plugin and contribution IDs should be clear and unique\n- **Follow naming conventions**: Use kebab-case for IDs, PascalCase for components\n- **Provide meaningful titles**: Titles are shown to users in the interface\n- **Set appropriate ranks**: Higher numbers = higher priority for rankable contributions\n- **Include proper metadata**: Namespace helps organize plugins by owner\n\n### Validation\n\nUse the Plugin Discovery Service to validate your plugin descriptor:\n\n\\`\\`\\`typescript\nimport { PluginDiscoveryService } from '@kosdev-code/kos-ui-plugin';\n\nconst validation = PluginDiscoveryService.validatePluginDescriptor(yourDescriptor);\nconsole.log(validation.errors); // Check for errors\nconsole.log(validation.warnings); // Check for warnings\n\\`\\`\\`\n\n`;\n }\n\n /**\n * Generate troubleshooting section\n */\n private static generateTroubleshootingSection(): string {\n return `## Troubleshooting\n\n### Common Issues\n\n**Plugin not appearing in extension point**\n- Check plugin descriptor syntax\n- Verify contribution key matches extension point requirements\n- Ensure experienceId references exist in experiences section\n\n**Component fails to load**\n- Verify component path in experience location\n- Check module federation configuration\n- Use Plugin Explorer to see detailed error messages\n\n**Type errors with simplified extension points**\n- Ensure extension point is properly imported\n- Check that component props match expected interface\n- Verify extension point is registered before use\n\n### Debugging Tools\n\n**Plugin Explorer**\n- Press Ctrl+Shift+P in development mode\n- View all extension points and their plugins\n- See plugin health status and capabilities\n- Test component rendering with error boundaries\n\n**Validation Service**\n- Use \\`PluginDiscoveryService.validatePluginDescriptor()\\`\n- Check \\`PluginDiscoveryService.checkPluginCompatibility()\\`\n- Run \\`PluginDiscoveryService.analyzePluginDescriptor()\\` for full analysis\n\n**Browser DevTools**\n- Check \\`window.KosPlugins.extensions\\` for runtime state\n- Look for module federation errors in Network tab\n- Use React DevTools to inspect component loading\n\n---\n\n*Generated by KOS Plugin Documentation Generator*\n`;\n }\n\n // Helper methods\n private static getExtensionPointImportName(id: string): string {\n // Check if there's an explicit export name in metadata\n const registry = getExtensionPointRegistry();\n const point = registry.getExtensionPoint(id);\n\n if (point?.config.metadata?.exportName) {\n return point.config.metadata.exportName;\n }\n\n // Fallback: Convert ID to PascalCase and handle hyphens properly\n const parts = id.split(\".\");\n\n // Skip the namespace part (usually first part like \"ddk\")\n // Focus on the meaningful parts (e.g., \"dashboard.pump-detail\")\n const meaningfulParts = parts.length > 1 ? parts.slice(1) : parts;\n\n return (\n meaningfulParts\n .map((part) =>\n // Handle hyphenated parts (e.g., \"pump-detail\" -> \"PumpDetail\")\n part\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\"\")\n )\n .join(\"\") + \"Extension\"\n );\n }\n\n private static getExtensionPointTypeName(id: string): string {\n return this.getExtensionPointImportName(id) + \"Type\";\n }\n\n private static getHealthEmoji(status: string): string {\n switch (status) {\n case \"healthy\":\n return \"✅\";\n case \"warning\":\n return \"⚠️\";\n case \"error\":\n return \"❌\";\n default:\n return \"❓\";\n }\n }\n\n private static inferContributionKey(\n extensionPoint: ExtensionPointInfo\n ): string {\n // Try to get from simplified extension point registry\n if (extensionPoint.source === \"simplified\") {\n const registry = getExtensionPointRegistry();\n const point = registry.getExtensionPoint(extensionPoint.id);\n if (point?.config.contributionKey) {\n return point.config.contributionKey;\n }\n }\n\n // Fallback to ID-based inference\n const parts = extensionPoint.id.split(\".\");\n const lastPart = parts[parts.length - 1];\n\n // Common mappings\n const mappings: Record<string, string> = {\n cui: \"cui\",\n utility: \"utilities\",\n utilities: \"utilities\",\n setup: \"setupStep\",\n settings: \"settings\",\n nav: \"navViews\",\n troubleAction: \"troubleActions\",\n controlPour: \"controlPour\",\n };\n\n return mappings[lastPart] || lastPart + \"s\";\n }\n\n private static isViewBasedExtensionPoint(\n extensionPoint: ExtensionPointInfo\n ): boolean {\n if (extensionPoint.source === \"simplified\") {\n const registry = getExtensionPointRegistry();\n const point = registry.getExtensionPoint(extensionPoint.id);\n return point?.config.hasView || false;\n }\n\n // Heuristic for legacy extension points\n return extensionPoint.plugins.some(\n (plugin) => (plugin as any).experienceId\n );\n }\n\n private static isRankableExtensionPoint(\n extensionPoint: ExtensionPointInfo\n ): boolean {\n if (extensionPoint.source === \"simplified\") {\n const registry = getExtensionPointRegistry();\n const point = registry.getExtensionPoint(extensionPoint.id);\n return point?.config.isRankable || false;\n }\n\n // Heuristic for legacy extension points\n return extensionPoint.plugins.some(\n (plugin) => typeof (plugin as any).rank === \"number\"\n );\n }\n\n /**\n * Get schema fields for contribution structure generation\n */\n private static getSchemaFieldsForContribution(\n extensionPoint: ExtensionPointInfo\n ): SchemaFieldInfo[] {\n // Only get schema for simplified extension points\n if (extensionPoint.source !== \"simplified\") {\n return [];\n }\n\n const registry = getExtensionPointRegistry();\n const point = registry.getExtensionPoint(extensionPoint.id);\n\n if (!point?.getSchemaFieldInfo) {\n return [];\n }\n\n return point.getSchemaFieldInfo();\n }\n\n private static getSpecificFields(\n extensionPoint: ExtensionPointInfo\n ): string[] {\n const fields: string[] = [];\n const contributionKey = this.inferContributionKey(extensionPoint);\n\n // Add specific fields based on contribution type\n switch (contributionKey) {\n case \"utilities\":\n fields.push('\"utilDescriptor\": \"your-util-descriptor\"');\n break;\n case \"setupStep\":\n fields.push('\"setupDescriptor\": \"your-setup-descriptor\"');\n break;\n case \"settings\":\n fields.push('\"settingsGroup\": \"your-settings-group\"');\n break;\n case \"navViews\":\n fields.push('\"navDescriptor\": \"your-nav-descriptor\"');\n break;\n case \"troubleActions\":\n fields.push('\"troubleType\": \"your-trouble-type\"');\n break;\n case \"cui\":\n fields.push('\"cuiDescriptor\": \"your-cui-descriptor\"');\n break;\n }\n\n return fields;\n }\n}\n"],"names":["dynamicFederation","remoteUrlDefinitions","resolveRemoteUrl","remoteModuleMap","remoteContainerMap","initialSharingScopeCreated","setRemoteUrlResolver","_resolveRemoteUrl","setRemoteDefinitions","definitions","loadRemoteModule","remoteName","moduleName","remoteModuleKey","Module","loadRemoteContainer","fetchRemoteModule","url","resolve","reject","script","request","arg","e","remoteUrl","containerUrl","container","exports","dynamic_federation_1","require$$0","resolveBestExtension","extensions","module","exact","ext","a","b","aRank","bRank","aId","bId","ContributionRegistryImpl","__publicField","contributionId","extensionPoint","contribution","dynamicContribution","context","enabled","reason","previousState","error","listener","_a","_b","updates","validatedUpdates","update","timestamp","validated","includeDisabled","contributionIds","contributions","id","ids","event","listeners","ContributionRegistry","extensionPointRegistry","registerExtensionReducer","reducer","applyExtensionReducers","base","experiences","acc","extractSchemaFieldInfo","schema","objectSchema","fields","fieldName","fieldSchema","zodField","fieldInfo","typeName","ValidationContextImpl","message","issue","ValidationResultsCache","pluginId","results","validationCache","getValidationResults","SimplifiedExtensionPointRegistry","config","definition","contributionData","key","rawData","validationContext","issues","i","processedData","extension","experienceId","view","registry","getExtensionPointRegistry","getExtensionPointSchema","createViewAwareTransform","options","experienceIdProperty","flattenComponentProperties","customTransform","data","result","defineExtensionPoint","SPECIAL_VARIABLES","parseJsonExtensionPoint","jsonDef","generateExportName","createZodSchemaFromJson","createValidationFunction","createTransformFunction","part","jsonSchema","z","shape","propSchema","createZodPropertyFromJson","validationRules","createModuleValidationFunction","dataRecord","rule","validateRule","validateRequiredRule","validateRangeRule","validatePatternRule","validateDependencyRule","validateCustomRule","value","evaluateSimpleExpression","modulePath","_data","transformOps","createModuleTransformFunction","_context","resolveSpecialVariable","field","oldName","newName","operation","applyStringOperation","resolver","toCamelCase","toKebabCase","str","_","char","expression","evalExpression","quotedValue","left","right","s","contributionReducer","remotes","remote","sectionId","experience","contributionKey","contribId","initPluginManager","remotesOverride","extensionPoints","extensionPointId","loadExtensions","DEFAULT_CONTRIBUTIONS","getContributions","jsonExtensionPoints","epDef","InitPlugin","initPlugin","reducedExtensions","getExtensions","getQueryParams","query","pair","val","getDefaultHost","defaultHost","params","initializeKosPlugins","props","pluginBaseUrl","pluginApiPath","overrides","pluginContext","queryParams","pluginDevServers","validDevResponses","serverUrl","response","r","devServerOverrides","devResponse","contextGroup","existingContext","ctx","plugin","mergedOverrides","pluginData","item","pluginGroup","allRemotes","baseUrl","filteredExtensions","groups","contributes","hasContributes","filteredContributes","c","init","ReactiveExtensionRegistry","allExtensions","currentBest","changeType","changeEvent","normalizeVersion","version","match","major","minor","generatePluginConfiguration","sdkVersion","ddkVersion","projectId","pluginObj","obj","mfConfig","BaseViewExtensionSchema","RankableViewExtensionSchema","validateWithSchema","validateDescriptorFormat","descriptorField","descriptorValue","validateRank","rank","maxReasonableRank","createExtensionSchema","additionalFields","validateRankIfPresent","PluginDiscoveryService","includeLegacyExtensions","includeEmptyExtensionPoints","simplifiedExtensionPoints","point","plugins","extensionId","extensionPlugins","searchTerm","term","_d","_c","_f","_e","tag","totalExtensionPoints","extensionPointsWithPlugins","totalPlugins","sum","legacyExtensionPoints","deprecatedExtensionPoints","hasComponent","hasRank","capabilities","namespace","healthStatus","suggestions","parts","descriptor","errors","warnings","missingRequired","contributionKeys","contrib","index","pluginDescriptor","availableExtensionPoints","missingExtensionPoints","incompatibleTypes","availableIds","matchingPoint","validation","compatibility","recommendations","DocumentationGenerator","includeUsageExamples","includeTypeDefinitions","includePluginHealth","healthStats","content","toc","anchor","_extensionPoints","overview","section","metadata","examples","includeHealth","list","analysis","name","type","required","description","structure","schemaFields","fieldExamples","specificFields","f","word","status","lastPart"],"mappings":";;;;;;;;;;;;;;;;;;;;;AACA,OAAO,eAAeA,GAAS,cAAc,EAAE,OAAO,GAAI,CAAE;AAC5DA,EAAA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