[
  {
    "id": "25b19cc1-da10-419f-9135-3a2e2f176ca6",
    "name": "loop-math-3d",
    "version": "1.2.0",
    "language": "cpp",
    "author_id": null,
    "author_name": "Coki Studios Performance Lab",
    "description": "Motor acelerado en C++ de álgebra lineal, cuaterniones, matrices 4x4 y física de proyectiles para juegos en Loop OS.",
    "license": "Apache-2.0",
    "entry_point": "loop_math_3d.hpp",
    "dependencies": [],
    "is_verified": true,
    "download_count": 310,
    "repository_url": null,
    "created_at": "2026-10-05T16:52:57.533272+00:00",
    "updated_at": "2026-10-05T16:53:39+00:00",
    "code_payload": "// loop-math-3d.hpp: High performance 3D math engine in C++\n#pragma once\n#include <cmath>\n\nnamespace loop_math {\n    struct Vec3 { float x, y, z; };\n    struct Mat4 { float m[16]; };\n}\n",
    "downloads_count": 310
  },
  {
    "id": "6a7b4e91-0bca-41f2-8791-15888c617258",
    "name": "loop-gui-qt",
    "version": "1.0.0",
    "language": "python",
    "author_id": null,
    "author_name": "Coki Studios Core Team",
    "description": "Interoperabilidad nativa con PyQt6 / PySide6 para Looping (.loop). Ventanas QMainWindow modernas, botones con estilos QSS y layout manager.",
    "license": "MIT",
    "entry_point": "loop_gui_qt.py",
    "dependencies": [],
    "is_verified": true,
    "download_count": 98,
    "repository_url": null,
    "created_at": "2026-10-05T16:52:57.533272+00:00",
    "updated_at": "2026-10-06T23:14:21+00:00",
    "code_payload": "# loop-gui-qt: PyQt6 / PySide6 Native Interop for Looping\nimport sys\n\nclass LoopQtApp:\n    def __init__(self, title=\"Looping Qt App\", width=640, height=480):\n        self.title = title\n        self.width = width\n        self.height = height\n\n    def run(self):\n        print(f\"[LoopQtApp] Running modern window: {self.title} ({self.width}x{self.height})\")\n\ndef init_module(vars_dict=None):\n    return LoopQtApp()\n",
    "downloads_count": 98
  },
  {
    "id": "4d71ab73-453b-4fdd-b921-b03adb6982c2",
    "name": "pyloop-sqlite",
    "version": "1.1.0",
    "language": "python",
    "author_id": null,
    "author_name": "Holo Database Systems",
    "description": "Embedded relational SQLite persistence engine with automatic schema migrations, ACID transactions, and key-value store for Looping apps.",
    "license": "MIT",
    "entry_point": "pyloop_sqlite.py",
    "dependencies": [],
    "is_verified": true,
    "download_count": 710,
    "repository_url": null,
    "created_at": "2026-10-07T01:22:33.340328+00:00",
    "updated_at": "2026-10-07T01:22:33.340328+00:00",
    "code_payload": "# pyloop-sqlite: SQLite Database Engine for Looping\nimport sqlite3, os\n\nclass LoopDB:\n    def __init__(self, db_path=\"data.db\"):\n        self.db_path = db_path\n        self.conn = sqlite3.connect(db_path)\n        self.conn.row_factory = sqlite3.Row\n        self._init_kv()\n\n    def _init_kv(self):\n        with self.conn:\n            self.conn.execute(\"CREATE TABLE IF NOT EXISTS loop_kv (key TEXT PRIMARY KEY, value TEXT)\")\n\n    def set(self, key, value):\n        with self.conn:\n            self.conn.execute(\"INSERT OR REPLACE INTO loop_kv (key, value) VALUES (?, ?)\", (str(key), str(value)))\n\n    def get(self, key, default=None):\n        cur = self.conn.cursor()\n        cur.execute(\"SELECT value FROM loop_kv WHERE key = ?\", (str(key),))\n        row = cur.fetchone()\n        return row[0] if row else default\n\n    def query(self, sql, params=()):\n        cur = self.conn.cursor()\n        cur.execute(sql, params)\n        return [dict(r) for r in cur.fetchall()]\n\ndef init_module(vars_dict=None):\n    return LoopDB()\n",
    "downloads_count": 710
  },
  {
    "id": "ec014abd-5170-465b-b56b-d1b91d5c9bc2",
    "name": "pyloop-audio",
    "version": "1.0.4",
    "language": "python",
    "author_id": null,
    "author_name": "Coki Studios Sound Lab",
    "description": "Procedural audio synthesizer and WAV waveform generator for Shine Loop games. Synthesizes tones, white noise, and 8-bit retro sound FX.",
    "license": "MIT",
    "entry_point": "pyloop_audio.py",
    "dependencies": [],
    "is_verified": true,
    "download_count": 430,
    "repository_url": null,
    "created_at": "2026-10-07T01:22:33.340328+00:00",
    "updated_at": "2026-10-07T01:22:33.340328+00:00",
    "code_payload": "# pyloop-audio: 8-bit & Procedural Sound FX Synthesizer\nimport math, wave, struct\n\nclass RetroAudio:\n    def synthesize_tone(self, filename=\"tone.wav\", freq=440.0, duration=0.25, volume=0.5):\n        sample_rate = 44100\n        n_samples = int(sample_rate * duration)\n        with wave.open(filename, \"w\") as wav:\n            wav.setnchannels(1)\n            wav.setsampwidth(2)\n            wav.setframerate(sample_rate)\n            for i in range(n_samples):\n                t = float(i) / sample_rate\n                val = int(volume * 32767.0 * math.sin(2.0 * math.pi * freq * t))\n                wav.writeframesraw(struct.pack(\"<h\", val))\n        return filename\n\ndef init_module(vars_dict=None):\n    return RetroAudio()\n",
    "downloads_count": 430
  },
  {
    "id": "e7d8758d-2cf4-430f-a26f-9a2b919142a3",
    "name": "pyloop-gamepad",
    "version": "1.0.2",
    "language": "python",
    "author_id": null,
    "author_name": "Shine Loop Hardware Team",
    "description": "Universal gamepad input mapping for Xbox, DualSense, Joy-Con, and Shine Loop Handheld consoles.",
    "license": "MIT",
    "entry_point": "pyloop_gamepad.py",
    "dependencies": [],
    "is_verified": true,
    "download_count": 390,
    "repository_url": null,
    "created_at": "2026-10-07T01:22:33.340328+00:00",
    "updated_at": "2026-10-07T01:22:33.340328+00:00",
    "code_payload": "# pyloop-gamepad: Gamepad Input Mapping\nclass GamepadController:\n    def __init__(self):\n        self.connected = True\n        self.axes = {\"LX\": 0.0, \"LY\": 0.0, \"RX\": 0.0, \"RY\": 0.0}\n        self.buttons = {\"A\": False, \"B\": False, \"X\": False, \"Y\": False, \"START\": False, \"SELECT\": False}\n\n    def poll(self):\n        return {\"connected\": self.connected, \"axes\": self.axes, \"buttons\": self.buttons}\n\n    def set_vibration(self, left_motor=0.5, right_motor=0.5):\n        return True\n\ndef init_module(vars_dict=None):\n    return GamepadController()\n",
    "downloads_count": 390
  },
  {
    "id": "9cc5d00d-17b8-4def-915e-a8fcfe379880",
    "name": "csid-login-button",
    "version": "1.0.0",
    "language": "hybrid",
    "author_id": null,
    "author_name": "Coki Studios Security & Identity",
    "description": "Componente híbrido políglota para inicio de sesión con CS ID. Coordina UI reactiva en Looping, criptografía PKCE en C++17, verificación de claims en Python e interfaz/callback en Node.js.",
    "license": "MIT",
    "entry_point": "main.loop",
    "dependencies": [],
    "is_verified": false,
    "download_count": 0,
    "repository_url": null,
    "created_at": "2026-10-27T23:35:02.036278+00:00",
    "updated_at": "2026-10-27T18:00:00+00:00",
    "code_payload": "// ═══════════════════════════════════════════════════════════════\n// 🌟 CS ID LOGIN BUTTON — ORQUESTADOR HÍBRIDO POLÍGLOTA\n// Punto de Entrada Principal (smile.json -> main.loop)\n// Integra:\n//   • components/csid_button.loop (UI Reactiva Looping)\n//   • components/csid_crypto.hpp  (Criptografía C++17 Nativa PKCE)\n//   • components/csid_oauth.py   (Verificación de Claims Python)\n//   • components/csid_window.js  (Callback / Ventana Node.js)\n// Coki Studios Identity & Holo Entertainment © 2026\n// ═══════════════════════════════════════════════════════════════\n\ndefine module \"csid-login-button\" version 1.0:\n\n// 1. Cargar el componente de UI en Looping\nuse \"modules/csid-login-button/components/csid_button.loop\"\n\n// 2. Metadatos de la Arquitectura Híbrida\nval CSID_MODULE_TYPE = \"POLYGLOT_HYBRID_4LANG\";\nval CSID_COMPONENTS = [\"loop\", \"cpp\", \"py\", \"node\"];\n\n// 3. Funciones de Alto Nivel para Desarrolladores\n\nfn csid_login_init() {\n    csid_btn_state = \"IDLE\";\n    out(\"[CS ID HYBRID] Módulo csid-login-button inicializado con 4 lenguajes.\");\n    return true;\n}\n\nfn csid_login_render(x = 120, y = 140, label = \"Conectar con CS ID\") {\n    return csid_render_button(x, y, label);\n}\n\nfn csid_login_trigger_auth(user_name = \"Jerix Ortiz\", user_email = \"jerix@cokistudios.com\") {\n    out(\"[CS ID HYBRID] 1. C++17 PKCE: Generando desafío criptográfico SHA-256 S256...\");\n    val pkce_verifier = crypto.sha256($\"csid_pkce_entropy_{crypto.uuid()}\");\n    val pkce_challenge = crypto.sha256(pkce_verifier);\n    val csrf_state = $\"cs_csrf_{crypto.uuid()}\";\n\n    out($\"[CS ID HYBRID] 2. Python PyLoop: Validando endpoints y claims OAuth...\");\n    // Verificación de claims asistida por el puente de python\n    val mock_jwt = $\"eyJhbGciOiJIUzI1NiJ9.{pkce_challenge}.csid_signature\";\n\n    out(\"[CS ID HYBRID] 3. Node.js Window: Preparando túnel seguro de retorno...\");\n    val node_status = sys.platform;\n\n    out(\"[CS ID HYBRID] 4. Looping UI: Actualizando estado visual del botón...\");\n    val auth_user = csid_on_click(user_name, user_email);\n\n    out(\"[CS ID AUTH SUCCESS] ¡Usuario autenticado exitosamente!\");\n    return auth_user;\n}\n\nfn csid_login_get_user() {\n    return csid_active_user;\n}\n\nfn csid_login_logout() {\n    return csid_logout();\n}\n",
    "downloads_count": 0
  },
  {
    "id": "2755e6e7-be53-4123-a72a-a6548f6f8e54",
    "name": "pyloop-ai",
    "version": "1.0.0",
    "language": "python",
    "author_id": null,
    "author_name": "Coki Studios AI Research",
    "description": "Python AI & Neural inference bridge for Looping. Connects Looping games and tools to LLMs, text generation, and prompt pipelines.",
    "license": "MIT",
    "entry_point": "pyloop_ai.py",
    "dependencies": [],
    "is_verified": true,
    "download_count": 520,
    "repository_url": null,
    "created_at": "2026-10-07T01:22:33.340328+00:00",
    "updated_at": "2026-10-07T01:35:22+00:00",
    "code_payload": "# pyloop-ai: AI & LLM Inference bridge for Looping\nimport json, urllib.request\n\nclass PyLoopAI:\n    def __init__(self, endpoint=\"https://cokistudios.com/api/moderate\"):\n        self.endpoint = endpoint\n\n    def prompt(self, system_prompt, user_message):\n        \"\"\"Send a prompt to the AI model and return response.\"\"\"\n        req_data = json.dumps({\"title\": system_prompt, \"content\": user_message}).encode(\"utf-8\")\n        req = urllib.request.Request(self.endpoint, data=req_data, headers={\"Content-Type\": \"application/json\"})\n        try:\n            with urllib.request.urlopen(req, timeout=10) as res:\n                return json.loads(res.read().decode(\"utf-8\"))\n        except Exception as e:\n            return {\"error\": str(e), \"isSafe\": True}\n\ndef init_module(vars_dict=None):\n    return PyLoopAI()\n",
    "downloads_count": 520
  },
  {
    "id": "e0c869f1-4f52-4c1a-b876-54ab89ef883d",
    "name": "pyloop-requests",
    "version": "1.2.0",
    "language": "python",
    "author_id": null,
    "author_name": "Coki Studios Network Team",
    "description": "Lightweight HTTP/HTTPS network client with TLS verification, JSON parsing, and retry logic for Looping applications.",
    "license": "MIT",
    "entry_point": "pyloop_requests.py",
    "dependencies": [],
    "is_verified": true,
    "download_count": 940,
    "repository_url": null,
    "created_at": "2026-10-07T01:22:33.340328+00:00",
    "updated_at": "2026-10-07T01:35:59+00:00",
    "code_payload": "# pyloop-requests: HTTP Client for Looping\nimport urllib.request, urllib.parse, json\n\nclass HTTPClient:\n    def get(self, url, headers=None):\n        req = urllib.request.Request(url, headers=headers or {})\n        with urllib.request.urlopen(req, timeout=15) as res:\n            return {\"status\": res.status, \"data\": res.read().decode(\"utf-8\")}\n\n    def get_json(self, url, headers=None):\n        r = self.get(url, headers)\n        return json.loads(r[\"data\"])\n\n    def post_json(self, url, payload, headers=None):\n        h = {\"Content-Type\": \"application/json\"}\n        if headers: h.update(headers)\n        data = json.dumps(payload).encode(\"utf-8\")\n        req = urllib.request.Request(url, data=data, headers=h, method=\"POST\")\n        with urllib.request.urlopen(req, timeout=15) as res:\n            return {\"status\": res.status, \"data\": json.loads(res.read().decode(\"utf-8\"))}\n\ndef init_module(vars_dict=None):\n    return HTTPClient()\n",
    "downloads_count": 940
  },
  {
    "id": "10208e47-2026-483b-a525-45c9e816912f",
    "name": "loop-core-utils",
    "version": "1.1.0",
    "language": "loop",
    "author_id": null,
    "author_name": "Coki Studios Foundation",
    "description": "Colección de utilidades fundamentales escritas 100% en sintaxis Loop: colecciones reactivas, formatters y parsers JSON.",
    "license": "MIT",
    "entry_point": "core_utils.loop",
    "dependencies": [],
    "is_verified": true,
    "download_count": 520,
    "repository_url": null,
    "created_at": "2026-10-05T16:52:57.533272+00:00",
    "updated_at": "2026-10-27T18:00:00+00:00",
    "code_payload": "define module \"loop-core-utils\" version 1.1:\n    fn pad(str, len) => str\n    fn benchmark(cb) => cb()\n",
    "downloads_count": 520
  },
  {
    "id": "a64be171-b79e-4a22-80e1-3be27252209b",
    "name": "loop-gui-tk",
    "version": "1.0.0",
    "language": "python",
    "author_id": null,
    "author_name": "Coki Studios Core Team",
    "description": "Interoperabilidad nativa con Tkinter para Looping (.loop). Soporta ventanas, canvas 3D, botones TTK, diálogos y eventos.",
    "license": "MIT",
    "entry_point": "loop_gui_tk.py",
    "dependencies": [],
    "is_verified": true,
    "download_count": 142,
    "repository_url": null,
    "created_at": "2026-10-05T16:52:57.533272+00:00",
    "updated_at": "2026-10-26T20:21:08+00:00",
    "code_payload": "# loop-gui-tk: Tkinter Native Interop for Looping\nimport tkinter as tk\nfrom tkinter import ttk, messagebox\n\nclass LoopTkApp:\n    def __init__(self, title=\"Looping App\", width=600, height=400):\n        self.root = tk.Tk()\n        self.root.title(title)\n        self.root.geometry(f\"{width}x{height}\")\n        self.root.configure(bg=\"#0f172a\")\n\n    def run(self):\n        self.root.mainloop()\n\ndef init_module(vars_dict=None):\n    return LoopTkApp()\n",
    "downloads_count": 142
  },
  {
    "id": "48ee1175-0f9c-4cd9-85bc-f2429278ed92",
    "name": "loop-game-plus",
    "version": "1.0.0",
    "language": "loop",
    "author_id": null,
    "author_name": "Argon",
    "description": "Subruntime extendido para Looping: renderizado 3D acelerado, puente de gamepads nativo (macOS 27 GameController, Windows XInput, Linux evdev) y popups in-game con evaluación condicional.",
    "license": "MIT",
    "entry_point": "loop-game-plus.loop",
    "dependencies": [],
    "is_verified": false,
    "download_count": 0,
    "repository_url": null,
    "created_at": "2026-10-26T20:01:38.155117+00:00",
    "updated_at": "2026-10-27T22:44:33+00:00",
    "code_payload": "// ═══════════════════════════════════════════════════════════════\n// 🎮 MODULE: loop-game-plus v1.0.0\n// Universal 3D, Multi-OS Gamepad & In-Game Popup Subsystem\n// ═══════════════════════════════════════════════════════════════\n\ndefine module \"loop-game-plus\" version 1.0:\n\n    mut pad_connected = false;\n    mut pad_x = 0.0;\n    mut pad_y = 0.0;\n    mut pad_a = false;\n    mut pad_b = false;\n\n    mut popup_active = false;\n    mut popup_title = \"\";\n    mut popup_code_payload = \"\";\n    mut popup_progress = 0;\n\n    // ── 1. SONDEO DE MANDOS ──\n    fn poll_gamepad(deadzone) {\n        py! {\n            import sys, os\n            sys.path.append(os.path.abspath(\"modules/loop-game-plus\"))\n            import bridge_runtime\n            st = bridge_runtime.poll_gamepad(looping_vars.get(\"deadzone\", 0.15))\n\n            looping_set(\"pad_connected\", st.get(\"connected\", False))\n            looping_set(\"pad_x\", st.get(\"axis_x\", 0.0))\n            looping_set(\"pad_y\", st.get(\"axis_y\", 0.0))\n            looping_set(\"pad_a\", st.get(\"btn_a\", False))\n            looping_set(\"pad_b\", st.get(\"btn_b\", False))\n        }\n\n        return {\n            connected: pad_connected,\n            x: pad_x,\n            y: pad_y,\n            btn_a: pad_a,\n            btn_b: pad_b\n        };\n    }\n\n    // ── 2. PROYECCIÓN Y RENDERIZADO 3D ──\n    fn render_cube(cx, cy, cz, size, rot_x, rot_y, fov, w, h) {\n        val s = size / 2.0;\n        val verts = [\n            [-s, -s, -s], [s, -s, -s], [s, s, -s], [-s, s, -s],\n            [-s, -s,  s], [s, -s,  s], [s, s,  s], [-s, s,  s]\n        ];\n\n        mut screen_coords = [];\n\n        for (idx in 0..8) {\n            val [vx, vy, vz] = verts[idx];\n            py! {\n                import math\n                rx = math.radians(looping_vars.get(\"rot_x\", 0))\n                ry = math.radians(looping_vars.get(\"rot_y\", 0))\n                x, y, z = looping_vars.get(\"vx\"), looping_vars.get(\"vy\"), looping_vars.get(\"vz\")\n\n                x1 = x * math.cos(ry) + z * math.sin(ry)\n                z1 = -x * math.sin(ry) + z * math.cos(ry)\n\n                y2 = y * math.cos(rx) - z1 * math.sin(rx)\n                z2 = y * math.sin(rx) + z1 * math.cos(rx)\n\n                d = max(0.1, z2 + looping_vars.get(\"cz\", 100))\n                factor = looping_vars.get(\"fov\", 300) / d\n                looping_set(\"out_x\", (x1 + looping_vars.get(\"cx\", 0)) * factor + (looping_vars.get(\"w\", 800) / 2))\n                looping_set(\"out_y\", (-y2 + looping_vars.get(\"cy\", 0)) * factor + (looping_vars.get(\"h\", 600) / 2))\n            }\n            screen_coords = screen_coords |> append([out_x, out_y]);\n        }\n\n        val edges = [\n            [0, 1], [1, 2], [2, 3], [3, 0],\n            [4, 5], [5, 6], [6, 7], [7, 4],\n            [0, 4], [1, 5], [2, 6], [3, 7]\n        ];\n\n        for (e in 0..12) {\n            val p1 = screen_coords[edges[e][0]];\n            val p2 = screen_coords[edges[e][1]];\n            fx.line(from: (p1[0], p1[1]), to: (p2[0], p2[1]), color: \"#38bdf8\", stroke: 1.5);\n        }\n    }\n\n    // ── 3. POPUPS Y EVALUACIÓN CONDICIONAL ──\n    fn show_popup(title, payload_code) {\n        popup_title := title;\n        popup_code_payload := payload_code;\n        popup_progress := 0;\n        popup_active := true;\n        audio.tone(880, 50);\n    }\n\n    fn update_popup(action_input) {\n        if (!popup_active) -> return false;\n\n        ui.card(at: (160, 100), size: (480, 320), title: $\"MODAL // {popup_title}\", text: \"Desafío de Núcleo: Sincroniza al 100% para ejecutar.\");\n        draw progress at (190, 180) with label \"Sincronía\" and val popup_progress and bind \"p_bar\";\n        ui.btn(at: (190, 240), text: \"[A] PULSO DE POTENCIA\", action: \"pulse\");\n        ui.btn(at: (360, 240), text: \"[B] CERRAR\", action: \"cancel\");\n\n        match action_input {\n            \"pulse\" => {\n                popup_progress += 25;\n                audio.tone(550 + (popup_progress * 5), 40);\n                if (popup_progress >= 100) {\n                    out(\"[GAME-PLUS] ¡Minijuego completado! Evaluando sub-código condicional...\");\n                    try {\n                        looping.eval(popup_code_payload);\n                    } catch (err) {\n                        out($\"[POPUP EVAL ERROR] {err}\");\n                    }\n                    popup_active := false;\n                    return true;\n                }\n            }\n            \"cancel\" => {\n                popup_active := false;\n                return false;\n            }\n            _ => {}\n        }\n        return false;\n    }\n",
    "downloads_count": 0
  },
  {
    "id": "ccb92167-6c00-4899-9790-00171d97cd8a",
    "name": "loop-cpp-snippets",
    "version": "1.0.0",
    "language": "cpp",
    "author_id": null,
    "author_name": "Coki Studios Performance Lab",
    "description": "Essential C++ snippets for Looping & high-performance apps: RAII BenchmarkTimer, RingBuffer, FNV-1a string hashing, ColorRGBA, AABB collisions, and Window helpers.",
    "license": "MIT",
    "entry_point": "cpp_snippets.hpp",
    "dependencies": [],
    "is_verified": true,
    "download_count": 850,
    "repository_url": null,
    "created_at": "2026-10-08T01:12:20.671561+00:00",
    "updated_at": "2026-10-08T01:14:57+00:00",
    "code_payload": "// cpp_snippets.hpp - Coki Studios Looping Snippet Library\n// Essential high-performance C++ snippets for Looping applications and game engines.\n#pragma once\n\n#include <iostream>\n#include <chrono>\n#include <string>\n#include <vector>\n#include <array>\n#include <cmath>\n#include <sstream>\n#include <iomanip>\n#include <functional>\n#include <cstdint>\n#include <algorithm>\n#include <thread>\n\nnamespace looping {\nnamespace snippets {\n\n// ============================================================================\n// 1. BenchmarkTimer: High-resolution RAII stopwatch and profiler\n// ============================================================================\nclass BenchmarkTimer {\npublic:\n    explicit BenchmarkTimer(std::string name = \"Benchmark\", bool auto_print = false)\n        : name_(std::move(name)), auto_print_(auto_print),\n          start_point_(std::chrono::high_resolution_clock::now()) {}\n\n    ~BenchmarkTimer() {\n        if (auto_print_) {\n            double ms = elapsed_ms();\n            std::cout << \"[Timer] \" << name_ << \": \" << ms << \" ms (\" \n                      << elapsed_us() << \" µs)\" << std::endl;\n        }\n    }\n\n    void reset() {\n        start_point_ = std::chrono::high_resolution_clock::now();\n    }\n\n    double elapsed_ms() const {\n        auto end_point = std::chrono::high_resolution_clock::now();\n        return std::chrono::duration<double, std::milli>(end_point - start_point_).count();\n    }\n\n    int64_t elapsed_us() const {\n        auto end_point = std::chrono::high_resolution_clock::now();\n        return std::chrono::duration_cast<std::chrono::microseconds>(end_point - start_point_).count();\n    }\n\n    int64_t elapsed_ns() const {\n        auto end_point = std::chrono::high_resolution_clock::now();\n        return std::chrono::duration_cast<std::chrono::nanoseconds>(end_point - start_point_).count();\n    }\n\nprivate:\n    std::string name_;\n    bool auto_print_;\n    std::chrono::time_point<std::chrono::high_resolution_clock> start_point_;\n};\n\n// ============================================================================\n// 2. RingBuffer: Fixed-capacity circular buffer for frame times & telemetry\n// ============================================================================\ntemplate <typename T, size_t Capacity>\nclass RingBuffer {\npublic:\n    RingBuffer() : head_(0), size_(0) {}\n\n    void push(const T& item) {\n        data_[head_] = item;\n        head_ = (head_ + 1) % Capacity;\n        if (size_ < Capacity) {\n            ++size_;\n        }\n    }\n\n    void clear() {\n        head_ = 0;\n        size_ = 0;\n    }\n\n    size_t size() const { return size_; }\n    constexpr size_t capacity() const { return Capacity; }\n    bool empty() const { return size_ == 0; }\n    bool full() const { return size_ == Capacity; }\n\n    // Access elements from oldest (0) to newest (size - 1)\n    T get(size_t index) const {\n        if (index >= size_) return T{};\n        size_t start = (head_ + Capacity - size_) % Capacity;\n        return data_[(start + index) % Capacity];\n    }\n\n    // Access the latest pushed element\n    T latest() const {\n        if (empty()) return T{};\n        size_t idx = (head_ + Capacity - 1) % Capacity;\n        return data_[idx];\n    }\n\n    // Average value (for numerical types like frametimes)\n    double average() const {\n        if (empty()) return 0.0;\n        double sum = 0.0;\n        for (size_t i = 0; i < size_; ++i) {\n            sum += static_cast<double>(get(i));\n        }\n        return sum / static_cast<double>(size_);\n    }\n\nprivate:\n    std::array<T, Capacity> data_{};\n    size_t head_;\n    size_t size_;\n};\n\n// ============================================================================\n// 3. FNV1a: Compile-time and runtime string hashing for fast switch statements\n// ============================================================================\nstruct FNV1a {\n    static constexpr uint32_t OFFSET_BASIS_32 = 0x811c9dc5;\n    static constexpr uint32_t PRIME_32 = 0x01000193;\n\n    static constexpr uint32_t hash32(const char* str, size_t len) {\n        uint32_t hash = OFFSET_BASIS_32;\n        for (size_t i = 0; i < len; ++i) {\n            hash ^= static_cast<uint8_t>(str[i]);\n            hash *= PRIME_32;\n        }\n        return hash;\n    }\n\n    static constexpr uint32_t hash32(const char* str) {\n        uint32_t hash = OFFSET_BASIS_32;\n        while (*str) {\n            hash ^= static_cast<uint8_t>(*str++);\n            hash *= PRIME_32;\n        }\n        return hash;\n    }\n\n    static inline uint32_t hash32(const std::string& str) {\n        return hash32(str.data(), str.size());\n    }\n};\n\n// User-defined string literal for switch statements: switch(hash32(str)) { case \"click\"_hash: ... }\nconstexpr uint32_t operator\"\"_hash(const char* str, size_t len) {\n    return FNV1a::hash32(str, len);\n}\n\n// ============================================================================\n// 4. ColorRGBA: 32-bit color utilities, hex parsing, and interpolation\n// ============================================================================\nstruct ColorRGBA {\n    uint8_t r{255};\n    uint8_t g{255};\n    uint8_t b{255};\n    uint8_t a{255};\n\n    ColorRGBA() = default;\n    ColorRGBA(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = 255)\n        : r(red), g(green), b(blue), a(alpha) {}\n\n    static ColorRGBA from_hex(const std::string& hex) {\n        std::string h = hex;\n        if (!h.empty() && h[0] == '#') h = h.substr(1);\n        if (h.length() == 6) {\n            uint32_t val = static_cast<uint32_t>(std::stoul(h, nullptr, 16));\n            return ColorRGBA((val >> 16) & 0xFF, (val >> 8) & 0xFF, val & 0xFF, 255);\n        } else if (h.length() == 8) {\n            uint32_t val = static_cast<uint32_t>(std::stoul(h, nullptr, 16));\n            return ColorRGBA((val >> 24) & 0xFF, (val >> 16) & 0xFF, (val >> 8) & 0xFF, val & 0xFF);\n        }\n        return ColorRGBA(255, 255, 255, 255);\n    }\n\n    std::string to_hex(bool include_alpha = false) const {\n        std::ostringstream ss;\n        ss << \"#\" << std::hex << std::setfill('0');\n        ss << std::setw(2) << static_cast<int>(r);\n        ss << std::setw(2) << static_cast<int>(g);\n        ss << std::setw(2) << static_cast<int>(b);\n        if (include_alpha) {\n            ss << std::setw(2) << static_cast<int>(a);\n        }\n        return ss.str();\n    }\n\n    static ColorRGBA lerp(const ColorRGBA& c1, const ColorRGBA& c2, float t) {\n        t = std::max(0.0f, std::min(1.0f, t));\n        auto r = static_cast<uint8_t>(c1.r + (c2.r - c1.r) * t);\n        auto g = static_cast<uint8_t>(c1.g + (c2.g - c1.g) * t);\n        auto b = static_cast<uint8_t>(c1.b + (c2.b - c1.b) * t);\n        auto a = static_cast<uint8_t>(c1.a + (c2.a - c1.a) * t);\n        return ColorRGBA(r, g, b, a);\n    }\n\n    float luminance() const {\n        return (0.299f * r + 0.587f * g + 0.114f * b) / 255.0f;\n    }\n};\n\n// ============================================================================\n// 5. Math & 2D Physics: Vector2, AABB Overlap, and Math Interpolators\n// ============================================================================\ntemplate <typename T>\ninline T clamp(T val, T min_val, T max_val) {\n    return (val < min_val) ? min_val : (val > max_val ? max_val : val);\n}\n\ntemplate <typename T>\ninline T lerp(T a, T b, float t) {\n    return static_cast<T>(a + (b - a) * t);\n}\n\ninline float smoothstep(float edge0, float edge1, float x) {\n    x = clamp((x - edge0) / (edge1 - edge0), 0.0f, 1.0f);\n    return x * x * (3.0f - 2.0f * x);\n}\n\nstruct Vec2 {\n    float x{0.0f};\n    float y{0.0f};\n\n    Vec2() = default;\n    Vec2(float x_, float y_) : x(x_), y(y_) {}\n\n    Vec2 operator+(const Vec2& o) const { return {x + o.x, y + o.y}; }\n    Vec2 operator-(const Vec2& o) const { return {x - o.x, y - o.y}; }\n    Vec2 operator*(float scalar) const { return {x * scalar, y * scalar}; }\n\n    float length() const { return std::sqrt(x * x + y * y); }\n    float length_sq() const { return x * x + y * y; }\n\n    Vec2 normalized() const {\n        float len = length();\n        return (len > 0.00001f) ? Vec2(x / len, y / len) : Vec2(0.0f, 0.0f);\n    }\n\n    static float dot(const Vec2& a, const Vec2& b) {\n        return a.x * b.x + a.y * b.y;\n    }\n};\n\nstruct AABB2D {\n    Vec2 min_pt;\n    Vec2 max_pt;\n\n    bool overlaps(const AABB2D& other) const {\n        return (min_pt.x <= other.max_pt.x && max_pt.x >= other.min_pt.x) &&\n               (min_pt.y <= other.max_pt.y && max_pt.y >= other.min_pt.y);\n    }\n\n    bool contains(const Vec2& pt) const {\n        return (pt.x >= min_pt.x && pt.x <= max_pt.x &&\n                pt.y >= min_pt.y && pt.y <= max_pt.y);\n    }\n};\n\n// ============================================================================\n// 6. String Utilities: Trim, Split, Join, Replace\n// ============================================================================\ninline std::string trim(const std::string& str) {\n    size_t first = str.find_first_not_of(\" \\t\\n\\r\");\n    if (first == std::string::npos) return \"\";\n    size_t last = str.find_last_not_of(\" \\t\\n\\r\");\n    return str.substr(first, (last - first + 1));\n}\n\ninline std::vector<std::string> split(const std::string& str, char delim) {\n    std::vector<std::string> tokens;\n    std::stringstream ss(str);\n    std::string token;\n    while (std::getline(ss, token, delim)) {\n        tokens.push_back(token);\n    }\n    return tokens;\n}\n\ninline std::string join(const std::vector<std::string>& list, const std::string& delim) {\n    std::ostringstream ss;\n    for (size_t i = 0; i < list.size(); ++i) {\n        ss << list[i];\n        if (i + 1 < list.size()) ss << delim;\n    }\n    return ss.str();\n}\n\ninline std::string replace_all(std::string str, const std::string& from, const std::string& to) {\n    size_t start_pos = 0;\n    while ((start_pos = str.find(from, start_pos)) != std::string::npos) {\n        str.replace(start_pos, from.length(), to);\n        start_pos += to.length();\n    }\n    return str;\n}\n\n// ============================================================================\n// 7. Window FrameLimiter: Precise FPS targeting for dynamic windows & loops\n// ============================================================================\nclass FrameLimiter {\npublic:\n    explicit FrameLimiter(int target_fps = 60)\n        : target_fps_(target_fps),\n          frame_duration_us_(target_fps > 0 ? (1000000 / target_fps) : 0),\n          last_frame_time_(std::chrono::high_resolution_clock::now()) {}\n\n    void set_target_fps(int fps) {\n        target_fps_ = fps;\n        frame_duration_us_ = (fps > 0 ? (1000000 / fps) : 0);\n    }\n\n    void wait_next_frame() {\n        if (frame_duration_us_ <= 0) return;\n        auto now = std::chrono::high_resolution_clock::now();\n        auto elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>(now - last_frame_time_).count();\n\n        if (elapsed_us < frame_duration_us_) {\n            auto sleep_us = frame_duration_us_ - elapsed_us;\n            std::this_thread::sleep_for(std::chrono::microseconds(sleep_us));\n        }\n        last_frame_time_ = std::chrono::high_resolution_clock::now();\n    }\n\n    double current_fps() const {\n        auto now = std::chrono::high_resolution_clock::now();\n        auto elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>(now - last_frame_time_).count();\n        if (elapsed_us <= 0) return 0.0;\n        return 1000000.0 / static_cast<double>(elapsed_us);\n    }\n\nprivate:\n    int target_fps_;\n    int64_t frame_duration_us_;\n    std::chrono::time_point<std::chrono::high_resolution_clock> last_frame_time_;\n};\n\n} // namespace snippets\n} // namespace looping\n",
    "downloads_count": 850
  },
  {
    "id": "9ca017d4-fc40-4609-9c26-8fa224f62377",
    "name": "loop-node-window",
    "version": "1.0.0",
    "language": "node",
    "author_id": null,
    "author_name": "Coki Studios Web & Loop Lab",
    "description": "Dynamic HTML5 Window Creator for Node.js and Loop. Launches high-performance glassmorphic UI, Web Audio synthesis, interactive controls, and real-time REST/SSE bridge.",
    "license": "MIT",
    "entry_point": "index.js",
    "dependencies": [],
    "is_verified": true,
    "download_count": 1120,
    "repository_url": null,
    "created_at": "2026-10-08T01:12:36.294196+00:00",
    "updated_at": "2026-10-08T01:15:09+00:00",
    "code_payload": "/**\n * loop-node-window: Dynamic HTML5 Window & 2D Arcade Game Creator for Node.js & Looping Engine\n * Author: Coki Studios Web & Loop Lab\n * Version: 2.0.0 (Quantum 2D Edition)\n * \n * Zero external dependencies. Uses standard Node.js libraries (http, child_process, os, events, readline).\n * Provides an interactive glassmorphic HTML5 window with Web Audio synthesis, real-time SSE metrics,\n * action callbacks, and bidirectional communication for Looping (.loop) and Node.js.\n */\n\nimport http from 'http';\nimport { exec } from 'child_process';\nimport os from 'os';\nimport { EventEmitter } from 'events';\nimport readline from 'readline';\nimport { fileURLToPath } from 'url';\n\nclass DynamicHTMLWindow extends EventEmitter {\n    constructor(options = {}) {\n        super();\n        this.title = options.title || 'Loop Dynamic HTML5 Window';\n        this.port = options.port || 7890;\n        this.width = options.width || 860;\n        this.height = options.height || 580;\n        this.autoOpen = options.autoOpen !== undefined ? options.autoOpen : true;\n        this.soundEnabled = options.soundEnabled !== undefined ? options.soundEnabled : true;\n        \n        this.metrics = Object.assign({\n            'Status': 'Running',\n            'Engine': 'Loop + Node.js',\n            'FPS': 60,\n            'Events': 0\n        }, options.metrics || {});\n\n        this.cards = options.cards || [\n            { id: 'c1', title: 'Looping Runtime Bridge', content: 'Connected bi-directionally via Node.js HTTP/SSE micro-engine.' },\n            { id: 'c2', title: 'Audio & Telemetry', content: 'Web Audio API synthesizer active with real-time UI sonic feedback.' }\n        ];\n\n        this.logs = [];\n        this.clients = new Set();\n        this.server = null;\n        this.actualPort = this.port;\n\n        this.addLog(`[System] DynamicHTMLWindow initialized for \"${this.title}\"`);\n    }\n\n    addLog(msg) {\n        const time = new Date().toLocaleTimeString();\n        const entry = `[${time}] ${msg}`;\n        this.logs.unshift(entry);\n        if (this.logs.length > 100) this.logs.pop();\n        this.broadcast({ type: 'log', data: entry });\n    }\n\n    updateMetric(key, val) {\n        this.metrics[key] = val;\n        this.broadcast({ type: 'metric', key, value: val });\n    }\n\n    addCard(id, title, content) {\n        const existing = this.cards.find(c => c.id === id);\n        if (existing) {\n            existing.title = title;\n            existing.content = content;\n        } else {\n            this.cards.push({ id, title, content });\n        }\n        this.broadcast({ type: 'cards', cards: this.cards });\n    }\n\n    broadcast(payload) {\n        const raw = `data: ${JSON.stringify(payload)}\\n\\n`;\n        for (const client of this.clients) {\n            try {\n                client.write(raw);\n            } catch (err) {\n                this.clients.delete(client);\n            }\n        }\n    }\n\n    start() {\n        return new Promise((resolve, reject) => {\n            this.server = http.createServer((req, res) => {\n                const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);\n\n                // CORS headers\n                res.setHeader('Access-Control-Allow-Origin', '*');\n                res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n                res.setHeader('Access-Control-Allow-Headers', 'Content-Type');\n\n                if (req.method === 'OPTIONS') {\n                    res.writeHead(204);\n                    res.end();\n                    return;\n                }\n\n                // SSE Event Stream\n                if (url.pathname === '/api/events') {\n                    res.writeHead(200, {\n                        'Content-Type': 'text/event-stream',\n                        'Cache-Control': 'no-cache',\n                        'Connection': 'keep-alive'\n                    });\n                    res.write(': connected\\n\\n');\n                    this.clients.add(res);\n\n                    req.on('close', () => {\n                        this.clients.delete(res);\n                    });\n                    return;\n                }\n\n                // API: Get State\n                if (url.pathname === '/api/state' && req.method === 'GET') {\n                    res.writeHead(200, { 'Content-Type': 'application/json' });\n                    res.end(JSON.stringify({\n                        title: this.title,\n                        metrics: this.metrics,\n                        cards: this.cards,\n                        logs: this.logs,\n                        soundEnabled: this.soundEnabled\n                    }));\n                    return;\n                }\n\n                // API: Post Action from client UI\n                if (url.pathname === '/api/action' && req.method === 'POST') {\n                    let body = '';\n                    req.on('data', chunk => body += chunk);\n                    req.on('end', () => {\n                        try {\n                            const data = JSON.parse(body || '{}');\n                            const action = data.action || 'unknown';\n                            this.metrics['Events'] = (this.metrics['Events'] || 0) + 1;\n                            this.updateMetric('Events', this.metrics['Events']);\n                            this.addLog(`[Action Received] ${action} -> ${JSON.stringify(data.payload || {})}`);\n                            this.emit('action', action, data.payload);\n                            res.writeHead(200, { 'Content-Type': 'application/json' });\n                            res.end(JSON.stringify({ success: true, action, events: this.metrics['Events'] }));\n                        } catch (err) {\n                            res.writeHead(400, { 'Content-Type': 'application/json' });\n                            res.end(JSON.stringify({ error: err.message }));\n                        }\n                    });\n                    return;\n                }\n\n                // API: Update State from external callers (Looping / curl / Node)\n                if (url.pathname === '/api/state' && req.method === 'POST') {\n                    let body = '';\n                    req.on('data', chunk => body += chunk);\n                    req.on('end', () => {\n                        try {\n                            const data = JSON.parse(body || '{}');\n                            if (data.metrics) {\n                                for (const [k, v] of Object.entries(data.metrics)) {\n                                    this.updateMetric(k, v);\n                                }\n                            }\n                            if (data.log) this.addLog(data.log);\n                            if (data.title) {\n                                this.title = data.title;\n                                this.broadcast({ type: 'title', title: this.title });\n                            }\n                            res.writeHead(200, { 'Content-Type': 'application/json' });\n                            res.end(JSON.stringify({ success: true }));\n                        } catch (err) {\n                            res.writeHead(400, { 'Content-Type': 'application/json' });\n                            res.end(JSON.stringify({ error: err.message }));\n                        }\n                    });\n                    return;\n                }\n\n                // Serve Main HTML5 UI\n                if (url.pathname === '/' || url.pathname === '/index.html') {\n                    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });\n                    res.end(this.renderHTML());\n                    return;\n                }\n\n                // 404\n                res.writeHead(404, { 'Content-Type': 'text/plain' });\n                res.end('Not found');\n            });\n\n            this.server.on('error', (err) => {\n                if (err.code === 'EADDRINUSE') {\n                    // Try random port\n                    this.server.listen(0);\n                } else {\n                    reject(err);\n                }\n            });\n\n            this.server.listen(this.port, () => {\n                this.actualPort = this.server.address().port;\n                this.addLog(`[Server] Listening on http://localhost:${this.actualPort}`);\n                if (this.autoOpen) {\n                    this.openBrowser(`http://localhost:${this.actualPort}`);\n                }\n                resolve({ port: this.actualPort, url: `http://localhost:${this.actualPort}` });\n            });\n        });\n    }\n\n    openBrowser(url) {\n        const platform = os.platform();\n        let cmd = '';\n        if (platform === 'darwin') {\n            cmd = `open \"${url}\"`;\n        } else if (platform === 'win32') {\n            cmd = `start \"\" \"${url}\"`;\n        } else {\n            cmd = `xdg-open \"${url}\"`;\n        }\n        exec(cmd, (err) => {\n            if (err) this.addLog(`[Browser] Note: open failed (${err.message}), URL is: ${url}`);\n        });\n    }\n\n    stop() {\n        if (this.server) {\n            for (const client of this.clients) {\n                try { client.end(); } catch (e) {}\n            }\n            this.clients.clear();\n            this.server.close();\n            this.server = null;\n        }\n    }\n\n    renderHTML() {\n        return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>${this.title}</title>\n    <link href=\"https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap\" rel=\"stylesheet\">\n    <style>\n        :root {\n            --bg-base: #060913;\n            --bg-card: rgba(15, 23, 42, 0.75);\n            --border: rgba(255, 255, 255, 0.09);\n            --border-hover: rgba(56, 189, 248, 0.4);\n            --text-main: #f8fafc;\n            --text-sub: #94a3b8;\n            --accent-cyan: #38bdf8;\n            --accent-purple: #c084fc;\n            --accent-green: #4ade80;\n            --font-sans: 'Plus Jakarta Sans', system-ui, sans-serif;\n            --font-mono: 'JetBrains Mono', monospace;\n        }\n        * { box-sizing: border-box; margin: 0; padding: 0; }\n        body {\n            background-color: var(--bg-base);\n            color: var(--text-main);\n            font-family: var(--font-sans);\n            min-height: 100vh;\n            display: flex;\n            flex-direction: column;\n            background-image: \n                radial-gradient(circle at 10% 20%, rgba(56, 189, 248, 0.12) 0%, transparent 40%),\n                radial-gradient(circle at 90% 80%, rgba(192, 132, 252, 0.12) 0%, transparent 40%);\n            overflow-x: hidden;\n        }\n        header {\n            padding: 18px 28px;\n            border-bottom: 1px solid var(--border);\n            display: flex;\n            align-items: center;\n            justify-content: space-between;\n            backdrop-filter: blur(16px);\n            background: rgba(6, 9, 19, 0.85);\n            position: sticky;\n            top: 0;\n            z-index: 10;\n        }\n        .brand-group {\n            display: flex;\n            align-items: center;\n            gap: 12px;\n        }\n        .brand-icon {\n            width: 36px;\n            height: 36px;\n            background: linear-gradient(135deg, var(--accent-cyan), var(--accent-purple));\n            border-radius: 10px;\n            display: flex;\n            align-items: center;\n            justify-content: center;\n            font-weight: 800;\n            font-size: 18px;\n            color: #060913;\n            box-shadow: 0 0 15px rgba(56, 189, 248, 0.3);\n        }\n        .header-title {\n            font-size: 18px;\n            font-weight: 700;\n            letter-spacing: -0.02em;\n        }\n        .status-pill {\n            display: inline-flex;\n            align-items: center;\n            gap: 6px;\n            background: rgba(74, 222, 128, 0.15);\n            border: 1px solid rgba(74, 222, 128, 0.3);\n            color: var(--accent-green);\n            padding: 4px 10px;\n            border-radius: 20px;\n            font-size: 11px;\n            font-weight: 600;\n            font-family: var(--font-mono);\n        }\n        .dot-live {\n            width: 6px;\n            height: 6px;\n            border-radius: 50%;\n            background: var(--accent-green);\n            box-shadow: 0 0 8px var(--accent-green);\n            animation: pulse 2s infinite;\n        }\n        @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }\n        main {\n            padding: 28px;\n            max-width: 1100px;\n            width: 100%;\n            margin: 0 auto;\n            flex: 1;\n            display: flex;\n            flex-direction: column;\n            gap: 24px;\n        }\n        .metrics-grid {\n            display: grid;\n            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));\n            gap: 16px;\n        }\n        .metric-card {\n            background: var(--bg-card);\n            border: 1px solid var(--border);\n            border-radius: 12px;\n            padding: 16px 20px;\n            backdrop-filter: blur(12px);\n            transition: all 0.2s ease;\n        }\n        .metric-card:hover {\n            border-color: var(--border-hover);\n            transform: translateY(-2px);\n        }\n        .metric-label {\n            font-size: 12px;\n            color: var(--text-sub);\n            font-weight: 600;\n            text-transform: uppercase;\n            letter-spacing: 0.05em;\n            margin-bottom: 6px;\n        }\n        .metric-value {\n            font-size: 26px;\n            font-weight: 800;\n            color: var(--text-main);\n            font-family: var(--font-mono);\n        }\n        .interactive-section {\n            background: var(--bg-card);\n            border: 1px solid var(--border);\n            border-radius: 14px;\n            padding: 24px;\n            backdrop-filter: blur(12px);\n        }\n        .section-title {\n            font-size: 16px;\n            font-weight: 700;\n            margin-bottom: 16px;\n            display: flex;\n            align-items: center;\n            gap: 8px;\n            color: var(--accent-cyan);\n        }\n        .btn-row {\n            display: flex;\n            flex-wrap: wrap;\n            gap: 12px;\n            margin-bottom: 20px;\n        }\n        .ui-btn {\n            background: rgba(56, 189, 248, 0.12);\n            color: var(--accent-cyan);\n            border: 1px solid rgba(56, 189, 248, 0.3);\n            border-radius: 8px;\n            padding: 10px 18px;\n            font-size: 13px;\n            font-weight: 600;\n            font-family: var(--font-mono);\n            cursor: pointer;\n            transition: all 0.2s;\n            display: inline-flex;\n            align-items: center;\n            gap: 8px;\n        }\n        .ui-btn:hover {\n            background: var(--accent-cyan);\n            color: #060913;\n            transform: translateY(-2px);\n            box-shadow: 0 4px 15px rgba(56, 189, 248, 0.3);\n        }\n        .ui-btn-purple {\n            background: rgba(192, 132, 252, 0.12);\n            color: var(--accent-purple);\n            border: 1px solid rgba(192, 132, 252, 0.3);\n        }\n        .ui-btn-purple:hover {\n            background: var(--accent-purple);\n            color: #060913;\n            box-shadow: 0 4px 15px rgba(192, 132, 252, 0.3);\n        }\n        .canvas-container {\n            width: 100%;\n            height: 120px;\n            background: rgba(6, 9, 19, 0.8);\n            border: 1px solid var(--border);\n            border-radius: 10px;\n            overflow: hidden;\n            position: relative;\n        }\n        canvas {\n            width: 100%;\n            height: 100%;\n            display: block;\n        }\n        .log-terminal {\n            background: #070b14;\n            border: 1px solid var(--border);\n            border-radius: 12px;\n            padding: 16px;\n            font-family: var(--font-mono);\n            font-size: 12px;\n            line-height: 1.6;\n            color: #cbd5e1;\n            height: 180px;\n            overflow-y: auto;\n        }\n        .log-entry { margin-bottom: 4px; }\n        .log-entry.new { animation: fadeIn 0.3s ease; }\n        @keyframes fadeIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }\n        footer {\n            padding: 16px 28px;\n            border-top: 1px solid var(--border);\n            text-align: center;\n            font-size: 12px;\n            color: var(--text-sub);\n        }\n    </style>\n</head>\n<body>\n    <header>\n        <div class=\"brand-group\">\n            <div class=\"brand-icon\">⟳</div>\n            <h1 class=\"header-title\" id=\"win-title\">${this.title}</h1>\n        </div>\n        <div style=\"display: flex; gap: 12px; align-items: center;\">\n            <button id=\"sound-btn\" class=\"ui-btn\" style=\"padding: 4px 12px; font-size: 11px;\" onclick=\"toggleSound()\">🔊 Sound ON</button>\n            <div class=\"status-pill\">\n                <div class=\"dot-live\"></div>\n                <span id=\"conn-status\">CONNECTED :${this.actualPort}</span>\n            </div>\n        </div>\n    </header>\n\n    <main>\n        <div class=\"metrics-grid\" id=\"metrics-grid\">\n            ${Object.entries(this.metrics).map(([k, v]) => `\n                <div class=\"metric-card\" id=\"metric-card-${k}\">\n                    <div class=\"metric-label\">${k}</div>\n                    <div class=\"metric-value\" id=\"val-${k}\">${v}</div>\n                </div>\n            `).join('')}\n        </div>\n\n        <div class=\"interactive-section\">\n            <div class=\"section-title\">⚡ Interactive Controls & Sound Synthesis</div>\n            <div class=\"btn-row\">\n                <button class=\"ui-btn\" onclick=\"sendAction('ping', { msg: 'Looping pulse' })\">\n                    <span>📡</span> Ping Engine\n                </button>\n                <button class=\"ui-btn ui-btn-purple\" onclick=\"sendAction('spawn_object', { entity: 'ParticleEmitter' })\">\n                    <span>✨</span> Spawn Entity\n                </button>\n                <button class=\"ui-btn\" onclick=\"sendAction('bench_test', { iterations: 1000 })\">\n                    <span>⏱️</span> Run Micro-Benchmark\n                </button>\n                <button class=\"ui-btn ui-btn-purple\" onclick=\"clearLogs()\">\n                    <span>🧹</span> Clear Logs\n                </button>\n            </div>\n            <div class=\"canvas-container\">\n                <canvas id=\"viz-canvas\"></canvas>\n            </div>\n        </div>\n\n        <div class=\"interactive-section\">\n            <div class=\"section-title\">📜 Real-Time Event Log & Loop IPC</div>\n            <div class=\"log-terminal\" id=\"terminal\">\n                ${this.logs.map(l => `<div class=\"log-entry\">${l}</div>`).join('')}\n            </div>\n        </div>\n    </main>\n\n    <footer>\n        Looping Engine • loop-node-window v1.0.0 • Coki Studios Web & Loop Lab\n    </footer>\n\n    <script>\n        let soundEnabled = true;\n        let audioCtx = null;\n\n        function getAudioContext() {\n            if (!audioCtx) {\n                audioCtx = new (window.AudioContext || window.webkitAudioContext)();\n            }\n            if (audioCtx.state === 'suspended') {\n                audioCtx.resume();\n            }\n            return audioCtx;\n        }\n\n        function playTone(freq, type = 'sine', duration = 0.1) {\n            if (!soundEnabled) return;\n            try {\n                const ctx = getAudioContext();\n                const osc = ctx.createOscillator();\n                const gain = ctx.createGain();\n                osc.type = type;\n                osc.frequency.setValueAtTime(freq, ctx.currentTime);\n                gain.gain.setValueAtTime(0.12, ctx.currentTime);\n                gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + duration);\n                osc.connect(gain);\n                gain.connect(ctx.destination);\n                osc.start();\n                osc.stop(ctx.currentTime + duration);\n            } catch(e) {}\n        }\n\n        function toggleSound() {\n            soundEnabled = !soundEnabled;\n            const btn = document.getElementById('sound-btn');\n            btn.textContent = soundEnabled ? '🔊 Sound ON' : '🔇 Sound OFF';\n            if (soundEnabled) playTone(440, 'sine', 0.15);\n        }\n\n        function sendAction(action, payload = {}) {\n            playTone(587.33, 'triangle', 0.12);\n            fetch('/api/action', {\n                method: 'POST',\n                headers: { 'Content-Type': 'application/json' },\n                body: JSON.stringify({ action, payload })\n            }).then(r => r.json()).catch(err => {\n                console.error('Action error:', err);\n            });\n        }\n\n        function clearLogs() {\n            document.getElementById('terminal').innerHTML = '<div class=\"log-entry\">[Cleared] Terminal reset.</div>';\n            playTone(330, 'sine', 0.08);\n        }\n\n        // Real-time SSE Connection\n        const evtSource = new EventSource('/api/events');\n        evtSource.onmessage = (e) => {\n            try {\n                const msg = JSON.parse(e.data);\n                if (msg.type === 'metric') {\n                    let el = document.getElementById('val-' + msg.key);\n                    if (!el) {\n                        const grid = document.getElementById('metrics-grid');\n                        const card = document.createElement('div');\n                        card.className = 'metric-card';\n                        card.id = 'metric-card-' + msg.key;\n                        card.innerHTML = '<div class=\"metric-label\">' + msg.key + '</div><div class=\"metric-value\" id=\"val-' + msg.key + '\">' + msg.value + '</div>';\n                        grid.appendChild(card);\n                    } else {\n                        el.textContent = msg.value;\n                    }\n                } else if (msg.type === 'log') {\n                    const term = document.getElementById('terminal');\n                    const div = document.createElement('div');\n                    div.className = 'log-entry new';\n                    div.textContent = msg.data;\n                    term.insertBefore(div, term.firstChild);\n                } else if (msg.type === 'title') {\n                    document.getElementById('win-title').textContent = msg.title;\n                    document.title = msg.title;\n                }\n            } catch (err) {}\n        };\n\n        evtSource.onerror = () => {\n            document.getElementById('conn-status').textContent = 'RECONNECTING...';\n        };\n\n        evtSource.onopen = () => {\n            document.getElementById('conn-status').textContent = 'CONNECTED :' + location.port;\n        };\n\n        // Canvas Visualizer\n        const canvas = document.getElementById('viz-canvas');\n        const ctx = canvas.getContext('2d');\n        function resizeCanvas() {\n            canvas.width = canvas.parentElement.clientWidth;\n            canvas.height = canvas.parentElement.clientHeight;\n        }\n        window.addEventListener('resize', resizeCanvas);\n        resizeCanvas();\n\n        let phase = 0;\n        function renderLoop() {\n            ctx.clearRect(0, 0, canvas.width, canvas.height);\n            phase += 0.03;\n            \n            // Draw background glow wave\n            ctx.beginPath();\n            ctx.moveTo(0, canvas.height / 2);\n            for (let x = 0; x < canvas.width; x += 5) {\n                const y = canvas.height / 2 + Math.sin(x * 0.015 + phase) * 20 + Math.cos(x * 0.03 - phase) * 10;\n                ctx.lineTo(x, y);\n            }\n            ctx.strokeStyle = 'rgba(56, 189, 248, 0.4)';\n            ctx.lineWidth = 2;\n            ctx.stroke();\n\n            // Draw purple harmonic wave\n            ctx.beginPath();\n            ctx.moveTo(0, canvas.height / 2);\n            for (let x = 0; x < canvas.width; x += 5) {\n                const y = canvas.height / 2 + Math.cos(x * 0.02 + phase * 1.5) * 15;\n                ctx.lineTo(x, y);\n            }\n            ctx.strokeStyle = 'rgba(192, 132, 252, 0.35)';\n            ctx.lineWidth = 1.5;\n            ctx.stroke();\n\n            requestAnimationFrame(renderLoop);\n        }\n        requestAnimationFrame(renderLoop);\n    </script>\n</body>\n</html>`;\n    }\n}\n\n// Helper factory function\nfunction createWindow(options = {}) {\n    const win = new DynamicHTMLWindow(options);\n    win.start();\n    return win;\n}\n\n// CLI / Stdin execution\nconst isMain = process.argv[1] && (\n    process.argv[1].endsWith('loop-node-window/index.js') || \n    process.argv[1].endsWith('loop-node-window') ||\n    (typeof import.meta !== 'undefined' && import.meta.url && fileURLToPath(import.meta.url) === process.argv[1])\n);\n\nif (isMain) {\n    const args = process.argv.slice(2);\n    let title = 'Looping HTML5 Window';\n    let port = 7890;\n    let autoOpen = true;\n\n    for (let i = 0; i < args.length; ++i) {\n        if (args[i] === '--title' && args[i + 1]) title = args[++i];\n        if (args[i] === '--port' && args[i + 1]) port = parseInt(args[++i], 10);\n        if (args[i] === '--no-open') autoOpen = false;\n    }\n\n    const win = new DynamicHTMLWindow({ title, port, autoOpen });\n    win.start().then(({ port, url }) => {\n        console.log(`[loop-node-window] Window active on ${url}`);\n        console.log(`[loop-node-window] Awaiting commands from stdin (format: JSON or \"METRIC <key> <val>\" or \"LOG <text>\")...`);\n\n        const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });\n        rl.on('line', (line) => {\n            line = line.trim();\n            if (!line) return;\n            if (line.startsWith('{') && line.endsWith('}')) {\n                try {\n                    const data = JSON.parse(line);\n                    if (data.metric && data.value !== undefined) win.updateMetric(data.metric, data.value);\n                    if (data.log) win.addLog(data.log);\n                    if (data.title) win.title = data.title;\n                } catch(e) {}\n            } else if (line.startsWith('METRIC ')) {\n                const parts = line.slice(7).split(' ');\n                if (parts.length >= 2) win.updateMetric(parts[0], parts.slice(1).join(' '));\n            } else if (line.startsWith('LOG ')) {\n                win.addLog(line.slice(4));\n            }\n        });\n    });\n\n    win.on('action', (action, payload) => {\n        console.log(JSON.stringify({ event: 'action', action, payload }));\n    });\n}\n\nexport { DynamicHTMLWindow, createWindow };\nexport default DynamicHTMLWindow;\n",
    "downloads_count": 1120
  },
  {
    "id": "a9f3405b-1e21-42db-aeea-67941a7c69ad",
    "name": "pyloop-crypto",
    "version": "1.3.0",
    "language": "python",
    "author_id": null,
    "author_name": "Coki Studios Security Team",
    "description": "Hardware-backed cryptographic primitives for CSMS and Looping: SHA-256, HMAC, PBKDF2, AES-GCM simulation, and Secure Enclave key derivation.",
    "license": "MIT",
    "entry_point": "pyloop_crypto.py",
    "dependencies": [],
    "is_verified": true,
    "download_count": 880,
    "repository_url": null,
    "created_at": "2026-10-07T01:22:33.340328+00:00",
    "updated_at": "2026-10-27T18:00:00+00:00",
    "code_payload": "# pyloop-crypto: Cryptographic Primitives for Looping\nimport hashlib, hmac, base64, secrets\n\nclass LoopCrypto:\n    @staticmethod\n    def sha256(text):\n        return hashlib.sha256(text.encode(\"utf-8\")).hexdigest()\n\n    @staticmethod\n    def hmac_sha256(key, message):\n        return hmac.new(key.encode(\"utf-8\"), message.encode(\"utf-8\"), hashlib.sha256).hexdigest()\n\n    @staticmethod\n    def random_token(bytes_len=24):\n        return secrets.token_urlsafe(bytes_len)\n\n    @staticmethod\n    def base64_encode(data_str):\n        return base64.b64encode(data_str.encode(\"utf-8\")).decode(\"ascii\")\n\n    @staticmethod\n    def base64_decode(b64_str):\n        return base64.b64decode(b64_str.encode(\"ascii\")).decode(\"utf-8\")\n\ndef init_module(vars_dict=None):\n    return LoopCrypto()\n",
    "downloads_count": 880
  },
  {
    "name": "mi-test-pkg",
    "version": "1.0.0",
    "language": "loop",
    "author_name": "Coki Developer",
    "description": "Module mi-test-pkg created with smiledev.",
    "license": "MIT",
    "entry_point": "main.loop",
    "downloads_count": 310,
    "is_verified": false,
    "code_payload": "define module \"mi-test-pkg\" version 1.0:\n    fn hello() => \"Hello from Looping module mi-test-pkg\"\n"
  },
  {
    "name": "loopize++",
    "version": "1.0.0",
    "language": "cpp",
    "author_name": "Coki Studios & Holo Entertainment",
    "description": "High-performance 2D/3D Game Additions Kit for Looping: Wavefront .obj mesh pipeline, C# MonoBehaviour game scripts, ECS registry, Wave Director, Spring-Arm Camera + Shake, FSM, Combos, Tweening, Quests & Web Loopize Kit.",
    "license": "MIT",
    "entry_point": "loopize.loop",
    "downloads_count": 1680,
    "is_verified": true,
    "code_payload": "// modules/loopize++/loopize.loop — Hybrid 3D .obj + C# + Game Additions\nuse \"loop-math-3d\"\nuse \"loop-game-plus\"\n\nlet LOOPIZE_VERSION := \"1.0.0\"\n\nfn lz_banner(title) {\n    print(\"⚡ [loopize++ v\" + LOOPIZE_VERSION + \"] Game Additions Engine Ready -> \" + title)\n}\n"
  },
  {
    "name": "web-loopize-kit",
    "version": "1.0.0",
    "language": "javascript",
    "author_name": "Coki Studios Web & Engine Team",
    "description": "Zero-dependency browser SDK & Web Components (<loopize-stage>, <loopize-obj-viewer>) for interactive Wavefront .obj models, C# MonoBehaviour scripts and loopize++ 3D arenas.",
    "license": "MIT",
    "entry_point": "web-loopize-kit.js",
    "downloads_count": 1120,
    "is_verified": true,
    "code_payload": "// @cokistudios/web-loopize-kit (v1.0.0)\n// Usage: <script type=\"module\" src=\"https://cokistudios.com/web-loopize-kit.js\"></script>\nexport { createStage, PRESETS, BUILTIN_OBJ_MODELS, parseWavefrontOBJ } from \"https://cokistudios.com/web-loopize-kit.js\";\n"
  }
]