1. Project Overview
Cat.js is a lightweight, state-of-the-art engine designed to build powerful User Interfaces (UIs). It prioritizes the highest performance and efficiency, based exclusively on modern native browser APIs, primarily Web Components.

- Version: 0.1.0 (as of October 1, 2024)

2. Core Concepts and Principles
- Utilizes modern native browser APIs, especially Web Components
- Focuses on maximum performance and efficiency
- Promotes a lightweight approach to UI development
- Emphasizes simplicity and ease of use

3. Technical Details

Key Features
- Client-Side Compiler (CSC) before loading the DOM
- Attachment through a script:src tag in the head of HTML documents
- Written in vanilla, low-level JavaScript optimized for browser runtime
- Beautiful and easy-to-use syntax
- Efficient project tree structure
- Compiles everything on the loading stage.
- Everything that was compiled it's "0-dependency", neither of cat.js.

Implementation Details
- No Virtual DOM or similar abstractions
- Avoids use of bundlers, Webpack, polyfills, etc.
- Discourages writing HTML or CSS code within JavaScript files
- Eliminates render methods for components and logic that trigger unnecessary reflows and repainting
- Avoid treat Cat.js as a runtime at any cost.

4. Code

```

// cat.js

// Immediately Invoked Function Expression (IIFE) to encapsulate the code
(function() {
  'use strict';

  /**
   * Internal module for tracking loaded files.
   */
  const Registry = (function() {
    const loadedFiles = new Set();

    return {
      isFileLoaded: (path) => loadedFiles.has(path),
      markFileAsLoaded: (path) => loadedFiles.add(path),
    };
  })();

  /**
   * Compiler module for generating self-contained component classes.
   */
  const Compiler = (function() {
    /**
     * Compiles the component's template and script into a component class definition.
     * @param {string} name - The name of the component (e.g., 'my-component').
     * @param {string} templateContent - The inner HTML of the component's <template>.
     * @param {string} scriptContent - The content of the component's <script>.
     */
    function compileComponent(name, templateContent, scriptContent) {
      // Check if the component is already defined
      if (customElements.get(name)) {
        console.warn(`Component ${name} is already defined.`);
        return;
      }

      // Create a template element and pre-clone its content
      const templateElement = document.createElement('template');
      templateElement.innerHTML = templateContent;
      const templateContentClone = templateElement.content;

      // Process the template to find bindings
      const bindings = []; // Array to hold binding info
      const propertyNames = new Set();

      // Process nodes recursively
      const processNode = (node, path) => {
        if (node.nodeType === Node.TEXT_NODE) {
          const text = node.textContent;
          const parts = parseTextContent(text);

          if (parts.some(part => part.dynamic)) {
            const binding = {
              type: 'text',
              nodePath: path.slice(),
              parts: parts,
            };

            // Collect variable names
            parts.forEach(part => {
              if (part.dynamic) {
                propertyNames.add(part.expression);
              }
            });

            bindings.push(binding);
          }
        } else if (node.nodeType === Node.ELEMENT_NODE) {
          if (node.nodeName.toLowerCase() === 'style') {
            // Do not process the content of style tags
            return;
          }

          // Process attributes
          Array.from(node.attributes).forEach(attr => {
            const parts = parseTextContent(attr.value);

            if (parts.some(part => part.dynamic)) {
              const binding = {
                type: 'attribute',
                nodePath: path.slice(),
                attributeName: attr.name,
                parts: parts,
              };

              // Collect variable names
              parts.forEach(part => {
                if (part.dynamic) {
                  propertyNames.add(part.expression);
                }
              });

              bindings.push(binding);
            }
          });

          // Process child nodes recursively
          node.childNodes.forEach((childNode, index) => {
            path.push(index);
            processNode(childNode, path);
            path.pop();
          });
        }
      };

      // Helper function to parse text content and extract static and dynamic parts
      function parseTextContent(text) {
        const regex = /\{([^}]+)\}/g;
        let lastIndex = 0;
        let match;
        const parts = [];

        while ((match = regex.exec(text)) !== null) {
          if (match.index > lastIndex) {
            parts.push({
              dynamic: false,
              value: text.slice(lastIndex, match.index),
            });
          }
          parts.push({
            dynamic: true,
            expression: match[1].trim(),
          });
          lastIndex = regex.lastIndex;
        }
        if (lastIndex < text.length) {
          parts.push({
            dynamic: false,
            value: text.slice(lastIndex),
          });
        }
        return parts;
      }

      // Start processing from templateElement.content
      templateElement.content.childNodes.forEach((node, index) => {
        processNode(node, [index]);
      });

      // Precompute propertyNames
      const properties = Array.from(propertyNames);

      // Generate the ComponentClass
      class ComponentClass extends HTMLElement {
        constructor() {
          super();
          this._propertyValues = {};
          this._bindingsMap = {};
          this._eventListeners = [];

          const shadowRoot = this.attachShadow({ mode: 'open' });

          // Clone the template content into the shadowRoot
          const instanceNodes = ComponentClass.templateContent.cloneNode(true);
          shadowRoot.appendChild(instanceNodes);

          // Setup bindings
          this._setupBindings(shadowRoot);

          // Initialize properties
          this._initProperties();

          // Execute user script in the context of 'this' safely
          if (ComponentClass.scriptFunction) {
            try {
              ComponentClass.scriptFunction.call(this);
            } catch (error) {
              console.error(`Error executing script in component ${name}: ${error.message}`);
            }
          }

          // Initial rendering
          this._initialRender();
        }

        _initProperties() {
          // Initialize property values
          ComponentClass.properties.forEach(varName => {
            if (!(varName in this._propertyValues)) {
              this._propertyValues[varName] = undefined;
            }
          });
        }

        _setupBindings(shadowRoot) {
          const bindings = [];

          // Setup per-instance bindings
          ComponentClass.bindings.forEach(templateBinding => {
            const node = this._getNodeByPath(shadowRoot, templateBinding.nodePath);

            if (templateBinding.type === 'text') {
              const textNodes = this._createTextBindings(node, templateBinding.parts);
              textNodes.forEach(textNode => bindings.push(textNode));
            } else if (templateBinding.type === 'attribute') {
              const attrBinding = this._createAttributeBinding(node, templateBinding);
              bindings.push(attrBinding);
            }
          });

          // Organize bindings by property for efficient updates
          bindings.forEach(binding => {
            binding.expressions.forEach(expr => {
              if (!this._bindingsMap[expr]) {
                this._bindingsMap[expr] = [];
              }
              this._bindingsMap[expr].push(binding);
            });
          });

          this._bindings = bindings;
        }

        _createTextBindings(node, parts) {
          const textNodes = [];
          const fragment = document.createDocumentFragment();
          parts.forEach(part => {
            if (part.dynamic) {
              const textNode = document.createTextNode('');
              textNodes.push({
                type: 'text-node',
                node: textNode,
                expressions: [part.expression],
                evaluate: () => {
                  let value = this[part.expression];
                  if (value === undefined || value === null) {
                    value = '';
                  }
                  textNode.textContent = value;
                },
              });
              fragment.appendChild(textNode);
            } else {
              fragment.appendChild(document.createTextNode(part.value));
            }
          });
          node.parentNode.replaceChild(fragment, node);
          return textNodes;
        }

        _createAttributeBinding(node, templateBinding) {
          return {
            type: 'attribute',
            node: node,
            attributeName: templateBinding.attributeName,
            expressions: templateBinding.parts.filter(p => p.dynamic).map(p => p.expression),
            evaluate: () => {
              const value = templateBinding.parts.map(part => {
                if (part.dynamic) {
                  let val = this[part.expression];
                  if (val === undefined || val === null) {
                    val = '';
                  }
                  return val;
                } else {
                  return part.value;
                }
              }).join('');
              node.setAttribute(templateBinding.attributeName, value);
            },
          };
        }

        _getNodeByPath(root, path) {
          let current = root;
          for (let i = 0; i < path.length; i++) {
            current = current.childNodes[path[i]];
          }
          return current;
        }

        _updateProperty(varName) {
          const bindings = this._bindingsMap[varName];
          if (bindings) {
            bindings.forEach(binding => {
              binding.evaluate();
            });
          }
        }

        _initialRender() {
          // Evaluate all bindings once to render initial content
          this._bindings.forEach(binding => {
            binding.evaluate();
          });
        }

        connectedCallback() {
          // Any additional initialization can be done here
          if (typeof this.onConnected === 'function') {
            this.onConnected();
          }
        }

        disconnectedCallback() {
          // Clean up event listeners
          this._eventListeners.forEach(({ target, type, listener, options }) => {
            target.removeEventListener(type, listener, options);
          });
          this._eventListeners = [];

          // Any additional cleanup
          if (typeof this.onDisconnected === 'function') {
            this.onDisconnected();
          }
        }

        // Method to add event listeners and track them
        _addEventListener(target, type, listener, options) {
          target.addEventListener(type, listener, options);
          this._eventListeners.push({ target, type, listener, options });
        }
      }

      // Attach static properties to the class
      ComponentClass.templateContent = templateContentClone;
      ComponentClass.bindings = bindings;
      ComponentClass.properties = properties;

      // Define properties on the prototype with getters and setters
      ComponentClass.properties.forEach(varName => {
        Object.defineProperty(ComponentClass.prototype, varName, {
          get: function() {
            return this._propertyValues[varName];
          },
          set: function(newValue) {
            if (this._propertyValues[varName] !== newValue) {
              this._propertyValues[varName] = newValue;
              this._updateProperty(varName);
            }
          },
        });
      });

      // Prepare and execute the scriptFunction once per component
      ComponentClass.scriptFunction = null;
      if (scriptContent.trim()) {
        try {
          // Wrap the script content in a function and execute it in the component's context
          ComponentClass.scriptFunction = new Function(scriptContent);
        } catch (error) {
          console.error(`Error compiling script in component ${name}: ${error.message}`);
        }
      }

      // Register the component
      customElements.define(name, ComponentClass);
    }

    return {
      compileComponent,
    };
  })();

  /**
   * Internal module for loading and parsing HTML files.
   */
  const Loader = (function() {
    /**
     * Loads an HTML file from the given path.
     * @param {string} path - The path to the HTML file (without .html extension).
     * @returns {Promise<string>} - A promise that resolves to the content of the HTML file.
     */
    async function loadFile(path) {
      const fullPath = `${path}.html`;

      try {
        const response = await fetch(fullPath);
        if (!response.ok) {
          throw new Error(`Failed to load: ${fullPath} (Status: ${response.status})`);
        }
        const content = await response.text();
        return content;
      } catch (error) {
        console.error(error.message);
        throw error;
      }
    }

    /**
     * Parses an HTML string into a Document object.
     * @param {string} htmlString - The HTML string to parse.
     * @returns {Document} - The parsed Document object.
     */
    function parseHTML(htmlString) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlString, 'text/html');
      return doc;
    }

    return {
      loadFile,
      parseHTML,
    };
  })();

  /**
   * Global load function.
   * @param {string} path - The path to the HTML file (without .html extension).
   */
  window.load = function(path) {
    console.log(`Loading: ${path}`);

    if (Registry.isFileLoaded(path)) {
      console.log(`Already loading or loaded: ${path}`);
      return;
    }

    // Mark the file as loaded immediately to prevent race conditions
    Registry.markFileAsLoaded(path);

    (async function() {
      try {
        const responseText = await Loader.loadFile(path);
        const doc = Loader.parseHTML(responseText);

        // Extract the <template> with the 'name' attribute
        const template = doc.querySelector('template[name]');
        if (!template) {
          console.error(`No <template name="..."> found in ${path}.html`);
          return;
        }

        const componentName = template.getAttribute('name');
        const templateContent = template.innerHTML;

        // Extract the <script> content
        const script = doc.querySelector('script');
        const scriptContent = script ? script.textContent : '';

        // Use compiler to generate and define the component
        Compiler.compileComponent(componentName, templateContent, scriptContent);

        console.log(`Component registered: ${componentName}`);
      } catch (error) {
        console.error(`Error loading component from ${path}: ${error.message}`);
        // Optionally, you can remove the path from the Registry to allow retries
        // Registry.removeFile(path);
      }
    })();
  };
})();

```

5. Sample component:

```
<!-- app/comp/counter.html -->
<template name="my-counter">
    <style>
        .on {
            background-color: blue;
        }
        .off {
            background-color: aliceblue;
        }
        .btn {
            padding: 20px;
        }
    </style>

    <button class="{status} btn">Count: {count}</button>
</template>

<script>
    this.count = 0;
    this.status = 'on';
    
    const button = this.shadowRoot.querySelector('button');
    const span = button.querySelector('span');

    const component = this; // To maintain correct context inside functions

    function updateCount() {
        component.count++;

        component.status = component.status === 'on' ? 'off' : 'on';
        // The reactive system will automatically update the DOM elements where {count} and {status} are used
    }

    button.addEventListener('click', updateCount);
</script>
```

Your objective it's:

Further Optimized Component

By introducing ahead-of-time compilation, the component class could be generated as follows:

```javascript
class MyCounter extends HTMLElement {
  constructor() {
    super();

    // Attach shadow DOM
    const shadowRoot = this.attachShadow({ mode: 'open' });

    // Create and append styles
    const style = document.createElement('style');
    style.textContent = `
      .on {
          background-color: blue;
          color: white;
      }
      .off {
          background-color: aliceblue;
          color: black;
      }
      .btn {
          padding: 20px;
      }
    `;
    shadowRoot.appendChild(style);

    // Create and append button
    this._button = document.createElement('button');
    this._button.className = 'on btn';
    this._button.textContent = 'Count: 0';
    shadowRoot.appendChild(this._button);

    // Create and append user-name component
    const userName = document.createElement('user-name');
    shadowRoot.appendChild(userName);
    load('app/comp/name');

    // Initialize properties
    this._count = 0;
    this._status = 'on';

    // Add event listener
    this._button.addEventListener('click', () => {
      this.count = this._count + 1;
      this.status = this._status === 'on' ? 'off' : 'on';
    });
  }

  get count() {
    return this._count;
  }
  set count(value) {
    this._count = value;
    this._button.textContent = `Count: ${this._count}`;
  }

  get status() {
    return this._status;
  }
  set status(value) {
    this._status = value;
    this._button.className = `${this._status} btn`;
  }
}

customElements.define('my-counter', MyCounter);
```

Advantages of This Approach

- No Bindings or Property Maps: Directly updates DOM without intermediate data structures.
- Reduced Memory Usage: Eliminates per-instance overhead from bindings and property storage.
- Improved Performance: Fewer function calls and lookups, leading to faster execution.

Your goal it's set the compiled components from cat.js as the most powerful, with the lowest performance and memory foot print, no matter the amount of instance of the same component. Being powerful, lightweight and 0-depenency type.

Take all the time you need, once finished, provide the cat.js with the implementation. And a sample of how looks the component after compiled.