preact-missing-hooks 4.0.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Readme.md CHANGED
@@ -34,6 +34,7 @@ A lightweight, extendable collection of React-like hooks for Preact, including u
34
34
  - **`useWebRTCIP`** — Detects client IP addresses using WebRTC ICE candidates and a STUN server (frontend-only). **Not highly reliable**; use as a first-priority hint and fall back to a public IP API (e.g. [ipapi.co](https://ipapi.co), [ipify](https://www.ipify.org), [ip-api.com](https://ip-api.com)) when it fails or returns empty.
35
35
  - **`useWasmCompute`** — Runs WebAssembly computation off the main thread via a Web Worker. Validates environment (browser, Worker, WebAssembly) and returns `compute(input)`, `result`, `loading`, `error`, `ready`.
36
36
  - **`useWorkerNotifications`** — Listens to a Worker's messages and maintains state: running tasks, completed/failed counts, event history, average task duration, throughput per second, and queue size. Worker posts `task_start` / `task_end` / `task_fail` / `queue_size`; returns `progress` (default view of all active worker data) plus individual stats.
37
+ - **`useLLMMetadata`** — Injects an AI-readable metadata block into the document head on route change. Works in React 18+ and Preact 10+. Supports **manual** (title, description, tags) and **auto-extract** (from `document.title`, visible `h1`/`h2`, first 3 `p`). Cacheable, SSR-safe, no router dependency.
37
38
  - Fully TypeScript compatible
38
39
  - Bundled with Microbundle
39
40
  - Zero dependencies (peer: `preact` or `react` — use `/react` for React)
@@ -75,7 +76,77 @@ import { useThreadedWorker, useClipboard } from "preact-missing-hooks";
75
76
  import { useWorkerNotifications } from "preact-missing-hooks/useWorkerNotifications";
76
77
  ```
77
78
 
78
- All hooks are available: `useTransition`, `useMutationObserver`, `useEventBus`, `useWrappedChildren`, `usePreferredTheme`, `useNetworkState`, `useClipboard`, `useRageClick`, `useThreadedWorker`, `useIndexedDB`, `useWebRTCIP`, `useWasmCompute`, `useWorkerNotifications`.
79
+ All hooks are available: `useTransition`, `useMutationObserver`, `useEventBus`, `useWrappedChildren`, `usePreferredTheme`, `useNetworkState`, `useClipboard`, `useRageClick`, `useThreadedWorker`, `useIndexedDB`, `useWebRTCIP`, `useWasmCompute`, `useWorkerNotifications`, `useLLMMetadata`.
80
+
81
+ ---
82
+
83
+ ## Quick start
84
+
85
+ Minimal example (Preact or React):
86
+
87
+ ```tsx
88
+ import {
89
+ useTransition,
90
+ useClipboard,
91
+ usePreferredTheme,
92
+ } from "preact-missing-hooks";
93
+
94
+ function App() {
95
+ const [startTransition, isPending] = useTransition();
96
+ const { copy, copied } = useClipboard();
97
+ const theme = usePreferredTheme();
98
+
99
+ return (
100
+ <div>
101
+ <button
102
+ onClick={() =>
103
+ startTransition(() => {
104
+ /* heavy update */
105
+ })
106
+ }
107
+ disabled={isPending}
108
+ >
109
+ {isPending ? "Loading…" : "Update"}
110
+ </button>
111
+ <button onClick={() => copy("Hello!")}>
112
+ {copied ? "Copied!" : "Copy"}
113
+ </button>
114
+ <span>Theme: {theme}</span>
115
+ </div>
116
+ );
117
+ }
118
+ ```
119
+
120
+ **Live demo:** Try every hook with live examples:
121
+
122
+ - **Online:** [preact-missing-hooks.vercel.app](https://preact-missing-hooks.vercel.app/)
123
+ - **Local:** Run the docs demo:
124
+
125
+ ```bash
126
+ npm run build && npx serve -l 5000
127
+ # Open http://localhost:5000/docs/
128
+ ```
129
+
130
+ Or open `docs/index.html` after building (see [docs/README.md](docs/README.md) for details).
131
+
132
+ **Usage at a glance:**
133
+
134
+ | Hook | One-liner |
135
+ | ------------------------------------------------- | --------------------------------------------------------------------------------- |
136
+ | [useTransition](#usetransition) | `const [startTransition, isPending] = useTransition();` |
137
+ | [useMutationObserver](#usemutationobserver) | `useMutationObserver(ref, callback, { childList: true });` |
138
+ | [useEventBus](#useeventbus) | `const { emit, on } = useEventBus();` |
139
+ | [useWrappedChildren](#usewrappedchildren) | `const wrapped = useWrappedChildren(children, { className: 'x' });` |
140
+ | [usePreferredTheme](#usepreferredtheme) | `const theme = usePreferredTheme(); // 'light' \| 'dark' \| 'no-preference'` |
141
+ | [useNetworkState](#usenetworkstate) | `const { online, effectiveType } = useNetworkState();` |
142
+ | [useClipboard](#useclipboard) | `const { copy, paste, copied } = useClipboard();` |
143
+ | [useRageClick](#userageclick) | `useRageClick(ref, { onRageClick, threshold: 5 });` |
144
+ | [useThreadedWorker](#usethreadedworker) | `const { run, loading, result } = useThreadedWorker(fn, { mode: 'sequential' });` |
145
+ | [useIndexedDB](#useindexeddb) | `const { db, isReady } = useIndexedDB({ name, version, tables });` |
146
+ | [useWebRTCIP](#usewebrtcip) | `const { ips, loading, error } = useWebRTCIP({ timeout: 3000 });` |
147
+ | [useWasmCompute](#usewasmcompute) | `const { compute, result, ready } = useWasmCompute({ wasmUrl });` |
148
+ | [useWorkerNotifications](#useworkernotifications) | `const { progress, eventHistory } = useWorkerNotifications(worker);` |
149
+ | [useLLMMetadata](#usellmmetadata) | `useLLMMetadata({ route: pathname, mode: 'auto-extract' });` |
79
150
 
80
151
  ---
81
152
 
@@ -502,6 +573,121 @@ function WorkerDashboard({ worker }) {
502
573
 
503
574
  ---
504
575
 
576
+ ### `useLLMMetadata`
577
+
578
+ Injects an AI-readable metadata block into the document head when the route changes. Works in **React 18+** and **Preact 10+** (framework-agnostic). No router dependency — you pass the current `route` string and the hook updates the script when it changes.
579
+
580
+ **Safe usage:** The hook **never throws**. It accepts `config` or `null`/`undefined`. When `config` is `null` or `undefined`, it injects a minimal payload with `route: "/"` and `generatedAt`. Invalid or missing values are normalized; all strings are length-limited and URLs validated; DOM access is wrapped in try/catch. Safe for SSR (no-op when `window` is undefined).
581
+
582
+ **API:**
583
+
584
+ ```ts
585
+ type OGType =
586
+ | "website"
587
+ | "article"
588
+ | "profile"
589
+ | "video.other"
590
+ | "product"
591
+ | "music.song"
592
+ | "book";
593
+
594
+ interface LLMConfig {
595
+ route: string;
596
+ mode?: "manual" | "auto-extract";
597
+ title?: string;
598
+ description?: string;
599
+ tags?: string[];
600
+ canonicalUrl?: string; // absolute URL
601
+ language?: string; // e.g. "en", "en-US"
602
+ ogType?: OGType; // Open Graph type
603
+ ogImage?: string; // absolute image URL
604
+ ogImageAlt?: string;
605
+ siteName?: string;
606
+ author?: string;
607
+ publishedTime?: string; // ISO date
608
+ modifiedTime?: string; // ISO date
609
+ robots?: string; // e.g. "index, follow"
610
+ extra?: Record<string, string | number | boolean | string[]>;
611
+ }
612
+
613
+ function useLLMMetadata(config: LLMConfig | null | undefined): void;
614
+ ```
615
+
616
+ **Behavior:**
617
+
618
+ - When `config` is `null` or `undefined`: injects a minimal payload with `route: "/"` and `generatedAt` (no throw).
619
+ - When `config.route` (or other deps) change: removes any existing `<script data-llm="true">`, then injects a new one.
620
+ - Script tag: `<script type="application/llm+json" data-llm="true">` with JSON payload. Only defined, safe fields are included.
621
+ - **Cacheable:** If the generated payload is unchanged, the script is not replaced.
622
+ - **SSR-safe:** No-op when `typeof window === "undefined"`.
623
+ - Cleans up on unmount (removes the script).
624
+
625
+ **Modes:**
626
+
627
+ - **`manual`** (default): Uses `title`, `description`, `tags`, and any other config fields you pass.
628
+ - **`auto-extract`**: Fills `title`, `description`, and `outline` from the DOM (`document.title`, visible `<h1>`/`<h2>`, first 3 visible `<p>`). You can still override with config. Ignores content inside `nav`, `footer`, `script`, `style`.
629
+
630
+ **Example payload (rich):**
631
+
632
+ ```json
633
+ {
634
+ "route": "/blog/ai-hooks",
635
+ "title": "AI Hooks in Preact",
636
+ "description": "A short summary...",
637
+ "tags": ["preact", "react", "hooks"],
638
+ "outline": ["Intro", "Problem", "Solution"],
639
+ "canonicalUrl": "https://example.com/blog/ai-hooks",
640
+ "language": "en",
641
+ "ogType": "article",
642
+ "ogImage": "https://example.com/og.png",
643
+ "siteName": "My Blog",
644
+ "author": "Jane Doe",
645
+ "publishedTime": "2025-02-14T10:00:00.000Z",
646
+ "modifiedTime": "2025-02-14T12:00:00.000Z",
647
+ "robots": "index, follow",
648
+ "generatedAt": "2025-02-14T12:00:00.000Z"
649
+ }
650
+ ```
651
+
652
+ **Example: React Router**
653
+
654
+ ```tsx
655
+ import { useLocation } from "react-router-dom";
656
+ import { useLLMMetadata } from "preact-missing-hooks"; // or "preact-missing-hooks/react"
657
+
658
+ function App() {
659
+ const { pathname } = useLocation();
660
+ useLLMMetadata({
661
+ route: pathname,
662
+ mode: "auto-extract",
663
+ title: document.title,
664
+ tags: ["my-app"],
665
+ });
666
+ return <Outlet />;
667
+ }
668
+ ```
669
+
670
+ **Example: Preact Router**
671
+
672
+ ```tsx
673
+ import { useLocation } from "preact-router";
674
+ import { useLLMMetadata } from "preact-missing-hooks";
675
+
676
+ function App() {
677
+ const [pathname] = useLocation();
678
+ useLLMMetadata({
679
+ route: pathname ?? "/",
680
+ mode: "manual",
681
+ title: "My Page",
682
+ description: "Page description",
683
+ tags: ["preact", "hooks"],
684
+ });
685
+ return <div>{/* your routes / children */}</div>;
686
+ }
687
+ ```
688
+
689
+ ---
690
+
505
691
  ## Built With
506
692
 
507
693
  - [Preact](https://preactjs.com)
package/dist/index.d.ts CHANGED
@@ -11,3 +11,4 @@ export * from "./useIndexedDB";
11
11
  export * from "./useWebRTCIP";
12
12
  export * from "./useWasmCompute";
13
13
  export * from "./useWorkerNotifications";
14
+ export * from "./useLLMMetadata";
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var e=require("preact/hooks"),n=require("preact"),r=new Map;function t(e,n){(null==n||n>e.length)&&(n=e.length);for(var r=0,t=Array(n);r<n;r++)t[r]=e[r];return t}function o(e,n){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,n){if(e){if("string"==typeof e)return t(e,n);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){r&&(e=r);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function u(){return u=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var r=arguments[n];for(var t in r)({}).hasOwnProperty.call(r,t)&&(e[t]=r[t])}return e},u.apply(null,arguments)}function i(){if("undefined"==typeof navigator)return{online:!0};var e={online:navigator.onLine},n=navigator.connection;return n&&(void 0!==n.effectiveType&&(e.effectiveType=n.effectiveType),void 0!==n.downlink&&(e.downlink=n.downlink),void 0!==n.rtt&&(e.rtt=n.rtt),void 0!==n.saveData&&(e.saveData=n.saveData),void 0!==n.type&&(e.connectionType=n.type)),e}function a(e,n){try{var r=e()}catch(e){return n(e)}return r&&r.then?r.then(void 0,n):r}var c=new Map;function s(e){return new Promise(function(n,r){e.onsuccess=function(){return n(e.result)},e.onerror=function(){var n;return r(null!=(n=e.error)?n:new DOMException("Unknown IndexedDB error"))}})}function f(e,n){return n?e.then(function(e){return null==n.onSuccess||n.onSuccess(e),e}).catch(function(e){throw null==n.onError||n.onError(e),e}):e}var l=/\b(?:25[0-5]|2[0-4]\d|1?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|1?\d{1,2})){3}\b/g,d=["stun:stun.l.google.com:19302"];exports.useClipboard=function(n){void 0===n&&(n={});var r=n.resetDelay,t=void 0===r?2e3:r,o=e.useState(!1),u=o[0],i=o[1],c=e.useState(null),s=c[0],f=c[1],l=e.useCallback(function(){i(!1),f(null)},[]);return{copy:e.useCallback(function(e){try{if(f(null),"undefined"==typeof navigator||!navigator.clipboard){var n=new Error("Clipboard API is not available");return f(n),Promise.resolve(!1)}return Promise.resolve(a(function(){return Promise.resolve(navigator.clipboard.writeText(e)).then(function(){return i(!0),t>0&&setTimeout(function(){return i(!1)},t),!0})},function(e){var n=e instanceof Error?e:new Error(String(e));return f(n),!1}))}catch(e){return Promise.reject(e)}},[t]),paste:e.useCallback(function(){try{if(f(null),"undefined"==typeof navigator||!navigator.clipboard){var e=new Error("Clipboard API is not available");return f(e),Promise.resolve("")}return Promise.resolve(a(function(){return Promise.resolve(navigator.clipboard.readText())},function(e){var n=e instanceof Error?e:new Error(String(e));return f(n),""}))}catch(e){return Promise.reject(e)}},[]),copied:u,error:s,reset:l}},exports.useEventBus=function(){return{emit:e.useCallback(function(e){var n=arguments,t=r.get(e);t&&t.forEach(function(e){return e.apply(void 0,[].slice.call(n,1))})},[]),on:e.useCallback(function(e,n){var t=r.get(e);return t||(t=new Set,r.set(e,t)),t.add(n),function(){t.delete(n),0===t.size&&r.delete(e)}},[])}},exports.useIndexedDB=function(n){var r=e.useState(null),t=r[0],i=r[1],a=e.useState(null),l=a[0],d=a[1],v=e.useState(!1),p=v[0],m=v[1],h=e.useRef(n);return h.current=n,e.useEffect(function(){var e=!1;d(null),m(!1),i(null);var n=h.current;return function(e){var n=e.name+"_v"+e.version,r=c.get(n);return r||(r=function(e){return new Promise(function(n,r){var t=indexedDB.open(e.name,e.version);t.onerror=function(){var e;return r(null!=(e=t.error)?e:new DOMException("Failed to open database"))},t.onsuccess=function(){return n(t.result)},t.onupgradeneeded=function(n){for(var r=n.target.result,t=e.tables,u=0,i=Object.keys(t);u<i.length;u++){var a=i[u],c=t[a];if(!r.objectStoreNames.contains(a)){var s,f=r.createObjectStore(a,{keyPath:c.keyPath,autoIncrement:null!=(s=c.autoIncrement)&&s});if(c.indexes)for(var l,d=o(c.indexes);!(l=d()).done;){var v=l.value;f.createIndex(v,v,{unique:!1})}}}}})}(e),c.set(n,r),r)}({name:n.name,version:n.version,tables:n.tables}).then(function(n){if(e)n.close();else{var r=function(e){return{get db(){return e},hasTable:function(n){return e.objectStoreNames.contains(n)},table:function(n){return function(e,n){return function(e,n){function r(r){return e.transaction([n],r).objectStore(n)}return{insert:function(e,n){return f(s(r("readwrite").add(e)),n)},update:function(e,n,t){var o=r("readwrite");return f(s(o.get(e)).then(function(e){if(void 0===e)throw new DOMException("Key not found","NotFoundError");var r=u({},e,n);return s(o.put(r))}).then(function(){}),t)},delete:function(e,n){return f(s(r("readwrite").delete(e)).then(function(){}),n)},exists:function(e){return s(r("readonly").getKey(e)).then(function(e){return void 0!==e})},query:function(e,n){var t=r("readonly").openCursor(),o=[];return f(new Promise(function(n,r){t.onsuccess=function(){var r=t.result;r?(e(r.value)&&o.push(r.value),r.continue()):n(o)},t.onerror=function(){var e;return r(null!=(e=t.error)?e:new DOMException("Unknown error"))}}),n)},upsert:function(e,n){return f(s(r("readwrite").put(e)),n)},bulkInsert:function(e,n){var t=r("readwrite"),o=[];if(0===e.length)return f(Promise.resolve(o),n);var u=0;return f(new Promise(function(n,r){e.forEach(function(i,a){var c=t.add(i);c.onsuccess=function(){o[a]=c.result,++u===e.length&&n(o)},c.onerror=function(){var e;return r(null!=(e=c.error)?e:new DOMException("Unknown error"))}})}),n)},clear:function(e){return f(s(r("readwrite").clear()).then(function(){}),e)},count:function(e){return f(s(r("readonly").count()),null!=e?e:{})}}}(e,n)}(e,n)},transaction:function(n,r,t,o){var i=e.transaction(n,r),a={table:function(e){return function(e,n){return function(e,n){function r(){return e.objectStore(n)}return{insert:function(e,n){return f(s(r().add(e)),n)},update:function(e,n,t){var o=r();return f(s(o.get(e)).then(function(e){if(void 0===e)throw new DOMException("Key not found","NotFoundError");var r=u({},e,n);return s(o.put(r))}).then(function(){}),t)},delete:function(e,n){return f(s(r().delete(e)).then(function(){}),n)},exists:function(e){return s(r().getKey(e)).then(function(e){return void 0!==e})},query:function(e,n){var t=r().openCursor(),o=[];return f(new Promise(function(n,r){t.onsuccess=function(){var r=t.result;r?(e(r.value)&&o.push(r.value),r.continue()):n(o)},t.onerror=function(){var e;return r(null!=(e=t.error)?e:new DOMException("Unknown error"))}}),n)},upsert:function(e,n){return f(s(r().put(e)),n)},bulkInsert:function(e,n){var t=r(),o=[];if(0===e.length)return f(Promise.resolve(o),n);var u=0;return f(new Promise(function(n,r){e.forEach(function(i,a){var c=t.add(i);c.onsuccess=function(){o[a]=c.result,++u===e.length&&n(o)},c.onerror=function(){var e;return r(null!=(e=c.error)?e:new DOMException("Unknown error"))}})}),n)},clear:function(e){return f(s(r().clear()).then(function(){}),e)},count:function(e){return f(s(r().count()),null!=e?e:{})}}}(e,n)}(i,e)}},c=new Promise(function(e,n){i.oncomplete=function(){return e()},i.onerror=function(){var e;return n(null!=(e=i.error)?e:new DOMException("Transaction failed"))}}),l=t(a);return function(e,n){return n?e.then(function(){return null==n.onSuccess?void 0:n.onSuccess()}).catch(function(e){throw null==n.onError||n.onError(e),e}):e}(Promise.resolve(l).then(function(){return c}),o)}}}(n);i(r),m(!0)}}).catch(function(n){e||d(n)}),function(){e=!0}},[n.name,n.version]),{db:t,isReady:p,error:l}},exports.useMutationObserver=function(n,r,t){e.useEffect(function(){var e=n.current;if(e){var o=new MutationObserver(r);return o.observe(e,t),function(){return o.disconnect()}}},[n,r,t])},exports.useNetworkState=function(){var n=e.useState(i),r=n[0],t=n[1];return e.useEffect(function(){if("undefined"!=typeof window){var e=function(){return t(i())};window.addEventListener("online",e),window.addEventListener("offline",e);var n=navigator.connection;return null!=n&&n.addEventListener&&n.addEventListener("change",e),function(){window.removeEventListener("online",e),window.removeEventListener("offline",e),null!=n&&n.removeEventListener&&n.removeEventListener("change",e)}}},[]),r},exports.usePreferredTheme=function(){var n=e.useState(function(){if("undefined"==typeof window)return"no-preference";var e=window.matchMedia("(prefers-color-scheme: dark)"),n=window.matchMedia("(prefers-color-scheme: light)");return e.matches?"dark":n.matches?"light":"no-preference"}),r=n[0],t=n[1];return e.useEffect(function(){if("undefined"!=typeof window){var e=window.matchMedia("(prefers-color-scheme: dark)"),n=function(e){t(e.matches?"dark":"light")},r=function(){var e=window.matchMedia("(prefers-color-scheme: dark)"),n=window.matchMedia("(prefers-color-scheme: light)");t(e.matches?"dark":n.matches?"light":"no-preference")};e.addEventListener("change",n);var o=window.matchMedia("(prefers-color-scheme: light)");return o.addEventListener("change",r),function(){e.removeEventListener("change",n),o.removeEventListener("change",r)}}},[]),r},exports.useRageClick=function(n,r){var t=r.onRageClick,o=r.threshold,u=void 0===o?5:o,i=r.timeWindow,a=void 0===i?1e3:i,c=r.distanceThreshold,s=void 0===c?30:c,f=e.useRef(t);f.current=t;var l=e.useRef([]);e.useEffect(function(){var e=n.current;if(e){var r=function(e){var n=Date.now(),r={time:n,x:e.clientX,y:e.clientY},t=n-a,o=l.current.filter(function(e){return e.time>=t});if(o.push(r),Infinity!==s){var i=o.filter(function(e){return n=e,t=r,Math.hypot(t.x-n.x,t.y-n.y)<=s;var n,t});if(i.length>=u)return f.current({count:i.length,event:e}),void(l.current=[])}else if(o.length>=u)return f.current({count:o.length,event:e}),void(l.current=[]);l.current=o};return e.addEventListener("click",r),function(){return e.removeEventListener("click",r)}}},[n,u,a,s])},exports.useThreadedWorker=function(n,r){var t=r.concurrency,o="sequential"===r.mode?1:Math.max(1,void 0===t?4:t),u=e.useState(!1),i=u[0],a=u[1],c=e.useState(void 0),s=c[0],f=c[1],l=e.useState(void 0),d=l[0],v=l[1],p=e.useState(0),m=p[0],h=p[1],y=e.useRef([]),w=e.useRef(0),g=e.useRef(0),b=e.useRef(!1),k=e.useRef(n);k.current=n;var E=e.useCallback(function(){h(y.current.length+g.current)},[]),S=e.useCallback(function(){if(!(b.current||g.current>=o)){if(0===y.current.length)return 0===g.current&&a(!1),void E();y.current.sort(function(e,n){return e.priority!==n.priority?e.priority-n.priority:e.sequence-n.sequence});var e=y.current.shift();g.current+=1,a(!0),E(),(0,k.current)(e.data).then(function(n){f(n),v(void 0),e.resolve(n)}).catch(function(n){v(n),e.reject(n)}).finally(function(){g.current-=1,E(),S()}),y.current.length>0&&g.current<o&&S()}},[o,E]),x=e.useCallback(function(e,n){var r;if(b.current)return Promise.reject(new Error("Worker is terminated"));var t=null!=(r=null==n?void 0:n.priority)?r:1,o=++w.current,u=new Promise(function(n,r){y.current.push({data:e,priority:t,sequence:o,resolve:n,reject:r})});return E(),a(!0),queueMicrotask(S),u},[S,E]),C=e.useCallback(function(){var e=y.current;y.current=[],e.forEach(function(e){return e.reject(new Error("Task cleared from queue"))}),E(),0===g.current&&a(!1)},[E]),M=e.useCallback(function(){b.current=!0,C()},[C]);return e.useEffect(function(){return function(){b.current=!0}},[]),{run:x,loading:i,result:s,error:d,queueSize:m,clearQueue:C,terminate:M}},exports.useTransition=function(){var n=e.useState(!1),r=n[0],t=n[1];return[e.useCallback(function(e){t(!0),Promise.resolve().then(function(){e(),t(!1)})},[]),r]},exports.useWasmCompute=function(n){var r=n.wasmUrl,t=n.exportName,o=void 0===t?"compute":t,u=n.workerUrl,i=n.importObject,a=e.useState(void 0),c=a[0],s=a[1],f=e.useState(!0),l=f[0],d=f[1],v=e.useState(null),p=v[0],m=v[1],h=e.useState(!1),y=h[0],w=h[1],g=e.useRef(null),b=e.useRef(null),k=e.useRef(null);return e.useEffect(function(){if("undefined"==typeof window)return m("useWasmCompute is not available during SSR"),void d(!1);if("undefined"==typeof Worker)return m("Worker is not supported in this environment"),void d(!1);if("undefined"==typeof WebAssembly||"function"!=typeof WebAssembly.instantiate)return m("WebAssembly is not supported in this environment"),void d(!1);m(null),w(!1);var e=function(e){if(e)return new Worker(e);var n=new Blob(["\nself.onmessage = async (e) => {\n const d = e.data;\n if (d.type === 'init') {\n try {\n const res = await fetch(d.wasmUrl);\n const buf = await res.arrayBuffer();\n const mod = await WebAssembly.instantiate(buf, d.importObject || {});\n self.wasmInstance = mod.instance;\n self.exportName = d.exportName || 'compute';\n self.postMessage({ type: 'ready' });\n } catch (err) {\n self.postMessage({ type: 'error', error: (err && err.message) || String(err) });\n }\n return;\n }\n if (d.type === 'compute') {\n try {\n const fn = self.wasmInstance.exports[self.exportName];\n if (typeof fn !== 'function') {\n self.postMessage({ type: 'error', error: 'Export \"' + self.exportName + '\" is not a function' });\n return;\n }\n const result = fn(d.input);\n self.postMessage({ type: 'result', result: result });\n } catch (err) {\n self.postMessage({ type: 'error', error: (err && err.message) || String(err) });\n }\n }\n};\n"],{type:"application/javascript"}),r=URL.createObjectURL(n),t=new Worker(r);return URL.revokeObjectURL(r),t}(u);g.current=e;var n=function(e){var n,r=null!=(n=e.data)?n:{},t=r.type,o=r.result,u=r.error;return"ready"===t?(w(!0),void d(!1)):"error"===t?(m(null!=u?u:"Unknown error"),d(!1),void(k.current&&(k.current(new Error(u)),b.current=null,k.current=null))):void("result"===t&&(s(o),d(!1),b.current&&(b.current(o),b.current=null,k.current=null)))};return e.addEventListener("message",n),e.postMessage({type:"init",wasmUrl:r,exportName:o,importObject:null!=i?i:{}}),function(){e.removeEventListener("message",n),e.terminate(),g.current=null,k.current&&(k.current(new Error("Worker terminated")),b.current=null,k.current=null)}},[r,o,u,i]),{compute:e.useCallback(function(e){return new Promise(function(n,r){g.current&&y?p?r(new Error(p)):(b.current=n,k.current=r,d(!0),g.current.postMessage({type:"compute",input:e})):r(new Error("WASM not ready"))})},[y,p]),result:c,loading:l,error:p,ready:y}},exports.useWebRTCIP=function(n){void 0===n&&(n={});var r=n.stunServers,t=void 0===r?d:r,o=n.timeout,u=void 0===o?3e3:o,i=n.onDetect,a=e.useState([]),c=a[0],s=a[1],f=e.useState(!0),v=f[0],p=f[1],m=e.useState(null),h=m[0],y=m[1],w=e.useRef(null),g=e.useRef(null),b=e.useRef(new Set),k=e.useRef(i);return k.current=i,e.useEffect(function(){if("undefined"==typeof window)return p(!1),void y("WebRTC IP detection is not available during SSR");if("undefined"==typeof RTCPeerConnection)return p(!1),void y("RTCPeerConnection is not available");var e=new Set;b.current=e;var n=function(){g.current&&(clearTimeout(g.current),g.current=null),w.current&&(w.current.close(),w.current=null),p(!1)},r=function(n){e.has(n)||(e.add(n),s(function(e){return[].concat(e,[n])}),null==k.current||k.current(n))};try{var o=new RTCPeerConnection({iceServers:[{urls:t}]});w.current=o,o.onicecandidate=function(e){var n,t=e.candidate;t&&t.candidate&&((n=t.candidate.match(l))?[].concat(n):[]).forEach(r)},o.createDataChannel(""),o.createOffer().then(function(e){return o.setLocalDescription(e)}).catch(function(e){y(e instanceof Error?e.message:"Failed to create offer"),n()}),g.current=setTimeout(function(){return n()},u)}catch(e){y(e instanceof Error?e.message:"WebRTC setup failed"),n()}return function(){n()}},[t.join(","),u]),{ips:c,loading:v,error:h}},exports.useWorkerNotifications=function(n,r){void 0===r&&(r={});var t=r.maxHistory,o=void 0===t?100:t,u=r.throughputWindowMs,i=void 0===u?1e3:u,a=e.useState([]),c=a[0],s=a[1],f=e.useState(0),l=f[0],d=f[1],v=e.useState(0),p=v[0],m=v[1],h=e.useState([]),y=h[0],w=h[1],g=e.useState(0),b=g[0],k=g[1],E=e.useRef([]),S=e.useRef(0),x=e.useRef(0);e.useEffect(function(){if(n){var e=function(e){var n=function(e){if(null==e||"object"!=typeof e)return null;var n=e.type;return"task_start"!==n&&"task_end"!==n&&"task_fail"!==n&&"queue_size"!==n?null:{type:n,taskId:"string"==typeof e.taskId?e.taskId:void 0,duration:"number"==typeof e.duration?e.duration:void 0,error:"string"==typeof e.error?e.error:void 0,size:"number"==typeof e.size?e.size:void 0,timestamp:Date.now()}}(e.data);if(n)if(w(function(e){return[].concat(e,[n]).slice(-o)}),"task_start"===n.type&&n.taskId)s(function(e){return e.includes(n.taskId)?e:[].concat(e,[n.taskId])});else if("task_end"===n.type){n.taskId&&s(function(e){return e.filter(function(e){return e!==n.taskId})}),d(function(e){return e+1});var r=Date.now()-i;E.current=[].concat(E.current.filter(function(e){return e>=r}),[n.timestamp]),"number"==typeof n.duration&&(S.current+=n.duration,x.current+=1)}else"task_fail"===n.type?(n.taskId&&s(function(e){return e.filter(function(e){return e!==n.taskId})}),m(function(e){return e+1})):"queue_size"===n.type&&"number"==typeof n.size&&k(n.size)};return n.addEventListener("message",e),function(){return n.removeEventListener("message",e)}}},[n,o]);var C=e.useMemo(function(){var e=x.current;return e>0?S.current/e:0},[y]),M=e.useMemo(function(){var e=Date.now()-i;return E.current.filter(function(n){return n>=e}).length/(i/1e3)},[y,i]),P=e.useMemo(function(){return{runningTasks:c,completedCount:l,failedCount:p,averageDurationMs:C,throughputPerSecond:M,currentQueueSize:b,totalProcessed:l+p,recentEventCount:y.length}},[c,l,p,C,M,b,y.length]);return{runningTasks:c,completedCount:l,failedCount:p,eventHistory:y,averageDurationMs:C,throughputPerSecond:M,currentQueueSize:b,progress:P}},exports.useWrappedChildren=function(r,t,o){return void 0===o&&(o="preserve"),e.useMemo(function(){if(!r)return r;var e=function(e){if(!n.isValidElement(e))return e;var r,i=e.props||{};r="override"===o?u({},i,t):u({},t,i);var a=null==i?void 0:i.style,c=null==t?void 0:t.style;return a&&c&&"object"==typeof a&&"object"==typeof c&&(r.style="override"===o?u({},a,c):u({},c,a)),n.cloneElement(e,r)};return Array.isArray(r)?r.map(e):e(r)},[r,t,o])};
1
+ var e=require("preact/hooks"),n=require("preact"),r=require("preact/compat"),t=new Map;function o(e,n){(null==n||n>e.length)&&(n=e.length);for(var r=0,t=Array(n);r<n;r++)t[r]=e[r];return t}function u(e,n){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,n){if(e){if("string"==typeof e)return o(e,n);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){r&&(e=r);var t=0;return function(){return t>=e.length?{done:!0}:{done:!1,value:e[t++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function i(){return i=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var r=arguments[n];for(var t in r)({}).hasOwnProperty.call(r,t)&&(e[t]=r[t])}return e},i.apply(null,arguments)}function a(){if("undefined"==typeof navigator)return{online:!0};var e={online:navigator.onLine},n=navigator.connection;return n&&(void 0!==n.effectiveType&&(e.effectiveType=n.effectiveType),void 0!==n.downlink&&(e.downlink=n.downlink),void 0!==n.rtt&&(e.rtt=n.rtt),void 0!==n.saveData&&(e.saveData=n.saveData),void 0!==n.type&&(e.connectionType=n.type)),e}function c(e,n){try{var r=e()}catch(e){return n(e)}return r&&r.then?r.then(void 0,n):r}var s=new Map;function l(e){return new Promise(function(n,r){e.onsuccess=function(){return n(e.result)},e.onerror=function(){var n;return r(null!=(n=e.error)?n:new DOMException("Unknown IndexedDB error"))}})}function f(e,n){return n?e.then(function(e){return null==n.onSuccess||n.onSuccess(e),e}).catch(function(e){throw null==n.onError||n.onError(e),e}):e}var d=/\b(?:25[0-5]|2[0-4]\d|1?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|1?\d{1,2})){3}\b/g,v=["stun:stun.l.google.com:19302"];function p(e,n){if(null==e)return"";var r=("string"==typeof e?e:String(e)).trim();return r.length>n?r.slice(0,n):r}function m(e){if(!Array.isArray(e))return[];for(var n=[],r=0;r<e.length&&n.length<50;r++){var t=p(e[r],100);t&&n.push(t)}return n}function g(e){var n=p(e,2048);if(!n)return"";try{var r=new URL(n);if("http:"===r.protocol||"https:"===r.protocol)return n}catch(e){}return""}function h(e){try{if("undefined"==typeof window)return!1;var n=window.getComputedStyle(e);return"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity}catch(e){return!1}}function y(e){var n={};try{for(var r,t=u(Object.keys(e).slice(0,20));!(r=t()).done;){var o=r.value,i=p(o,50);if(i){var a=e[o];"string"==typeof a?n[i]=a.slice(0,500):"number"==typeof a&&Number.isFinite(a)||"boolean"==typeof a?n[i]=a:Array.isArray(a)&&(n[i]=a.map(function(e){return p(e,200)}).filter(Boolean).slice(0,20))}}}catch(e){}return n}function w(){try{if("undefined"==typeof document||!document.querySelectorAll)return;document.querySelectorAll('script[data-llm="true"]').forEach(function(e){return e.remove()})}catch(e){}}exports.useClipboard=function(n){void 0===n&&(n={});var r=n.resetDelay,t=void 0===r?2e3:r,o=e.useState(!1),u=o[0],i=o[1],a=e.useState(null),s=a[0],l=a[1],f=e.useCallback(function(){i(!1),l(null)},[]);return{copy:e.useCallback(function(e){try{if(l(null),"undefined"==typeof navigator||!navigator.clipboard){var n=new Error("Clipboard API is not available");return l(n),Promise.resolve(!1)}return Promise.resolve(c(function(){return Promise.resolve(navigator.clipboard.writeText(e)).then(function(){return i(!0),t>0&&setTimeout(function(){return i(!1)},t),!0})},function(e){var n=e instanceof Error?e:new Error(String(e));return l(n),!1}))}catch(e){return Promise.reject(e)}},[t]),paste:e.useCallback(function(){try{if(l(null),"undefined"==typeof navigator||!navigator.clipboard){var e=new Error("Clipboard API is not available");return l(e),Promise.resolve("")}return Promise.resolve(c(function(){return Promise.resolve(navigator.clipboard.readText())},function(e){var n=e instanceof Error?e:new Error(String(e));return l(n),""}))}catch(e){return Promise.reject(e)}},[]),copied:u,error:s,reset:f}},exports.useEventBus=function(){return{emit:e.useCallback(function(e){var n=arguments,r=t.get(e);r&&r.forEach(function(e){return e.apply(void 0,[].slice.call(n,1))})},[]),on:e.useCallback(function(e,n){var r=t.get(e);return r||(r=new Set,t.set(e,r)),r.add(n),function(){r.delete(n),0===r.size&&t.delete(e)}},[])}},exports.useIndexedDB=function(n){var r=e.useState(null),t=r[0],o=r[1],a=e.useState(null),c=a[0],d=a[1],v=e.useState(!1),p=v[0],m=v[1],g=e.useRef(n);return g.current=n,e.useEffect(function(){var e=!1;d(null),m(!1),o(null);var n=g.current;return function(e){var n=e.name+"_v"+e.version,r=s.get(n);return r||(r=function(e){return new Promise(function(n,r){var t=indexedDB.open(e.name,e.version);t.onerror=function(){var e;return r(null!=(e=t.error)?e:new DOMException("Failed to open database"))},t.onsuccess=function(){return n(t.result)},t.onupgradeneeded=function(n){for(var r=n.target.result,t=e.tables,o=0,i=Object.keys(t);o<i.length;o++){var a=i[o],c=t[a];if(!r.objectStoreNames.contains(a)){var s,l=r.createObjectStore(a,{keyPath:c.keyPath,autoIncrement:null!=(s=c.autoIncrement)&&s});if(c.indexes)for(var f,d=u(c.indexes);!(f=d()).done;){var v=f.value;l.createIndex(v,v,{unique:!1})}}}}})}(e),s.set(n,r),r)}({name:n.name,version:n.version,tables:n.tables}).then(function(n){if(e)n.close();else{var r=function(e){return{get db(){return e},hasTable:function(n){return e.objectStoreNames.contains(n)},table:function(n){return function(e,n){return function(e,n){function r(r){return e.transaction([n],r).objectStore(n)}return{insert:function(e,n){return f(l(r("readwrite").add(e)),n)},update:function(e,n,t){var o=r("readwrite");return f(l(o.get(e)).then(function(e){if(void 0===e)throw new DOMException("Key not found","NotFoundError");var r=i({},e,n);return l(o.put(r))}).then(function(){}),t)},delete:function(e,n){return f(l(r("readwrite").delete(e)).then(function(){}),n)},exists:function(e){return l(r("readonly").getKey(e)).then(function(e){return void 0!==e})},query:function(e,n){var t=r("readonly").openCursor(),o=[];return f(new Promise(function(n,r){t.onsuccess=function(){var r=t.result;r?(e(r.value)&&o.push(r.value),r.continue()):n(o)},t.onerror=function(){var e;return r(null!=(e=t.error)?e:new DOMException("Unknown error"))}}),n)},upsert:function(e,n){return f(l(r("readwrite").put(e)),n)},bulkInsert:function(e,n){var t=r("readwrite"),o=[];if(0===e.length)return f(Promise.resolve(o),n);var u=0;return f(new Promise(function(n,r){e.forEach(function(i,a){var c=t.add(i);c.onsuccess=function(){o[a]=c.result,++u===e.length&&n(o)},c.onerror=function(){var e;return r(null!=(e=c.error)?e:new DOMException("Unknown error"))}})}),n)},clear:function(e){return f(l(r("readwrite").clear()).then(function(){}),e)},count:function(e){return f(l(r("readonly").count()),null!=e?e:{})}}}(e,n)}(e,n)},transaction:function(n,r,t,o){var u=e.transaction(n,r),a={table:function(e){return function(e,n){return function(e,n){function r(){return e.objectStore(n)}return{insert:function(e,n){return f(l(r().add(e)),n)},update:function(e,n,t){var o=r();return f(l(o.get(e)).then(function(e){if(void 0===e)throw new DOMException("Key not found","NotFoundError");var r=i({},e,n);return l(o.put(r))}).then(function(){}),t)},delete:function(e,n){return f(l(r().delete(e)).then(function(){}),n)},exists:function(e){return l(r().getKey(e)).then(function(e){return void 0!==e})},query:function(e,n){var t=r().openCursor(),o=[];return f(new Promise(function(n,r){t.onsuccess=function(){var r=t.result;r?(e(r.value)&&o.push(r.value),r.continue()):n(o)},t.onerror=function(){var e;return r(null!=(e=t.error)?e:new DOMException("Unknown error"))}}),n)},upsert:function(e,n){return f(l(r().put(e)),n)},bulkInsert:function(e,n){var t=r(),o=[];if(0===e.length)return f(Promise.resolve(o),n);var u=0;return f(new Promise(function(n,r){e.forEach(function(i,a){var c=t.add(i);c.onsuccess=function(){o[a]=c.result,++u===e.length&&n(o)},c.onerror=function(){var e;return r(null!=(e=c.error)?e:new DOMException("Unknown error"))}})}),n)},clear:function(e){return f(l(r().clear()).then(function(){}),e)},count:function(e){return f(l(r().count()),null!=e?e:{})}}}(e,n)}(u,e)}},c=new Promise(function(e,n){u.oncomplete=function(){return e()},u.onerror=function(){var e;return n(null!=(e=u.error)?e:new DOMException("Transaction failed"))}}),s=t(a);return function(e,n){return n?e.then(function(){return null==n.onSuccess?void 0:n.onSuccess()}).catch(function(e){throw null==n.onError||n.onError(e),e}):e}(Promise.resolve(s).then(function(){return c}),o)}}}(n);o(r),m(!0)}}).catch(function(n){e||d(n)}),function(){e=!0}},[n.name,n.version]),{db:t,isReady:p,error:c}},exports.useLLMMetadata=function(e){var n=r.useRef(null);r.useEffect(function(){try{if("undefined"==typeof window)return;var r=function(e){return null==e||"object"!=typeof e?{route:"/"}:{route:p(e.route,2048)||"/",mode:"auto-extract"===e.mode?"auto-extract":"manual",title:void 0!==e.title?p(e.title,200):void 0,description:void 0!==e.description?p(e.description,2e3):void 0,tags:void 0!==e.tags?m(e.tags):void 0,canonicalUrl:void 0!==e.canonicalUrl?g(e.canonicalUrl):void 0,language:void 0!==e.language?p(e.language,20):void 0,ogType:void 0!==e.ogType?p(e.ogType,50):void 0,ogImage:void 0!==e.ogImage?g(e.ogImage):void 0,ogImageAlt:void 0!==e.ogImageAlt?p(e.ogImageAlt,200):void 0,siteName:void 0!==e.siteName?p(e.siteName,100):void 0,author:void 0!==e.author?p(e.author,200):void 0,publishedTime:void 0!==e.publishedTime?p(e.publishedTime,50):void 0,modifiedTime:void 0!==e.modifiedTime?p(e.modifiedTime,50):void 0,robots:void 0!==e.robots?p(e.robots,100):void 0,extra:void 0===e.extra||"object"!=typeof e.extra||Array.isArray(e.extra)?void 0:y(e.extra)}}(e),t=function(e){try{var n=(new Date).toISOString(),r={route:e.route,generatedAt:n};if("auto-extract"===e.mode){var t,o,i=function(){var e={title:"",outline:[],description:""};try{if("undefined"==typeof document)return e;var n=p(document.title,200),r=[],t="";try{for(var o,i=document.querySelectorAll("nav, footer, [role='navigation'], [role='contentinfo'], script, style, noscript"),a=function(e){for(var n,r=u(i);!(n=r()).done;)if(n.value.contains(e))return!0;return!1},c=u(document.querySelectorAll("h1, h2"));!(o=c()).done;){var s=o.value;if(r.length>=50)break;if(h(s)&&!a(s)){var l=p(s.textContent,300);l&&r.push(l)}}for(var f,d=document.querySelectorAll("p"),v=[],m=u(d);!(f=m()).done;){var g=f.value;if(v.length>=3)break;if(h(g)&&!a(g)){var y=p(g.textContent,1e3);y&&v.push(y)}}t=v.join(" ").trim().slice(0,2e3)||""}catch(e){}return{title:n,outline:r,description:t}}catch(n){return e}}();r.title=(null!=(t=e.title)?t:i.title)||void 0,r.description=(null!=(o=e.description)?o:i.description)||void 0,i.outline.length>0&&(r.outline=i.outline)}else void 0!==e.title&&""!==e.title&&(r.title=e.title),void 0!==e.description&&""!==e.description&&(r.description=e.description);return e.tags&&e.tags.length>0&&(r.tags=e.tags),e.canonicalUrl&&(r.canonicalUrl=e.canonicalUrl),e.language&&(r.language=e.language),e.ogType&&(r.ogType=e.ogType),e.ogImage&&(r.ogImage=e.ogImage),e.ogImageAlt&&(r.ogImageAlt=e.ogImageAlt),e.siteName&&(r.siteName=e.siteName),e.author&&(r.author=e.author),e.publishedTime&&(r.publishedTime=e.publishedTime),e.modifiedTime&&(r.modifiedTime=e.modifiedTime),e.robots&&(r.robots=e.robots),e.extra&&Object.keys(e.extra).length>0&&(r.extra=e.extra),r}catch(n){var a;return{route:null!=(a=null==e?void 0:e.route)?a:"/",generatedAt:(new Date).toISOString()}}}(r),o=JSON.stringify(t);if(n.current===o)return;return n.current=o,w(),function(e){try{if("undefined"==typeof document||!document.head)return;var n=document.createElement("script");n.type="application/llm+json",n.setAttribute("data-llm","true"),n.textContent=JSON.stringify(e),document.head.appendChild(n)}catch(e){}}(t),function(){w(),n.current=null}}catch(e){}},[null==e?void 0:e.route,null==e?void 0:e.mode,null==e?void 0:e.title,null==e?void 0:e.description,null==e?void 0:e.tags,null==e?void 0:e.canonicalUrl,null==e?void 0:e.language,null==e?void 0:e.ogType,null==e?void 0:e.ogImage,null==e?void 0:e.ogImageAlt,null==e?void 0:e.siteName,null==e?void 0:e.author,null==e?void 0:e.publishedTime,null==e?void 0:e.modifiedTime,null==e?void 0:e.robots])},exports.useMutationObserver=function(n,r,t){e.useEffect(function(){var e=n.current;if(e){var o=new MutationObserver(r);return o.observe(e,t),function(){return o.disconnect()}}},[n,r,t])},exports.useNetworkState=function(){var n=e.useState(a),r=n[0],t=n[1];return e.useEffect(function(){if("undefined"!=typeof window){var e=function(){return t(a())};window.addEventListener("online",e),window.addEventListener("offline",e);var n=navigator.connection;return null!=n&&n.addEventListener&&n.addEventListener("change",e),function(){window.removeEventListener("online",e),window.removeEventListener("offline",e),null!=n&&n.removeEventListener&&n.removeEventListener("change",e)}}},[]),r},exports.usePreferredTheme=function(){var n=e.useState(function(){if("undefined"==typeof window)return"no-preference";var e=window.matchMedia("(prefers-color-scheme: dark)"),n=window.matchMedia("(prefers-color-scheme: light)");return e.matches?"dark":n.matches?"light":"no-preference"}),r=n[0],t=n[1];return e.useEffect(function(){if("undefined"!=typeof window){var e=window.matchMedia("(prefers-color-scheme: dark)"),n=function(e){t(e.matches?"dark":"light")},r=function(){var e=window.matchMedia("(prefers-color-scheme: dark)"),n=window.matchMedia("(prefers-color-scheme: light)");t(e.matches?"dark":n.matches?"light":"no-preference")};e.addEventListener("change",n);var o=window.matchMedia("(prefers-color-scheme: light)");return o.addEventListener("change",r),function(){e.removeEventListener("change",n),o.removeEventListener("change",r)}}},[]),r},exports.useRageClick=function(n,r){var t=r.onRageClick,o=r.threshold,u=void 0===o?5:o,i=r.timeWindow,a=void 0===i?1e3:i,c=r.distanceThreshold,s=void 0===c?30:c,l=e.useRef(t);l.current=t;var f=e.useRef([]);e.useEffect(function(){var e=n.current;if(e){var r=function(e){var n=Date.now(),r={time:n,x:e.clientX,y:e.clientY},t=n-a,o=f.current.filter(function(e){return e.time>=t});if(o.push(r),Infinity!==s){var i=o.filter(function(e){return n=e,t=r,Math.hypot(t.x-n.x,t.y-n.y)<=s;var n,t});if(i.length>=u)return l.current({count:i.length,event:e}),void(f.current=[])}else if(o.length>=u)return l.current({count:o.length,event:e}),void(f.current=[]);f.current=o};return e.addEventListener("click",r),function(){return e.removeEventListener("click",r)}}},[n,u,a,s])},exports.useThreadedWorker=function(n,r){var t=r.concurrency,o="sequential"===r.mode?1:Math.max(1,void 0===t?4:t),u=e.useState(!1),i=u[0],a=u[1],c=e.useState(void 0),s=c[0],l=c[1],f=e.useState(void 0),d=f[0],v=f[1],p=e.useState(0),m=p[0],g=p[1],h=e.useRef([]),y=e.useRef(0),w=e.useRef(0),b=e.useRef(!1),k=e.useRef(n);k.current=n;var S=e.useCallback(function(){g(h.current.length+w.current)},[]),E=e.useCallback(function(){if(!(b.current||w.current>=o)){if(0===h.current.length)return 0===w.current&&a(!1),void S();h.current.sort(function(e,n){return e.priority!==n.priority?e.priority-n.priority:e.sequence-n.sequence});var e=h.current.shift();w.current+=1,a(!0),S(),(0,k.current)(e.data).then(function(n){l(n),v(void 0),e.resolve(n)}).catch(function(n){v(n),e.reject(n)}).finally(function(){w.current-=1,S(),E()}),h.current.length>0&&w.current<o&&E()}},[o,S]),x=e.useCallback(function(e,n){var r;if(b.current)return Promise.reject(new Error("Worker is terminated"));var t=null!=(r=null==n?void 0:n.priority)?r:1,o=++y.current,u=new Promise(function(n,r){h.current.push({data:e,priority:t,sequence:o,resolve:n,reject:r})});return S(),a(!0),queueMicrotask(E),u},[E,S]),T=e.useCallback(function(){var e=h.current;h.current=[],e.forEach(function(e){return e.reject(new Error("Task cleared from queue"))}),S(),0===w.current&&a(!1)},[S]),C=e.useCallback(function(){b.current=!0,T()},[T]);return e.useEffect(function(){return function(){b.current=!0}},[]),{run:x,loading:i,result:s,error:d,queueSize:m,clearQueue:T,terminate:C}},exports.useTransition=function(){var n=e.useState(!1),r=n[0],t=n[1];return[e.useCallback(function(e){t(!0),Promise.resolve().then(function(){e(),t(!1)})},[]),r]},exports.useWasmCompute=function(n){var r=n.wasmUrl,t=n.exportName,o=void 0===t?"compute":t,u=n.workerUrl,i=n.importObject,a=e.useState(void 0),c=a[0],s=a[1],l=e.useState(!0),f=l[0],d=l[1],v=e.useState(null),p=v[0],m=v[1],g=e.useState(!1),h=g[0],y=g[1],w=e.useRef(null),b=e.useRef(null),k=e.useRef(null);return e.useEffect(function(){if("undefined"==typeof window)return m("useWasmCompute is not available during SSR"),void d(!1);if("undefined"==typeof Worker)return m("Worker is not supported in this environment"),void d(!1);if("undefined"==typeof WebAssembly||"function"!=typeof WebAssembly.instantiate)return m("WebAssembly is not supported in this environment"),void d(!1);m(null),y(!1);var e=function(e){if(e)return new Worker(e);var n=new Blob(["\nself.onmessage = async (e) => {\n const d = e.data;\n if (d.type === 'init') {\n try {\n const res = await fetch(d.wasmUrl);\n const buf = await res.arrayBuffer();\n const mod = await WebAssembly.instantiate(buf, d.importObject || {});\n self.wasmInstance = mod.instance;\n self.exportName = d.exportName || 'compute';\n self.postMessage({ type: 'ready' });\n } catch (err) {\n self.postMessage({ type: 'error', error: (err && err.message) || String(err) });\n }\n return;\n }\n if (d.type === 'compute') {\n try {\n const fn = self.wasmInstance.exports[self.exportName];\n if (typeof fn !== 'function') {\n self.postMessage({ type: 'error', error: 'Export \"' + self.exportName + '\" is not a function' });\n return;\n }\n const result = fn(d.input);\n self.postMessage({ type: 'result', result: result });\n } catch (err) {\n self.postMessage({ type: 'error', error: (err && err.message) || String(err) });\n }\n }\n};\n"],{type:"application/javascript"}),r=URL.createObjectURL(n),t=new Worker(r);return URL.revokeObjectURL(r),t}(u);w.current=e;var n=function(e){var n,r=null!=(n=e.data)?n:{},t=r.type,o=r.result,u=r.error;return"ready"===t?(y(!0),void d(!1)):"error"===t?(m(null!=u?u:"Unknown error"),d(!1),void(k.current&&(k.current(new Error(u)),b.current=null,k.current=null))):void("result"===t&&(s(o),d(!1),b.current&&(b.current(o),b.current=null,k.current=null)))};return e.addEventListener("message",n),e.postMessage({type:"init",wasmUrl:r,exportName:o,importObject:null!=i?i:{}}),function(){e.removeEventListener("message",n),e.terminate(),w.current=null,k.current&&(k.current(new Error("Worker terminated")),b.current=null,k.current=null)}},[r,o,u,i]),{compute:e.useCallback(function(e){return new Promise(function(n,r){w.current&&h?p?r(new Error(p)):(b.current=n,k.current=r,d(!0),w.current.postMessage({type:"compute",input:e})):r(new Error("WASM not ready"))})},[h,p]),result:c,loading:f,error:p,ready:h}},exports.useWebRTCIP=function(n){void 0===n&&(n={});var r=n.stunServers,t=void 0===r?v:r,o=n.timeout,u=void 0===o?3e3:o,i=n.onDetect,a=e.useState([]),c=a[0],s=a[1],l=e.useState(!0),f=l[0],p=l[1],m=e.useState(null),g=m[0],h=m[1],y=e.useRef(null),w=e.useRef(null),b=e.useRef(new Set),k=e.useRef(i);return k.current=i,e.useEffect(function(){if("undefined"==typeof window)return p(!1),void h("WebRTC IP detection is not available during SSR");if("undefined"==typeof RTCPeerConnection)return p(!1),void h("RTCPeerConnection is not available");var e=new Set;b.current=e;var n=function(){w.current&&(clearTimeout(w.current),w.current=null),y.current&&(y.current.close(),y.current=null),p(!1)},r=function(n){e.has(n)||(e.add(n),s(function(e){return[].concat(e,[n])}),null==k.current||k.current(n))};try{var o=new RTCPeerConnection({iceServers:[{urls:t}]});y.current=o,o.onicecandidate=function(e){var n,t=e.candidate;t&&t.candidate&&((n=t.candidate.match(d))?[].concat(n):[]).forEach(r)},o.createDataChannel(""),o.createOffer().then(function(e){return o.setLocalDescription(e)}).catch(function(e){h(e instanceof Error?e.message:"Failed to create offer"),n()}),w.current=setTimeout(function(){return n()},u)}catch(e){h(e instanceof Error?e.message:"WebRTC setup failed"),n()}return function(){n()}},[t.join(","),u]),{ips:c,loading:f,error:g}},exports.useWorkerNotifications=function(n,r){void 0===r&&(r={});var t=r.maxHistory,o=void 0===t?100:t,u=r.throughputWindowMs,i=void 0===u?1e3:u,a=e.useState([]),c=a[0],s=a[1],l=e.useState(0),f=l[0],d=l[1],v=e.useState(0),p=v[0],m=v[1],g=e.useState([]),h=g[0],y=g[1],w=e.useState(0),b=w[0],k=w[1],S=e.useRef([]),E=e.useRef(0),x=e.useRef(0);e.useEffect(function(){if(n){var e=function(e){var n=function(e){if(null==e||"object"!=typeof e)return null;var n=e.type;return"task_start"!==n&&"task_end"!==n&&"task_fail"!==n&&"queue_size"!==n?null:{type:n,taskId:"string"==typeof e.taskId?e.taskId:void 0,duration:"number"==typeof e.duration?e.duration:void 0,error:"string"==typeof e.error?e.error:void 0,size:"number"==typeof e.size?e.size:void 0,timestamp:Date.now()}}(e.data);if(n)if(y(function(e){return[].concat(e,[n]).slice(-o)}),"task_start"===n.type&&n.taskId)s(function(e){return e.includes(n.taskId)?e:[].concat(e,[n.taskId])});else if("task_end"===n.type){n.taskId&&s(function(e){return e.filter(function(e){return e!==n.taskId})}),d(function(e){return e+1});var r=Date.now()-i;S.current=[].concat(S.current.filter(function(e){return e>=r}),[n.timestamp]),"number"==typeof n.duration&&(E.current+=n.duration,x.current+=1)}else"task_fail"===n.type?(n.taskId&&s(function(e){return e.filter(function(e){return e!==n.taskId})}),m(function(e){return e+1})):"queue_size"===n.type&&"number"==typeof n.size&&k(n.size)};return n.addEventListener("message",e),function(){return n.removeEventListener("message",e)}}},[n,o]);var T=e.useMemo(function(){var e=x.current;return e>0?E.current/e:0},[h]),C=e.useMemo(function(){var e=Date.now()-i;return S.current.filter(function(n){return n>=e}).length/(i/1e3)},[h,i]),I=e.useMemo(function(){return{runningTasks:c,completedCount:f,failedCount:p,averageDurationMs:T,throughputPerSecond:C,currentQueueSize:b,totalProcessed:f+p,recentEventCount:h.length}},[c,f,p,T,C,b,h.length]);return{runningTasks:c,completedCount:f,failedCount:p,eventHistory:h,averageDurationMs:T,throughputPerSecond:C,currentQueueSize:b,progress:I}},exports.useWrappedChildren=function(r,t,o){return void 0===o&&(o="preserve"),e.useMemo(function(){if(!r)return r;var e=function(e){if(!n.isValidElement(e))return e;var r,u=e.props||{};r="override"===o?i({},u,t):i({},t,u);var a=null==u?void 0:u.style,c=null==t?void 0:t.style;return a&&c&&"object"==typeof a&&"object"==typeof c&&(r.style="override"===o?i({},a,c):i({},c,a)),n.cloneElement(e,r)};return Array.isArray(r)?r.map(e):e(r)},[r,t,o])};
2
2
  //# sourceMappingURL=index.js.map