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

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

4. Code

```

// cat.js

// Immediately Invoked Function Expression (IIFE) to encapsulate the engine
(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>.
     * @returns {Function} - A function that defines and registers the component.
     */
    function compileComponent(name, templateContent, scriptContent) {
      // Parse the template content
      const parser = new DOMParser();
      const doc = parser.parseFromString(`<template>${templateContent}</template>`, 'text/html');
      const template = doc.querySelector('template');
      const content = template.content;

      // Collect bindings and generate code
      const bindings = [];
      const propertyNames = new Set();

      function processNode(node, path) {
        if (node.nodeType === Node.TEXT_NODE) {
          const originalText = node.textContent;
          const regex = /\{(\w+)\}/g;
          let match;
          while ((match = regex.exec(originalText)) !== null) {
            const varName = match[1];
            propertyNames.add(varName);

            bindings.push({
              type: 'text',
              varName,
              originalText,
              path: path.slice(),
            });
          }
        } else if (node.nodeType === Node.ELEMENT_NODE) {
          // Process attributes
          for (let attr of Array.from(node.attributes)) {
            const originalValue = attr.value;
            const regex = /\{(\w+)\}/g;
            let match;
            while ((match = regex.exec(originalValue)) !== null) {
              const varName = match[1];
              propertyNames.add(varName);

              bindings.push({
                type: 'attribute',
                varName,
                attributeName: attr.name,
                originalValue,
                path: path.slice(),
              });
            }
          }

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

      // Start processing from the template's content
      content.childNodes.forEach((childNode, index) => {
        processNode(childNode, [index]);
      });

      // Generate the component class code
      let classCode = `
        (function() {
          class ${capitalizeComponentName(name)} extends HTMLElement {
            constructor() {
              super();
              const shadowRoot = this.attachShadow({ mode: 'open' });
      `;

      // Inject the template content into the shadowRoot
      classCode += `
              const template = document.createElement('template');
              template.innerHTML = \`${templateContent.replace(/`/g, '\\`')}\`;
              shadowRoot.appendChild(template.content.cloneNode(true));
      `;

      // Generate code to get references to the nodes that need to be updated
      bindings.forEach((binding, index) => {
        classCode += `
              this._binding${index}_node = shadowRoot`;
        binding.path.forEach(pathIndex => {
          classCode += `.childNodes[${pathIndex}]`;
        });
        classCode += `;\n`;
      });

      // Initialize properties and define reactive setters
      propertyNames.forEach(varName => {
        classCode += `
              this._${varName} = '';
        `;
      });

      classCode += `
            }
      `; // End of constructor

      // Define property getters and setters with direct DOM updates
      propertyNames.forEach(varName => {
        classCode += `
            get ${varName}() {
              return this._${varName};
            }
            set ${varName}(value) {
              this._${varName} = value;
        `;
        // For each binding related to this property, update the DOM directly
        bindings.filter(binding => binding.varName === varName).forEach((binding) => {
          if (binding.type === 'text') {
            // Update text content
            classCode += `
              this._binding${bindings.indexOf(binding)}_node.textContent = \`${binding.originalText.replace(/\{(\w+)\}/g, (_, name) => `\${this['${name}']}`)}\`;
            `;
          } else if (binding.type === 'attribute') {
            // Update attribute value
            classCode += `
              this._binding${bindings.indexOf(binding)}_node.setAttribute('${binding.attributeName}', \`${binding.originalValue.replace(/\{(\w+)\}/g, (_, name) => `\${this['${name}']}`)}\`);
            `;
          }
        });
        classCode += `
            } // End of setter for ${varName}
        `;
      });

      // Define connectedCallback to run the user script
      classCode += `
            connectedCallback() {
      `;

      // Append user-defined script content inside connectedCallback
      if (scriptContent.trim()) {
        classCode += `
              ${scriptContent}
        `;
      }

      classCode += `
            } // End of connectedCallback
      `;

      // Close the class definition and define the custom element
      classCode += `
          } // End of class ${capitalizeComponentName(name)}

          customElements.define('${name}', ${capitalizeComponentName(name)});
        })();
      `;

      // Return the component definer function
      try {
        const componentDefiner = new Function(classCode);
        return componentDefiner;
      } catch (error) {
        console.error(`Error compiling component '${name}': ${error.message}`);
        console.error(classCode);
        throw error;
      }
    }

    // Helper function to capitalize component name for class name
    function capitalizeComponentName(name) {
      return name
        .replace(/-([a-z])/g, (match, p1) => p1.toUpperCase())
        .replace(/^./, str => str.toUpperCase());
    }

    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).
   * @returns {Promise<void>}
   */
  window.load = async function(path) {
    console.log(`Loading: ${path}`);

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

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

      Registry.markFileAsLoaded(path);

      // 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
      const defineComponent = Compiler.compileComponent(componentName, templateContent, scriptContent);

      // Execute the function to define the component
      defineComponent();

      console.log(`Component registered: ${componentName}`);
    } catch (error) {
      console.error(`Error loading component from ${path}: ${error.message}`);
    }
  };
})();

```

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: <span>{count}</span></button>
</template>

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

    const component = this;

    function updateCount() {
        component.count++;

        component.status = component.status === 'on' ? 'off' : 'on';
    }

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

```

Your first task it's outperform the quality of the compiled components, not the compiler, the compiled component. Compiling components that are highly efficient, 0 dependency of external lib or neither cat.js to work after compiled, native low level JavaScript that fits perfectly with the browser runtime and memory usage. Invest all the time needed until you find the most optimal approach.

Our current approach works pretty well, but doesn't outperform svelte compiled components, so invest time understanding how it works, and from there start exploring the enhancements.

There's only one rule, the syntax of our sample component can't change.