{"version":3,"file":"vdom-pool.mjs","sources":["../../../src/lib/vdom/vdom-pool.ts"],"sourcesContent":["/**\n * @file VDOM Pool Implementation\n * @module vdom/vdom-pool\n * @description Memory-efficient virtual node pooling system with automatic\n * garbage collection, pool size management, and memory pressure detection.\n * Implements the Object Pool pattern for optimal VDOM performance.\n *\n * @author Agent 5 - PhD Virtual DOM Expert\n * @version 1.0.0\n */\n\nimport type { ComponentType } from 'react';\nimport {\n  type VirtualNode,\n  type VNodeId,\n  type VNodeProps,\n  type VNodeCreateOptions,\n  type VDOMPoolConfig,\n  type VDOMPoolStats,\n  type ModuleId,\n  VNodeType,\n  HydrationState,\n  DEFAULT_POOL_CONFIG,\n  createVNodeId,\n} from './types';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Estimated bytes per virtual node (rough approximation).\n */\nconst ESTIMATED_BYTES_PER_NODE = 256;\n\n/**\n * Counter for generating unique node IDs.\n */\nlet nodeIdCounter = 0;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Generates a unique node ID.\n * @returns Unique VNodeId\n */\nfunction generateNodeId(): VNodeId {\n  nodeIdCounter += 1;\n  return createVNodeId(`vnode_${Date.now().toString(36)}_${nodeIdCounter.toString(36)}`);\n}\n\n/**\n * Creates an empty virtual node for pooling.\n * @param generation - Pool generation number\n * @returns Empty VirtualNode\n */\nfunction createEmptyNode(generation: number): VirtualNode {\n  return {\n    id: generateNodeId(),\n    type: VNodeType.ELEMENT,\n    tag: 'div',\n    props: {},\n    children: [],\n    parent: null,\n    element: null,\n    moduleId: null,\n    hydrationState: HydrationState.DEHYDRATED,\n    poolGeneration: generation,\n    isPooled: true,\n    lastUpdated: 0,\n  };\n}\n\n/**\n * Resets a virtual node to its initial state.\n * @param node - Node to reset\n * @param generation - Current pool generation\n */\nfunction resetNode(node: VirtualNode, generation: number): void {\n  // Use type assertion since we're modifying a readonly type during reset\n  const mutableNode = node as {\n    -readonly [K in keyof VirtualNode]: VirtualNode[K];\n  };\n\n  mutableNode.id = generateNodeId();\n  mutableNode.type = VNodeType.ELEMENT;\n  mutableNode.tag = 'div';\n  mutableNode.props = {};\n  mutableNode.children = [];\n  mutableNode.parent = null;\n  mutableNode.element = null;\n  mutableNode.moduleId = null;\n  mutableNode.hydrationState = HydrationState.DEHYDRATED;\n  mutableNode.poolGeneration = generation;\n  mutableNode.isPooled = true;\n  mutableNode.lastUpdated = 0;\n}\n\n// ============================================================================\n// MemoryPressureDetector Class\n// ============================================================================\n\n/**\n * Detects memory pressure using Performance API.\n */\nclass MemoryPressureDetector {\n  private readonly threshold: number;\n  private lastCheck: number = 0;\n  private readonly checkInterval: number = 1000; // 1 second\n\n  constructor(threshold: number) {\n    this.threshold = threshold;\n  }\n\n  /**\n   * Checks if memory pressure is detected.\n   * @returns Whether memory pressure is above threshold\n   */\n  isUnderPressure(): boolean {\n    const now = Date.now();\n    if (now - this.lastCheck < this.checkInterval) {\n      return false; // Throttle checks\n    }\n\n    this.lastCheck = now;\n\n    // Use Performance.memory if available (Chrome only)\n    const performance = globalThis.performance as Performance & {\n      memory?: {\n        usedJSHeapSize: number;\n        jsHeapSizeLimit: number;\n      };\n    };\n\n    if (performance.memory) {\n      const { usedJSHeapSize, jsHeapSizeLimit } = performance.memory;\n      const usage = usedJSHeapSize / jsHeapSizeLimit;\n      return usage > this.threshold;\n    }\n\n    return false;\n  }\n\n  /**\n   * Gets current memory usage ratio.\n   * @returns Memory usage ratio (0-1) or null if unavailable\n   */\n  getMemoryUsage(): number | null {\n    const performance = globalThis.performance as Performance & {\n      memory?: {\n        usedJSHeapSize: number;\n        jsHeapSizeLimit: number;\n      };\n    };\n\n    if (performance.memory) {\n      return performance.memory.usedJSHeapSize / performance.memory.jsHeapSizeLimit;\n    }\n\n    return null;\n  }\n}\n\n// ============================================================================\n// VDOMPool Class\n// ============================================================================\n\n/**\n * Memory-efficient virtual node pool with automatic garbage collection.\n * Implements the Object Pool pattern for optimal performance.\n *\n * @example\n * ```typescript\n * const pool = new VDOMPool({ initialSize: 100, maxSize: 1000 });\n *\n * // Acquire a node\n * const node = pool.acquire({\n *   type: VNodeType.ELEMENT,\n *   tag: 'div',\n *   props: { className: 'container' },\n * });\n *\n * // Use the node...\n *\n * // Release back to pool\n * pool.release(node);\n * ```\n */\nexport class VDOMPool {\n  /** Pool configuration */\n  private readonly config: VDOMPoolConfig;\n\n  /** Available (free) nodes */\n  private readonly freeNodes: VirtualNode[] = [];\n\n  /** In-use nodes (weak reference to allow GC) */\n  private readonly inUseNodes: Set<VNodeId> = new Set();\n\n  /** All nodes in pool (for GC) */\n  private readonly allNodes: Map<VNodeId, VirtualNode> = new Map();\n\n  /** Current pool generation (increments on GC) */\n  private generation: number = 0;\n\n  /** Statistics tracking */\n  private stats: VDOMPoolStats;\n\n  /** Memory pressure detector */\n  private readonly memoryDetector: MemoryPressureDetector;\n\n  /** GC interval handle */\n  private gcIntervalId: ReturnType<typeof setInterval> | null = null;\n\n  /** Whether pool is disposed */\n  private isDisposed: boolean = false;\n\n  /**\n   * Creates a new VDOM Pool.\n   * @param config - Pool configuration (partial)\n   */\n  constructor(config: Partial<VDOMPoolConfig> = {}) {\n    this.config = { ...DEFAULT_POOL_CONFIG, ...config };\n\n    this.stats = {\n      totalNodes: 0,\n      inUseNodes: 0,\n      freeNodes: 0,\n      acquireCount: 0,\n      releaseCount: 0,\n      expansionCount: 0,\n      gcCount: 0,\n      gcCollectedCount: 0,\n      generation: 0,\n      estimatedMemoryBytes: 0,\n      lastGcTimestamp: 0,\n      utilization: 0,\n    };\n\n    this.memoryDetector = new MemoryPressureDetector(\n      this.config.memoryPressureThreshold\n    );\n\n    // Initialize pool with initial size\n    this.expand(this.config.initialSize);\n\n    // Start GC interval\n    this.startGCInterval();\n  }\n\n  // ==========================================================================\n  // Public API\n  // ==========================================================================\n\n  /**\n   * Checks if pool is disposed.\n   */\n  get disposed(): boolean {\n    return this.isDisposed;\n  }\n\n  /**\n   * Gets the current generation number.\n   */\n  get currentGeneration(): number {\n    return this.generation;\n  }\n\n  /**\n   * Acquires a virtual node from the pool.\n   * @param options - Node creation options\n   * @returns Virtual node instance\n   */\n  acquire(options: {\n    type?: VNodeType;\n    tag?: string | ComponentType<unknown>;\n    props?: VNodeProps;\n    children?: (VirtualNode | string)[];\n    moduleId?: ModuleId;\n    hydrationState?: HydrationState;\n  } = {}): VirtualNode {\n    if (this.isDisposed) {\n      throw new Error('Cannot acquire from disposed pool');\n    }\n\n    // Check if expansion needed\n    if (this.freeNodes.length < this.config.minFreeNodes) {\n      this.maybeExpand();\n    }\n\n    // Get node from pool or create new\n    let node: VirtualNode;\n\n    if (this.freeNodes.length > 0) {\n      const poppedNode = this.freeNodes.pop();\n      if (!poppedNode) {\n        throw new Error('Unexpected: freeNodes.pop() returned undefined');\n      }\n      node = poppedNode;\n    } else {\n      node = createEmptyNode(this.generation);\n      this.allNodes.set(node.id, node);\n    }\n\n    // Configure node\n    const mutableNode = node as {\n      -readonly [K in keyof VirtualNode]: VirtualNode[K];\n    };\n\n    mutableNode.type = options.type ?? VNodeType.ELEMENT;\n    mutableNode.tag = options.tag ?? 'div';\n    mutableNode.props = options.props ?? {};\n    mutableNode.children = options.children ?? [];\n    mutableNode.moduleId = options.moduleId ?? null;\n    mutableNode.hydrationState = options.hydrationState ?? HydrationState.DEHYDRATED;\n    mutableNode.isPooled = false;\n    mutableNode.lastUpdated = Date.now();\n\n    // Track in-use\n    this.inUseNodes.add(node.id);\n\n    // Update stats\n    this.updateStats({\n      acquireCount: this.stats.acquireCount + 1,\n    });\n\n    return node;\n  }\n\n  /**\n   * Releases a virtual node back to the pool.\n   * @param node - Node to release\n   */\n  release(node: VirtualNode): void {\n    if (this.isDisposed) {\n      return;\n    }\n\n    if (!this.allNodes.has(node.id)) {\n      // Node not from this pool, ignore\n      return;\n    }\n\n    if (node.isPooled) {\n      // Already released\n      return;\n    }\n\n    // Release children recursively\n    for (const child of node.children) {\n      if (typeof child !== 'string' && !child.isPooled) {\n        this.release(child);\n      }\n    }\n\n    // Reset node\n    resetNode(node, this.generation);\n\n    // Remove from in-use tracking\n    this.inUseNodes.delete(node.id);\n\n    // Add back to free pool\n    this.freeNodes.push(node);\n\n    // Update stats\n    this.updateStats({\n      releaseCount: this.stats.releaseCount + 1,\n    });\n  }\n\n  /**\n   * Releases multiple nodes at once.\n   * @param nodes - Nodes to release\n   */\n  releaseMany(nodes: VirtualNode[]): void {\n    for (const node of nodes) {\n      this.release(node);\n    }\n  }\n\n  /**\n   * Forces garbage collection of old nodes.\n   */\n  gc(): void {\n    if (this.isDisposed) {\n      return;\n    }\n\n    const now = Date.now();\n    const nodeTtl = this.config.nodeTtlMs;\n    let collectedCount = 0;\n\n    // Collect old free nodes\n    const nodesToKeep: VirtualNode[] = [];\n    const nodesToRemove: VNodeId[] = [];\n\n    for (const node of this.freeNodes) {\n      const age = now - node.lastUpdated;\n      const isOld = age > nodeTtl;\n      const exceedsShrinkThreshold =\n        this.freeNodes.length > this.config.maxSize * this.config.shrinkThreshold;\n\n      if (isOld && exceedsShrinkThreshold) {\n        nodesToRemove.push(node.id);\n        collectedCount++;\n      } else {\n        nodesToKeep.push(node);\n      }\n    }\n\n    // Remove collected nodes\n    for (const nodeId of nodesToRemove) {\n      this.allNodes.delete(nodeId);\n    }\n\n    // Update free nodes array\n    this.freeNodes.length = 0;\n    this.freeNodes.push(...nodesToKeep);\n\n    // Increment generation\n    this.generation++;\n\n    // Update stats\n    this.updateStats({\n      gcCount: this.stats.gcCount + 1,\n      gcCollectedCount: this.stats.gcCollectedCount + collectedCount,\n      lastGcTimestamp: now,\n      generation: this.generation,\n    });\n  }\n\n  /**\n   * Gets current pool statistics.\n   * @returns Pool statistics\n   */\n  getStats(): VDOMPoolStats {\n    this.recalculateStats();\n    return { ...this.stats };\n  }\n\n  /**\n   * Clears all nodes from the pool.\n   */\n  clear(): void {\n    this.freeNodes.length = 0;\n    this.inUseNodes.clear();\n    this.allNodes.clear();\n    this.generation++;\n\n    this.updateStats({\n      totalNodes: 0,\n      inUseNodes: 0,\n      freeNodes: 0,\n      generation: this.generation,\n    });\n  }\n\n  /**\n   * Disposes the pool and releases all resources.\n   */\n  dispose(): void {\n    if (this.isDisposed) {\n      return;\n    }\n\n    this.stopGCInterval();\n    this.clear();\n    this.isDisposed = true;\n  }\n\n  // ==========================================================================\n  // Node Creation Helpers\n  // ==========================================================================\n\n  /**\n   * Creates an element node.\n   * @param tag - HTML tag name\n   * @param props - Node properties\n   * @param children - Child nodes\n   * @param options - Additional options\n   * @returns Element virtual node\n   */\n  createElement(\n    tag: string,\n    props: VNodeProps = {},\n    children: (VirtualNode | string)[] = [],\n    options: VNodeCreateOptions = {}\n  ): VirtualNode {\n    return this.acquire({\n      type: VNodeType.ELEMENT,\n      tag,\n      props,\n      children,\n      moduleId: options.moduleId,\n      hydrationState: options.hydrationState,\n    });\n  }\n\n  /**\n   * Creates a text node.\n   * @param text - Text content\n   * @param options - Additional options\n   * @returns Text virtual node\n   */\n  createText(text: string, options: VNodeCreateOptions = {}): VirtualNode {\n    return this.acquire({\n      type: VNodeType.TEXT,\n      tag: '#text',\n      props: {},\n      children: [text],\n      moduleId: options.moduleId,\n      hydrationState: options.hydrationState,\n    });\n  }\n\n  /**\n   * Creates a fragment node.\n   * @param children - Child nodes\n   * @param options - Additional options\n   * @returns Fragment virtual node\n   */\n  createFragment(\n    children: (VirtualNode | string)[] = [],\n    options: VNodeCreateOptions = {}\n  ): VirtualNode {\n    return this.acquire({\n      type: VNodeType.FRAGMENT,\n      tag: '#fragment',\n      props: {},\n      children,\n      moduleId: options.moduleId,\n      hydrationState: options.hydrationState,\n    });\n  }\n\n  /**\n   * Creates a component node.\n   * @param component - React component\n   * @param props - Component props\n   * @param children - Child nodes\n   * @param options - Additional options\n   * @returns Component virtual node\n   */\n  createComponent(\n    component: ComponentType<unknown>,\n    props: VNodeProps = {},\n    children: (VirtualNode | string)[] = [],\n    options: VNodeCreateOptions = {}\n  ): VirtualNode {\n    return this.acquire({\n      type: VNodeType.COMPONENT,\n      tag: component,\n      props,\n      children,\n      moduleId: options.moduleId,\n      hydrationState: options.hydrationState,\n    });\n  }\n\n  /**\n   * Creates a module boundary node.\n   * @param moduleId - Module ID\n   * @param children - Child nodes\n   * @param options - Additional options\n   * @returns Module boundary virtual node\n   */\n  createModuleBoundary(\n    moduleId: ModuleId,\n    children: (VirtualNode | string)[] = [],\n    options: Omit<VNodeCreateOptions, 'moduleId'> = {}\n  ): VirtualNode {\n    return this.acquire({\n      type: VNodeType.MODULE_BOUNDARY,\n      tag: '#module-boundary',\n      props: { attributes: { 'data-module-id': moduleId } },\n      children,\n      moduleId,\n      hydrationState: options.hydrationState,\n    });\n  }\n\n  // ==========================================================================\n  // Tree Operations\n  // ==========================================================================\n\n  /**\n   * Clones a virtual node tree.\n   * @param node - Node to clone\n   * @param deep - Whether to clone children\n   * @returns Cloned node\n   */\n  clone(node: VirtualNode, deep: boolean = true): VirtualNode {\n    const clonedChildren: (VirtualNode | string)[] = deep\n      ? node.children.map((child) =>\n          typeof child === 'string' ? child : this.clone(child, true)\n        )\n      : [...node.children];\n\n    const cloned = this.acquire({\n      type: node.type,\n      tag: node.tag,\n      props: { ...node.props },\n      children: clonedChildren,\n      moduleId: node.moduleId ?? undefined,\n      hydrationState: node.hydrationState,\n    });\n\n    // Update parent references\n    if (deep) {\n      for (const child of clonedChildren) {\n        if (typeof child !== 'string') {\n          child.parent = cloned;\n        }\n      }\n    }\n\n    return cloned;\n  }\n\n  /**\n   * Appends a child to a node.\n   * @param parent - Parent node\n   * @param child - Child to append\n   */\n  appendChild(parent: VirtualNode, child: VirtualNode | string): void {\n    const mutableParent = parent as {\n      -readonly [K in keyof VirtualNode]: VirtualNode[K];\n    };\n    mutableParent.children = [...parent.children, child];\n\n    if (typeof child !== 'string') {\n      child.parent = parent;\n    }\n  }\n\n  /**\n   * Removes a child from a node.\n   * @param parent - Parent node\n   * @param child - Child to remove\n   */\n  removeChild(parent: VirtualNode, child: VirtualNode): void {\n    const mutableParent = parent as {\n      -readonly [K in keyof VirtualNode]: VirtualNode[K];\n    };\n    mutableParent.children = parent.children.filter((c) => c !== child);\n    child.parent = null;\n  }\n\n  /**\n   * Replaces a child node.\n   * @param parent - Parent node\n   * @param oldChild - Child to replace\n   * @param newChild - New child\n   */\n  replaceChild(\n    parent: VirtualNode,\n    oldChild: VirtualNode,\n    newChild: VirtualNode | string\n  ): void {\n    const mutableParent = parent as {\n      -readonly [K in keyof VirtualNode]: VirtualNode[K];\n    };\n    const index = parent.children.indexOf(oldChild);\n\n    if (index !== -1) {\n      const newChildren = [...parent.children];\n      newChildren[index] = newChild;\n      mutableParent.children = newChildren;\n\n      oldChild.parent = null;\n      if (typeof newChild !== 'string') {\n        newChild.parent = parent;\n      }\n    }\n  }\n\n  // ==========================================================================\n  // Private Methods\n  // ==========================================================================\n\n  /**\n   * Expands the pool by creating new nodes.\n   * @param count - Number of nodes to create\n   */\n  private expand(count: number): void {\n    const actualCount = Math.min(\n      count,\n      this.config.maxSize - this.allNodes.size\n    );\n\n    if (actualCount <= 0) {\n      return;\n    }\n\n    for (let i = 0; i < actualCount; i++) {\n      const node = createEmptyNode(this.generation);\n      this.allNodes.set(node.id, node);\n      this.freeNodes.push(node);\n    }\n\n    this.updateStats({\n      expansionCount: this.stats.expansionCount + 1,\n    });\n  }\n\n  /**\n   * Expands the pool if needed.\n   */\n  private maybeExpand(): void {\n    // Check memory pressure first\n    if (\n      this.config.enableMemoryPressure &&\n      this.memoryDetector.isUnderPressure()\n    ) {\n      // Under pressure, run GC instead of expanding\n      this.gc();\n      return;\n    }\n\n    // Check if we can expand\n    if (this.allNodes.size >= this.config.maxSize) {\n      return;\n    }\n\n    // Calculate expansion size\n    const currentFree = this.freeNodes.length;\n    const targetFree = this.config.minFreeNodes * this.config.growthFactor;\n    const neededNodes = Math.ceil(targetFree - currentFree);\n\n    if (neededNodes > 0) {\n      this.expand(neededNodes);\n    }\n  }\n\n  /**\n   * Recalculates pool statistics.\n   */\n  private recalculateStats(): void {\n    const totalNodes = this.allNodes.size;\n    const inUseNodes = this.inUseNodes.size;\n    const freeNodes = this.freeNodes.length;\n    const utilization = totalNodes > 0 ? inUseNodes / totalNodes : 0;\n    const estimatedMemoryBytes = totalNodes * ESTIMATED_BYTES_PER_NODE;\n\n    this.stats = {\n      ...this.stats,\n      totalNodes,\n      inUseNodes,\n      freeNodes,\n      utilization,\n      estimatedMemoryBytes,\n    };\n  }\n\n  /**\n   * Updates specific stats.\n   * @param updates - Partial stats to update\n   */\n  private updateStats(updates: Partial<VDOMPoolStats>): void {\n    this.stats = { ...this.stats, ...updates };\n  }\n\n  /**\n   * Starts the GC interval.\n   */\n  private startGCInterval(): void {\n    if (this.config.gcIntervalMs > 0) {\n      this.gcIntervalId = setInterval(() => {\n        this.gc();\n      }, this.config.gcIntervalMs);\n    }\n  }\n\n  /**\n   * Stops the GC interval.\n   */\n  private stopGCInterval(): void {\n    if (this.gcIntervalId !== null) {\n      clearInterval(this.gcIntervalId);\n      this.gcIntervalId = null;\n    }\n  }\n}\n\n// ============================================================================\n// Singleton Instance\n// ============================================================================\n\n/**\n * Default global VDOM pool instance.\n */\nlet defaultPool: VDOMPool | null = null;\n\n/**\n * Gets the default global VDOM pool.\n * @returns Default VDOMPool instance\n */\nexport function getDefaultPool(): VDOMPool {\n  if (!defaultPool || defaultPool.disposed) {\n    defaultPool = new VDOMPool();\n  }\n  return defaultPool;\n}\n\n/**\n * Sets the default global VDOM pool.\n * @param pool - Pool to set as default\n */\nexport function setDefaultPool(pool: VDOMPool): void {\n  if (defaultPool && !defaultPool.disposed) {\n    defaultPool.dispose();\n  }\n  defaultPool = pool;\n}\n\n/**\n * Resets the default global VDOM pool.\n */\nexport function resetDefaultPool(): void {\n  if (defaultPool) {\n    defaultPool.dispose();\n    defaultPool = null;\n  }\n}\n\n// ============================================================================\n// Convenience Factory Functions\n// ============================================================================\n\n/**\n * Creates a new VDOM pool with custom configuration.\n * @param config - Pool configuration\n * @returns New VDOMPool instance\n *\n * @example\n * ```typescript\n * const pool = createVDOMPool({\n *   initialSize: 200,\n *   maxSize: 5000,\n *   gcIntervalMs: 15000,\n * });\n * ```\n */\nexport function createVDOMPool(config: Partial<VDOMPoolConfig> = {}): VDOMPool {\n  return new VDOMPool(config);\n}\n\n/**\n * Acquires a node from the default pool.\n * @param options - Node options\n * @returns Virtual node\n */\nexport function acquireNode(\n  options: Parameters<VDOMPool['acquire']>[0] = {}\n): VirtualNode {\n  return getDefaultPool().acquire(options);\n}\n\n/**\n * Releases a node to the default pool.\n * @param node - Node to release\n */\nexport function releaseNode(node: VirtualNode): void {\n  getDefaultPool().release(node);\n}\n"],"names":["ESTIMATED_BYTES_PER_NODE","nodeIdCounter","generateNodeId","createVNodeId","createEmptyNode","generation","VNodeType","HydrationState","resetNode","node","mutableNode","MemoryPressureDetector","threshold","now","performance","usedJSHeapSize","jsHeapSizeLimit","VDOMPool","config","DEFAULT_POOL_CONFIG","options","poppedNode","child","nodes","nodeTtl","collectedCount","nodesToKeep","nodesToRemove","isOld","exceedsShrinkThreshold","nodeId","tag","props","children","text","component","moduleId","deep","clonedChildren","cloned","parent","mutableParent","c","oldChild","newChild","index","newChildren","count","actualCount","i","currentFree","targetFree","neededNodes","totalNodes","inUseNodes","freeNodes","utilization","estimatedMemoryBytes","updates","defaultPool","getDefaultPool","setDefaultPool","pool","resetDefaultPool","createVDOMPool","acquireNode","releaseNode"],"mappings":";AAiCA,MAAMA,IAA2B;AAKjC,IAAIC,IAAgB;AAUpB,SAASC,IAA0B;AACjC,SAAAD,KAAiB,GACVE,EAAc,SAAS,KAAK,IAAA,EAAM,SAAS,EAAE,CAAC,IAAIF,EAAc,SAAS,EAAE,CAAC,EAAE;AACvF;AAOA,SAASG,EAAgBC,GAAiC;AACxD,SAAO;AAAA,IACL,IAAIH,EAAA;AAAA,IACJ,MAAMI,EAAU;AAAA,IAChB,KAAK;AAAA,IACL,OAAO,CAAA;AAAA,IACP,UAAU,CAAA;AAAA,IACV,QAAQ;AAAA,IACR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