diff --git a/cdn/requirements.txt b/cdn/requirements.txt index 7285e52..c8c8b6a 100644 --- a/cdn/requirements.txt +++ b/cdn/requirements.txt @@ -1,2 +1,2 @@ # The publishing tool, `cardvision cdn` (the toolkit's docs/cdn.md), with boto3 for the uploads. -cardvision[cdn]==0.10.0 +cardvision[cdn]==0.10.1 diff --git a/docs/how-it-works.md b/docs/how-it-works.md index f84cf43..5bd491b 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -91,7 +91,8 @@ in [PRIVACY.md](../PRIVACY.md). Nothing else leaves the browser. the bundled release on any problem. Frames, pictures and results never go to the network. With a newer release, the frame also sends each shown card's name to the tooltip frame over a channel the page cannot reach. - **The tooltip frame** gets a card id and name, loads the card's picture (from the CDN, or none with `namesOnly`), and reports its size back. The - content script places it, and draws the **outline** around the same box. + content script places it, and draws the **outline** around the same box; a card lying at an + angle is outlined, and hovered, along its own edges (the runtime's turned outlines). - **The details panel:** with card details on, the tooltip frame also loads the card details file the settings file names (`src/details/`), once, and keeps it in the extension's Cache Storage. For a card it lists, the frame fills a text panel (as plain text, never markup), measures it at a diff --git a/src/compute/frame.ts b/src/compute/frame.ts index c923438..2814be4 100644 --- a/src/compute/frame.ts +++ b/src/compute/frame.ts @@ -4,7 +4,8 @@ // rule, the worker and its one restart, the remote release's rules 10 to 12, the messages and the // pictures it closes. What is DuelSight's own: // - the options it starts with: its message tag, the pages it serves (`allowedParentOrigin`), -// the shown card held through short gaps (`SHOWN_HOLD`), the release it loads; +// the shown card held through short gaps (`SHOWN_HOLD`), turned cards' outlines +// (`rotatedOutlines`), the release it loads; // - the card facts channel. A card of a remote release goes to the tooltip frame with its facts // over an extension-only channel (`postFacts`), never through the page, and they leave before // the card does. A tooltip frame that lacks a card's facts asks on that channel, and is @@ -66,7 +67,7 @@ export function createFactsChannel(postFacts: (message: CardFactsMessage) => voi } /** What DuelSight's compute frame starts from: the toolkit's options, less the ones it sets. */ -export type DuelSightFrameEnv = Omit & { +export type DuelSightFrameEnv = Omit & { /** `location.ancestorOrigins[0]`: missing, or the string "null" when a referrer policy hides it. */ parentOrigin: string | null | undefined; dev: boolean; @@ -86,6 +87,9 @@ export function computeFrameEnv(env: DuelSightFrameEnv, facts: FactsChannel): Co // A card stays shown through short gaps (a live stream's flicker): two analyses in a row with // nothing there, or 5 s with no analysis seeing it. hold: SHOWN_HOLD, + // A card lying at an angle is hovered and outlined along its own edges, not its upright box + // (the shown card then carries `rotation`, `localWidth`, `localHeight`; outline.ts draws them). + rotatedOutlines: true, onShown: facts.onShown, }; } diff --git a/src/content/agent.ts b/src/content/agent.ts index abba70e..c17eabe 100644 --- a/src/content/agent.ts +++ b/src/content/agent.ts @@ -14,8 +14,9 @@ // compute frame names, placed off the cards around it and scaled down when the page has no // room for it, and hides it shortly after. Nothing it shows takes the pointer: hovering goes // on to the card underneath. -// - It outlines the card the tooltip names (outline.ts): the same accepted box, shown and -// hidden with the tooltip, never taking the pointer. +// - It outlines the card the tooltip names (outline.ts): the same accepted box (along the +// card's own edges when it lies at an angle), shown and hidden with the tooltip, never taking +// the pointer. // - It is on for every video (owner, 2026-10-27: no per-channel switch; the popup's switch is // the only control). The popup's switch turned off removes the frames again. // - It takes a message from one of its frames only when the browser delivered it from that @@ -28,7 +29,7 @@ import { type CaptureControl, computeProtocol, createCaptureControl, fromExtensi import { availableSpace, CARD_CORNER, fitBesideCard, fitsBesideCard, fitTooltipSize, fitWithPanel, fractionIn, pictureRect, placeTooltipAvoiding, type Rect, scaleTooltipSize, tooltipRadius } from "./geometry.js"; import { arrange } from "../shared/panel-layout.js"; import { isActivePage } from "./site.js"; -import { CardOutline, outlineRect } from "./outline.js"; +import { CardOutline, outlinePlacement } from "./outline.js"; /** The two-frame contract under DuelSight's tag; the compute frame uses the same. */ const PROTOCOL = computeProtocol(TAG); @@ -447,8 +448,9 @@ export class Agent { if (this.outline && !this.outline.element.isConnected) { this.outline = new CardOutline(this.tooltip!.parentElement ?? this.mountHost()); } - // The same box, on the same picture; nothing when the picture's size is not known. - this.outline?.show(ready ? outlineRect(picture, card.box, video.videoWidth > 0 && video.videoHeight > 0) : null); + // The same box, on the same picture (along the card's own edges when it is turned); nothing + // when the picture's size is not known. + this.outline?.show(ready ? outlinePlacement(picture, card, video.videoWidth > 0 && video.videoHeight > 0) : null); } private hideTooltip(): void { diff --git a/src/content/outline.ts b/src/content/outline.ts index 21c06db..754b584 100644 --- a/src/content/outline.ts +++ b/src/content/outline.ts @@ -1,7 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // The outline drawn around the card whose tooltip is showing. It is the accepted detection's // box (the one the tooltip is placed beside), mapped onto the picture on screen the same way -// (letterboxing, full screen, theater, resizing). The agent shows and hides it with the tooltip. +// (letterboxing, full screen, theater, resizing). A card lying at an angle is outlined along its +// own edges instead: the shown card's `rotation`, `localWidth` and `localHeight` (the toolkit's +// `rotatedOutlines`), the same outline the hover test uses. The agent shows and hides it with the +// tooltip. // // It never takes the pointer and never moves the page: a fixed-position element with // pointer-events none, nothing focusable, drawn in a closed shadow root so the page's styles do @@ -43,6 +46,40 @@ export function outlineRect(picture: Rect, box: FractionBox, pictureKnown = true return rect.width >= MIN_OUTLINE_SIDE && rect.height >= MIN_OUTLINE_SIDE ? rect : null; } +/** Where the outline goes, turned: its upright rectangle on screen and the turn about its center + * (degrees, positive clockwise as CSS `rotate()` turns; 0 for an upright card). */ +export interface OutlinePlacement extends Rect { + rotation: number; +} + +/** The card the outline is drawn for: its box, and its outline when it is turned. */ +export interface OutlinedCard { + box: FractionBox; + rotation?: number; + localWidth?: number; + localHeight?: number; +} + +/** + * Where the outline goes for `card`. An upright card (no outline fields) is `outlineRect` of its + * box. A turned card is a rectangle of its own sides (`localWidth`, `localHeight`, fractions of + * the picture's width and height) about the center of its box, turned by `rotation`: the toolkit's + * `computeCardQuad`, as CSS draws it. Its box must still pass `outlineRect` (on the picture, + * large enough); a turned outline is not clipped at the picture's edge. + */ +export function outlinePlacement(picture: Rect, card: OutlinedCard, pictureKnown = true): OutlinePlacement | null { + const upright = outlineRect(picture, card.box, pictureKnown); + if (!upright) return null; + const { rotation, localWidth, localHeight } = card; + if (rotation === undefined || localWidth === undefined || localHeight === undefined || rotation === 0) return { ...upright, rotation: 0 }; + const width = localWidth * picture.width; + const height = localHeight * picture.height; + if (![rotation, width, height].every(Number.isFinite) || width < MIN_OUTLINE_SIDE || height < MIN_OUTLINE_SIDE) return { ...upright, rotation: 0 }; + const cx = picture.left + (card.box.x + card.box.width / 2) * picture.width; + const cy = picture.top + (card.box.y + card.box.height / 2) * picture.height; + return { left: cx - width / 2, top: cy - height / 2, width, height, rotation }; +} + /** * The outline's edge: a solid edge fading into a glow (RiftSight's hover cue, here in a * card-back navy and a brighter blue), with a faint light hairline inside the edge so a navy @@ -93,8 +130,9 @@ export class CardOutline { return this.visible; } - /** Draw it around `rect` (page coordinates), or hide it when `rect` is null. */ - show(rect: Rect | null): void { + /** Draw it around `rect` (page coordinates), turned about its center by `rect.rotation` when it + * has one, or hide it when `rect` is null. */ + show(rect: Rect | OutlinePlacement | null): void { if (!rect) { this.hide(); return; @@ -104,6 +142,8 @@ export class CardOutline { s.top = `${rect.top}px`; s.width = `${rect.width}px`; s.height = `${rect.height}px`; + const rotation = "rotation" in rect ? rect.rotation : 0; + s.transform = rotation ? `rotate(${rotation}deg)` : "none"; if (this.visible) return; this.visible = true; s.display = "block"; diff --git a/test/agent.test.ts b/test/agent.test.ts index b3b9a58..63147fb 100644 --- a/test/agent.test.ts +++ b/test/agent.test.ts @@ -81,7 +81,14 @@ function fromFrame(frame: HTMLIFrameElement | undefined, data: object): void { /** The compute frame names a card, and the tooltip frame answers with its size for it (the * frame is shown only once that size has come). */ -function showCard(card: { cardId: string; name: string; box: { x: number; y: number; width: number; height: number } }): void { +function showCard(card: { + cardId: string; + name: string; + box: { x: number; y: number; width: number; height: number }; + rotation?: number; + localWidth?: number; + localHeight?: number; +}): void { fromFrame(compute(), { kind: "shown", card }); fromFrame(tooltip(), { kind: "size", width: 320, height: 448, shape: "card", cardId: card.cardId }); } @@ -494,6 +501,30 @@ describe("Agent", () => { expect(el.style.display).toBe("none"); }); + it("outlines a turned card along its own edges, and follows it when only its turn changes", async () => { + vi.useFakeTimers(); + agent = await startAgent(); + move(100, 100); + const card = { cardId: "89631139", name: "Blue-Eyes White Dragon", box: { x: 0.1, y: 0.1, width: 0.1, height: 0.2 } }; + showCard({ ...card, rotation: 15, localWidth: 0.08, localHeight: 0.16 }); + const el = outline()!; + expect(el.style.display).toBe("block"); + // Box center (144, 108) in page pixels; sides 76.8 x 86.4. + const r = [el.style.left, el.style.top, el.style.width, el.style.height].map(parseFloat); + [105.6, 64.8, 76.8, 86.4].forEach((v, i) => expect(r[i]).toBeCloseTo(v, 3)); + expect(el.style.transform).toBe("rotate(15deg)"); + showCard({ ...card, rotation: -20, localWidth: 0.08, localHeight: 0.16 }); + expect(el.style.transform).toBe("rotate(-20deg)"); + // Upright again (no outline fields): the box, unturned. + showCard(card); + expect([el.style.left, el.style.top, el.style.width, el.style.height].map(parseFloat)).toEqual([96, 54, 96, 108]); + expect(el.style.transform).toBe("none"); + // A malformed outline is dropped by the parser: the card still shows, upright. + showCard({ ...card, rotation: 90, localWidth: 0.08, localHeight: 0.16 }); + expect(el.style.display).toBe("block"); + expect(el.style.transform).toBe("none"); + }); + it("hides the outline with the tooltip when the pointer leaves the player", async () => { vi.useFakeTimers(); agent = await startAgent(); diff --git a/test/compute-frame.test.ts b/test/compute-frame.test.ts index e9ea322..cf6e0b1 100644 --- a/test/compute-frame.test.ts +++ b/test/compute-frame.test.ts @@ -65,6 +65,10 @@ describe("compute frame: the pages it serves", () => { }); describe("compute frame: the shown card", () => { + it("asks for turned cards' outlines (rotatedOutlines is on)", () => { + expect(computeFrameEnv({ ...computeHarness().env }, createFactsChannel(() => undefined)).rotatedOutlines).toBe(true); + }); + it("holds the shown card through short gaps (SHOWN_HOLD is on)", () => { expect(computeFrameEnv({ ...computeHarness().env }, createFactsChannel(() => undefined)).hold).toBe(SHOWN_HOLD); const h = computeHarness(); diff --git a/test/outline.test.ts b/test/outline.test.ts index fcf72df..2a3f133 100644 --- a/test/outline.test.ts +++ b/test/outline.test.ts @@ -5,7 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { pictureRect, type Rect } from "../src/content/geometry.js"; -import { CardOutline, MIN_OUTLINE_SIDE, OUTLINE_WIDTH, outlineEdgeStyle, outlineRect } from "../src/content/outline.js"; +import { CardOutline, MIN_OUTLINE_SIDE, OUTLINE_WIDTH, outlineEdgeStyle, outlinePlacement, outlineRect } from "../src/content/outline.js"; import { OUTLINE_COLOR, OUTLINE_GLOW_COLOR } from "../src/constants.js"; /** Equal to a hundredth of a pixel (fractions do not add up exactly in floating point). */ @@ -58,6 +58,32 @@ describe("outlineRect", () => { }); }); +describe("outlinePlacement: a turned card", () => { + const picture = { left: 10, top: 20, width: 1000, height: 500 }; + + it("is outlineRect, unturned, for an upright card", () => { + expect(outlinePlacement(picture, { box })).toEqual({ ...outlineRect(picture, box)!, rotation: 0 }); + // Never rotation 0 from the toolkit, but drawn upright if it came. + expect(outlinePlacement(picture, { box, rotation: 0, localWidth: 0.05, localHeight: 0.1 })).toEqual({ ...outlineRect(picture, box)!, rotation: 0 }); + }); + + it("is the card's own sides about the center of its box, turned (computeCardQuad, as CSS draws it)", () => { + // Box center: (10 + 0.3 * 1000, 20 + 0.6 * 500) = (310, 320); sides 80 x 90 px. + const p = outlinePlacement(picture, { box, rotation: 12.5, localWidth: 0.08, localHeight: 0.18 })!; + expectRect(p, { left: 270, top: 275, width: 80, height: 90 }); + expect(p.rotation).toBe(12.5); + }); + + it("draws nothing where the box draws nothing, and falls back to the box for an unusable outline", () => { + expect(outlinePlacement(picture, { box: { x: 1.2, y: 0.1, width: 0.1, height: 0.1 }, rotation: 10, localWidth: 0.05, localHeight: 0.1 })).toBeNull(); + expect(outlinePlacement(picture, { box, rotation: 10, localWidth: 0.05, localHeight: 0.1 }, false)).toBeNull(); + const upright = { ...outlineRect(picture, box)!, rotation: 0 }; + expect(outlinePlacement(picture, { box, rotation: 10, localWidth: 0.001, localHeight: 0.1 })).toEqual(upright); + expect(outlinePlacement(picture, { box, rotation: Number.NaN, localWidth: 0.05, localHeight: 0.1 })).toEqual(upright); + expect(outlinePlacement(picture, { box, rotation: 10, localWidth: 0.05 })).toEqual(upright); + }); +}); + describe("CardOutline", () => { it("never takes the pointer, is hidden from assistive tech, and has nothing focusable", () => { document.body.innerHTML = ""; @@ -71,6 +97,12 @@ describe("CardOutline", () => { expect(el.style.display).toBe("none"); outline.show({ left: 10, top: 20, width: 30, height: 40 }); expect([el.style.display, el.style.left, el.style.top, el.style.width, el.style.height]).toEqual(["block", "10px", "20px", "30px", "40px"]); + expect(el.style.transform).toBe("none"); + // Turned about its center, and upright again. + outline.show({ left: 10, top: 20, width: 30, height: 40, rotation: -8 }); + expect(el.style.transform).toBe("rotate(-8deg)"); + outline.show({ left: 10, top: 20, width: 30, height: 40, rotation: 0 }); + expect(el.style.transform).toBe("none"); outline.show(null); expect(el.style.display).toBe("none"); outline.remove(); diff --git a/vendor/cardvision-browser/VENDOR.json b/vendor/cardvision-browser/VENDOR.json index 7b28418..6dc2f8b 100644 --- a/vendor/cardvision-browser/VENDOR.json +++ b/vendor/cardvision-browser/VENDOR.json @@ -3,8 +3,8 @@ "version": "0.1.0", "license": "Apache-2.0", "source": "cardvision-browser, the browser runtime of the cardvision toolkit (source published with the toolkit release)", - "commit": "d0584b7f6cf1ddc1938ba654f025483768fce429", - "toolkitRelease": "cardvision 0.10.0", + "commit": "8a0f2c269b9df699c38928d9d4da745111469bd7", + "toolkitRelease": "cardvision 0.10.1", "onnxruntimeWeb": "1.29.0", "ortFiles": [ "ort-wasm-simd-threaded.jsep.mjs", diff --git a/vendor/cardvision-browser/cardvision.js b/vendor/cardvision-browser/cardvision.js index 7d1a11e..51ed90e 100644 --- a/vendor/cardvision-browser/cardvision.js +++ b/vendor/cardvision-browser/cardvision.js @@ -1,4 +1,4 @@ -var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var m3=Object.create,Jo=Object.defineProperty,g3=Object.getOwnPropertyDescriptor,b3=Object.getOwnPropertyNames,y3=Object.getPrototypeOf,w3=Object.prototype.hasOwnProperty,Bu=(e=>typeof jr<"u"?jr:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof jr<"u"?jr:t)[n]}):e)(function(e){if(typeof jr<"u")return jr.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),D=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(i){throw n=[i],i}},ae=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},wn=(e,t)=>{for(var n in t)Jo(e,n,{get:t[n],enumerable:!0})},l0=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of b3(t))!w3.call(e,u)&&u!==n&&Jo(e,u,{get:()=>t[u],enumerable:!(i=g3(t,u))||i.enumerable});return e},be=(e,t,n)=>(n=e!=null?m3(y3(e)):{},l0(t||!e||!e.__esModule?Jo(n,"default",{value:e,enumerable:!0}):n,e)),Nn=e=>l0(Jo({},"__esModule",{value:!0}),e),ri,br,pn,oh,d0,c0=D(()=>{"use strict";ri=new Map,br=[],pn=(e,t,n)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=ri.get(e);if(i===void 0)ri.set(e,{backend:t,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let u=br.indexOf(e);u!==-1&&br.splice(u,1);for(let l=0;l{let t=ri.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return n||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},d0=async e=>{let t=e.executionProviders||[],n=t.map(s=>typeof s=="string"?s:s.name),i=n.length===0?br:n,u,l=[],d=new Set;for(let s of i){let r=await oh(s);typeof r=="string"?l.push({name:s,err:r}):(u||(u=r),u===r&&d.add(s))}if(!u)throw new Error(`no available backend found. ERR: ${l.map(s=>`[${s.name}] ${s.err}`).join(", ")}`);for(let{name:s,err:r}of l)n.includes(s)&&console.warn(`removing requested execution provider "${s}" from session options because it is not available: ${r}`);let c=t.filter(s=>d.has(typeof s=="string"?s:s.name));return[u,new Proxy(e,{get:(s,r)=>r==="executionProviders"?c:Reflect.get(s,r)})]}}),_3=D(()=>{"use strict";c0()}),p0,v3=D(()=>{"use strict";p0="1.29.0"}),aa,st,h0=D(()=>{"use strict";v3(),aa="warning",st={wasm:{},webgl:{},webgpu:{},versions:{common:p0},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);aa=e}},get logLevel(){return aa}},Object.defineProperty(st,"logLevel",{enumerable:!0})}),me,x3=D(()=>{"use strict";h0(),me=st}),f0,m0,$3=D(()=>{"use strict";f0=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let i=n.getContext("2d");if(i!=null){let u,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],l=e.dims[3]):(u=e.dims[3],l=e.dims[2]);let d=t?.format!==void 0?t.format:"RGB",c=t?.norm,s,r;c===void 0||c.mean===void 0?s=[255,255,255,255]:typeof c.mean=="number"?s=[c.mean,c.mean,c.mean,c.mean]:(s=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(s[3]=c.mean[3])),c===void 0||c.bias===void 0?r=[0,0,0,0]:typeof c.bias=="number"?r=[c.bias,c.bias,c.bias,c.bias]:(r=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(r[3]=c.bias[3]));let o=l*u,a=0,p=o,h=o*2,m=-1;d==="RGBA"?(a=0,p=o,h=o*2,m=o*3):d==="RGB"?(a=0,p=o,h=o*2):d==="RBG"&&(a=0,h=o,p=o*2);for(let g=0;g{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(n!=null){let u,l,d;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],l=e.dims[1],d=e.dims[3]):(u=e.dims[3],l=e.dims[2],d=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",s=t?.norm,r,o;s===void 0||s.mean===void 0?r=[255,255,255,255]:typeof s.mean=="number"?r=[s.mean,s.mean,s.mean,s.mean]:(r=[s.mean[0],s.mean[1],s.mean[2],255],s.mean[3]!==void 0&&(r[3]=s.mean[3])),s===void 0||s.bias===void 0?o=[0,0,0,0]:typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:(o=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(o[3]=s.bias[3]));let a=l*u;if(t!==void 0&&(t.format!==void 0&&d===4&&t.format!=="RGBA"||d===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let p=4,h=0,m=1,g=2,_=3,w=0,y=a,T=a*2,S=-1;c==="RGBA"?(w=0,y=a,T=a*2,S=a*3):c==="RGB"?(w=0,y=a,T=a*2):c==="RBG"&&(w=0,T=a,y=a*2),i=n.createImageData(u,l);for(let O=0;O{"use strict";ql(),yo=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:n,width:i}=t,u=t.norm??{mean:255,bias:0},l,d;typeof u.mean=="number"?l=[u.mean,u.mean,u.mean,u.mean]:l=[u.mean[0],u.mean[1],u.mean[2],u.mean[3]??255],typeof u.bias=="number"?d=[u.bias,u.bias,u.bias,u.bias]:d=[u.bias[0],u.bias[1],u.bias[2],u.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",s=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",r=n*i,o=s==="RGBA"?new Float32Array(r*4):new Float32Array(r*3),a=4,p=0,h=1,m=2,g=3,_=0,w=r,y=r*2,T=-1;c==="RGB"&&(a=3,p=0,h=1,m=2,g=-1),s==="RGBA"?T=r*3:s==="RBG"?(_=0,y=r,w=r*2):s==="BGR"&&(y=0,w=r,_=r*2);for(let S=0;S{let n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,u=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",d,c=t??{},s=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},r=o=>typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas?o.getContext("2d"):null;if(n){let o=s();o.width=e.width,o.height=e.height;let a=r(o);if(a!=null){let p=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(p=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=p,c.width=h}else c.tensorFormat="RGBA",c.height=p,c.width=h;a.drawImage(e,0,0),d=a.getImageData(0,0,h,p).data}else throw new Error("Can not access image data")}else if(i){let o,a;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(o=t.resizedHeight,a=t.resizedWidth):(o=e.height,a=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=o,c.width=a,t!==void 0){let p=s();p.width=a,p.height=o;let h=r(p);if(h!=null)h.putImageData(e,0,0),d=h.getImageData(0,0,a,o).data;else throw new Error("Can not access image data")}else d=e.data}else if(u){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let o=s();o.width=e.width,o.height=e.height;let a=r(o);if(a!=null){let p=e.height,h=e.width;return a.drawImage(e,0,0,h,p),d=a.getImageData(0,0,h,p).data,c.height=p,c.width=h,yo(d,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((o,a)=>{let p=s(),h=r(p);if(!e||!h)return a();let m=new Image;m.crossOrigin="Anonymous",m.src=e,m.onload=()=>{p.width=m.width,p.height=m.height,h.drawImage(m,0,0,p.width,p.height);let g=h.getImageData(0,0,p.width,p.height);c.height=p.height,c.width=p.width,o(yo(g.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return yo(d,c);throw new Error("Input data provided is not supported - aborted tensor creation")},b0=(e,t)=>{let{width:n,height:i,download:u,dispose:l}=t,d=[1,i,n,4];return new _t({location:"texture",type:"float32",texture:e,dims:d,download:u,dispose:l})},y0=(e,t)=>{let{dataType:n,dims:i,download:u,dispose:l}=t;return new _t({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:u,dispose:l})},w0=(e,t)=>{let{dataType:n,dims:i,download:u,dispose:l}=t;return new _t({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:u,dispose:l})},_0=(e,t,n)=>new _t({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),an,wi,ua,v0,S3=D(()=>{"use strict";an=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),wi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ua=!1,v0=()=>{if(!ua){ua=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(an.set("int64",BigInt64Array),wi.set(BigInt64Array,"int64")),t&&(an.set("uint64",BigUint64Array),wi.set(BigUint64Array,"uint64")),i?(an.set("float16",n),wi.set(n,"float16")):an.set("float16",Uint16Array)}}}),x0,$0,I3=D(()=>{"use strict";ql(),x0=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new _t(e.type,e.data,t);case"cpu-pinned":return new _t({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new _t({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new _t({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new _t({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),_t,ql=D(()=>{"use strict";$3(),T3(),S3(),I3(),_t=class{constructor(e,t,n){v0();let i,u;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,u=e.dims,e.location){case"cpu-pinned":{let d=an.get(i);if(!d)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=e.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,c;if(typeof e=="string")if(i=e,c=n,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");d=t}else{let s=an.get(e);if(s===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&s===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${s.name} as data.`);e==="uint64"||e==="int64"?d=s.from(t,BigInt):d=s.from(t)}else if(t instanceof s)d=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")d=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&s!==Uint16Array)d=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${s}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let s=typeof e[0];if(s==="string")i="string",d=e;else if(s==="boolean")i="bool",d=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${s}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",d=Uint8Array.from(e);else{let s=wi.get(e.constructor);if(s===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=s,d=e}if(c===void 0)c=[d.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");u=c,this.cpuData=d,this.dataLocation="cpu"}let l=x0(u);if(this.cpuData&&l!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(l/2)===this.cpuData.length))throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=u,this.size=l}static async fromImage(e,t){return g0(e,t)}static fromTexture(e,t){return b0(e,t)}static fromGpuBuffer(e,t){return y0(e,t)}static fromMLTensor(e,t){return w0(e,t)}static fromPinnedBuffer(e,t,n){return _0(e,t,n)}toDataURL(e){return f0(this,e)}toImageData(e){return m0(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return $0(this,e)}}}),vt,T0=D(()=>{"use strict";ql(),vt=_t}),Lo,la,Jt,Vt,hn,fn,S0=D(()=>{"use strict";h0(),Lo=(e,t)=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.timeStamp(`${e}::ORT::${t}`)},la=(e,t)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let u=0;u{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||la("BEGIN",e)},Vt=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||la("END",e)},hn=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.time(`ORT::${e}`)},fn=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.timeEnd(`ORT::${e}`)}}),I0,O3=D(()=>{"use strict";c0(),T0(),S0(),I0=class O0{constructor(t){this.handler=t}async run(t,n,i){Jt(),hn("InferenceSession.run");let u={},l={};if(typeof t!="object"||t===null||t instanceof vt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof vt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let r of n){if(typeof r!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(r)===-1)throw new RangeError(`'fetches' contains invalid output name: ${r}.`);u[r]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let r=!1,o=Object.getOwnPropertyNames(n);for(let a of this.outputNames)if(o.indexOf(a)!==-1){let p=n[a];(p===null||p instanceof vt)&&(r=!0,d=!1,u[a]=p)}if(r){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let r of this.inputNames)if(typeof t[r]>"u")throw new Error(`input '${r}' is missing in 'feeds'.`);if(d)for(let r of this.outputNames)u[r]=null;let c=await this.handler.run(t,u,l),s={};for(let r in c)if(Object.hasOwnProperty.call(c,r)){let o=c[r];o instanceof vt?s[r]=o:s[r]=new vt(o.type,o.data,o.dims)}return fn("InferenceSession.run"),Vt(),s}async release(){return this.handler.dispose()}static async create(t,n,i,u){Jt(),hn("InferenceSession.create");let l,d={};if(typeof t=="string"){if(l=t,typeof n=="object"&&n!==null)d=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof n=="object"&&n!==null)d=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let o=t,a=0,p=t.byteLength;if(typeof n=="object"&&n!==null)d=n;else if(typeof n=="number"){if(a=n,!Number.isSafeInteger(a))throw new RangeError("'byteOffset' must be an integer.");if(a<0||a>=o.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${o.byteLength}).`);if(p=t.byteLength-a,typeof i=="number"){if(p=i,!Number.isSafeInteger(p))throw new RangeError("'byteLength' must be an integer.");if(p<=0||a+p>o.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${o.byteLength-a}].`);if(typeof u=="object"&&u!==null)d=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(o,a,p)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,s]=await d0(d),r=await c.createInferenceSessionHandler(l,s);return fn("InferenceSession.create"),Vt(),new O0(r)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Qo,E3=D(()=>{"use strict";O3(),Qo=I0}),A3=D(()=>{"use strict"}),k3=D(()=>{"use strict"}),P3=D(()=>{"use strict"}),C3=D(()=>{"use strict"}),R3={};wn(R3,{InferenceSession:()=>Qo,TRACE:()=>Lo,TRACE_EVENT_BEGIN:()=>hn,TRACE_EVENT_END:()=>fn,TRACE_FUNC_BEGIN:()=>Jt,TRACE_FUNC_END:()=>Vt,Tensor:()=>vt,env:()=>me,registerBackend:()=>pn});var dt=D(()=>{"use strict";_3(),x3(),E3(),T0(),A3(),k3(),S0(),P3(),C3()});function un(e,t,n,i){if(t===void 0)return D3(e);if(n===void 0)wo(e,t,1);else if(typeof n=="number"&&i===void 0)wo(e,t,n);else if(typeof n=="string"&&i===void 0)wo(e,n,1,t);else if(typeof n=="string"&&typeof i=="number")wo(e,n,i,t);else throw new TypeError("input is valid")}function D3(e){return{verbose:un.verbose.bind(null,e),info:un.info.bind(null,e),warning:un.warning.bind(null,e),error:un.error.bind(null,e),fatal:un.fatal.bind(null,e)}}function wo(e,t,n,i){let u=Dn[i||""]||Dn[""];Fu[e]{"use strict";sh=class{log(e,t,n){}},ah=class{log(e,t,n){console.log(`${this.color(e)} ${n?"\x1B[35m"+n+"\x1B[0m ":""}${t}`)}color(e){switch(e){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${e}`)}}},Fu={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},E0={none:new sh,console:new ah},da={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1},Dn={"":da},(e=>{function t(r,o){e("verbose",r,o)}e.verbose=t;function n(r,o){e("info",r,o)}e.info=n;function i(r,o){e("warning",r,o)}e.warning=i;function u(r,o){e("error",r,o)}e.error=u;function l(r,o){e("fatal",r,o)}e.fatal=l;function d(r){Dn={},c("",r||{})}e.reset=d;function c(r,o){if(r==="*")d(o);else{let a=Dn[r]||da;Dn[r]={provider:o.provider||a.provider,minimalSeverity:o.minimalSeverity||a.minimalSeverity,logDateTime:o.logDateTime===void 0?a.logDateTime:o.logDateTime,logSourceLocation:o.logSourceLocation===void 0?a.logSourceLocation:o.logSourceLocation}}}e.set=c;function s(r){let o={};r.logLevel&&(o.minimalSeverity=r.logLevel),c("",o)}e.setWithEnv=s})(un||={}),Je=un,ca=class{constructor(e,t,n,i,u,l){this.category=e,this.name=t,this.startTime=n,this.endCallback=i,this.timer=u,this.ctx=l}async end(){return this.endCallback(this)}async checkTimer(){if(this.ctx===void 0||this.timer===void 0)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}},pa=class{constructor(e,t,n,i){this.category=e,this.name=t,this.startTime=n,this.endTime=i}},A0=class{constructor(e,t,n){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=e===void 0?1e4:e,this._flushBatchSize=t===void 0?10:t,this._flushIntervalInMilliseconds=n===void 0?5e3:n}static create(e){return e===void 0?new this:new this(e.maxNumberEvents,e.flushBatchSize,e.flushIntervalInMilliseconds)}start(){this._started=!0,this._timingEvents=[],this._flushTime=ni(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer{d.then(async r=>{u&&await u.end(),c(r)},async r=>{u&&await u.end(),s(r)})});if(!l&&u){let c=u.end();if(c&&typeof c.then=="function")return new Promise((s,r)=>{c.then(()=>{s(d)},o=>{r(o)})})}return d}begin(e,t,n){if(!this._started)throw new Error("profiler is not started yet");if(n===void 0){let i=ni();return this.flush(i),new ca(e,t,i,u=>this.endSync(u))}else{let i=n.beginTimer();return new ca(e,t,0,async u=>this.end(u),i,n)}}async end(e){let t=await e.checkTimer();this._timingEvents.length=this._flushBatchSize||e-this._flushTime>=this._flushIntervalInMilliseconds){for(let t=this._flushPointer;this._flushPointerperformance.now():Date.now});function M3(e,t,n){for(let i of n){let u=i[0],l=i[1],d=i[2],c=i[3],s=i[4];if(e.opType===u){for(let r of t)if((r.domain===l||r.domain==="ai.onnx"&&l==="")&&N3(r.version,d))return{opImpl:c,opInit:s}}}throw new TypeError(`cannot resolve operator '${e.opType}' with opsets: ${t.map(i=>`${i.domain||"ai.onnx"} v${i.version}`).join(", ")}`)}function N3(e,t){if(t.endsWith("+")){let n=Number.parseInt(t.substring(0,t.length-1),10);return!isNaN(n)&&n<=e}else if(t.split("-").length===2){let n=t.split("-"),i=Number.parseInt(n[0],10),u=Number.parseInt(n[1],10);return!isNaN(i)&&!isNaN(u)&&i<=e&&e<=u}else return Number.parseInt(t,10)===e}var z3=D(()=>{"use strict"}),B3=ae(e=>{"use strict";e.__esModule=!0;var t=(function(){function n(i){if(!i)throw new TypeError("Invalid argument; `value` has no value.");this.value=n.EMPTY,i&&n.isGuid(i)&&(this.value=i)}return n.isGuid=function(i){var u=i.toString();return i&&(i instanceof n||n.validator.test(u))},n.create=function(){return new n([n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-"))},n.createEmpty=function(){return new n("emptyguid")},n.parse=function(i){return new n(i)},n.raw=function(){return[n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-")},n.gen=function(i){for(var u="",l=0;l>>=0,(u=0<=e&&e<256)&&(i=ju[e],i)?i:(n=Ce(e,0,!0),u&&(ju[e]=n),n)):(e|=0,(u=-128<=e&&e<128)&&(i=Lu[e],i)?i:(n=Ce(e,e<0?-1:0,!1),u&&(Lu[e]=n),n))}function Rt(e,t){if(isNaN(e))return t?Zt:Ct;if(t){if(e<0)return Zt;if(e>=Uu)return Gu}else{if(e<=-Vu)return pt;if(e+1>=Vu)return qu}return e<0?Rt(-e,t).neg():Ce(e%ln|0,e/ln|0,t)}function Ce(e,t,n){return new ze(e,t,n)}function Gl(e,t,n){if(e.length===0)throw Error("empty string");if(typeof t=="number"?(n=t,t=!1):t=!!t,e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return t?Zt:Ct;if(n=n||10,n<2||360)throw Error("interior hyphen");if(i===0)return Gl(e.substring(1),t,n).neg();for(var u=Rt(Oi(n,8)),l=Ct,d=0;d{gt=null;try{gt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}ze.prototype.__isLong__,Object.defineProperty(ze.prototype,"__isLong__",{value:!0}),ze.isLong=lt,Lu={},ju={},ze.fromInt=Ur,ze.fromNumber=Rt,ze.fromBits=Ce,Oi=Math.pow,ze.fromString=Gl,ze.fromValue=Et,ha=65536,lh=1<<24,ln=ha*ha,Uu=ln*ln,Vu=Uu/2,fa=Ur(lh),Ct=Ur(0),ze.ZERO=Ct,Zt=Ur(0,!0),ze.UZERO=Zt,Vr=Ur(1),ze.ONE=Vr,ma=Ur(1,!0),ze.UONE=ma,_o=Ur(-1),ze.NEG_ONE=_o,qu=Ce(-1,2147483647,!1),ze.MAX_VALUE=qu,Gu=Ce(-1,-1,!0),ze.MAX_UNSIGNED_VALUE=Gu,pt=Ce(0,-2147483648,!1),ze.MIN_VALUE=pt,Z=ze.prototype,Z.toInt=function(){return this.unsigned?this.low>>>0:this.low},Z.toNumber=function(){return this.unsigned?(this.high>>>0)*ln+(this.low>>>0):this.high*ln+(this.low>>>0)},Z.toString=function(e){if(e=e||10,e<2||36>>0,r=s.toString(e);if(l=c,l.isZero())return r+d;for(;r.length<6;)r="0"+r;d=""+r+d}},Z.getHighBits=function(){return this.high},Z.getHighBitsUnsigned=function(){return this.high>>>0},Z.getLowBits=function(){return this.low},Z.getLowBitsUnsigned=function(){return this.low>>>0},Z.getNumBitsAbs=function(){if(this.isNegative())return this.eq(pt)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&(e&1<>21;return e?this.unsigned?!1:e===-1&&!(this.low===0&&this.high===-2097152):!0},Z.isZero=function(){return this.high===0&&this.low===0},Z.eqz=Z.isZero,Z.isNegative=function(){return!this.unsigned&&this.high<0},Z.isPositive=function(){return this.unsigned||this.high>=0},Z.isOdd=function(){return(this.low&1)===1},Z.isEven=function(){return(this.low&1)===0},Z.equals=function(e){return lt(e)||(e=Et(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low},Z.eq=Z.equals,Z.notEquals=function(e){return!this.eq(e)},Z.neq=Z.notEquals,Z.ne=Z.notEquals,Z.lessThan=function(e){return this.comp(e)<0},Z.lt=Z.lessThan,Z.lessThanOrEqual=function(e){return this.comp(e)<=0},Z.lte=Z.lessThanOrEqual,Z.le=Z.lessThanOrEqual,Z.greaterThan=function(e){return this.comp(e)>0},Z.gt=Z.greaterThan,Z.greaterThanOrEqual=function(e){return this.comp(e)>=0},Z.gte=Z.greaterThanOrEqual,Z.ge=Z.greaterThanOrEqual,Z.compare=function(e){if(lt(e)||(e=Et(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Z.comp=Z.compare,Z.negate=function(){return!this.unsigned&&this.eq(pt)?pt:this.not().add(Vr)},Z.neg=Z.negate,Z.add=function(e){lt(e)||(e=Et(e));var t=this.high>>>16,n=this.high&65535,i=this.low>>>16,u=this.low&65535,l=e.high>>>16,d=e.high&65535,c=e.low>>>16,s=e.low&65535,r=0,o=0,a=0,p=0;return p+=u+s,a+=p>>>16,p&=65535,a+=i+c,o+=a>>>16,a&=65535,o+=n+d,r+=o>>>16,o&=65535,r+=t+l,r&=65535,Ce(a<<16|p,r<<16|o,this.unsigned)},Z.subtract=function(e){return lt(e)||(e=Et(e)),this.add(e.neg())},Z.sub=Z.subtract,Z.multiply=function(e){if(this.isZero())return this;if(lt(e)||(e=Et(e)),gt){var t=gt.mul(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Zt:Ct;if(this.eq(pt))return e.isOdd()?pt:Ct;if(e.eq(pt))return this.isOdd()?pt:Ct;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(fa)&&e.lt(fa))return Rt(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,i=this.high&65535,u=this.low>>>16,l=this.low&65535,d=e.high>>>16,c=e.high&65535,s=e.low>>>16,r=e.low&65535,o=0,a=0,p=0,h=0;return h+=l*r,p+=h>>>16,h&=65535,p+=u*r,a+=p>>>16,p&=65535,p+=l*s,a+=p>>>16,p&=65535,a+=i*r,o+=a>>>16,a&=65535,a+=u*s,o+=a>>>16,a&=65535,a+=l*c,o+=a>>>16,a&=65535,o+=n*r+i*s+u*c+l*d,o&=65535,Ce(p<<16|h,o<<16|a,this.unsigned)},Z.mul=Z.multiply,Z.divide=function(e){if(lt(e)||(e=Et(e)),e.isZero())throw Error("division by zero");if(gt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?gt.div_u:gt.div_s)(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Zt:Ct;var n,i,u;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Zt;if(e.gt(this.shru(1)))return ma;u=Zt}else{if(this.eq(pt)){if(e.eq(Vr)||e.eq(_o))return pt;if(e.eq(pt))return Vr;var l=this.shr(1);return n=l.div(e).shl(1),n.eq(Ct)?e.isNegative()?Vr:_o:(i=this.sub(e.mul(n)),u=n.add(i.div(e)),u)}else if(e.eq(pt))return this.unsigned?Zt:Ct;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();u=Ct}for(i=this;i.gte(e);){n=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var d=Math.ceil(Math.log(n)/Math.LN2),c=d<=48?1:Oi(2,d-48),s=Rt(n),r=s.mul(e);r.isNegative()||r.gt(i);)n-=c,s=Rt(n,this.unsigned),r=s.mul(e);s.isZero()&&(s=Vr),u=u.add(s),i=i.sub(r)}return u},Z.div=Z.divide,Z.modulo=function(e){if(lt(e)||(e=Et(e)),gt){var t=(this.unsigned?gt.rem_u:gt.rem_s)(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))},Z.mod=Z.modulo,Z.rem=Z.modulo,Z.not=function(){return Ce(~this.low,~this.high,this.unsigned)},Z.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},Z.clz=Z.countLeadingZeros,Z.countTrailingZeros=function(){return this.low?uh(this.low):uh(this.high)+32},Z.ctz=Z.countTrailingZeros,Z.and=function(e){return lt(e)||(e=Et(e)),Ce(this.low&e.low,this.high&e.high,this.unsigned)},Z.or=function(e){return lt(e)||(e=Et(e)),Ce(this.low|e.low,this.high|e.high,this.unsigned)},Z.xor=function(e){return lt(e)||(e=Et(e)),Ce(this.low^e.low,this.high^e.high,this.unsigned)},Z.shiftLeft=function(e){return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ce(this.low<>>32-e,this.unsigned):Ce(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Ce(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Z.shr=Z.shiftRight,Z.shiftRightUnsigned=function(e){return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ce(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Ce(this.high,0,this.unsigned):Ce(this.high>>>e-32,0,this.unsigned)},Z.shru=Z.shiftRightUnsigned,Z.shr_u=Z.shiftRightUnsigned,Z.rotateLeft=function(e){var t;return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ce(this.high,this.low,this.unsigned):e<32?(t=32-e,Ce(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Ce(this.high<>>t,this.low<>>t,this.unsigned))},Z.rotl=Z.rotateLeft,Z.rotateRight=function(e){var t;return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ce(this.high,this.low,this.unsigned):e<32?(t=32-e,Ce(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Ce(this.low<>>e,this.high<>>e,this.unsigned))},Z.rotr=Z.rotateRight,Z.toSigned=function(){return this.unsigned?Ce(this.low,this.high,!1):this},Z.toUnsigned=function(){return this.unsigned?this:Ce(this.low,this.high,!0)},Z.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Z.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]},Z.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]},ze.fromBytes=function(e,t,n){return n?ze.fromBytesLE(e,t):ze.fromBytesBE(e,t)},ze.fromBytesLE=function(e,t){return new ze(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},ze.fromBytesBE=function(e,t){return new ze(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},typeof BigInt=="function"&&(ze.fromBigInt=function(e,t){var n=Number(BigInt.asIntN(32,e)),i=Number(BigInt.asIntN(32,e>>BigInt(32)));return Ce(n,i,t)},ze.fromValue=function(e,t){return typeof e=="bigint"?ze.fromBigInt(e,t):Et(e,t)},Z.toBigInt=function(){var e=BigInt(this.low>>>0),t=BigInt(this.unsigned?this.high>>>0:this.high);return t<{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ArgType=void 0;var t;(function(n){n[n.INPUT=0]="INPUT",n[n.OUTPUT=1]="OUTPUT"})(t||(e.ArgType=t={}))}),Hl=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SIZE_PREFIX_LENGTH=e.FILE_IDENTIFIER_LENGTH=e.SIZEOF_INT=e.SIZEOF_SHORT=void 0,e.SIZEOF_SHORT=2,e.SIZEOF_INT=4,e.FILE_IDENTIFIER_LENGTH=4,e.SIZE_PREFIX_LENGTH=4}),C0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isLittleEndian=e.float64=e.float32=e.int32=void 0,e.int32=new Int32Array(2),e.float32=new Float32Array(e.int32.buffer),e.float64=new Float64Array(e.int32.buffer),e.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1}),R0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Encoding=void 0;var t;(function(n){n[n.UTF8_BYTES=1]="UTF8_BYTES",n[n.UTF16_STRING=2]="UTF16_STRING"})(t||(e.Encoding=t={}))}),D0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ByteBuffer=void 0;var t=Hl(),n=R0(),i=C0(),u=class M0{constructor(d){this.bytes_=d,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(d){return new M0(new Uint8Array(d))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(d){this.position_=d}capacity(){return this.bytes_.length}readInt8(d){return this.readUint8(d)<<24>>24}readUint8(d){return this.bytes_[d]}readInt16(d){return this.readUint16(d)<<16>>16}readUint16(d){return this.bytes_[d]|this.bytes_[d+1]<<8}readInt32(d){return this.bytes_[d]|this.bytes_[d+1]<<8|this.bytes_[d+2]<<16|this.bytes_[d+3]<<24}readUint32(d){return this.readInt32(d)>>>0}readInt64(d){return BigInt.asIntN(64,BigInt(this.readUint32(d))+(BigInt(this.readUint32(d+4))<>8}writeUint16(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8}writeInt32(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8,this.bytes_[d+2]=c>>16,this.bytes_[d+3]=c>>24}writeUint32(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8,this.bytes_[d+2]=c>>16,this.bytes_[d+3]=c>>24}writeInt64(d,c){this.writeInt32(d,Number(BigInt.asIntN(32,c))),this.writeInt32(d+4,Number(BigInt.asIntN(32,c>>BigInt(32))))}writeUint64(d,c){this.writeUint32(d,Number(BigInt.asUintN(32,c))),this.writeUint32(d+4,Number(BigInt.asUintN(32,c>>BigInt(32))))}writeFloat32(d,c){i.float32[0]=c,this.writeInt32(d,i.int32[0])}writeFloat64(d,c){i.float64[0]=c,this.writeInt32(d,i.int32[i.isLittleEndian?0:1]),this.writeInt32(d+4,i.int32[i.isLittleEndian?1:0])}getBufferIdentifier(){if(this.bytes_.length{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Builder=void 0;var t=D0(),n=Hl(),i=class N0{constructor(l){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null,this.text_encoder=new TextEncoder;let d;l?d=l:d=1024,this.bb=t.ByteBuffer.allocate(d),this.space=d}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(l){this.force_defaults=l}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(l,d){l>this.minalign&&(this.minalign=l);let c=~(this.bb.capacity()-this.space+d)+1&l-1;for(;this.space=0&&this.vtable[d]==0;d--);let c=d+1;for(;d>=0;d--)this.addInt16(this.vtable[d]!=0?l-this.vtable[d]:0);let s=2;this.addInt16(l-this.object_start);let r=(c+s)*n.SIZEOF_SHORT;this.addInt16(r);let o=0,a=this.space;e:for(d=0;d=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,n.SIZEOF_INT+s),this.addOffset(l),s&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(l,d){this.finish(l,d,!0)}requiredField(l,d){let c=this.bb.capacity()-l,s=c-this.bb.readInt32(c);if(!(d{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Encoding=e.ByteBuffer=e.Builder=e.isLittleEndian=e.int32=e.float64=e.float32=e.SIZE_PREFIX_LENGTH=e.SIZEOF_SHORT=e.SIZEOF_INT=e.FILE_IDENTIFIER_LENGTH=void 0;var t=Hl();Object.defineProperty(e,"FILE_IDENTIFIER_LENGTH",{enumerable:!0,get:function(){return t.FILE_IDENTIFIER_LENGTH}}),Object.defineProperty(e,"SIZEOF_INT",{enumerable:!0,get:function(){return t.SIZEOF_INT}}),Object.defineProperty(e,"SIZEOF_SHORT",{enumerable:!0,get:function(){return t.SIZEOF_SHORT}}),Object.defineProperty(e,"SIZE_PREFIX_LENGTH",{enumerable:!0,get:function(){return t.SIZE_PREFIX_LENGTH}});var n=C0();Object.defineProperty(e,"float32",{enumerable:!0,get:function(){return n.float32}}),Object.defineProperty(e,"float64",{enumerable:!0,get:function(){return n.float64}}),Object.defineProperty(e,"int32",{enumerable:!0,get:function(){return n.int32}}),Object.defineProperty(e,"isLittleEndian",{enumerable:!0,get:function(){return n.isLittleEndian}});var i=F3();Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return i.Builder}});var u=D0();Object.defineProperty(e,"ByteBuffer",{enumerable:!0,get:function(){return u.ByteBuffer}});var l=R0();Object.defineProperty(e,"Encoding",{enumerable:!0,get:function(){return l.Encoding}})}),z0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AttributeType=void 0;var t;(function(n){n[n.UNDEFINED=0]="UNDEFINED",n[n.FLOAT=1]="FLOAT",n[n.INT=2]="INT",n[n.STRING=3]="STRING",n[n.TENSOR=4]="TENSOR",n[n.GRAPH=5]="GRAPH",n[n.FLOATS=6]="FLOATS",n[n.INTS=7]="INTS",n[n.STRINGS=8]="STRINGS",n[n.TENSORS=9]="TENSORS",n[n.GRAPHS=10]="GRAPHS",n[n.SPARSE_TENSOR=11]="SPARSE_TENSOR",n[n.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(t||(e.AttributeType=t={}))}),F0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.NodeType=void 0;var t;(function(n){n[n.Primitive=0]="Primitive",n[n.Fused=1]="Fused"})(t||(e.NodeType=t={}))}),L0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p=0;a--)r.addOffset(o[a]);return r.endVector()}static startInputsVector(r,o){r.startVector(4,o,4)}static addOutputs(r,o){r.addFieldOffset(9,o,0)}static createOutputsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startOutputsVector(r,o){r.startVector(4,o,4)}static addAttributes(r,o){r.addFieldOffset(10,o,0)}static createAttributesVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startAttributesVector(r,o){r.startVector(4,o,4)}static addInputArgCounts(r,o){r.addFieldOffset(11,o,0)}static createInputArgCountsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addInt32(o[a]);return r.endVector()}static startInputArgCountsVector(r,o){r.startVector(4,o,4)}static addImplicitInputs(r,o){r.addFieldOffset(12,o,0)}static createImplicitInputsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startImplicitInputsVector(r,o){r.startVector(4,o,4)}static endNode(r){return r.endObject()}static createNode(r,o,a,p,h,m,g,_,w,y,T,S,O,A){return ot.startNode(r),ot.addName(r,o),ot.addDocString(r,a),ot.addDomain(r,p),ot.addSinceVersion(r,h),ot.addIndex(r,m),ot.addOpType(r,g),ot.addType(r,_),ot.addExecutionProviderType(r,w),ot.addInputs(r,y),ot.addOutputs(r,T),ot.addAttributes(r,S),ot.addInputArgCounts(r,O),ot.addImplicitInputs(r,A),ot.endNode(r)}};e.Node=c}),j0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.EdgeEnd=void 0;var t=class{constructor(){this.bb=null,this.bb_pos=0}__init(n,i){return this.bb_pos=n,this.bb=i,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static sizeOf(){return 12}static createEdgeEnd(n,i,u,l){return n.prep(4,12),n.writeInt32(l),n.writeInt32(u),n.writeInt32(i),n.offset()}};e.EdgeEnd=t}),U0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o=0;r--)c.addInt32(s[r]);return c.endVector()}static startNodeIndicesVector(c,s){c.startVector(4,s,4)}static addNumInputs(c,s){c.addFieldInt32(1,s,0)}static addNumOutputs(c,s){c.addFieldInt32(2,s,0)}static addHasVariadicInput(c,s){c.addFieldInt8(3,+s,0)}static addHasVariadicOutput(c,s){c.addFieldInt8(4,+s,0)}static addNumVariadicInputs(c,s){c.addFieldInt32(5,s,0)}static addNumVariadicOutputs(c,s){c.addFieldInt32(6,s,0)}static endNodesToOptimizeIndices(c){return c.endObject()}static createNodesToOptimizeIndices(c,s,r,o,a,p,h,m){return kt.startNodesToOptimizeIndices(c),kt.addNodeIndices(c,s),kt.addNumInputs(c,r),kt.addNumOutputs(c,o),kt.addHasVariadicInput(c,a),kt.addHasVariadicOutput(c,p),kt.addNumVariadicInputs(c,h),kt.addNumVariadicOutputs(c,m),kt.endNodesToOptimizeIndices(c)}};e.NodesToOptimizeIndices=l}),q0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startProducedOpIdsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizationRecord(s){return s.endObject()}};e.RuntimeOptimizationRecord=d}),G0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startRuntimeOptimizationRecordsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizationRecordContainerEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createRuntimeOptimizationRecordContainerEntry(s,r,o){return Zr.startRuntimeOptimizationRecordContainerEntry(s),Zr.addOptimizerName(s,r),Zr.addRuntimeOptimizationRecords(s,o),Zr.endRuntimeOptimizationRecordContainerEntry(s)}};e.RuntimeOptimizationRecordContainerEntry=d}),H0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startRecordsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizations(s){return s.endObject()}static createRuntimeOptimizations(s,r){return kn.startRuntimeOptimizations(s),kn.addRecords(s,r),kn.endRuntimeOptimizations(s)}};e.RuntimeOptimizations=d}),es=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TensorDataType=void 0;var t;(function(n){n[n.UNDEFINED=0]="UNDEFINED",n[n.FLOAT=1]="FLOAT",n[n.UINT8=2]="UINT8",n[n.INT8=3]="INT8",n[n.UINT16=4]="UINT16",n[n.INT16=5]="INT16",n[n.INT32=6]="INT32",n[n.INT64=7]="INT64",n[n.STRING=8]="STRING",n[n.BOOL=9]="BOOL",n[n.FLOAT16=10]="FLOAT16",n[n.DOUBLE=11]="DOUBLE",n[n.UINT32=12]="UINT32",n[n.UINT64=13]="UINT64",n[n.COMPLEX64=14]="COMPLEX64",n[n.COMPLEX128=15]="COMPLEX128",n[n.BFLOAT16=16]="BFLOAT16",n[n.FLOAT8E4M3FN=17]="FLOAT8E4M3FN",n[n.FLOAT8E4M3FNUZ=18]="FLOAT8E4M3FNUZ",n[n.FLOAT8E5M2=19]="FLOAT8E5M2",n[n.FLOAT8E5M2FNUZ=20]="FLOAT8E5M2FNUZ"})(t||(e.TensorDataType=t={}))}),ts=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addInt64(r[o]);return s.endVector()}static startDimsVector(s,r){s.startVector(8,r,8)}static addDataType(s,r){s.addFieldInt32(3,r,l.TensorDataType.UNDEFINED)}static addRawData(s,r){s.addFieldOffset(4,r,0)}static createRawDataVector(s,r){s.startVector(1,r.length,1);for(let o=r.length-1;o>=0;o--)s.addInt8(r[o]);return s.endVector()}static startRawDataVector(s,r){s.startVector(1,r,1)}static addStringData(s,r){s.addFieldOffset(5,r,0)}static createStringDataVector(s,r){s.startVector(4,r.length,4);for(let o=r.length-1;o>=0;o--)s.addOffset(r[o]);return s.endVector()}static startStringDataVector(s,r){s.startVector(4,r,4)}static addExternalDataOffset(s,r){s.addFieldInt64(6,r,BigInt("-1"))}static endTensor(s){return s.endObject()}static createTensor(s,r,o,a,p,h,m,g){return Pt.startTensor(s),Pt.addName(s,r),Pt.addDocString(s,o),Pt.addDims(s,a),Pt.addDataType(s,p),Pt.addRawData(s,h),Pt.addStringData(s,m),Pt.addExternalDataOffset(s,g),Pt.endTensor(s)}};e.Tensor=d}),W0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addInt64(r[o]);return s.endVector()}static startDimsVector(s,r){s.startVector(8,r,8)}static endSparseTensor(s){return s.endObject()}};e.SparseTensor=d}),K0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DimensionValueType=void 0;var t;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.VALUE=1]="VALUE",n[n.PARAM=2]="PARAM"})(t||(e.DimensionValueType=t={}))}),Y0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startDimVector(s,r){s.startVector(4,r,4)}static endShape(s){return s.endObject()}static createShape(s,r){return Cn.startShape(s),Cn.addDim(s,r),Cn.endShape(s)}};e.Shape=d}),ew=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TypeInfoValue=void 0,e.unionToTypeInfoValue=l,e.unionListToTypeInfoValue=d;var t=K0(),n=X0(),i=ew(),u;(function(c){c[c.NONE=0]="NONE",c[c.tensor_type=1]="tensor_type",c[c.sequence_type=2]="sequence_type",c[c.map_type=3]="map_type"})(u||(e.TypeInfoValue=u={}));function l(c,s){switch(u[c]){case"NONE":return null;case"tensor_type":return s(new i.TensorTypeAndShape);case"sequence_type":return s(new n.SequenceType);case"map_type":return s(new t.MapType);default:return null}}function d(c,s,r){switch(u[c]){case"NONE":return null;case"tensor_type":return s(r,new i.TensorTypeAndShape);case"sequence_type":return s(r,new n.SequenceType);case"map_type":return s(r,new t.MapType);default:return null}}}),rs=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(p,h,m,g){g===void 0&&(g=m);var _=Object.getOwnPropertyDescriptor(h,m);(!_||("get"in _?!h.__esModule:_.writable||_.configurable))&&(_={enumerable:!0,get:function(){return h[m]}}),Object.defineProperty(p,g,_)}:function(p,h,m,g){g===void 0&&(g=m),p[g]=h[m]}),n=e&&e.__setModuleDefault||(Object.create?function(p,h){Object.defineProperty(p,"default",{enumerable:!0,value:h})}:function(p,h){p.default=h}),i=e&&e.__importStar||(function(){var p=function(h){return p=Object.getOwnPropertyNames||function(m){var g=[];for(var _ in m)Object.prototype.hasOwnProperty.call(m,_)&&(g[g.length]=_);return g},p(h)};return function(h){if(h&&h.__esModule)return h;var m={};if(h!=null)for(var g=p(h),_=0;_=0;g--)h.addOffset(m[g]);return h.endVector()}static startInitializersVector(h,m){h.startVector(4,m,4)}static addNodeArgs(h,m){h.addFieldOffset(1,m,0)}static createNodeArgsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodeArgsVector(h,m){h.startVector(4,m,4)}static addNodes(h,m){h.addFieldOffset(2,m,0)}static createNodesVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodesVector(h,m){h.startVector(4,m,4)}static addMaxNodeIndex(h,m){h.addFieldInt32(3,m,0)}static addNodeEdges(h,m){h.addFieldOffset(4,m,0)}static createNodeEdgesVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodeEdgesVector(h,m){h.startVector(4,m,4)}static addInputs(h,m){h.addFieldOffset(5,m,0)}static createInputsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startInputsVector(h,m){h.startVector(4,m,4)}static addOutputs(h,m){h.addFieldOffset(6,m,0)}static createOutputsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startOutputsVector(h,m){h.startVector(4,m,4)}static addSparseInitializers(h,m){h.addFieldOffset(7,m,0)}static createSparseInitializersVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startSparseInitializersVector(h,m){h.startVector(4,m,4)}static addRuntimeOptimizations(h,m){h.addFieldOffset(8,m,0)}static endGraph(h){return h.endObject()}};e.Graph=a}),nw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(r,o,a,p){p===void 0&&(p=a);var h=Object.getOwnPropertyDescriptor(o,a);(!h||("get"in h?!o.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(r,p,h)}:function(r,o,a,p){p===void 0&&(p=a),r[p]=o[a]}),n=e&&e.__setModuleDefault||(Object.create?function(r,o){Object.defineProperty(r,"default",{enumerable:!0,value:o})}:function(r,o){r.default=o}),i=e&&e.__importStar||(function(){var r=function(o){return r=Object.getOwnPropertyNames||function(a){var p=[];for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(p[p.length]=h);return p},r(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var p=r(o),h=0;h=0;p--)o.addFloat32(a[p]);return o.endVector()}static startFloatsVector(o,a){o.startVector(4,a,4)}static addInts(o,a){o.addFieldOffset(9,a,0)}static createIntsVector(o,a){o.startVector(8,a.length,8);for(let p=a.length-1;p>=0;p--)o.addInt64(a[p]);return o.endVector()}static startIntsVector(o,a){o.startVector(8,a,8)}static addStrings(o,a){o.addFieldOffset(10,a,0)}static createStringsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startStringsVector(o,a){o.startVector(4,a,4)}static addTensors(o,a){o.addFieldOffset(11,a,0)}static createTensorsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startTensorsVector(o,a){o.startVector(4,a,4)}static addGraphs(o,a){o.addFieldOffset(12,a,0)}static createGraphsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startGraphsVector(o,a){o.startVector(4,a,4)}static endAttribute(o){return o.endObject()}};e.Attribute=s}),iw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o=0;r--)c.addInt32(s[r]);return c.endVector()}static startNodeIndicesVector(c,s){c.startVector(4,s,4)}static addKernelDefHashes(c,s){c.addFieldOffset(1,s,0)}static createKernelDefHashesVector(c,s){c.startVector(8,s.length,8);for(let r=s.length-1;r>=0;r--)c.addInt64(s[r]);return c.endVector()}static startKernelDefHashesVector(c,s){c.startVector(8,s,8)}static endDeprecatedKernelCreateInfos(c){return c.endObject()}static createDeprecatedKernelCreateInfos(c,s,r){return Jr.startDeprecatedKernelCreateInfos(c),Jr.addNodeIndices(c,s),Jr.addKernelDefHashes(c,r),Jr.endDeprecatedKernelCreateInfos(c)}};e.DeprecatedKernelCreateInfos=l}),L3=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p=0;a--)r.addOffset(o[a]);return r.endVector()}static startSubGraphSessionStatesVector(r,o){r.startVector(4,o,4)}static endDeprecatedSessionState(r){return r.endObject()}static createDeprecatedSessionState(r,o,a){return en.startDeprecatedSessionState(r),en.addKernels(r,o),en.addSubGraphSessionStates(r,a),en.endDeprecatedSessionState(r)}};e.DeprecatedSessionState=c}),aw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startArgsVector(s,r){s.startVector(4,r,4)}static endKernelTypeStrArgsEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createKernelTypeStrArgsEntry(s,r,o){return tn.startKernelTypeStrArgsEntry(s),tn.addKernelTypeStr(s,r),tn.addArgs(s,o),tn.endKernelTypeStrArgsEntry(s)}};e.KernelTypeStrArgsEntry=d}),uw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startKernelTypeStrArgsVector(s,r){s.startVector(4,r,4)}static endOpIdKernelTypeStrArgsEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createOpIdKernelTypeStrArgsEntry(s,r,o){return rn.startOpIdKernelTypeStrArgsEntry(s),rn.addOpId(s,r),rn.addKernelTypeStrArgs(s,o),rn.endOpIdKernelTypeStrArgsEntry(s)}};e.OpIdKernelTypeStrArgsEntry=d}),lw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startOpKernelTypeStrArgsVector(s,r){s.startVector(4,r,4)}static endKernelTypeStrResolver(s){return s.endObject()}static createKernelTypeStrResolver(s,r){return Rn.startKernelTypeStrResolver(s),Rn.addOpKernelTypeStrArgs(s,r),Rn.endKernelTypeStrResolver(s)}};e.KernelTypeStrResolver=d}),dw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(r,o,a,p){p===void 0&&(p=a);var h=Object.getOwnPropertyDescriptor(o,a);(!h||("get"in h?!o.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(r,p,h)}:function(r,o,a,p){p===void 0&&(p=a),r[p]=o[a]}),n=e&&e.__setModuleDefault||(Object.create?function(r,o){Object.defineProperty(r,"default",{enumerable:!0,value:o})}:function(r,o){r.default=o}),i=e&&e.__importStar||(function(){var r=function(o){return r=Object.getOwnPropertyNames||function(a){var p=[];for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(p[p.length]=h);return p},r(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var p=r(o),h=0;h=0;p--)o.addOffset(a[p]);return o.endVector()}static startOpsetImportVector(o,a){o.startVector(4,a,4)}static addProducerName(o,a){o.addFieldOffset(2,a,0)}static addProducerVersion(o,a){o.addFieldOffset(3,a,0)}static addDomain(o,a){o.addFieldOffset(4,a,0)}static addModelVersion(o,a){o.addFieldInt64(5,a,BigInt("0"))}static addDocString(o,a){o.addFieldOffset(6,a,0)}static addGraph(o,a){o.addFieldOffset(7,a,0)}static addGraphDocString(o,a){o.addFieldOffset(8,a,0)}static addMetadataProps(o,a){o.addFieldOffset(9,a,0)}static createMetadataPropsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startMetadataPropsVector(o,a){o.startVector(4,a,4)}static endModel(o){return o.endObject()}};e.Model=s}),j3=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";U3=be(P0()),V3=be(z0()),rl=be(nw()),jt=be(B0()),q3=be(iw()),G3=be(L3()),H3=be(sw()),W3=be(ow()),K3=be(J0()),X3=be(Y0()),Z3=be(Z0()),Y3=be(j0()),hw=be(Wl()),fw=be(j3()),J3=be(aw()),Q3=be(lw()),eO=be(K0()),tO=be(pw()),mw=be(L0()),rO=be(U0()),nO=be(F0()),iO=be(V0()),oO=be(uw()),sO=be(dw()),aO=be(q0()),uO=be(G0()),lO=be(H0()),dO=be(X0()),cO=be(Q0()),pO=be(W0()),hO=be(cw()),fO=be(ts()),No=be(es()),gw=be(ew()),mO=be(rs()),bw=be(tw()),gO=be(rw())}),ns=D(()=>{"use strict";bO()}),yO=ae((e,t)=>{"use strict";t.exports=n;function n(i,u){for(var l=new Array(arguments.length-1),d=0,c=2,s=!0;c{"use strict";var t=e;t.length=function(d){var c=d.length;if(!c)return 0;for(var s=0;--c%4>1&&d.charAt(c)==="=";)++s;return Math.ceil(d.length*3)/4-s};var n=new Array(64),i=new Array(123);for(u=0;u<64;)i[n[u]=u<26?u+65:u<52?u+71:u<62?u-4:u-59|43]=u++;var u;t.encode=function(d,c,s){for(var r=null,o=[],a=0,p=0,h;c>2],h=(m&3)<<4,p=1;break;case 1:o[a++]=n[h|m>>4],h=(m&15)<<2,p=2;break;case 2:o[a++]=n[h|m>>6],o[a++]=n[m&63],p=0;break}a>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,o)),a=0)}return p&&(o[a++]=n[h],o[a++]=61,p===1&&(o[a++]=61)),r?(a&&r.push(String.fromCharCode.apply(String,o.slice(0,a))),r.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var l="invalid encoding";t.decode=function(d,c,s){for(var r=s,o=0,a,p=0;p1)break;if((h=i[h])===void 0)throw Error(l);switch(o){case 0:a=h,o=1;break;case 1:c[s++]=a<<2|(h&48)>>4,a=h,o=2;break;case 2:c[s++]=(a&15)<<4|(h&60)>>2,a=h,o=3;break;case 3:c[s++]=(a&3)<<6|h,o=0;break}}if(o===1)throw Error(l);return s-r},t.test=function(d){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(d)}}),_O=ae((e,t)=>{"use strict";t.exports=n;function n(){this._listeners=Object.create(null)}n.prototype.on=function(i,u,l){return(this._listeners[i]||(this._listeners[i]=[])).push({fn:u,ctx:l||this}),this},n.prototype.off=function(i,u){if(i===void 0)this._listeners=Object.create(null);else if(u===void 0)this._listeners[i]=[];else{var l=this._listeners[i];if(!l)return this;for(var d=0;d{"use strict";t.exports=n(n);function n(c){return typeof Float32Array<"u"?(function(){var s=new Float32Array([-0]),r=new Uint8Array(s.buffer),o=r[3]===128;function a(g,_,w){s[0]=g,_[w]=r[0],_[w+1]=r[1],_[w+2]=r[2],_[w+3]=r[3]}function p(g,_,w){s[0]=g,_[w]=r[3],_[w+1]=r[2],_[w+2]=r[1],_[w+3]=r[0]}c.writeFloatLE=o?a:p,c.writeFloatBE=o?p:a;function h(g,_){return r[0]=g[_],r[1]=g[_+1],r[2]=g[_+2],r[3]=g[_+3],s[0]}function m(g,_){return r[3]=g[_],r[2]=g[_+1],r[1]=g[_+2],r[0]=g[_+3],s[0]}c.readFloatLE=o?h:m,c.readFloatBE=o?m:h})():(function(){function s(o,a,p,h){var m=a<0?1:0;if(m&&(a=-a),a===0)o(1/a>0?0:2147483648,p,h);else if(isNaN(a))o(2143289344,p,h);else if(a>34028234663852886e22)o((m<<31|2139095040)>>>0,p,h);else if(a<11754943508222875e-54)o((m<<31|Math.round(a/1401298464324817e-60))>>>0,p,h);else{var g=Math.floor(Math.log(a)/Math.LN2),_=Math.round(a*Math.pow(2,-g)*8388608)&8388607;o((m<<31|g+127<<23|_)>>>0,p,h)}}c.writeFloatLE=s.bind(null,i),c.writeFloatBE=s.bind(null,u);function r(o,a,p){var h=o(a,p),m=(h>>31)*2+1,g=h>>>23&255,_=h&8388607;return g===255?_?NaN:m*(1/0):g===0?m*1401298464324817e-60*_:m*Math.pow(2,g-150)*(_+8388608)}c.readFloatLE=r.bind(null,l),c.readFloatBE=r.bind(null,d)})(),typeof Float64Array<"u"?(function(){var s=new Float64Array([-0]),r=new Uint8Array(s.buffer),o=r[7]===128;function a(g,_,w){s[0]=g,_[w]=r[0],_[w+1]=r[1],_[w+2]=r[2],_[w+3]=r[3],_[w+4]=r[4],_[w+5]=r[5],_[w+6]=r[6],_[w+7]=r[7]}function p(g,_,w){s[0]=g,_[w]=r[7],_[w+1]=r[6],_[w+2]=r[5],_[w+3]=r[4],_[w+4]=r[3],_[w+5]=r[2],_[w+6]=r[1],_[w+7]=r[0]}c.writeDoubleLE=o?a:p,c.writeDoubleBE=o?p:a;function h(g,_){return r[0]=g[_],r[1]=g[_+1],r[2]=g[_+2],r[3]=g[_+3],r[4]=g[_+4],r[5]=g[_+5],r[6]=g[_+6],r[7]=g[_+7],s[0]}function m(g,_){return r[7]=g[_],r[6]=g[_+1],r[5]=g[_+2],r[4]=g[_+3],r[3]=g[_+4],r[2]=g[_+5],r[1]=g[_+6],r[0]=g[_+7],s[0]}c.readDoubleLE=o?h:m,c.readDoubleBE=o?m:h})():(function(){function s(o,a,p,h,m,g){var _=h<0?1:0;if(_&&(h=-h),h===0)o(0,m,g+a),o(1/h>0?0:2147483648,m,g+p);else if(isNaN(h))o(0,m,g+a),o(2146959360,m,g+p);else if(h>17976931348623157e292)o(0,m,g+a),o((_<<31|2146435072)>>>0,m,g+p);else{var w;if(h<22250738585072014e-324)w=h/5e-324,o(w>>>0,m,g+a),o((_<<31|w/4294967296)>>>0,m,g+p);else{var y=Math.floor(Math.log(h)/Math.LN2);y===1024&&(y=1023),w=h*Math.pow(2,-y),o(w*4503599627370496>>>0,m,g+a),o((_<<31|y+1023<<20|w*1048576&1048575)>>>0,m,g+p)}}}c.writeDoubleLE=s.bind(null,i,0,4),c.writeDoubleBE=s.bind(null,u,4,0);function r(o,a,p,h,m){var g=o(h,m+a),_=o(h,m+p),w=(_>>31)*2+1,y=_>>>20&2047,T=4294967296*(_&1048575)+g;return y===2047?T?NaN:w*(1/0):y===0?w*5e-324*T:w*Math.pow(2,y-1075)*(T+4503599627370496)}c.readDoubleLE=r.bind(null,l,0,4),c.readDoubleBE=r.bind(null,d,4,0)})(),c}function i(c,s,r){s[r]=c&255,s[r+1]=c>>>8&255,s[r+2]=c>>>16&255,s[r+3]=c>>>24}function u(c,s,r){s[r]=c>>>24,s[r+1]=c>>>16&255,s[r+2]=c>>>8&255,s[r+3]=c&255}function l(c,s){return(c[s]|c[s+1]<<8|c[s+2]<<16|c[s+3]<<24)>>>0}function d(c,s){return(c[s]<<24|c[s+1]<<16|c[s+2]<<8|c[s+3])>>>0}}),xO=ae((e,t)=>{"use strict";t.exports=n;function n(i){try{if(typeof Bu!="function")return null;var u=Bu(i);return u&&(u.length||Object.keys(u).length)?u:null}catch{return null}}}),$O=ae(e=>{"use strict";var t=e,n="\uFFFD";t.length=function(i){for(var u=0,l=0,d=0;d=192&&s<224){var r=(s&31)<<6|i[c++]&63;d+=r>=128?String.fromCharCode(r):n}else if(s>=224&&s<240){var o=(s&15)<<12|(i[c++]&63)<<6|i[c++]&63;d+=o>=2048?String.fromCharCode(o):n}else if(s>=240){var a=(s&7)<<18|(i[c++]&63)<<12|(i[c++]&63)<<6|i[c++]&63;a<65536||a>1114111?d+=n:(a-=65536,d+=String.fromCharCode(55296+(a>>10)),d+=String.fromCharCode(56320+(a&1023)))}}return d},t.write=function(i,u,l){for(var d=l,c,s,r=0;r>6|192,u[l++]=c&63|128):(c&64512)===55296&&((s=i.charCodeAt(r+1))&64512)===56320?(c=65536+((c&1023)<<10)+(s&1023),++r,u[l++]=c>>18|240,u[l++]=c>>12&63|128,u[l++]=c>>6&63|128,u[l++]=c&63|128):(u[l++]=c>>12|224,u[l++]=c>>6&63|128,u[l++]=c&63|128);return l-d}}),TO=ae((e,t)=>{"use strict";t.exports=n;function n(i,u,l){var d=l||8192,c=d>>>1,s=null,r=d;return function(o){if(o<1||o>c)return i(o);r+o>d&&(s=i(d),r=0);var a=u.call(s,r,r+=o);return r&7&&(r=(r|7)+1),a}}}),SO=ae((e,t)=>{"use strict";t.exports=i;var n=_n();function i(c,s){this.lo=c>>>0,this.hi=s>>>0}var u=i.zero=new i(0,0);u.toNumber=function(){return 0},u.zzEncode=u.zzDecode=function(){return this},u.length=function(){return 1};var l=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(c){if(c===0)return u;var s=c<0;s&&(c=-c);var r=c>>>0,o=(c-r)/4294967296>>>0;return s&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new i(r,o)},i.from=function(c){if(typeof c=="number")return i.fromNumber(c);if(n.isString(c))if(n.Long)c=n.Long.fromString(c);else return i.fromNumber(parseInt(c,10));return c.low||c.high?new i(c.low>>>0,c.high>>>0):u},i.prototype.toNumber=function(c){if(!c&&this.hi>>>31){var s=~this.lo+1>>>0,r=~this.hi>>>0;return s||(r=r+1>>>0),-(s+r*4294967296)}return this.lo+this.hi*4294967296},i.prototype.toLong=function(c){return n.Long?new n.Long(this.lo|0,this.hi|0,!!c):{low:this.lo|0,high:this.hi|0,unsigned:!!c}};var d=String.prototype.charCodeAt;i.fromHash=function(c){return c===l?u:new i((d.call(c,0)|d.call(c,1)<<8|d.call(c,2)<<16|d.call(c,3)<<24)>>>0,(d.call(c,4)|d.call(c,5)<<8|d.call(c,6)<<16|d.call(c,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var c=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^c)>>>0,this.lo=(this.lo<<1^c)>>>0,this},i.prototype.zzDecode=function(){var c=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^c)>>>0,this.hi=(this.hi>>>1^c)>>>0,this},i.prototype.length=function(){var c=this.lo,s=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?s===0?c<16384?c<128?1:2:c<2097152?3:4:s<16384?s<128?5:6:s<2097152?7:8:r<128?9:10}}),IO=ae((e,t)=>{(function(n,i){function u(l){return l.default||l}typeof define=="function"&&define.amd?define([],function(){var l={};return i(l),u(l)}):typeof e=="object"?(i(e),typeof t=="object"&&(t.exports=u(e))):(function(){var l={};i(l),n.Long=u(l)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:e,function(n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=null;try{i=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function u(v,R,H){this.low=v|0,this.high=R|0,this.unsigned=!!H}u.prototype.__isLong__,Object.defineProperty(u.prototype,"__isLong__",{value:!0});function l(v){return(v&&v.__isLong__)===!0}function d(v){var R=Math.clz32(v&-v);return v?31-R:R}u.isLong=l;var c={},s={};function r(v,R){var H,L,V;return R?(v>>>=0,(V=0<=v&&v<256)&&(L=s[v],L)?L:(H=a(v,0,!0),V&&(s[v]=H),H)):(v|=0,(V=-128<=v&&v<128)&&(L=c[v],L)?L:(H=a(v,v<0?-1:0,!1),V&&(c[v]=H),H))}u.fromInt=r;function o(v,R){if(isNaN(v))return R?A:O;if(R){if(v<0)return A;if(v>=y)return J}else{if(v<=-T)return q;if(v+1>=T)return G}return v<0?o(-v,R).neg():a(v%w|0,v/w|0,R)}u.fromNumber=o;function a(v,R,H){return new u(v,R,H)}u.fromBits=a;var p=Math.pow;function h(v,R,H){if(v.length===0)throw Error("empty string");if(typeof R=="number"?(H=R,R=!1):R=!!R,v==="NaN"||v==="Infinity"||v==="+Infinity"||v==="-Infinity")return R?A:O;if(H=H||10,H<2||360)throw Error("interior hyphen");if(L===0)return h(v.substring(1),R,H).neg();for(var V=o(p(H,8)),K=O,B=0;B>>0:this.low},C.toNumber=function(){return this.unsigned?(this.high>>>0)*w+(this.low>>>0):this.high*w+(this.low>>>0)},C.toString=function(v){if(v=v||10,v<2||36>>0,N=Y.toString(v);if(K=te,K.isZero())return N+B;for(;N.length<6;)N="0"+N;B=""+N+B}},C.getHighBits=function(){return this.high},C.getHighBitsUnsigned=function(){return this.high>>>0},C.getLowBits=function(){return this.low},C.getLowBitsUnsigned=function(){return this.low>>>0},C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(q)?64:this.neg().getNumBitsAbs();for(var v=this.high!=0?this.high:this.low,R=31;R>0&&(v&1<>21;return v?this.unsigned?!1:v===-1&&!(this.low===0&&this.high===-2097152):!0},C.isZero=function(){return this.high===0&&this.low===0},C.eqz=C.isZero,C.isNegative=function(){return!this.unsigned&&this.high<0},C.isPositive=function(){return this.unsigned||this.high>=0},C.isOdd=function(){return(this.low&1)===1},C.isEven=function(){return(this.low&1)===0},C.equals=function(v){return l(v)||(v=m(v)),this.unsigned!==v.unsigned&&this.high>>>31===1&&v.high>>>31===1?!1:this.high===v.high&&this.low===v.low},C.eq=C.equals,C.notEquals=function(v){return!this.eq(v)},C.neq=C.notEquals,C.ne=C.notEquals,C.lessThan=function(v){return this.comp(v)<0},C.lt=C.lessThan,C.lessThanOrEqual=function(v){return this.comp(v)<=0},C.lte=C.lessThanOrEqual,C.le=C.lessThanOrEqual,C.greaterThan=function(v){return this.comp(v)>0},C.gt=C.greaterThan,C.greaterThanOrEqual=function(v){return this.comp(v)>=0},C.gte=C.greaterThanOrEqual,C.ge=C.greaterThanOrEqual,C.compare=function(v){if(l(v)||(v=m(v)),this.eq(v))return 0;var R=this.isNegative(),H=v.isNegative();return R&&!H?-1:!R&&H?1:this.unsigned?v.high>>>0>this.high>>>0||v.high===this.high&&v.low>>>0>this.low>>>0?-1:1:this.sub(v).isNegative()?-1:1},C.comp=C.compare,C.negate=function(){return!this.unsigned&&this.eq(q)?q:this.not().add(P)},C.neg=C.negate,C.add=function(v){l(v)||(v=m(v));var R=this.high>>>16,H=this.high&65535,L=this.low>>>16,V=this.low&65535,K=v.high>>>16,B=v.high&65535,te=v.low>>>16,Y=v.low&65535,N=0,X=0,W=0,ne=0;return ne+=V+Y,W+=ne>>>16,ne&=65535,W+=L+te,X+=W>>>16,W&=65535,X+=H+B,N+=X>>>16,X&=65535,N+=R+K,N&=65535,a(W<<16|ne,N<<16|X,this.unsigned)},C.subtract=function(v){return l(v)||(v=m(v)),this.add(v.neg())},C.sub=C.subtract,C.multiply=function(v){if(this.isZero())return this;if(l(v)||(v=m(v)),i){var R=i.mul(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}if(v.isZero())return this.unsigned?A:O;if(this.eq(q))return v.isOdd()?q:O;if(v.eq(q))return this.isOdd()?q:O;if(this.isNegative())return v.isNegative()?this.neg().mul(v.neg()):this.neg().mul(v).neg();if(v.isNegative())return this.mul(v.neg()).neg();if(this.lt(S)&&v.lt(S))return o(this.toNumber()*v.toNumber(),this.unsigned);var H=this.high>>>16,L=this.high&65535,V=this.low>>>16,K=this.low&65535,B=v.high>>>16,te=v.high&65535,Y=v.low>>>16,N=v.low&65535,X=0,W=0,ne=0,le=0;return le+=K*N,ne+=le>>>16,le&=65535,ne+=V*N,W+=ne>>>16,ne&=65535,ne+=K*Y,W+=ne>>>16,ne&=65535,W+=L*N,X+=W>>>16,W&=65535,W+=V*Y,X+=W>>>16,W&=65535,W+=K*te,X+=W>>>16,W&=65535,X+=H*N+L*Y+V*te+K*B,X&=65535,a(ne<<16|le,X<<16|W,this.unsigned)},C.mul=C.multiply,C.divide=function(v){if(l(v)||(v=m(v)),v.isZero())throw Error("division by zero");if(i){if(!this.unsigned&&this.high===-2147483648&&v.low===-1&&v.high===-1)return this;var R=(this.unsigned?i.div_u:i.div_s)(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?A:O;var H,L,V;if(this.unsigned){if(v.unsigned||(v=v.toUnsigned()),v.gt(this))return A;if(v.gt(this.shru(1)))return I;V=A}else{if(this.eq(q)){if(v.eq(P)||v.eq(z))return q;if(v.eq(q))return P;var K=this.shr(1);return H=K.div(v).shl(1),H.eq(O)?v.isNegative()?P:z:(L=this.sub(v.mul(H)),V=H.add(L.div(v)),V)}else if(v.eq(q))return this.unsigned?A:O;if(this.isNegative())return v.isNegative()?this.neg().div(v.neg()):this.neg().div(v).neg();if(v.isNegative())return this.div(v.neg()).neg();V=O}for(L=this;L.gte(v);){H=Math.max(1,Math.floor(L.toNumber()/v.toNumber()));for(var B=Math.ceil(Math.log(H)/Math.LN2),te=B<=48?1:p(2,B-48),Y=o(H),N=Y.mul(v);N.isNegative()||N.gt(L);)H-=te,Y=o(H,this.unsigned),N=Y.mul(v);Y.isZero()&&(Y=P),V=V.add(Y),L=L.sub(N)}return V},C.div=C.divide,C.modulo=function(v){if(l(v)||(v=m(v)),i){var R=(this.unsigned?i.rem_u:i.rem_s)(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}return this.sub(this.div(v).mul(v))},C.mod=C.modulo,C.rem=C.modulo,C.not=function(){return a(~this.low,~this.high,this.unsigned)},C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},C.clz=C.countLeadingZeros,C.countTrailingZeros=function(){return this.low?d(this.low):d(this.high)+32},C.ctz=C.countTrailingZeros,C.and=function(v){return l(v)||(v=m(v)),a(this.low&v.low,this.high&v.high,this.unsigned)},C.or=function(v){return l(v)||(v=m(v)),a(this.low|v.low,this.high|v.high,this.unsigned)},C.xor=function(v){return l(v)||(v=m(v)),a(this.low^v.low,this.high^v.high,this.unsigned)},C.shiftLeft=function(v){return l(v)&&(v=v.toInt()),(v&=63)===0?this:v<32?a(this.low<>>32-v,this.unsigned):a(0,this.low<>>v|this.high<<32-v,this.high>>v,this.unsigned):a(this.high>>v-32,this.high>=0?0:-1,this.unsigned)},C.shr=C.shiftRight,C.shiftRightUnsigned=function(v){return l(v)&&(v=v.toInt()),(v&=63)===0?this:v<32?a(this.low>>>v|this.high<<32-v,this.high>>>v,this.unsigned):v===32?a(this.high,0,this.unsigned):a(this.high>>>v-32,0,this.unsigned)},C.shru=C.shiftRightUnsigned,C.shr_u=C.shiftRightUnsigned,C.rotateLeft=function(v){var R;return l(v)&&(v=v.toInt()),(v&=63)===0?this:v===32?a(this.high,this.low,this.unsigned):v<32?(R=32-v,a(this.low<>>R,this.high<>>R,this.unsigned)):(v-=32,R=32-v,a(this.high<>>R,this.low<>>R,this.unsigned))},C.rotl=C.rotateLeft,C.rotateRight=function(v){var R;return l(v)&&(v=v.toInt()),(v&=63)===0?this:v===32?a(this.high,this.low,this.unsigned):v<32?(R=32-v,a(this.high<>>v,this.low<>>v,this.unsigned)):(v-=32,R=32-v,a(this.low<>>v,this.high<>>v,this.unsigned))},C.rotr=C.rotateRight,C.toSigned=function(){return this.unsigned?a(this.low,this.high,!1):this},C.toUnsigned=function(){return this.unsigned?this:a(this.low,this.high,!0)},C.toBytes=function(v){return v?this.toBytesLE():this.toBytesBE()},C.toBytesLE=function(){var v=this.high,R=this.low;return[R&255,R>>>8&255,R>>>16&255,R>>>24,v&255,v>>>8&255,v>>>16&255,v>>>24]},C.toBytesBE=function(){var v=this.high,R=this.low;return[v>>>24,v>>>16&255,v>>>8&255,v&255,R>>>24,R>>>16&255,R>>>8&255,R&255]},u.fromBytes=function(v,R,H){return H?u.fromBytesLE(v,R):u.fromBytesBE(v,R)},u.fromBytesLE=function(v,R){return new u(v[0]|v[1]<<8|v[2]<<16|v[3]<<24,v[4]|v[5]<<8|v[6]<<16|v[7]<<24,R)},u.fromBytesBE=function(v,R){return new u(v[4]<<24|v[5]<<16|v[6]<<8|v[7],v[0]<<24|v[1]<<16|v[2]<<8|v[3],R)},typeof BigInt=="function"&&(u.fromBigInt=function(v,R){var H=Number(BigInt.asIntN(32,v)),L=Number(BigInt.asIntN(32,v>>BigInt(32)));return a(H,L,R)},u.fromValue=function(v,R){return typeof v=="bigint"?u.fromBigInt(v,R):m(v,R)},C.toBigInt=function(){var v=BigInt(this.low>>>0),R=BigInt(this.unsigned?this.high>>>0:this.high);return R<{"use strict";var t=e;t.asPromise=yO(),t.base64=wO(),t.EventEmitter=_O(),t.float=vO(),t.inquire=xO(),t.utf8=$O(),t.pool=TO(),t.LongBits=SO();function n(l){return l==="__proto__"||l==="prototype"||l==="constructor"}t.isUnsafeProperty=n,t.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node),t.global=t.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||e,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(l){return typeof l=="number"&&isFinite(l)&&Math.floor(l)===l},t.isString=function(l){return typeof l=="string"||l instanceof String},t.isObject=function(l){return l&&typeof l=="object"},t.isset=t.isSet=function(l,d){var c=l[d];return c!=null&&Object.hasOwnProperty.call(l,d)?typeof c!="object"||(Array.isArray(c)?c.length:Object.keys(c).length)>0:!1},t.Buffer=(function(){try{var l=t.global.Buffer;return l.prototype.utf8Write?l:null}catch{return null}})(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(l){return typeof l=="number"?t.Buffer?t._Buffer_allocUnsafe(l):new t.Array(l):t.Buffer?t._Buffer_from(l):typeof Uint8Array>"u"?l:new Uint8Array(l)},t.Array=typeof Uint8Array<"u"?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||(function(){try{var l=IO();return l&&l.isLong?l:null}catch{return null}})(),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(l){return l?t.LongBits.from(l).toHash():t.LongBits.zeroHash},t.longFromHash=function(l,d){var c=t.LongBits.fromHash(l);return t.Long?t.Long.fromBits(c.lo,c.hi,d):c.toNumber(!!d)};function i(l){var d=typeof arguments[arguments.length-1]=="boolean",c=d?arguments.length-1:arguments.length;d=d&&arguments[arguments.length-1];for(var s=1;s-1;--r)if(d[s[r]]===1&&this[s[r]]!==void 0&&this[s[r]]!==null)return s[r]}},t.oneOfSetter=function(l){return function(d){for(var c=0;c{"use strict";t.exports=o;var n=_n(),i,u=n.LongBits,l=n.base64,d=n.utf8;function c(y,T,S){this.fn=y,this.len=T,this.next=void 0,this.val=S}function s(){}function r(y){this.head=y.head,this.tail=y.tail,this.len=y.len,this.next=y.states}function o(){this.len=0,this.head=new c(s,0,0),this.tail=this.head,this.states=null}var a=function(){return n.Buffer?function(){return(o.create=function(){return new i})()}:function(){return new o}};o.create=a(),o.alloc=function(y){return new n.Array(y)},n.Array!==Array&&(o.alloc=n.pool(o.alloc,n.Array.prototype.subarray)),o.prototype._push=function(y,T,S){return this.tail=this.tail.next=new c(y,T,S),this.len+=T,this};function p(y,T,S){T[S]=y&255}function h(y,T,S){for(;y>127;)T[S++]=y&127|128,y>>>=7;T[S]=y}function m(y,T){this.len=y,this.next=void 0,this.val=T}m.prototype=Object.create(c.prototype),m.prototype.fn=h,o.prototype.uint32=function(y){return this.len+=(this.tail=this.tail.next=new m((y=y>>>0)<128?1:y<16384?2:y<2097152?3:y<268435456?4:5,y)).len,this},o.prototype.int32=function(y){return(y|=0)<0?this._push(g,10,u.fromNumber(y)):this.uint32(y)},o.prototype.sint32=function(y){return this.uint32((y<<1^y>>31)>>>0)};function g(y,T,S){for(var O=y.lo,A=y.hi;A;)T[S++]=O&127|128,O=(O>>>7|A<<25)>>>0,A>>>=7;for(;O>127;)T[S++]=O&127|128,O=O>>>7;T[S++]=O}o.prototype.uint64=function(y){var T=u.from(y);return this._push(g,T.length(),T)},o.prototype.int64=o.prototype.uint64,o.prototype.sint64=function(y){var T=u.from(y).zzEncode();return this._push(g,T.length(),T)},o.prototype.bool=function(y){return this._push(p,1,y?1:0)};function _(y,T,S){T[S]=y&255,T[S+1]=y>>>8&255,T[S+2]=y>>>16&255,T[S+3]=y>>>24}o.prototype.fixed32=function(y){return this._push(_,4,y>>>0)},o.prototype.sfixed32=o.prototype.fixed32,o.prototype.fixed64=function(y){var T=u.from(y);return this._push(_,4,T.lo)._push(_,4,T.hi)},o.prototype.sfixed64=o.prototype.fixed64,o.prototype.float=function(y){return this._push(n.float.writeFloatLE,4,y)},o.prototype.double=function(y){return this._push(n.float.writeDoubleLE,8,y)};var w=n.Array.prototype.set?function(y,T,S){T.set(y,S)}:function(y,T,S){for(var O=0;O>>0;if(!T)return this._push(p,1,0);if(n.isString(y)){var S=o.alloc(T=l.length(y));l.decode(y,S,0),y=S}return this.uint32(T)._push(w,T,y)},o.prototype.string=function(y){var T=d.length(y);return T?this.uint32(T)._push(d.write,T,y):this._push(p,1,0)},o.prototype.fork=function(){return this.states=new r(this),this.head=this.tail=new c(s,0,0),this.len=0,this},o.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(s,0,0),this.len=0),this},o.prototype.ldelim=function(){var y=this.head,T=this.tail,S=this.len;return this.reset().uint32(S),S&&(this.tail.next=y.next,this.tail=T,this.len+=S),this},o.prototype.finish=function(){for(var y=this.head.next,T=this.constructor.alloc(this.len),S=0;y;)y.fn(y.val,T,S),S+=y.len,y=y.next;return T},o._configure=function(y){i=y,o.create=a(),i._configure()}}),OO=ae((e,t)=>{"use strict";t.exports=u;var n=yw();(u.prototype=Object.create(n.prototype)).constructor=u;var i=_n();function u(){n.call(this)}u._configure=function(){u.alloc=i._Buffer_allocUnsafe,u.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&i.Buffer.prototype.set.name==="set"?function(d,c,s){c.set(d,s)}:function(d,c,s){if(d.copy)d.copy(c,s,0,d.length);else for(var r=0;r>>0;return this.uint32(c),c&&this._push(u.writeBytesBuffer,c,d),this};function l(d,c,s){d.length<40?i.utf8.write(d,c,s):c.utf8Write?c.utf8Write(d,s):c.write(d,s)}u.prototype.string=function(d){var c=i.Buffer.byteLength(d);return this.uint32(c),c&&this._push(l,c,d),this},u._configure()}),ww=ae((e,t)=>{"use strict";t.exports=c;var n=_n(),i,u=n.LongBits,l=n.utf8;function d(h,m){return RangeError("index out of range: "+h.pos+" + "+(m||1)+" > "+h.len)}function c(h){this.buf=h,this.pos=0,this.len=h.length}var s=typeof Uint8Array<"u"?function(h){if(h instanceof Uint8Array||Array.isArray(h))return new c(h);throw Error("illegal buffer")}:function(h){if(Array.isArray(h))return new c(h);throw Error("illegal buffer")},r=function(){return n.Buffer?function(h){return(c.create=function(m){return n.Buffer.isBuffer(m)?new i(m):s(m)})(h)}:s};c.create=r(),c.prototype._slice=n.Array.prototype.subarray||n.Array.prototype.slice,c.prototype.uint32=(function(){var h=4294967295;return function(){if(h=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(h=(h|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return h;if((this.pos+=5)>this.len)throw this.pos=this.len,d(this,10);return h}})(),c.prototype.int32=function(){return this.uint32()|0},c.prototype.sint32=function(){var h=this.uint32();return h>>>1^-(h&1)|0};function o(){var h=new u(0,0),m=0;if(this.len-this.pos>4){for(;m<4;++m)if(h.lo=(h.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h;if(h.lo=(h.lo|(this.buf[this.pos]&127)<<28)>>>0,h.hi=(h.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return h;m=0}else{for(;m<3;++m){if(this.pos>=this.len)throw d(this);if(h.lo=(h.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}return h.lo=(h.lo|(this.buf[this.pos++]&127)<>>0,h}if(this.len-this.pos>4){for(;m<5;++m)if(h.hi=(h.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}else for(;m<5;++m){if(this.pos>=this.len)throw d(this);if(h.hi=(h.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}throw Error("invalid varint encoding")}c.prototype.bool=function(){return this.uint32()!==0};function a(h,m){return(h[m-4]|h[m-3]<<8|h[m-2]<<16|h[m-1]<<24)>>>0}c.prototype.fixed32=function(){if(this.pos+4>this.len)throw d(this,4);return a(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw d(this,4);return a(this.buf,this.pos+=4)|0};function p(){if(this.pos+8>this.len)throw d(this,8);return new u(a(this.buf,this.pos+=4),a(this.buf,this.pos+=4))}c.prototype.float=function(){if(this.pos+4>this.len)throw d(this,4);var h=n.float.readFloatLE(this.buf,this.pos);return this.pos+=4,h},c.prototype.double=function(){if(this.pos+8>this.len)throw d(this,4);var h=n.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,h},c.prototype.bytes=function(){var h=this.uint32(),m=this.pos,g=this.pos+h;if(g>this.len)throw d(this,h);if(this.pos+=h,Array.isArray(this.buf))return this.buf.slice(m,g);if(m===g){var _=n.Buffer;return _?_.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,m,g)},c.prototype.string=function(){var h=this.bytes();return l.read(h,0,h.length)},c.prototype.skip=function(h){if(typeof h=="number"){if(this.pos+h>this.len)throw d(this,h);this.pos+=h}else do if(this.pos>=this.len)throw d(this);while(this.buf[this.pos++]&128);return this},c.recursionLimit=n.recursionLimit,c.prototype.skipType=function(h,m){if(m===void 0&&(m=0),m>c.recursionLimit)throw Error("maximum nesting depth exceeded");switch(h){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(h=this.uint32()&7)!==4;)this.skipType(h,m+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+h+" at offset "+this.pos)}return this},c._configure=function(h){i=h,c.create=r(),i._configure();var m=n.Long?"toLong":"toNumber";n.merge(c.prototype,{int64:function(){return o.call(this)[m](!1)},uint64:function(){return o.call(this)[m](!0)},sint64:function(){return o.call(this).zzDecode()[m](!1)},fixed64:function(){return p.call(this)[m](!0)},sfixed64:function(){return p.call(this)[m](!1)}})}}),EO=ae((e,t)=>{"use strict";t.exports=u;var n=ww();(u.prototype=Object.create(n.prototype)).constructor=u;var i=_n();function u(l){n.call(this,l)}u._configure=function(){i.Buffer&&(u.prototype._slice=i.Buffer.prototype.slice)},u.prototype.string=function(){var l=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+l,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+l,this.len))},u._configure()}),AO=ae((e,t)=>{"use strict";t.exports=i;var n=_n();(i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i;function i(u,l,d){if(typeof u!="function")throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=u,this.requestDelimited=!!l,this.responseDelimited=!!d}i.prototype.rpcCall=function u(l,d,c,s,r){if(!s)throw TypeError("request must be specified");var o=this;if(!r)return n.asPromise(u,o,l,d,c,s);if(!o.rpcImpl){setTimeout(function(){r(Error("already ended"))},0);return}try{return o.rpcImpl(l,d[o.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(a,p){if(a)return o.emit("error",a,l),r(a);if(p===null){o.end(!0);return}if(!(p instanceof c))try{p=c[o.responseDelimited?"decodeDelimited":"decode"](p)}catch(h){return o.emit("error",h,l),r(h)}return o.emit("data",p,l),r(null,p)})}catch(a){o.emit("error",a,l),setTimeout(function(){r(a)},0);return}},i.prototype.end=function(u){return this.rpcImpl&&(u||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}}),kO=ae(e=>{"use strict";var t=e;t.Service=AO()}),PO=ae((e,t)=>{"use strict";t.exports=Object.create(null)}),CO=ae(e=>{"use strict";var t=e;t.build="minimal",t.Writer=yw(),t.BufferWriter=OO(),t.Reader=ww(),t.BufferReader=EO(),t.util=_n(),t.rpc=kO(),t.roots=PO(),t.configure=n;function n(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}n()}),RO=ae((e,t)=>{"use strict";t.exports=CO()}),Ni=ae((e,t)=>{"use strict";var n=RO(),i=n.Reader,u=n.Writer,l=n.util,d=n.roots.default||(n.roots.default={});d.onnx=(function(){var c={};return c.Version=(function(){var s={},r=Object.create(s);return r[s[0]="_START_VERSION"]=0,r[s[1]="IR_VERSION_2017_10_10"]=1,r[s[2]="IR_VERSION_2017_10_30"]=2,r[s[3]="IR_VERSION_2017_11_3"]=3,r[s[4]="IR_VERSION_2019_1_22"]=4,r[s[5]="IR_VERSION_2019_3_18"]=5,r[s[6]="IR_VERSION_2019_9_19"]=6,r[s[7]="IR_VERSION_2020_5_8"]=7,r[s[8]="IR_VERSION_2021_7_30"]=8,r[s[9]="IR_VERSION"]=9,r})(),c.AttributeProto=(function(){function s(r){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparseTensors=[],this.typeProtos=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.name=r.string();break}case 21:{p.refAttrName=r.string();break}case 13:{p.docString=r.string();break}case 20:{p.type=r.int32();break}case 2:{p.f=r.float();break}case 3:{p.i=r.int64();break}case 4:{p.s=r.bytes();break}case 5:{p.t=d.onnx.TensorProto.decode(r,r.uint32());break}case 6:{p.g=d.onnx.GraphProto.decode(r,r.uint32());break}case 22:{p.sparseTensor=d.onnx.SparseTensorProto.decode(r,r.uint32());break}case 14:{p.tp=d.onnx.TypeProto.decode(r,r.uint32());break}case 7:{if(p.floats&&p.floats.length||(p.floats=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.i.high>>>0).toNumber())),r.s!=null&&(typeof r.s=="string"?l.base64.decode(r.s,o.s=l.newBuffer(l.base64.length(r.s)),0):r.s.length>=0&&(o.s=r.s)),r.t!=null){if(typeof r.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");o.t=d.onnx.TensorProto.fromObject(r.t)}if(r.g!=null){if(typeof r.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");o.g=d.onnx.GraphProto.fromObject(r.g)}if(r.sparseTensor!=null){if(typeof r.sparseTensor!="object")throw TypeError(".onnx.AttributeProto.sparseTensor: object expected");o.sparseTensor=d.onnx.SparseTensorProto.fromObject(r.sparseTensor)}if(r.tp!=null){if(typeof r.tp!="object")throw TypeError(".onnx.AttributeProto.tp: object expected");o.tp=d.onnx.TypeProto.fromObject(r.tp)}if(r.floats){if(!Array.isArray(r.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");o.floats=[];for(var a=0;a>>0,r.ints[a].high>>>0).toNumber())}if(r.strings){if(!Array.isArray(r.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");o.strings=[];for(var a=0;a=0&&(o.strings[a]=r.strings[a])}if(r.tensors){if(!Array.isArray(r.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");o.tensors=[];for(var a=0;a>>0,r.i.high>>>0).toNumber():r.i),r.s!=null&&r.hasOwnProperty("s")&&(a.s=o.bytes===String?l.base64.encode(r.s,0,r.s.length):o.bytes===Array?Array.prototype.slice.call(r.s):r.s),r.t!=null&&r.hasOwnProperty("t")&&(a.t=d.onnx.TensorProto.toObject(r.t,o)),r.g!=null&&r.hasOwnProperty("g")&&(a.g=d.onnx.GraphProto.toObject(r.g,o)),r.floats&&r.floats.length){a.floats=[];for(var h=0;h>>0,r.ints[h].high>>>0).toNumber():r.ints[h]}if(r.strings&&r.strings.length){a.strings=[];for(var h=0;h>>3){case 1:{p.name=r.string();break}case 2:{p.type=d.onnx.TypeProto.decode(r,r.uint32());break}case 3:{p.docString=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!l.isString(r.name))return"name: string expected";if(r.type!=null&&r.hasOwnProperty("type")){var o=d.onnx.TypeProto.verify(r.type);if(o)return"type."+o}return r.docString!=null&&r.hasOwnProperty("docString")&&!l.isString(r.docString)?"docString: string expected":null},s.fromObject=function(r){if(r instanceof d.onnx.ValueInfoProto)return r;var o=new d.onnx.ValueInfoProto;if(r.name!=null&&(o.name=String(r.name)),r.type!=null){if(typeof r.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");o.type=d.onnx.TypeProto.fromObject(r.type)}return r.docString!=null&&(o.docString=String(r.docString)),o},s.toObject=function(r,o){o||(o={});var a={};return o.defaults&&(a.name="",a.type=null,a.docString=""),r.name!=null&&r.hasOwnProperty("name")&&(a.name=r.name),r.type!=null&&r.hasOwnProperty("type")&&(a.type=d.onnx.TypeProto.toObject(r.type,o)),r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.ValueInfoProto"},s})(),c.NodeProto=(function(){function s(r){if(this.input=[],this.output=[],this.attribute=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.input&&p.input.length||(p.input=[]),p.input.push(r.string());break}case 2:{p.output&&p.output.length||(p.output=[]),p.output.push(r.string());break}case 3:{p.name=r.string();break}case 4:{p.opType=r.string();break}case 7:{p.domain=r.string();break}case 5:{p.attribute&&p.attribute.length||(p.attribute=[]),p.attribute.push(d.onnx.AttributeProto.decode(r,r.uint32()));break}case 6:{p.docString=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var o=0;o>>3){case 1:{p.initialization=d.onnx.GraphProto.decode(r,r.uint32());break}case 2:{p.algorithm=d.onnx.GraphProto.decode(r,r.uint32());break}case 3:{p.initializationBinding&&p.initializationBinding.length||(p.initializationBinding=[]),p.initializationBinding.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 4:{p.updateBinding&&p.updateBinding.length||(p.updateBinding=[]),p.updateBinding.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.initialization!=null&&r.hasOwnProperty("initialization")){var o=d.onnx.GraphProto.verify(r.initialization);if(o)return"initialization."+o}if(r.algorithm!=null&&r.hasOwnProperty("algorithm")){var o=d.onnx.GraphProto.verify(r.algorithm);if(o)return"algorithm."+o}if(r.initializationBinding!=null&&r.hasOwnProperty("initializationBinding")){if(!Array.isArray(r.initializationBinding))return"initializationBinding: array expected";for(var a=0;a>>3){case 1:{p.irVersion=r.int64();break}case 8:{p.opsetImport&&p.opsetImport.length||(p.opsetImport=[]),p.opsetImport.push(d.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 2:{p.producerName=r.string();break}case 3:{p.producerVersion=r.string();break}case 4:{p.domain=r.string();break}case 5:{p.modelVersion=r.int64();break}case 6:{p.docString=r.string();break}case 7:{p.graph=d.onnx.GraphProto.decode(r,r.uint32());break}case 14:{p.metadataProps&&p.metadataProps.length||(p.metadataProps=[]),p.metadataProps.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 20:{p.trainingInfo&&p.trainingInfo.length||(p.trainingInfo=[]),p.trainingInfo.push(d.onnx.TrainingInfoProto.decode(r,r.uint32()));break}case 25:{p.functions&&p.functions.length||(p.functions=[]),p.functions.push(d.onnx.FunctionProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.irVersion!=null&&r.hasOwnProperty("irVersion")&&!l.isInteger(r.irVersion)&&!(r.irVersion&&l.isInteger(r.irVersion.low)&&l.isInteger(r.irVersion.high)))return"irVersion: integer|Long expected";if(r.opsetImport!=null&&r.hasOwnProperty("opsetImport")){if(!Array.isArray(r.opsetImport))return"opsetImport: array expected";for(var o=0;o>>0,r.irVersion.high>>>0).toNumber())),r.opsetImport){if(!Array.isArray(r.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");o.opsetImport=[];for(var a=0;a>>0,r.modelVersion.high>>>0).toNumber())),r.docString!=null&&(o.docString=String(r.docString)),r.graph!=null){if(typeof r.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");o.graph=d.onnx.GraphProto.fromObject(r.graph)}if(r.metadataProps){if(!Array.isArray(r.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");o.metadataProps=[];for(var a=0;a>>0,r.irVersion.high>>>0).toNumber():r.irVersion),r.producerName!=null&&r.hasOwnProperty("producerName")&&(a.producerName=r.producerName),r.producerVersion!=null&&r.hasOwnProperty("producerVersion")&&(a.producerVersion=r.producerVersion),r.domain!=null&&r.hasOwnProperty("domain")&&(a.domain=r.domain),r.modelVersion!=null&&r.hasOwnProperty("modelVersion")&&(typeof r.modelVersion=="number"?a.modelVersion=o.longs===String?String(r.modelVersion):r.modelVersion:a.modelVersion=o.longs===String?l.Long.prototype.toString.call(r.modelVersion):o.longs===Number?new l.LongBits(r.modelVersion.low>>>0,r.modelVersion.high>>>0).toNumber():r.modelVersion),r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),r.graph!=null&&r.hasOwnProperty("graph")&&(a.graph=d.onnx.GraphProto.toObject(r.graph,o)),r.opsetImport&&r.opsetImport.length){a.opsetImport=[];for(var h=0;h>>3){case 1:{p.key=r.string();break}case 2:{p.value=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){return typeof r!="object"||r===null?"object expected":r.key!=null&&r.hasOwnProperty("key")&&!l.isString(r.key)?"key: string expected":r.value!=null&&r.hasOwnProperty("value")&&!l.isString(r.value)?"value: string expected":null},s.fromObject=function(r){if(r instanceof d.onnx.StringStringEntryProto)return r;var o=new d.onnx.StringStringEntryProto;return r.key!=null&&(o.key=String(r.key)),r.value!=null&&(o.value=String(r.value)),o},s.toObject=function(r,o){o||(o={});var a={};return o.defaults&&(a.key="",a.value=""),r.key!=null&&r.hasOwnProperty("key")&&(a.key=r.key),r.value!=null&&r.hasOwnProperty("value")&&(a.value=r.value),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.StringStringEntryProto"},s})(),c.TensorAnnotation=(function(){function s(r){if(this.quantParameterTensorNames=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.tensorName=r.string();break}case 2:{p.quantParameterTensorNames&&p.quantParameterTensorNames.length||(p.quantParameterTensorNames=[]),p.quantParameterTensorNames.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.tensorName!=null&&r.hasOwnProperty("tensorName")&&!l.isString(r.tensorName))return"tensorName: string expected";if(r.quantParameterTensorNames!=null&&r.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(r.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var o=0;o>>3){case 1:{p.node&&p.node.length||(p.node=[]),p.node.push(d.onnx.NodeProto.decode(r,r.uint32()));break}case 2:{p.name=r.string();break}case 5:{p.initializer&&p.initializer.length||(p.initializer=[]),p.initializer.push(d.onnx.TensorProto.decode(r,r.uint32()));break}case 15:{p.sparseInitializer&&p.sparseInitializer.length||(p.sparseInitializer=[]),p.sparseInitializer.push(d.onnx.SparseTensorProto.decode(r,r.uint32()));break}case 10:{p.docString=r.string();break}case 11:{p.input&&p.input.length||(p.input=[]),p.input.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 12:{p.output&&p.output.length||(p.output=[]),p.output.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 13:{p.valueInfo&&p.valueInfo.length||(p.valueInfo=[]),p.valueInfo.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 14:{p.quantizationAnnotation&&p.quantizationAnnotation.length||(p.quantizationAnnotation=[]),p.quantizationAnnotation.push(d.onnx.TensorAnnotation.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.node!=null&&r.hasOwnProperty("node")){if(!Array.isArray(r.node))return"node: array expected";for(var o=0;o>>3){case 1:{if(p.dims&&p.dims.length||(p.dims=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[a].high>>>0).toNumber())}if(r.dataType!=null&&(o.dataType=r.dataType|0),r.segment!=null){if(typeof r.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");o.segment=d.onnx.TensorProto.Segment.fromObject(r.segment)}if(r.floatData){if(!Array.isArray(r.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");o.floatData=[];for(var a=0;a=0&&(o.stringData[a]=r.stringData[a])}if(r.int64Data){if(!Array.isArray(r.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");o.int64Data=[];for(var a=0;a>>0,r.int64Data[a].high>>>0).toNumber())}if(r.name!=null&&(o.name=String(r.name)),r.docString!=null&&(o.docString=String(r.docString)),r.rawData!=null&&(typeof r.rawData=="string"?l.base64.decode(r.rawData,o.rawData=l.newBuffer(l.base64.length(r.rawData)),0):r.rawData.length>=0&&(o.rawData=r.rawData)),r.externalData){if(!Array.isArray(r.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");o.externalData=[];for(var a=0;a>>0,r.uint64Data[a].high>>>0).toNumber(!0))}return o},s.toObject=function(r,o){o||(o={});var a={};if((o.arrays||o.defaults)&&(a.dims=[],a.floatData=[],a.int32Data=[],a.stringData=[],a.int64Data=[],a.doubleData=[],a.uint64Data=[],a.externalData=[]),o.defaults&&(a.dataType=0,a.segment=null,a.name="",o.bytes===String?a.rawData="":(a.rawData=[],o.bytes!==Array&&(a.rawData=l.newBuffer(a.rawData))),a.docString="",a.dataLocation=o.enums===String?"DEFAULT":0),r.dims&&r.dims.length){a.dims=[];for(var p=0;p>>0,r.dims[p].high>>>0).toNumber():r.dims[p]}if(r.dataType!=null&&r.hasOwnProperty("dataType")&&(a.dataType=r.dataType),r.segment!=null&&r.hasOwnProperty("segment")&&(a.segment=d.onnx.TensorProto.Segment.toObject(r.segment,o)),r.floatData&&r.floatData.length){a.floatData=[];for(var p=0;p>>0,r.int64Data[p].high>>>0).toNumber():r.int64Data[p]}if(r.name!=null&&r.hasOwnProperty("name")&&(a.name=r.name),r.rawData!=null&&r.hasOwnProperty("rawData")&&(a.rawData=o.bytes===String?l.base64.encode(r.rawData,0,r.rawData.length):o.bytes===Array?Array.prototype.slice.call(r.rawData):r.rawData),r.doubleData&&r.doubleData.length){a.doubleData=[];for(var p=0;p>>0,r.uint64Data[p].high>>>0).toNumber(!0):r.uint64Data[p]}if(r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),r.externalData&&r.externalData.length){a.externalData=[];for(var p=0;p>>3){case 1:{h.begin=o.int64();break}case 2:{h.end=o.int64();break}default:o.skipType(m&7);break}}return h},r.decodeDelimited=function(o){return o instanceof i||(o=new i(o)),this.decode(o,o.uint32())},r.verify=function(o){return typeof o!="object"||o===null?"object expected":o.begin!=null&&o.hasOwnProperty("begin")&&!l.isInteger(o.begin)&&!(o.begin&&l.isInteger(o.begin.low)&&l.isInteger(o.begin.high))?"begin: integer|Long expected":o.end!=null&&o.hasOwnProperty("end")&&!l.isInteger(o.end)&&!(o.end&&l.isInteger(o.end.low)&&l.isInteger(o.end.high))?"end: integer|Long expected":null},r.fromObject=function(o){if(o instanceof d.onnx.TensorProto.Segment)return o;var a=new d.onnx.TensorProto.Segment;return o.begin!=null&&(l.Long?(a.begin=l.Long.fromValue(o.begin)).unsigned=!1:typeof o.begin=="string"?a.begin=parseInt(o.begin,10):typeof o.begin=="number"?a.begin=o.begin:typeof o.begin=="object"&&(a.begin=new l.LongBits(o.begin.low>>>0,o.begin.high>>>0).toNumber())),o.end!=null&&(l.Long?(a.end=l.Long.fromValue(o.end)).unsigned=!1:typeof o.end=="string"?a.end=parseInt(o.end,10):typeof o.end=="number"?a.end=o.end:typeof o.end=="object"&&(a.end=new l.LongBits(o.end.low>>>0,o.end.high>>>0).toNumber())),a},r.toObject=function(o,a){a||(a={});var p={};if(a.defaults){if(l.Long){var h=new l.Long(0,0,!1);p.begin=a.longs===String?h.toString():a.longs===Number?h.toNumber():h}else p.begin=a.longs===String?"0":0;if(l.Long){var h=new l.Long(0,0,!1);p.end=a.longs===String?h.toString():a.longs===Number?h.toNumber():h}else p.end=a.longs===String?"0":0}return o.begin!=null&&o.hasOwnProperty("begin")&&(typeof o.begin=="number"?p.begin=a.longs===String?String(o.begin):o.begin:p.begin=a.longs===String?l.Long.prototype.toString.call(o.begin):a.longs===Number?new l.LongBits(o.begin.low>>>0,o.begin.high>>>0).toNumber():o.begin),o.end!=null&&o.hasOwnProperty("end")&&(typeof o.end=="number"?p.end=a.longs===String?String(o.end):o.end:p.end=a.longs===String?l.Long.prototype.toString.call(o.end):a.longs===Number?new l.LongBits(o.end.low>>>0,o.end.high>>>0).toNumber():o.end),p},r.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},r.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TensorProto.Segment"},r})(),s.DataLocation=(function(){var r={},o=Object.create(r);return o[r[0]="DEFAULT"]=0,o[r[1]="EXTERNAL"]=1,o})(),s})(),c.SparseTensorProto=(function(){function s(r){if(this.dims=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.values=d.onnx.TensorProto.decode(r,r.uint32());break}case 2:{p.indices=d.onnx.TensorProto.decode(r,r.uint32());break}case 3:{if(p.dims&&p.dims.length||(p.dims=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[a].high>>>0).toNumber())}return o},s.toObject=function(r,o){o||(o={});var a={};if((o.arrays||o.defaults)&&(a.dims=[]),o.defaults&&(a.values=null,a.indices=null),r.values!=null&&r.hasOwnProperty("values")&&(a.values=d.onnx.TensorProto.toObject(r.values,o)),r.indices!=null&&r.hasOwnProperty("indices")&&(a.indices=d.onnx.TensorProto.toObject(r.indices,o)),r.dims&&r.dims.length){a.dims=[];for(var p=0;p>>0,r.dims[p].high>>>0).toNumber():r.dims[p]}return a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.SparseTensorProto"},s})(),c.TensorShapeProto=(function(){function s(r){if(this.dim=[],r)for(var o=Object.keys(r),a=0;a>>3===1?(p.dim&&p.dim.length||(p.dim=[]),p.dim.push(d.onnx.TensorShapeProto.Dimension.decode(r,r.uint32()))):r.skipType(h&7)}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.dim!=null&&r.hasOwnProperty("dim")){if(!Array.isArray(r.dim))return"dim: array expected";for(var o=0;o>>3){case 1:{m.dimValue=a.int64();break}case 2:{m.dimParam=a.string();break}case 3:{m.denotation=a.string();break}default:a.skipType(g&7);break}}return m},r.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},r.verify=function(a){if(typeof a!="object"||a===null)return"object expected";var p={};if(a.dimValue!=null&&a.hasOwnProperty("dimValue")&&(p.value=1,!l.isInteger(a.dimValue)&&!(a.dimValue&&l.isInteger(a.dimValue.low)&&l.isInteger(a.dimValue.high))))return"dimValue: integer|Long expected";if(a.dimParam!=null&&a.hasOwnProperty("dimParam")){if(p.value===1)return"value: multiple values";if(p.value=1,!l.isString(a.dimParam))return"dimParam: string expected"}return a.denotation!=null&&a.hasOwnProperty("denotation")&&!l.isString(a.denotation)?"denotation: string expected":null},r.fromObject=function(a){if(a instanceof d.onnx.TensorShapeProto.Dimension)return a;var p=new d.onnx.TensorShapeProto.Dimension;return a.dimValue!=null&&(l.Long?(p.dimValue=l.Long.fromValue(a.dimValue)).unsigned=!1:typeof a.dimValue=="string"?p.dimValue=parseInt(a.dimValue,10):typeof a.dimValue=="number"?p.dimValue=a.dimValue:typeof a.dimValue=="object"&&(p.dimValue=new l.LongBits(a.dimValue.low>>>0,a.dimValue.high>>>0).toNumber())),a.dimParam!=null&&(p.dimParam=String(a.dimParam)),a.denotation!=null&&(p.denotation=String(a.denotation)),p},r.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.denotation=""),a.dimValue!=null&&a.hasOwnProperty("dimValue")&&(typeof a.dimValue=="number"?h.dimValue=p.longs===String?String(a.dimValue):a.dimValue:h.dimValue=p.longs===String?l.Long.prototype.toString.call(a.dimValue):p.longs===Number?new l.LongBits(a.dimValue.low>>>0,a.dimValue.high>>>0).toNumber():a.dimValue,p.oneofs&&(h.value="dimValue")),a.dimParam!=null&&a.hasOwnProperty("dimParam")&&(h.dimParam=a.dimParam,p.oneofs&&(h.value="dimParam")),a.denotation!=null&&a.hasOwnProperty("denotation")&&(h.denotation=a.denotation),h},r.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},r.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TensorShapeProto.Dimension"},r})(),s})(),c.TypeProto=(function(){function s(o){if(o)for(var a=Object.keys(o),p=0;p>>3){case 1:{h.tensorType=d.onnx.TypeProto.Tensor.decode(o,o.uint32());break}case 4:{h.sequenceType=d.onnx.TypeProto.Sequence.decode(o,o.uint32());break}case 5:{h.mapType=d.onnx.TypeProto.Map.decode(o,o.uint32());break}case 9:{h.optionalType=d.onnx.TypeProto.Optional.decode(o,o.uint32());break}case 8:{h.sparseTensorType=d.onnx.TypeProto.SparseTensor.decode(o,o.uint32());break}case 6:{h.denotation=o.string();break}default:o.skipType(m&7);break}}return h},s.decodeDelimited=function(o){return o instanceof i||(o=new i(o)),this.decode(o,o.uint32())},s.verify=function(o){if(typeof o!="object"||o===null)return"object expected";var a={};if(o.tensorType!=null&&o.hasOwnProperty("tensorType")){a.value=1;{var p=d.onnx.TypeProto.Tensor.verify(o.tensorType);if(p)return"tensorType."+p}}if(o.sequenceType!=null&&o.hasOwnProperty("sequenceType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Sequence.verify(o.sequenceType);if(p)return"sequenceType."+p}}if(o.mapType!=null&&o.hasOwnProperty("mapType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Map.verify(o.mapType);if(p)return"mapType."+p}}if(o.optionalType!=null&&o.hasOwnProperty("optionalType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Optional.verify(o.optionalType);if(p)return"optionalType."+p}}if(o.sparseTensorType!=null&&o.hasOwnProperty("sparseTensorType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.SparseTensor.verify(o.sparseTensorType);if(p)return"sparseTensorType."+p}}return o.denotation!=null&&o.hasOwnProperty("denotation")&&!l.isString(o.denotation)?"denotation: string expected":null},s.fromObject=function(o){if(o instanceof d.onnx.TypeProto)return o;var a=new d.onnx.TypeProto;if(o.tensorType!=null){if(typeof o.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");a.tensorType=d.onnx.TypeProto.Tensor.fromObject(o.tensorType)}if(o.sequenceType!=null){if(typeof o.sequenceType!="object")throw TypeError(".onnx.TypeProto.sequenceType: object expected");a.sequenceType=d.onnx.TypeProto.Sequence.fromObject(o.sequenceType)}if(o.mapType!=null){if(typeof o.mapType!="object")throw TypeError(".onnx.TypeProto.mapType: object expected");a.mapType=d.onnx.TypeProto.Map.fromObject(o.mapType)}if(o.optionalType!=null){if(typeof o.optionalType!="object")throw TypeError(".onnx.TypeProto.optionalType: object expected");a.optionalType=d.onnx.TypeProto.Optional.fromObject(o.optionalType)}if(o.sparseTensorType!=null){if(typeof o.sparseTensorType!="object")throw TypeError(".onnx.TypeProto.sparseTensorType: object expected");a.sparseTensorType=d.onnx.TypeProto.SparseTensor.fromObject(o.sparseTensorType)}return o.denotation!=null&&(a.denotation=String(o.denotation)),a},s.toObject=function(o,a){a||(a={});var p={};return a.defaults&&(p.denotation=""),o.tensorType!=null&&o.hasOwnProperty("tensorType")&&(p.tensorType=d.onnx.TypeProto.Tensor.toObject(o.tensorType,a),a.oneofs&&(p.value="tensorType")),o.sequenceType!=null&&o.hasOwnProperty("sequenceType")&&(p.sequenceType=d.onnx.TypeProto.Sequence.toObject(o.sequenceType,a),a.oneofs&&(p.value="sequenceType")),o.mapType!=null&&o.hasOwnProperty("mapType")&&(p.mapType=d.onnx.TypeProto.Map.toObject(o.mapType,a),a.oneofs&&(p.value="mapType")),o.denotation!=null&&o.hasOwnProperty("denotation")&&(p.denotation=o.denotation),o.sparseTensorType!=null&&o.hasOwnProperty("sparseTensorType")&&(p.sparseTensorType=d.onnx.TypeProto.SparseTensor.toObject(o.sparseTensorType,a),a.oneofs&&(p.value="sparseTensorType")),o.optionalType!=null&&o.hasOwnProperty("optionalType")&&(p.optionalType=d.onnx.TypeProto.Optional.toObject(o.optionalType,a),a.oneofs&&(p.value="optionalType")),p},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TypeProto"},s.Tensor=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.elemType=a.int32();break}case 2:{m.shape=d.onnx.TensorShapeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")&&!l.isInteger(a.elemType))return"elemType: integer expected";if(a.shape!=null&&a.hasOwnProperty("shape")){var p=d.onnx.TensorShapeProto.verify(a.shape);if(p)return"shape."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Tensor)return a;var p=new d.onnx.TypeProto.Tensor;if(a.elemType!=null&&(p.elemType=a.elemType|0),a.shape!=null){if(typeof a.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");p.shape=d.onnx.TensorShapeProto.fromObject(a.shape)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=0,h.shape=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=a.elemType),a.shape!=null&&a.hasOwnProperty("shape")&&(h.shape=d.onnx.TensorShapeProto.toObject(a.shape,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Tensor"},o})(),s.Sequence=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3===1?m.elemType=d.onnx.TypeProto.decode(a,a.uint32()):a.skipType(g&7)}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")){var p=d.onnx.TypeProto.verify(a.elemType);if(p)return"elemType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Sequence)return a;var p=new d.onnx.TypeProto.Sequence;if(a.elemType!=null){if(typeof a.elemType!="object")throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected");p.elemType=d.onnx.TypeProto.fromObject(a.elemType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=d.onnx.TypeProto.toObject(a.elemType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Sequence"},o})(),s.Map=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.keyType=a.int32();break}case 2:{m.valueType=d.onnx.TypeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.keyType!=null&&a.hasOwnProperty("keyType")&&!l.isInteger(a.keyType))return"keyType: integer expected";if(a.valueType!=null&&a.hasOwnProperty("valueType")){var p=d.onnx.TypeProto.verify(a.valueType);if(p)return"valueType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Map)return a;var p=new d.onnx.TypeProto.Map;if(a.keyType!=null&&(p.keyType=a.keyType|0),a.valueType!=null){if(typeof a.valueType!="object")throw TypeError(".onnx.TypeProto.Map.valueType: object expected");p.valueType=d.onnx.TypeProto.fromObject(a.valueType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.keyType=0,h.valueType=null),a.keyType!=null&&a.hasOwnProperty("keyType")&&(h.keyType=a.keyType),a.valueType!=null&&a.hasOwnProperty("valueType")&&(h.valueType=d.onnx.TypeProto.toObject(a.valueType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Map"},o})(),s.Optional=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3===1?m.elemType=d.onnx.TypeProto.decode(a,a.uint32()):a.skipType(g&7)}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")){var p=d.onnx.TypeProto.verify(a.elemType);if(p)return"elemType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Optional)return a;var p=new d.onnx.TypeProto.Optional;if(a.elemType!=null){if(typeof a.elemType!="object")throw TypeError(".onnx.TypeProto.Optional.elemType: object expected");p.elemType=d.onnx.TypeProto.fromObject(a.elemType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=d.onnx.TypeProto.toObject(a.elemType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Optional"},o})(),s.SparseTensor=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.elemType=a.int32();break}case 2:{m.shape=d.onnx.TensorShapeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")&&!l.isInteger(a.elemType))return"elemType: integer expected";if(a.shape!=null&&a.hasOwnProperty("shape")){var p=d.onnx.TensorShapeProto.verify(a.shape);if(p)return"shape."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.SparseTensor)return a;var p=new d.onnx.TypeProto.SparseTensor;if(a.elemType!=null&&(p.elemType=a.elemType|0),a.shape!=null){if(typeof a.shape!="object")throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected");p.shape=d.onnx.TensorShapeProto.fromObject(a.shape)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=0,h.shape=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=a.elemType),a.shape!=null&&a.hasOwnProperty("shape")&&(h.shape=d.onnx.TensorShapeProto.toObject(a.shape,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.SparseTensor"},o})(),s})(),c.OperatorSetIdProto=(function(){function s(r){if(r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.domain=r.string();break}case 2:{p.version=r.int64();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){return typeof r!="object"||r===null?"object expected":r.domain!=null&&r.hasOwnProperty("domain")&&!l.isString(r.domain)?"domain: string expected":r.version!=null&&r.hasOwnProperty("version")&&!l.isInteger(r.version)&&!(r.version&&l.isInteger(r.version.low)&&l.isInteger(r.version.high))?"version: integer|Long expected":null},s.fromObject=function(r){if(r instanceof d.onnx.OperatorSetIdProto)return r;var o=new d.onnx.OperatorSetIdProto;return r.domain!=null&&(o.domain=String(r.domain)),r.version!=null&&(l.Long?(o.version=l.Long.fromValue(r.version)).unsigned=!1:typeof r.version=="string"?o.version=parseInt(r.version,10):typeof r.version=="number"?o.version=r.version:typeof r.version=="object"&&(o.version=new l.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber())),o},s.toObject=function(r,o){o||(o={});var a={};if(o.defaults)if(a.domain="",l.Long){var p=new l.Long(0,0,!1);a.version=o.longs===String?p.toString():o.longs===Number?p.toNumber():p}else a.version=o.longs===String?"0":0;return r.domain!=null&&r.hasOwnProperty("domain")&&(a.domain=r.domain),r.version!=null&&r.hasOwnProperty("version")&&(typeof r.version=="number"?a.version=o.longs===String?String(r.version):r.version:a.version=o.longs===String?l.Long.prototype.toString.call(r.version):o.longs===Number?new l.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber():r.version),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.OperatorSetIdProto"},s})(),c.OperatorStatus=(function(){var s={},r=Object.create(s);return r[s[0]="EXPERIMENTAL"]=0,r[s[1]="STABLE"]=1,r})(),c.FunctionProto=(function(){function s(r){if(this.input=[],this.output=[],this.attribute=[],this.attributeProto=[],this.node=[],this.opsetImport=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.name=r.string();break}case 4:{p.input&&p.input.length||(p.input=[]),p.input.push(r.string());break}case 5:{p.output&&p.output.length||(p.output=[]),p.output.push(r.string());break}case 6:{p.attribute&&p.attribute.length||(p.attribute=[]),p.attribute.push(r.string());break}case 11:{p.attributeProto&&p.attributeProto.length||(p.attributeProto=[]),p.attributeProto.push(d.onnx.AttributeProto.decode(r,r.uint32()));break}case 7:{p.node&&p.node.length||(p.node=[]),p.node.push(d.onnx.NodeProto.decode(r,r.uint32()));break}case 8:{p.docString=r.string();break}case 9:{p.opsetImport&&p.opsetImport.length||(p.opsetImport=[]),p.opsetImport.push(d.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 10:{p.domain=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!l.isString(r.name))return"name: string expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var o=0;o{"use strict";k0(),Le=be(Ni()),Ln(),_i=class{static arraysEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n1&&o>1)return;c[d-s]=Math.max(r,o)}return c}static index(t,n){let i=new Array(n.length);return vi.fillIndex(t,n,i),i}static fillIndex(t,n,i){let u=t.length-n.length;for(let l=0;l=0;y--)r[y]=_%d[y],_=Math.floor(_/d[y]);m||(vi.fillIndex(r,t.dims,o),p=t.get(o)),g||(vi.fillIndex(r,n.dims,a),h=n.get(a)),s.set(r,i(p,h))}}return s}}static isValidBroadcast(t,n){let i=t.length,u=n.length;if(i>u)return!1;for(let l=1;l<=i;l++)if(t[i-l]!==1&&t[i-l]!==n[u-l])return!1;return!0}static getBroadcastDims(t,n){let i=t.length,u=[];for(let l=0;l1&&c===1&&u.unshift(d)}return u}},_w=class{static getShapeOfGemmResult(e,t,n,i,u){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,d,c;t?(l=e[1],d=e[0]):(l=e[0],d=e[1]);let s=-1;if(i?(c=n[0],s=1):(c=n[1],s=0),n[s]!==d)throw new Error("dimension mismatch");if(l<=0||c<=0||d<=0)throw new Error("invalid shape specified");if(u&&!Qt.isValidBroadcast(u,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,d]}},wt=class ol{static tensorDataTypeFromProto(t){switch(t){case Le.onnx.TensorProto.DataType.INT8:return"int8";case Le.onnx.TensorProto.DataType.UINT8:return"uint8";case Le.onnx.TensorProto.DataType.BOOL:return"bool";case Le.onnx.TensorProto.DataType.INT16:return"int16";case Le.onnx.TensorProto.DataType.UINT16:return"uint16";case Le.onnx.TensorProto.DataType.INT32:return"int32";case Le.onnx.TensorProto.DataType.UINT32:return"uint32";case Le.onnx.TensorProto.DataType.FLOAT:return"float32";case Le.onnx.TensorProto.DataType.DOUBLE:return"float64";case Le.onnx.TensorProto.DataType.STRING:return"string";case Le.onnx.TensorProto.DataType.INT64:return"int32";case Le.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${Le.onnx.TensorProto.DataType[t]}`)}}static tensorDataTypeStringToEnum(t){switch(t){case"int8":return Le.onnx.TensorProto.DataType.INT8;case"uint8":return Le.onnx.TensorProto.DataType.UINT8;case"bool":return Le.onnx.TensorProto.DataType.BOOL;case"int16":return Le.onnx.TensorProto.DataType.INT16;case"uint16":return Le.onnx.TensorProto.DataType.UINT16;case"int32":return Le.onnx.TensorProto.DataType.INT32;case"uint32":return Le.onnx.TensorProto.DataType.UINT32;case"float32":return Le.onnx.TensorProto.DataType.FLOAT;case"float64":return Le.onnx.TensorProto.DataType.DOUBLE;case"string":return Le.onnx.TensorProto.DataType.STRING;case"int64":return Le.onnx.TensorProto.DataType.INT64;case"uint64":return Le.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${t}`)}}static tensorDimsFromProto(t){return t.map(n=>mn.isLong(n)?n.toNumber():n)}static tensorValueTypeFromProto(t){return{tensorType:ol.tensorDataTypeFromProto(t.elemType),shape:{dims:ol.tensorDimsFromProto(t.shape.dim.map(n=>n.dimValue))}}}static tensorDimsFromORTFormat(t){let n=[];for(let i=0;it.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Sr.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Sr.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let u=1;for(let l=n;l=0;--u)i[u]=i[u+1]*t[u+1];return i}static transpose(t){return t.slice().reverse()}static indicesToOffset(t,n,i){i===void 0&&(i=t.length);let u=0;for(let l=0;l=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n))}static incrementIndex(t,n,i){if(n.length===0||t.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(i===void 0)i=n.length;else if(i<=0||i>n.length)throw new Error("Incorrect axis to increment on");for(let u=i-1;u>=0&&(t[u]++,!(t[u]=t.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");u[s]=t[s]}else u[s]=n[s];d*=u[s]}}let c=Sr.size(t);if(l!==-1){if(c%d!==0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t}] Output shape: [${n}]`);u[l]=c/d}else if(d!==c)throw new Error("reshapedDims and originalDims don't have matching sizes");return u}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((u,l)=>u+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,u)=>i===n[u])}static validateDimsAndCalcSize(t){if(t.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let n=1;for(let i of t){if(!Number.isInteger(i))throw new TypeError(`Invalid shape: ${i} is not an integer`);if(i<0||i>2147483647)throw new TypeError(`Invalid shape: length ${i} is not allowed`);n*=i}return n}static flattenShape(t,n){n<0&&(n+=t.length);let i=t.reduce((l,d)=>l*d,1),u=t.slice(n).reduce((l,d)=>l*d,1);return[i/u,u]}static squeezeShape(t,n){let i=new Array;n=Sr.normalizeAxes(n,t.length);for(let u=0;u=0;if(l&&t[u]!==1)throw new Error("squeeze an axis of size different than 1");(n.length===0&&t[u]>1||n.length>0&&!l)&&i.push(t[u])}return i}static unsqueezeShape(t,n){let i=new Array(t.length+n.length);i.fill(0);for(let l=0;l=i.length)throw new Error("'axes' has an out of range axis");if(i[d]!==0)throw new Error("'axes' has a duplicate axis");i[d]=1}let u=0;for(let l=0;l=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c=i[c]||d[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,u,l,d){if(d){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let c=0;c=i+u&&(d-=1)),d}static adjustPadAndReturnShape(t,n,i,u,l,d,c,s,r=0){let o=i*(u-1)+1;if(s&&s!=="NOTSET")switch(s){case"VALID":return l[d]=0,l[c]=0,Ir.computeOutputSize(t-o,n,t,0,r);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let a=(Math.floor((t+n-1)/n)-1)*n+u-t;return l[d]=Math.floor(s==="SAME_LOWER"?(a+1)/2:a/2),l[c]=a-l[d],Ir.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}default:throw new Error("Unsupported AutoPad type")}else return Ir.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}},Ci=-34028234663852886e22,Ri=34028234663852886e22});function DO(e){switch(e){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${e}`)}}function ch(e){switch(e){case ve.onnx.TensorProto.DataType.UINT8:case ve.onnx.TensorProto.DataType.INT8:case ve.onnx.TensorProto.DataType.BOOL:return 1;case ve.onnx.TensorProto.DataType.UINT16:case ve.onnx.TensorProto.DataType.INT16:return 2;case ve.onnx.TensorProto.DataType.FLOAT:case ve.onnx.TensorProto.DataType.INT32:case ve.onnx.TensorProto.DataType.UINT32:return 4;case ve.onnx.TensorProto.DataType.INT64:case ve.onnx.TensorProto.DataType.DOUBLE:case ve.onnx.TensorProto.DataType.UINT64:return 8;default:throw new Error(`cannot calculate sizeof() on type ${ve.onnx.TensorProto.DataType[e]}`)}}function MO(e,t){return new(xw(t))(e)}function xw(e){switch(e){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw new Error("unspecified error")}}function sl(e,t){if(t===ve.onnx.TensorProto.DataType.INT64||t===No.TensorDataType.INT64){if(e.greaterThanOrEqual(2147483648)||e.lessThan(-2147483648))throw new TypeError("int64 is not supported")}else if(t===ve.onnx.TensorProto.DataType.UINT32||t===No.TensorDataType.UINT32||t===ve.onnx.TensorProto.DataType.UINT64||t===No.TensorDataType.UINT64){if(e.greaterThanOrEqual(4294967296)||e.lessThan(0))throw new TypeError("uint64 is not supported")}else throw new TypeError(`not a LONG type: ${ve.onnx.TensorProto.DataType[t]}`);return e.toNumber()}function ph(e,t,n){switch(t){case ve.onnx.TensorProto.DataType.BOOL:case ve.onnx.TensorProto.DataType.UINT8:return e.getUint8(n);case ve.onnx.TensorProto.DataType.INT8:return e.getInt8(n);case ve.onnx.TensorProto.DataType.UINT16:return e.getUint16(n,!0);case ve.onnx.TensorProto.DataType.INT16:return e.getInt16(n,!0);case ve.onnx.TensorProto.DataType.FLOAT:return e.getFloat32(n,!0);case ve.onnx.TensorProto.DataType.INT32:return e.getInt32(n,!0);case ve.onnx.TensorProto.DataType.UINT32:return e.getUint32(n,!0);case ve.onnx.TensorProto.DataType.INT64:return sl(mn.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!1),t);case ve.onnx.TensorProto.DataType.DOUBLE:return e.getFloat64(n,!0);case ve.onnx.TensorProto.DataType.UINT64:return sl(mn.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!0),t);default:throw new Error(`cannot read from DataView for type ${ve.onnx.TensorProto.DataType[t]}`)}}var hh,ve,xt,Ln=D(()=>{"use strict";hh=be(B3()),k0(),ns(),ve=be(Ni()),Me(),xt=class zo{constructor(t,n,i,u,l,d=hh.Guid.create()){this.dims=t,this.type=n,this.dataProvider=i,this.asyncDataProvider=u,this.cache=l,this.dataId=d,this.size=ye.validateDimsAndCalcSize(t);let c=this.size,s=i===void 0&&u===void 0&&l===void 0;if(l!==void 0&&l.length!==c)throw new RangeError("Input dims doesn't match data length.");if(n==="string"){if(l!==void 0&&(!Array.isArray(l)||!l.every(r=>typeof r=="string")))throw new TypeError("cache should be a string array");s&&(this.cache=new Array(c))}else{if(l!==void 0){let r=xw(n);if(!(l instanceof r))throw new TypeError(`cache should be type ${r.name}`)}if(s){let r=new ArrayBuffer(c*DO(n));this.cache=MO(r,n)}}}get data(){if(this.cache===void 0){let t=this.dataProvider(this.dataId);if(t.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=t}return this.cache}get stringData(){if(this.type!=="string")throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if(this.type!=="string")return this.data;throw new TypeError("type cannot be non-number (string)")}get(t){return this.data[ye.indicesToOffset(t,this.strides)]}set(t,n){this.data[ye.indicesToOffset(t,this.strides)]=n}async getData(){return this.cache===void 0&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=ye.computeStrides(this.dims)),this._strides}static fromProto(t){if(!t)throw new Error("cannot construct Value from an empty tensor");let n=wt.tensorDataTypeFromProto(t.dataType),i=wt.tensorDimsFromProto(t.dims),u=new zo(i,n);if(n==="string")t.stringData.forEach((l,d)=>{u.data[d]=nl(l)});else if(t.rawData&&typeof t.rawData.byteLength=="number"&&t.rawData.byteLength>0){let l=u.data,d=new DataView(t.rawData.buffer,t.rawData.byteOffset,t.rawData.byteLength),c=ch(t.dataType),s=t.rawData.byteLength/c;if(t.rawData.byteLength%c!==0)throw new Error("invalid buffer length");if(l.length!==s)throw new Error("buffer length mismatch");for(let r=0;r0){let l=u.data,d=new DataView(t.rawDataArray().buffer,t.rawDataArray().byteOffset,t.rawDataLength()),c=ch(t.dataType()),s=t.rawDataLength()/c;if(t.rawDataLength()%c!==0)throw new Error("invalid buffer length");if(l.length!==s)throw new Error("buffer length mismatch");for(let r=0;rtypeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var m3=Object.create,Jo=Object.defineProperty,g3=Object.getOwnPropertyDescriptor,b3=Object.getOwnPropertyNames,y3=Object.getPrototypeOf,w3=Object.prototype.hasOwnProperty,Bu=(e=>typeof jr<"u"?jr:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof jr<"u"?jr:t)[n]}):e)(function(e){if(typeof jr<"u")return jr.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),D=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(i){throw n=[i],i}},ae=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},wn=(e,t)=>{for(var n in t)Jo(e,n,{get:t[n],enumerable:!0})},l0=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of b3(t))!w3.call(e,u)&&u!==n&&Jo(e,u,{get:()=>t[u],enumerable:!(i=g3(t,u))||i.enumerable});return e},be=(e,t,n)=>(n=e!=null?m3(y3(e)):{},l0(t||!e||!e.__esModule?Jo(n,"default",{value:e,enumerable:!0}):n,e)),Nn=e=>l0(Jo({},"__esModule",{value:!0}),e),ri,br,pn,oh,d0,c0=D(()=>{"use strict";ri=new Map,br=[],pn=(e,t,n)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=ri.get(e);if(i===void 0)ri.set(e,{backend:t,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let u=br.indexOf(e);u!==-1&&br.splice(u,1);for(let l=0;l{let t=ri.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return n||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},d0=async e=>{let t=e.executionProviders||[],n=t.map(s=>typeof s=="string"?s:s.name),i=n.length===0?br:n,u,l=[],d=new Set;for(let s of i){let r=await oh(s);typeof r=="string"?l.push({name:s,err:r}):(u||(u=r),u===r&&d.add(s))}if(!u)throw new Error(`no available backend found. ERR: ${l.map(s=>`[${s.name}] ${s.err}`).join(", ")}`);for(let{name:s,err:r}of l)n.includes(s)&&console.warn(`removing requested execution provider "${s}" from session options because it is not available: ${r}`);let c=t.filter(s=>d.has(typeof s=="string"?s:s.name));return[u,new Proxy(e,{get:(s,r)=>r==="executionProviders"?c:Reflect.get(s,r)})]}}),_3=D(()=>{"use strict";c0()}),p0,v3=D(()=>{"use strict";p0="1.29.0"}),aa,st,h0=D(()=>{"use strict";v3(),aa="warning",st={wasm:{},webgl:{},webgpu:{},versions:{common:p0},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);aa=e}},get logLevel(){return aa}},Object.defineProperty(st,"logLevel",{enumerable:!0})}),me,x3=D(()=>{"use strict";h0(),me=st}),f0,m0,$3=D(()=>{"use strict";f0=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let i=n.getContext("2d");if(i!=null){let u,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],l=e.dims[3]):(u=e.dims[3],l=e.dims[2]);let d=t?.format!==void 0?t.format:"RGB",c=t?.norm,s,r;c===void 0||c.mean===void 0?s=[255,255,255,255]:typeof c.mean=="number"?s=[c.mean,c.mean,c.mean,c.mean]:(s=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(s[3]=c.mean[3])),c===void 0||c.bias===void 0?r=[0,0,0,0]:typeof c.bias=="number"?r=[c.bias,c.bias,c.bias,c.bias]:(r=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(r[3]=c.bias[3]));let o=l*u,a=0,p=o,h=o*2,m=-1;d==="RGBA"?(a=0,p=o,h=o*2,m=o*3):d==="RGB"?(a=0,p=o,h=o*2):d==="RBG"&&(a=0,h=o,p=o*2);for(let g=0;g{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(n!=null){let u,l,d;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],l=e.dims[1],d=e.dims[3]):(u=e.dims[3],l=e.dims[2],d=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",s=t?.norm,r,o;s===void 0||s.mean===void 0?r=[255,255,255,255]:typeof s.mean=="number"?r=[s.mean,s.mean,s.mean,s.mean]:(r=[s.mean[0],s.mean[1],s.mean[2],255],s.mean[3]!==void 0&&(r[3]=s.mean[3])),s===void 0||s.bias===void 0?o=[0,0,0,0]:typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:(o=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(o[3]=s.bias[3]));let a=l*u;if(t!==void 0&&(t.format!==void 0&&d===4&&t.format!=="RGBA"||d===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let p=4,h=0,m=1,g=2,_=3,w=0,y=a,T=a*2,S=-1;c==="RGBA"?(w=0,y=a,T=a*2,S=a*3):c==="RGB"?(w=0,y=a,T=a*2):c==="RBG"&&(w=0,T=a,y=a*2),i=n.createImageData(u,l);for(let O=0;O{"use strict";ql(),yo=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:n,width:i}=t,u=t.norm??{mean:255,bias:0},l,d;typeof u.mean=="number"?l=[u.mean,u.mean,u.mean,u.mean]:l=[u.mean[0],u.mean[1],u.mean[2],u.mean[3]??255],typeof u.bias=="number"?d=[u.bias,u.bias,u.bias,u.bias]:d=[u.bias[0],u.bias[1],u.bias[2],u.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",s=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",r=n*i,o=s==="RGBA"?new Float32Array(r*4):new Float32Array(r*3),a=4,p=0,h=1,m=2,g=3,_=0,w=r,y=r*2,T=-1;c==="RGB"&&(a=3,p=0,h=1,m=2,g=-1),s==="RGBA"?T=r*3:s==="RBG"?(_=0,y=r,w=r*2):s==="BGR"&&(y=0,w=r,_=r*2);for(let S=0;S{let n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,u=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",d,c=t??{},s=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},r=o=>typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas?o.getContext("2d"):null;if(n){let o=s();o.width=e.width,o.height=e.height;let a=r(o);if(a!=null){let p=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(p=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=p,c.width=h}else c.tensorFormat="RGBA",c.height=p,c.width=h;a.drawImage(e,0,0),d=a.getImageData(0,0,h,p).data}else throw new Error("Can not access image data")}else if(i){let o,a;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(o=t.resizedHeight,a=t.resizedWidth):(o=e.height,a=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=o,c.width=a,t!==void 0){let p=s();p.width=a,p.height=o;let h=r(p);if(h!=null)h.putImageData(e,0,0),d=h.getImageData(0,0,a,o).data;else throw new Error("Can not access image data")}else d=e.data}else if(u){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let o=s();o.width=e.width,o.height=e.height;let a=r(o);if(a!=null){let p=e.height,h=e.width;return a.drawImage(e,0,0,h,p),d=a.getImageData(0,0,h,p).data,c.height=p,c.width=h,yo(d,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((o,a)=>{let p=s(),h=r(p);if(!e||!h)return a();let m=new Image;m.crossOrigin="Anonymous",m.src=e,m.onload=()=>{p.width=m.width,p.height=m.height,h.drawImage(m,0,0,p.width,p.height);let g=h.getImageData(0,0,p.width,p.height);c.height=p.height,c.width=p.width,o(yo(g.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return yo(d,c);throw new Error("Input data provided is not supported - aborted tensor creation")},b0=(e,t)=>{let{width:n,height:i,download:u,dispose:l}=t,d=[1,i,n,4];return new _t({location:"texture",type:"float32",texture:e,dims:d,download:u,dispose:l})},y0=(e,t)=>{let{dataType:n,dims:i,download:u,dispose:l}=t;return new _t({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:u,dispose:l})},w0=(e,t)=>{let{dataType:n,dims:i,download:u,dispose:l}=t;return new _t({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:u,dispose:l})},_0=(e,t,n)=>new _t({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),an,wi,ua,v0,S3=D(()=>{"use strict";an=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),wi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ua=!1,v0=()=>{if(!ua){ua=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(an.set("int64",BigInt64Array),wi.set(BigInt64Array,"int64")),t&&(an.set("uint64",BigUint64Array),wi.set(BigUint64Array,"uint64")),i?(an.set("float16",n),wi.set(n,"float16")):an.set("float16",Uint16Array)}}}),x0,$0,I3=D(()=>{"use strict";ql(),x0=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new _t(e.type,e.data,t);case"cpu-pinned":return new _t({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new _t({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new _t({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new _t({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),_t,ql=D(()=>{"use strict";$3(),T3(),S3(),I3(),_t=class{constructor(e,t,n){v0();let i,u;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,u=e.dims,e.location){case"cpu-pinned":{let d=an.get(i);if(!d)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=e.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,c;if(typeof e=="string")if(i=e,c=n,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");d=t}else{let s=an.get(e);if(s===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&s===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${s.name} as data.`);e==="uint64"||e==="int64"?d=s.from(t,BigInt):d=s.from(t)}else if(t instanceof s)d=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")d=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&s!==Uint16Array)d=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${s}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let s=typeof e[0];if(s==="string")i="string",d=e;else if(s==="boolean")i="bool",d=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${s}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",d=Uint8Array.from(e);else{let s=wi.get(e.constructor);if(s===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=s,d=e}if(c===void 0)c=[d.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");u=c,this.cpuData=d,this.dataLocation="cpu"}let l=x0(u);if(this.cpuData&&l!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(l/2)===this.cpuData.length))throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=u,this.size=l}static async fromImage(e,t){return g0(e,t)}static fromTexture(e,t){return b0(e,t)}static fromGpuBuffer(e,t){return y0(e,t)}static fromMLTensor(e,t){return w0(e,t)}static fromPinnedBuffer(e,t,n){return _0(e,t,n)}toDataURL(e){return f0(this,e)}toImageData(e){return m0(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return $0(this,e)}}}),vt,T0=D(()=>{"use strict";ql(),vt=_t}),Lo,la,Jt,Vt,hn,fn,S0=D(()=>{"use strict";h0(),Lo=(e,t)=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.timeStamp(`${e}::ORT::${t}`)},la=(e,t)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let u=0;u{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||la("BEGIN",e)},Vt=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||la("END",e)},hn=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.time(`ORT::${e}`)},fn=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.timeEnd(`ORT::${e}`)}}),I0,O3=D(()=>{"use strict";c0(),T0(),S0(),I0=class O0{constructor(t){this.handler=t}async run(t,n,i){Jt(),hn("InferenceSession.run");let u={},l={};if(typeof t!="object"||t===null||t instanceof vt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof vt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let r of n){if(typeof r!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(r)===-1)throw new RangeError(`'fetches' contains invalid output name: ${r}.`);u[r]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let r=!1,o=Object.getOwnPropertyNames(n);for(let a of this.outputNames)if(o.indexOf(a)!==-1){let p=n[a];(p===null||p instanceof vt)&&(r=!0,d=!1,u[a]=p)}if(r){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let r of this.inputNames)if(typeof t[r]>"u")throw new Error(`input '${r}' is missing in 'feeds'.`);if(d)for(let r of this.outputNames)u[r]=null;let c=await this.handler.run(t,u,l),s={};for(let r in c)if(Object.hasOwnProperty.call(c,r)){let o=c[r];o instanceof vt?s[r]=o:s[r]=new vt(o.type,o.data,o.dims)}return fn("InferenceSession.run"),Vt(),s}async release(){return this.handler.dispose()}static async create(t,n,i,u){Jt(),hn("InferenceSession.create");let l,d={};if(typeof t=="string"){if(l=t,typeof n=="object"&&n!==null)d=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof n=="object"&&n!==null)d=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let o=t,a=0,p=t.byteLength;if(typeof n=="object"&&n!==null)d=n;else if(typeof n=="number"){if(a=n,!Number.isSafeInteger(a))throw new RangeError("'byteOffset' must be an integer.");if(a<0||a>=o.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${o.byteLength}).`);if(p=t.byteLength-a,typeof i=="number"){if(p=i,!Number.isSafeInteger(p))throw new RangeError("'byteLength' must be an integer.");if(p<=0||a+p>o.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${o.byteLength-a}].`);if(typeof u=="object"&&u!==null)d=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(o,a,p)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,s]=await d0(d),r=await c.createInferenceSessionHandler(l,s);return fn("InferenceSession.create"),Vt(),new O0(r)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Qo,E3=D(()=>{"use strict";O3(),Qo=I0}),A3=D(()=>{"use strict"}),k3=D(()=>{"use strict"}),P3=D(()=>{"use strict"}),C3=D(()=>{"use strict"}),R3={};wn(R3,{InferenceSession:()=>Qo,TRACE:()=>Lo,TRACE_EVENT_BEGIN:()=>hn,TRACE_EVENT_END:()=>fn,TRACE_FUNC_BEGIN:()=>Jt,TRACE_FUNC_END:()=>Vt,Tensor:()=>vt,env:()=>me,registerBackend:()=>pn});var dt=D(()=>{"use strict";_3(),x3(),E3(),T0(),A3(),k3(),S0(),P3(),C3()});function un(e,t,n,i){if(t===void 0)return D3(e);if(n===void 0)wo(e,t,1);else if(typeof n=="number"&&i===void 0)wo(e,t,n);else if(typeof n=="string"&&i===void 0)wo(e,n,1,t);else if(typeof n=="string"&&typeof i=="number")wo(e,n,i,t);else throw new TypeError("input is valid")}function D3(e){return{verbose:un.verbose.bind(null,e),info:un.info.bind(null,e),warning:un.warning.bind(null,e),error:un.error.bind(null,e),fatal:un.fatal.bind(null,e)}}function wo(e,t,n,i){let u=Dn[i||""]||Dn[""];Fu[e]{"use strict";sh=class{log(e,t,n){}},ah=class{log(e,t,n){console.log(`${this.color(e)} ${n?"\x1B[35m"+n+"\x1B[0m ":""}${t}`)}color(e){switch(e){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${e}`)}}},Fu={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},E0={none:new sh,console:new ah},da={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1},Dn={"":da},(e=>{function t(r,o){e("verbose",r,o)}e.verbose=t;function n(r,o){e("info",r,o)}e.info=n;function i(r,o){e("warning",r,o)}e.warning=i;function u(r,o){e("error",r,o)}e.error=u;function l(r,o){e("fatal",r,o)}e.fatal=l;function d(r){Dn={},c("",r||{})}e.reset=d;function c(r,o){if(r==="*")d(o);else{let a=Dn[r]||da;Dn[r]={provider:o.provider||a.provider,minimalSeverity:o.minimalSeverity||a.minimalSeverity,logDateTime:o.logDateTime===void 0?a.logDateTime:o.logDateTime,logSourceLocation:o.logSourceLocation===void 0?a.logSourceLocation:o.logSourceLocation}}}e.set=c;function s(r){let o={};r.logLevel&&(o.minimalSeverity=r.logLevel),c("",o)}e.setWithEnv=s})(un||={}),Je=un,ca=class{constructor(e,t,n,i,u,l){this.category=e,this.name=t,this.startTime=n,this.endCallback=i,this.timer=u,this.ctx=l}async end(){return this.endCallback(this)}async checkTimer(){if(this.ctx===void 0||this.timer===void 0)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}},pa=class{constructor(e,t,n,i){this.category=e,this.name=t,this.startTime=n,this.endTime=i}},A0=class{constructor(e,t,n){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=e===void 0?1e4:e,this._flushBatchSize=t===void 0?10:t,this._flushIntervalInMilliseconds=n===void 0?5e3:n}static create(e){return e===void 0?new this:new this(e.maxNumberEvents,e.flushBatchSize,e.flushIntervalInMilliseconds)}start(){this._started=!0,this._timingEvents=[],this._flushTime=ni(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer{d.then(async r=>{u&&await u.end(),c(r)},async r=>{u&&await u.end(),s(r)})});if(!l&&u){let c=u.end();if(c&&typeof c.then=="function")return new Promise((s,r)=>{c.then(()=>{s(d)},o=>{r(o)})})}return d}begin(e,t,n){if(!this._started)throw new Error("profiler is not started yet");if(n===void 0){let i=ni();return this.flush(i),new ca(e,t,i,u=>this.endSync(u))}else{let i=n.beginTimer();return new ca(e,t,0,async u=>this.end(u),i,n)}}async end(e){let t=await e.checkTimer();this._timingEvents.length=this._flushBatchSize||e-this._flushTime>=this._flushIntervalInMilliseconds){for(let t=this._flushPointer;this._flushPointerperformance.now():Date.now});function M3(e,t,n){for(let i of n){let u=i[0],l=i[1],d=i[2],c=i[3],s=i[4];if(e.opType===u){for(let r of t)if((r.domain===l||r.domain==="ai.onnx"&&l==="")&&N3(r.version,d))return{opImpl:c,opInit:s}}}throw new TypeError(`cannot resolve operator '${e.opType}' with opsets: ${t.map(i=>`${i.domain||"ai.onnx"} v${i.version}`).join(", ")}`)}function N3(e,t){if(t.endsWith("+")){let n=Number.parseInt(t.substring(0,t.length-1),10);return!isNaN(n)&&n<=e}else if(t.split("-").length===2){let n=t.split("-"),i=Number.parseInt(n[0],10),u=Number.parseInt(n[1],10);return!isNaN(i)&&!isNaN(u)&&i<=e&&e<=u}else return Number.parseInt(t,10)===e}var z3=D(()=>{"use strict"}),B3=ae(e=>{"use strict";e.__esModule=!0;var t=(function(){function n(i){if(!i)throw new TypeError("Invalid argument; `value` has no value.");this.value=n.EMPTY,i&&n.isGuid(i)&&(this.value=i)}return n.isGuid=function(i){var u=i.toString();return i&&(i instanceof n||n.validator.test(u))},n.create=function(){return new n([n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-"))},n.createEmpty=function(){return new n("emptyguid")},n.parse=function(i){return new n(i)},n.raw=function(){return[n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-")},n.gen=function(i){for(var u="",l=0;l>>=0,(u=0<=e&&e<256)&&(i=ju[e],i)?i:(n=Ce(e,0,!0),u&&(ju[e]=n),n)):(e|=0,(u=-128<=e&&e<128)&&(i=Lu[e],i)?i:(n=Ce(e,e<0?-1:0,!1),u&&(Lu[e]=n),n))}function Rt(e,t){if(isNaN(e))return t?Zt:Ct;if(t){if(e<0)return Zt;if(e>=Uu)return Gu}else{if(e<=-Vu)return pt;if(e+1>=Vu)return qu}return e<0?Rt(-e,t).neg():Ce(e%ln|0,e/ln|0,t)}function Ce(e,t,n){return new ze(e,t,n)}function Gl(e,t,n){if(e.length===0)throw Error("empty string");if(typeof t=="number"?(n=t,t=!1):t=!!t,e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return t?Zt:Ct;if(n=n||10,n<2||360)throw Error("interior hyphen");if(i===0)return Gl(e.substring(1),t,n).neg();for(var u=Rt(Oi(n,8)),l=Ct,d=0;d{gt=null;try{gt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}ze.prototype.__isLong__,Object.defineProperty(ze.prototype,"__isLong__",{value:!0}),ze.isLong=lt,Lu={},ju={},ze.fromInt=Ur,ze.fromNumber=Rt,ze.fromBits=Ce,Oi=Math.pow,ze.fromString=Gl,ze.fromValue=Et,ha=65536,lh=1<<24,ln=ha*ha,Uu=ln*ln,Vu=Uu/2,fa=Ur(lh),Ct=Ur(0),ze.ZERO=Ct,Zt=Ur(0,!0),ze.UZERO=Zt,Vr=Ur(1),ze.ONE=Vr,ma=Ur(1,!0),ze.UONE=ma,_o=Ur(-1),ze.NEG_ONE=_o,qu=Ce(-1,2147483647,!1),ze.MAX_VALUE=qu,Gu=Ce(-1,-1,!0),ze.MAX_UNSIGNED_VALUE=Gu,pt=Ce(0,-2147483648,!1),ze.MIN_VALUE=pt,Z=ze.prototype,Z.toInt=function(){return this.unsigned?this.low>>>0:this.low},Z.toNumber=function(){return this.unsigned?(this.high>>>0)*ln+(this.low>>>0):this.high*ln+(this.low>>>0)},Z.toString=function(e){if(e=e||10,e<2||36>>0,r=s.toString(e);if(l=c,l.isZero())return r+d;for(;r.length<6;)r="0"+r;d=""+r+d}},Z.getHighBits=function(){return this.high},Z.getHighBitsUnsigned=function(){return this.high>>>0},Z.getLowBits=function(){return this.low},Z.getLowBitsUnsigned=function(){return this.low>>>0},Z.getNumBitsAbs=function(){if(this.isNegative())return this.eq(pt)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&(e&1<>21;return e?this.unsigned?!1:e===-1&&!(this.low===0&&this.high===-2097152):!0},Z.isZero=function(){return this.high===0&&this.low===0},Z.eqz=Z.isZero,Z.isNegative=function(){return!this.unsigned&&this.high<0},Z.isPositive=function(){return this.unsigned||this.high>=0},Z.isOdd=function(){return(this.low&1)===1},Z.isEven=function(){return(this.low&1)===0},Z.equals=function(e){return lt(e)||(e=Et(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low},Z.eq=Z.equals,Z.notEquals=function(e){return!this.eq(e)},Z.neq=Z.notEquals,Z.ne=Z.notEquals,Z.lessThan=function(e){return this.comp(e)<0},Z.lt=Z.lessThan,Z.lessThanOrEqual=function(e){return this.comp(e)<=0},Z.lte=Z.lessThanOrEqual,Z.le=Z.lessThanOrEqual,Z.greaterThan=function(e){return this.comp(e)>0},Z.gt=Z.greaterThan,Z.greaterThanOrEqual=function(e){return this.comp(e)>=0},Z.gte=Z.greaterThanOrEqual,Z.ge=Z.greaterThanOrEqual,Z.compare=function(e){if(lt(e)||(e=Et(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Z.comp=Z.compare,Z.negate=function(){return!this.unsigned&&this.eq(pt)?pt:this.not().add(Vr)},Z.neg=Z.negate,Z.add=function(e){lt(e)||(e=Et(e));var t=this.high>>>16,n=this.high&65535,i=this.low>>>16,u=this.low&65535,l=e.high>>>16,d=e.high&65535,c=e.low>>>16,s=e.low&65535,r=0,o=0,a=0,p=0;return p+=u+s,a+=p>>>16,p&=65535,a+=i+c,o+=a>>>16,a&=65535,o+=n+d,r+=o>>>16,o&=65535,r+=t+l,r&=65535,Ce(a<<16|p,r<<16|o,this.unsigned)},Z.subtract=function(e){return lt(e)||(e=Et(e)),this.add(e.neg())},Z.sub=Z.subtract,Z.multiply=function(e){if(this.isZero())return this;if(lt(e)||(e=Et(e)),gt){var t=gt.mul(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Zt:Ct;if(this.eq(pt))return e.isOdd()?pt:Ct;if(e.eq(pt))return this.isOdd()?pt:Ct;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(fa)&&e.lt(fa))return Rt(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,i=this.high&65535,u=this.low>>>16,l=this.low&65535,d=e.high>>>16,c=e.high&65535,s=e.low>>>16,r=e.low&65535,o=0,a=0,p=0,h=0;return h+=l*r,p+=h>>>16,h&=65535,p+=u*r,a+=p>>>16,p&=65535,p+=l*s,a+=p>>>16,p&=65535,a+=i*r,o+=a>>>16,a&=65535,a+=u*s,o+=a>>>16,a&=65535,a+=l*c,o+=a>>>16,a&=65535,o+=n*r+i*s+u*c+l*d,o&=65535,Ce(p<<16|h,o<<16|a,this.unsigned)},Z.mul=Z.multiply,Z.divide=function(e){if(lt(e)||(e=Et(e)),e.isZero())throw Error("division by zero");if(gt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?gt.div_u:gt.div_s)(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Zt:Ct;var n,i,u;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Zt;if(e.gt(this.shru(1)))return ma;u=Zt}else{if(this.eq(pt)){if(e.eq(Vr)||e.eq(_o))return pt;if(e.eq(pt))return Vr;var l=this.shr(1);return n=l.div(e).shl(1),n.eq(Ct)?e.isNegative()?Vr:_o:(i=this.sub(e.mul(n)),u=n.add(i.div(e)),u)}else if(e.eq(pt))return this.unsigned?Zt:Ct;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();u=Ct}for(i=this;i.gte(e);){n=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var d=Math.ceil(Math.log(n)/Math.LN2),c=d<=48?1:Oi(2,d-48),s=Rt(n),r=s.mul(e);r.isNegative()||r.gt(i);)n-=c,s=Rt(n,this.unsigned),r=s.mul(e);s.isZero()&&(s=Vr),u=u.add(s),i=i.sub(r)}return u},Z.div=Z.divide,Z.modulo=function(e){if(lt(e)||(e=Et(e)),gt){var t=(this.unsigned?gt.rem_u:gt.rem_s)(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))},Z.mod=Z.modulo,Z.rem=Z.modulo,Z.not=function(){return Ce(~this.low,~this.high,this.unsigned)},Z.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},Z.clz=Z.countLeadingZeros,Z.countTrailingZeros=function(){return this.low?uh(this.low):uh(this.high)+32},Z.ctz=Z.countTrailingZeros,Z.and=function(e){return lt(e)||(e=Et(e)),Ce(this.low&e.low,this.high&e.high,this.unsigned)},Z.or=function(e){return lt(e)||(e=Et(e)),Ce(this.low|e.low,this.high|e.high,this.unsigned)},Z.xor=function(e){return lt(e)||(e=Et(e)),Ce(this.low^e.low,this.high^e.high,this.unsigned)},Z.shiftLeft=function(e){return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ce(this.low<>>32-e,this.unsigned):Ce(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Ce(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Z.shr=Z.shiftRight,Z.shiftRightUnsigned=function(e){return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ce(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Ce(this.high,0,this.unsigned):Ce(this.high>>>e-32,0,this.unsigned)},Z.shru=Z.shiftRightUnsigned,Z.shr_u=Z.shiftRightUnsigned,Z.rotateLeft=function(e){var t;return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ce(this.high,this.low,this.unsigned):e<32?(t=32-e,Ce(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Ce(this.high<>>t,this.low<>>t,this.unsigned))},Z.rotl=Z.rotateLeft,Z.rotateRight=function(e){var t;return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ce(this.high,this.low,this.unsigned):e<32?(t=32-e,Ce(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Ce(this.low<>>e,this.high<>>e,this.unsigned))},Z.rotr=Z.rotateRight,Z.toSigned=function(){return this.unsigned?Ce(this.low,this.high,!1):this},Z.toUnsigned=function(){return this.unsigned?this:Ce(this.low,this.high,!0)},Z.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Z.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]},Z.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]},ze.fromBytes=function(e,t,n){return n?ze.fromBytesLE(e,t):ze.fromBytesBE(e,t)},ze.fromBytesLE=function(e,t){return new ze(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},ze.fromBytesBE=function(e,t){return new ze(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},typeof BigInt=="function"&&(ze.fromBigInt=function(e,t){var n=Number(BigInt.asIntN(32,e)),i=Number(BigInt.asIntN(32,e>>BigInt(32)));return Ce(n,i,t)},ze.fromValue=function(e,t){return typeof e=="bigint"?ze.fromBigInt(e,t):Et(e,t)},Z.toBigInt=function(){var e=BigInt(this.low>>>0),t=BigInt(this.unsigned?this.high>>>0:this.high);return t<{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ArgType=void 0;var t;(function(n){n[n.INPUT=0]="INPUT",n[n.OUTPUT=1]="OUTPUT"})(t||(e.ArgType=t={}))}),Hl=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SIZE_PREFIX_LENGTH=e.FILE_IDENTIFIER_LENGTH=e.SIZEOF_INT=e.SIZEOF_SHORT=void 0,e.SIZEOF_SHORT=2,e.SIZEOF_INT=4,e.FILE_IDENTIFIER_LENGTH=4,e.SIZE_PREFIX_LENGTH=4}),C0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isLittleEndian=e.float64=e.float32=e.int32=void 0,e.int32=new Int32Array(2),e.float32=new Float32Array(e.int32.buffer),e.float64=new Float64Array(e.int32.buffer),e.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1}),R0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Encoding=void 0;var t;(function(n){n[n.UTF8_BYTES=1]="UTF8_BYTES",n[n.UTF16_STRING=2]="UTF16_STRING"})(t||(e.Encoding=t={}))}),D0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ByteBuffer=void 0;var t=Hl(),n=R0(),i=C0(),u=class M0{constructor(d){this.bytes_=d,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(d){return new M0(new Uint8Array(d))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(d){this.position_=d}capacity(){return this.bytes_.length}readInt8(d){return this.readUint8(d)<<24>>24}readUint8(d){return this.bytes_[d]}readInt16(d){return this.readUint16(d)<<16>>16}readUint16(d){return this.bytes_[d]|this.bytes_[d+1]<<8}readInt32(d){return this.bytes_[d]|this.bytes_[d+1]<<8|this.bytes_[d+2]<<16|this.bytes_[d+3]<<24}readUint32(d){return this.readInt32(d)>>>0}readInt64(d){return BigInt.asIntN(64,BigInt(this.readUint32(d))+(BigInt(this.readUint32(d+4))<>8}writeUint16(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8}writeInt32(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8,this.bytes_[d+2]=c>>16,this.bytes_[d+3]=c>>24}writeUint32(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8,this.bytes_[d+2]=c>>16,this.bytes_[d+3]=c>>24}writeInt64(d,c){this.writeInt32(d,Number(BigInt.asIntN(32,c))),this.writeInt32(d+4,Number(BigInt.asIntN(32,c>>BigInt(32))))}writeUint64(d,c){this.writeUint32(d,Number(BigInt.asUintN(32,c))),this.writeUint32(d+4,Number(BigInt.asUintN(32,c>>BigInt(32))))}writeFloat32(d,c){i.float32[0]=c,this.writeInt32(d,i.int32[0])}writeFloat64(d,c){i.float64[0]=c,this.writeInt32(d,i.int32[i.isLittleEndian?0:1]),this.writeInt32(d+4,i.int32[i.isLittleEndian?1:0])}getBufferIdentifier(){if(this.bytes_.length{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Builder=void 0;var t=D0(),n=Hl(),i=class N0{constructor(l){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null,this.text_encoder=new TextEncoder;let d;l?d=l:d=1024,this.bb=t.ByteBuffer.allocate(d),this.space=d}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(l){this.force_defaults=l}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(l,d){l>this.minalign&&(this.minalign=l);let c=~(this.bb.capacity()-this.space+d)+1&l-1;for(;this.space=0&&this.vtable[d]==0;d--);let c=d+1;for(;d>=0;d--)this.addInt16(this.vtable[d]!=0?l-this.vtable[d]:0);let s=2;this.addInt16(l-this.object_start);let r=(c+s)*n.SIZEOF_SHORT;this.addInt16(r);let o=0,a=this.space;e:for(d=0;d=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,n.SIZEOF_INT+s),this.addOffset(l),s&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(l,d){this.finish(l,d,!0)}requiredField(l,d){let c=this.bb.capacity()-l,s=c-this.bb.readInt32(c);if(!(d{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Encoding=e.ByteBuffer=e.Builder=e.isLittleEndian=e.int32=e.float64=e.float32=e.SIZE_PREFIX_LENGTH=e.SIZEOF_SHORT=e.SIZEOF_INT=e.FILE_IDENTIFIER_LENGTH=void 0;var t=Hl();Object.defineProperty(e,"FILE_IDENTIFIER_LENGTH",{enumerable:!0,get:function(){return t.FILE_IDENTIFIER_LENGTH}}),Object.defineProperty(e,"SIZEOF_INT",{enumerable:!0,get:function(){return t.SIZEOF_INT}}),Object.defineProperty(e,"SIZEOF_SHORT",{enumerable:!0,get:function(){return t.SIZEOF_SHORT}}),Object.defineProperty(e,"SIZE_PREFIX_LENGTH",{enumerable:!0,get:function(){return t.SIZE_PREFIX_LENGTH}});var n=C0();Object.defineProperty(e,"float32",{enumerable:!0,get:function(){return n.float32}}),Object.defineProperty(e,"float64",{enumerable:!0,get:function(){return n.float64}}),Object.defineProperty(e,"int32",{enumerable:!0,get:function(){return n.int32}}),Object.defineProperty(e,"isLittleEndian",{enumerable:!0,get:function(){return n.isLittleEndian}});var i=F3();Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return i.Builder}});var u=D0();Object.defineProperty(e,"ByteBuffer",{enumerable:!0,get:function(){return u.ByteBuffer}});var l=R0();Object.defineProperty(e,"Encoding",{enumerable:!0,get:function(){return l.Encoding}})}),z0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AttributeType=void 0;var t;(function(n){n[n.UNDEFINED=0]="UNDEFINED",n[n.FLOAT=1]="FLOAT",n[n.INT=2]="INT",n[n.STRING=3]="STRING",n[n.TENSOR=4]="TENSOR",n[n.GRAPH=5]="GRAPH",n[n.FLOATS=6]="FLOATS",n[n.INTS=7]="INTS",n[n.STRINGS=8]="STRINGS",n[n.TENSORS=9]="TENSORS",n[n.GRAPHS=10]="GRAPHS",n[n.SPARSE_TENSOR=11]="SPARSE_TENSOR",n[n.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(t||(e.AttributeType=t={}))}),F0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.NodeType=void 0;var t;(function(n){n[n.Primitive=0]="Primitive",n[n.Fused=1]="Fused"})(t||(e.NodeType=t={}))}),L0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p=0;a--)r.addOffset(o[a]);return r.endVector()}static startInputsVector(r,o){r.startVector(4,o,4)}static addOutputs(r,o){r.addFieldOffset(9,o,0)}static createOutputsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startOutputsVector(r,o){r.startVector(4,o,4)}static addAttributes(r,o){r.addFieldOffset(10,o,0)}static createAttributesVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startAttributesVector(r,o){r.startVector(4,o,4)}static addInputArgCounts(r,o){r.addFieldOffset(11,o,0)}static createInputArgCountsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addInt32(o[a]);return r.endVector()}static startInputArgCountsVector(r,o){r.startVector(4,o,4)}static addImplicitInputs(r,o){r.addFieldOffset(12,o,0)}static createImplicitInputsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startImplicitInputsVector(r,o){r.startVector(4,o,4)}static endNode(r){return r.endObject()}static createNode(r,o,a,p,h,m,g,_,w,y,T,S,O,A){return ot.startNode(r),ot.addName(r,o),ot.addDocString(r,a),ot.addDomain(r,p),ot.addSinceVersion(r,h),ot.addIndex(r,m),ot.addOpType(r,g),ot.addType(r,_),ot.addExecutionProviderType(r,w),ot.addInputs(r,y),ot.addOutputs(r,T),ot.addAttributes(r,S),ot.addInputArgCounts(r,O),ot.addImplicitInputs(r,A),ot.endNode(r)}};e.Node=c}),j0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.EdgeEnd=void 0;var t=class{constructor(){this.bb=null,this.bb_pos=0}__init(n,i){return this.bb_pos=n,this.bb=i,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static sizeOf(){return 12}static createEdgeEnd(n,i,u,l){return n.prep(4,12),n.writeInt32(l),n.writeInt32(u),n.writeInt32(i),n.offset()}};e.EdgeEnd=t}),U0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o=0;r--)c.addInt32(s[r]);return c.endVector()}static startNodeIndicesVector(c,s){c.startVector(4,s,4)}static addNumInputs(c,s){c.addFieldInt32(1,s,0)}static addNumOutputs(c,s){c.addFieldInt32(2,s,0)}static addHasVariadicInput(c,s){c.addFieldInt8(3,+s,0)}static addHasVariadicOutput(c,s){c.addFieldInt8(4,+s,0)}static addNumVariadicInputs(c,s){c.addFieldInt32(5,s,0)}static addNumVariadicOutputs(c,s){c.addFieldInt32(6,s,0)}static endNodesToOptimizeIndices(c){return c.endObject()}static createNodesToOptimizeIndices(c,s,r,o,a,p,h,m){return kt.startNodesToOptimizeIndices(c),kt.addNodeIndices(c,s),kt.addNumInputs(c,r),kt.addNumOutputs(c,o),kt.addHasVariadicInput(c,a),kt.addHasVariadicOutput(c,p),kt.addNumVariadicInputs(c,h),kt.addNumVariadicOutputs(c,m),kt.endNodesToOptimizeIndices(c)}};e.NodesToOptimizeIndices=l}),q0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startProducedOpIdsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizationRecord(s){return s.endObject()}};e.RuntimeOptimizationRecord=d}),G0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startRuntimeOptimizationRecordsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizationRecordContainerEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createRuntimeOptimizationRecordContainerEntry(s,r,o){return Zr.startRuntimeOptimizationRecordContainerEntry(s),Zr.addOptimizerName(s,r),Zr.addRuntimeOptimizationRecords(s,o),Zr.endRuntimeOptimizationRecordContainerEntry(s)}};e.RuntimeOptimizationRecordContainerEntry=d}),H0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startRecordsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizations(s){return s.endObject()}static createRuntimeOptimizations(s,r){return kn.startRuntimeOptimizations(s),kn.addRecords(s,r),kn.endRuntimeOptimizations(s)}};e.RuntimeOptimizations=d}),es=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TensorDataType=void 0;var t;(function(n){n[n.UNDEFINED=0]="UNDEFINED",n[n.FLOAT=1]="FLOAT",n[n.UINT8=2]="UINT8",n[n.INT8=3]="INT8",n[n.UINT16=4]="UINT16",n[n.INT16=5]="INT16",n[n.INT32=6]="INT32",n[n.INT64=7]="INT64",n[n.STRING=8]="STRING",n[n.BOOL=9]="BOOL",n[n.FLOAT16=10]="FLOAT16",n[n.DOUBLE=11]="DOUBLE",n[n.UINT32=12]="UINT32",n[n.UINT64=13]="UINT64",n[n.COMPLEX64=14]="COMPLEX64",n[n.COMPLEX128=15]="COMPLEX128",n[n.BFLOAT16=16]="BFLOAT16",n[n.FLOAT8E4M3FN=17]="FLOAT8E4M3FN",n[n.FLOAT8E4M3FNUZ=18]="FLOAT8E4M3FNUZ",n[n.FLOAT8E5M2=19]="FLOAT8E5M2",n[n.FLOAT8E5M2FNUZ=20]="FLOAT8E5M2FNUZ"})(t||(e.TensorDataType=t={}))}),ts=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addInt64(r[o]);return s.endVector()}static startDimsVector(s,r){s.startVector(8,r,8)}static addDataType(s,r){s.addFieldInt32(3,r,l.TensorDataType.UNDEFINED)}static addRawData(s,r){s.addFieldOffset(4,r,0)}static createRawDataVector(s,r){s.startVector(1,r.length,1);for(let o=r.length-1;o>=0;o--)s.addInt8(r[o]);return s.endVector()}static startRawDataVector(s,r){s.startVector(1,r,1)}static addStringData(s,r){s.addFieldOffset(5,r,0)}static createStringDataVector(s,r){s.startVector(4,r.length,4);for(let o=r.length-1;o>=0;o--)s.addOffset(r[o]);return s.endVector()}static startStringDataVector(s,r){s.startVector(4,r,4)}static addExternalDataOffset(s,r){s.addFieldInt64(6,r,BigInt("-1"))}static endTensor(s){return s.endObject()}static createTensor(s,r,o,a,p,h,m,g){return Pt.startTensor(s),Pt.addName(s,r),Pt.addDocString(s,o),Pt.addDims(s,a),Pt.addDataType(s,p),Pt.addRawData(s,h),Pt.addStringData(s,m),Pt.addExternalDataOffset(s,g),Pt.endTensor(s)}};e.Tensor=d}),W0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addInt64(r[o]);return s.endVector()}static startDimsVector(s,r){s.startVector(8,r,8)}static endSparseTensor(s){return s.endObject()}};e.SparseTensor=d}),K0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DimensionValueType=void 0;var t;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.VALUE=1]="VALUE",n[n.PARAM=2]="PARAM"})(t||(e.DimensionValueType=t={}))}),Y0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startDimVector(s,r){s.startVector(4,r,4)}static endShape(s){return s.endObject()}static createShape(s,r){return Cn.startShape(s),Cn.addDim(s,r),Cn.endShape(s)}};e.Shape=d}),ew=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TypeInfoValue=void 0,e.unionToTypeInfoValue=l,e.unionListToTypeInfoValue=d;var t=K0(),n=X0(),i=ew(),u;(function(c){c[c.NONE=0]="NONE",c[c.tensor_type=1]="tensor_type",c[c.sequence_type=2]="sequence_type",c[c.map_type=3]="map_type"})(u||(e.TypeInfoValue=u={}));function l(c,s){switch(u[c]){case"NONE":return null;case"tensor_type":return s(new i.TensorTypeAndShape);case"sequence_type":return s(new n.SequenceType);case"map_type":return s(new t.MapType);default:return null}}function d(c,s,r){switch(u[c]){case"NONE":return null;case"tensor_type":return s(r,new i.TensorTypeAndShape);case"sequence_type":return s(r,new n.SequenceType);case"map_type":return s(r,new t.MapType);default:return null}}}),rs=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(p,h,m,g){g===void 0&&(g=m);var _=Object.getOwnPropertyDescriptor(h,m);(!_||("get"in _?!h.__esModule:_.writable||_.configurable))&&(_={enumerable:!0,get:function(){return h[m]}}),Object.defineProperty(p,g,_)}:function(p,h,m,g){g===void 0&&(g=m),p[g]=h[m]}),n=e&&e.__setModuleDefault||(Object.create?function(p,h){Object.defineProperty(p,"default",{enumerable:!0,value:h})}:function(p,h){p.default=h}),i=e&&e.__importStar||(function(){var p=function(h){return p=Object.getOwnPropertyNames||function(m){var g=[];for(var _ in m)Object.prototype.hasOwnProperty.call(m,_)&&(g[g.length]=_);return g},p(h)};return function(h){if(h&&h.__esModule)return h;var m={};if(h!=null)for(var g=p(h),_=0;_=0;g--)h.addOffset(m[g]);return h.endVector()}static startInitializersVector(h,m){h.startVector(4,m,4)}static addNodeArgs(h,m){h.addFieldOffset(1,m,0)}static createNodeArgsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodeArgsVector(h,m){h.startVector(4,m,4)}static addNodes(h,m){h.addFieldOffset(2,m,0)}static createNodesVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodesVector(h,m){h.startVector(4,m,4)}static addMaxNodeIndex(h,m){h.addFieldInt32(3,m,0)}static addNodeEdges(h,m){h.addFieldOffset(4,m,0)}static createNodeEdgesVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodeEdgesVector(h,m){h.startVector(4,m,4)}static addInputs(h,m){h.addFieldOffset(5,m,0)}static createInputsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startInputsVector(h,m){h.startVector(4,m,4)}static addOutputs(h,m){h.addFieldOffset(6,m,0)}static createOutputsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startOutputsVector(h,m){h.startVector(4,m,4)}static addSparseInitializers(h,m){h.addFieldOffset(7,m,0)}static createSparseInitializersVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startSparseInitializersVector(h,m){h.startVector(4,m,4)}static addRuntimeOptimizations(h,m){h.addFieldOffset(8,m,0)}static endGraph(h){return h.endObject()}};e.Graph=a}),nw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(r,o,a,p){p===void 0&&(p=a);var h=Object.getOwnPropertyDescriptor(o,a);(!h||("get"in h?!o.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(r,p,h)}:function(r,o,a,p){p===void 0&&(p=a),r[p]=o[a]}),n=e&&e.__setModuleDefault||(Object.create?function(r,o){Object.defineProperty(r,"default",{enumerable:!0,value:o})}:function(r,o){r.default=o}),i=e&&e.__importStar||(function(){var r=function(o){return r=Object.getOwnPropertyNames||function(a){var p=[];for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(p[p.length]=h);return p},r(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var p=r(o),h=0;h=0;p--)o.addFloat32(a[p]);return o.endVector()}static startFloatsVector(o,a){o.startVector(4,a,4)}static addInts(o,a){o.addFieldOffset(9,a,0)}static createIntsVector(o,a){o.startVector(8,a.length,8);for(let p=a.length-1;p>=0;p--)o.addInt64(a[p]);return o.endVector()}static startIntsVector(o,a){o.startVector(8,a,8)}static addStrings(o,a){o.addFieldOffset(10,a,0)}static createStringsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startStringsVector(o,a){o.startVector(4,a,4)}static addTensors(o,a){o.addFieldOffset(11,a,0)}static createTensorsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startTensorsVector(o,a){o.startVector(4,a,4)}static addGraphs(o,a){o.addFieldOffset(12,a,0)}static createGraphsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startGraphsVector(o,a){o.startVector(4,a,4)}static endAttribute(o){return o.endObject()}};e.Attribute=s}),iw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o=0;r--)c.addInt32(s[r]);return c.endVector()}static startNodeIndicesVector(c,s){c.startVector(4,s,4)}static addKernelDefHashes(c,s){c.addFieldOffset(1,s,0)}static createKernelDefHashesVector(c,s){c.startVector(8,s.length,8);for(let r=s.length-1;r>=0;r--)c.addInt64(s[r]);return c.endVector()}static startKernelDefHashesVector(c,s){c.startVector(8,s,8)}static endDeprecatedKernelCreateInfos(c){return c.endObject()}static createDeprecatedKernelCreateInfos(c,s,r){return Jr.startDeprecatedKernelCreateInfos(c),Jr.addNodeIndices(c,s),Jr.addKernelDefHashes(c,r),Jr.endDeprecatedKernelCreateInfos(c)}};e.DeprecatedKernelCreateInfos=l}),L3=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p=0;a--)r.addOffset(o[a]);return r.endVector()}static startSubGraphSessionStatesVector(r,o){r.startVector(4,o,4)}static endDeprecatedSessionState(r){return r.endObject()}static createDeprecatedSessionState(r,o,a){return en.startDeprecatedSessionState(r),en.addKernels(r,o),en.addSubGraphSessionStates(r,a),en.endDeprecatedSessionState(r)}};e.DeprecatedSessionState=c}),aw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startArgsVector(s,r){s.startVector(4,r,4)}static endKernelTypeStrArgsEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createKernelTypeStrArgsEntry(s,r,o){return tn.startKernelTypeStrArgsEntry(s),tn.addKernelTypeStr(s,r),tn.addArgs(s,o),tn.endKernelTypeStrArgsEntry(s)}};e.KernelTypeStrArgsEntry=d}),uw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startKernelTypeStrArgsVector(s,r){s.startVector(4,r,4)}static endOpIdKernelTypeStrArgsEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createOpIdKernelTypeStrArgsEntry(s,r,o){return rn.startOpIdKernelTypeStrArgsEntry(s),rn.addOpId(s,r),rn.addKernelTypeStrArgs(s,o),rn.endOpIdKernelTypeStrArgsEntry(s)}};e.OpIdKernelTypeStrArgsEntry=d}),lw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startOpKernelTypeStrArgsVector(s,r){s.startVector(4,r,4)}static endKernelTypeStrResolver(s){return s.endObject()}static createKernelTypeStrResolver(s,r){return Rn.startKernelTypeStrResolver(s),Rn.addOpKernelTypeStrArgs(s,r),Rn.endKernelTypeStrResolver(s)}};e.KernelTypeStrResolver=d}),dw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(r,o,a,p){p===void 0&&(p=a);var h=Object.getOwnPropertyDescriptor(o,a);(!h||("get"in h?!o.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(r,p,h)}:function(r,o,a,p){p===void 0&&(p=a),r[p]=o[a]}),n=e&&e.__setModuleDefault||(Object.create?function(r,o){Object.defineProperty(r,"default",{enumerable:!0,value:o})}:function(r,o){r.default=o}),i=e&&e.__importStar||(function(){var r=function(o){return r=Object.getOwnPropertyNames||function(a){var p=[];for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(p[p.length]=h);return p},r(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var p=r(o),h=0;h=0;p--)o.addOffset(a[p]);return o.endVector()}static startOpsetImportVector(o,a){o.startVector(4,a,4)}static addProducerName(o,a){o.addFieldOffset(2,a,0)}static addProducerVersion(o,a){o.addFieldOffset(3,a,0)}static addDomain(o,a){o.addFieldOffset(4,a,0)}static addModelVersion(o,a){o.addFieldInt64(5,a,BigInt("0"))}static addDocString(o,a){o.addFieldOffset(6,a,0)}static addGraph(o,a){o.addFieldOffset(7,a,0)}static addGraphDocString(o,a){o.addFieldOffset(8,a,0)}static addMetadataProps(o,a){o.addFieldOffset(9,a,0)}static createMetadataPropsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startMetadataPropsVector(o,a){o.startVector(4,a,4)}static endModel(o){return o.endObject()}};e.Model=s}),j3=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";U3=be(P0()),V3=be(z0()),rl=be(nw()),jt=be(B0()),q3=be(iw()),G3=be(L3()),H3=be(sw()),W3=be(ow()),K3=be(J0()),X3=be(Y0()),Z3=be(Z0()),Y3=be(j0()),hw=be(Wl()),fw=be(j3()),J3=be(aw()),Q3=be(lw()),eO=be(K0()),tO=be(pw()),mw=be(L0()),rO=be(U0()),nO=be(F0()),iO=be(V0()),oO=be(uw()),sO=be(dw()),aO=be(q0()),uO=be(G0()),lO=be(H0()),dO=be(X0()),cO=be(Q0()),pO=be(W0()),hO=be(cw()),fO=be(ts()),No=be(es()),gw=be(ew()),mO=be(rs()),bw=be(tw()),gO=be(rw())}),ns=D(()=>{"use strict";bO()}),yO=ae((e,t)=>{"use strict";t.exports=n;function n(i,u){for(var l=new Array(arguments.length-1),d=0,c=2,s=!0;c{"use strict";var t=e;t.length=function(d){var c=d.length;if(!c)return 0;for(var s=0;--c%4>1&&d.charAt(c)==="=";)++s;return Math.ceil(d.length*3)/4-s};var n=new Array(64),i=new Array(123);for(u=0;u<64;)i[n[u]=u<26?u+65:u<52?u+71:u<62?u-4:u-59|43]=u++;var u;t.encode=function(d,c,s){for(var r=null,o=[],a=0,p=0,h;c>2],h=(m&3)<<4,p=1;break;case 1:o[a++]=n[h|m>>4],h=(m&15)<<2,p=2;break;case 2:o[a++]=n[h|m>>6],o[a++]=n[m&63],p=0;break}a>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,o)),a=0)}return p&&(o[a++]=n[h],o[a++]=61,p===1&&(o[a++]=61)),r?(a&&r.push(String.fromCharCode.apply(String,o.slice(0,a))),r.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var l="invalid encoding";t.decode=function(d,c,s){for(var r=s,o=0,a,p=0;p1)break;if((h=i[h])===void 0)throw Error(l);switch(o){case 0:a=h,o=1;break;case 1:c[s++]=a<<2|(h&48)>>4,a=h,o=2;break;case 2:c[s++]=(a&15)<<4|(h&60)>>2,a=h,o=3;break;case 3:c[s++]=(a&3)<<6|h,o=0;break}}if(o===1)throw Error(l);return s-r},t.test=function(d){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(d)}}),_O=ae((e,t)=>{"use strict";t.exports=n;function n(){this._listeners=Object.create(null)}n.prototype.on=function(i,u,l){return(this._listeners[i]||(this._listeners[i]=[])).push({fn:u,ctx:l||this}),this},n.prototype.off=function(i,u){if(i===void 0)this._listeners=Object.create(null);else if(u===void 0)this._listeners[i]=[];else{var l=this._listeners[i];if(!l)return this;for(var d=0;d{"use strict";t.exports=n(n);function n(c){return typeof Float32Array<"u"?(function(){var s=new Float32Array([-0]),r=new Uint8Array(s.buffer),o=r[3]===128;function a(g,_,w){s[0]=g,_[w]=r[0],_[w+1]=r[1],_[w+2]=r[2],_[w+3]=r[3]}function p(g,_,w){s[0]=g,_[w]=r[3],_[w+1]=r[2],_[w+2]=r[1],_[w+3]=r[0]}c.writeFloatLE=o?a:p,c.writeFloatBE=o?p:a;function h(g,_){return r[0]=g[_],r[1]=g[_+1],r[2]=g[_+2],r[3]=g[_+3],s[0]}function m(g,_){return r[3]=g[_],r[2]=g[_+1],r[1]=g[_+2],r[0]=g[_+3],s[0]}c.readFloatLE=o?h:m,c.readFloatBE=o?m:h})():(function(){function s(o,a,p,h){var m=a<0?1:0;if(m&&(a=-a),a===0)o(1/a>0?0:2147483648,p,h);else if(isNaN(a))o(2143289344,p,h);else if(a>34028234663852886e22)o((m<<31|2139095040)>>>0,p,h);else if(a<11754943508222875e-54)o((m<<31|Math.round(a/1401298464324817e-60))>>>0,p,h);else{var g=Math.floor(Math.log(a)/Math.LN2),_=Math.round(a*Math.pow(2,-g)*8388608)&8388607;o((m<<31|g+127<<23|_)>>>0,p,h)}}c.writeFloatLE=s.bind(null,i),c.writeFloatBE=s.bind(null,u);function r(o,a,p){var h=o(a,p),m=(h>>31)*2+1,g=h>>>23&255,_=h&8388607;return g===255?_?NaN:m*(1/0):g===0?m*1401298464324817e-60*_:m*Math.pow(2,g-150)*(_+8388608)}c.readFloatLE=r.bind(null,l),c.readFloatBE=r.bind(null,d)})(),typeof Float64Array<"u"?(function(){var s=new Float64Array([-0]),r=new Uint8Array(s.buffer),o=r[7]===128;function a(g,_,w){s[0]=g,_[w]=r[0],_[w+1]=r[1],_[w+2]=r[2],_[w+3]=r[3],_[w+4]=r[4],_[w+5]=r[5],_[w+6]=r[6],_[w+7]=r[7]}function p(g,_,w){s[0]=g,_[w]=r[7],_[w+1]=r[6],_[w+2]=r[5],_[w+3]=r[4],_[w+4]=r[3],_[w+5]=r[2],_[w+6]=r[1],_[w+7]=r[0]}c.writeDoubleLE=o?a:p,c.writeDoubleBE=o?p:a;function h(g,_){return r[0]=g[_],r[1]=g[_+1],r[2]=g[_+2],r[3]=g[_+3],r[4]=g[_+4],r[5]=g[_+5],r[6]=g[_+6],r[7]=g[_+7],s[0]}function m(g,_){return r[7]=g[_],r[6]=g[_+1],r[5]=g[_+2],r[4]=g[_+3],r[3]=g[_+4],r[2]=g[_+5],r[1]=g[_+6],r[0]=g[_+7],s[0]}c.readDoubleLE=o?h:m,c.readDoubleBE=o?m:h})():(function(){function s(o,a,p,h,m,g){var _=h<0?1:0;if(_&&(h=-h),h===0)o(0,m,g+a),o(1/h>0?0:2147483648,m,g+p);else if(isNaN(h))o(0,m,g+a),o(2146959360,m,g+p);else if(h>17976931348623157e292)o(0,m,g+a),o((_<<31|2146435072)>>>0,m,g+p);else{var w;if(h<22250738585072014e-324)w=h/5e-324,o(w>>>0,m,g+a),o((_<<31|w/4294967296)>>>0,m,g+p);else{var y=Math.floor(Math.log(h)/Math.LN2);y===1024&&(y=1023),w=h*Math.pow(2,-y),o(w*4503599627370496>>>0,m,g+a),o((_<<31|y+1023<<20|w*1048576&1048575)>>>0,m,g+p)}}}c.writeDoubleLE=s.bind(null,i,0,4),c.writeDoubleBE=s.bind(null,u,4,0);function r(o,a,p,h,m){var g=o(h,m+a),_=o(h,m+p),w=(_>>31)*2+1,y=_>>>20&2047,T=4294967296*(_&1048575)+g;return y===2047?T?NaN:w*(1/0):y===0?w*5e-324*T:w*Math.pow(2,y-1075)*(T+4503599627370496)}c.readDoubleLE=r.bind(null,l,0,4),c.readDoubleBE=r.bind(null,d,4,0)})(),c}function i(c,s,r){s[r]=c&255,s[r+1]=c>>>8&255,s[r+2]=c>>>16&255,s[r+3]=c>>>24}function u(c,s,r){s[r]=c>>>24,s[r+1]=c>>>16&255,s[r+2]=c>>>8&255,s[r+3]=c&255}function l(c,s){return(c[s]|c[s+1]<<8|c[s+2]<<16|c[s+3]<<24)>>>0}function d(c,s){return(c[s]<<24|c[s+1]<<16|c[s+2]<<8|c[s+3])>>>0}}),xO=ae((e,t)=>{"use strict";t.exports=n;function n(i){try{if(typeof Bu!="function")return null;var u=Bu(i);return u&&(u.length||Object.keys(u).length)?u:null}catch{return null}}}),$O=ae(e=>{"use strict";var t=e,n="\uFFFD";t.length=function(i){for(var u=0,l=0,d=0;d=192&&s<224){var r=(s&31)<<6|i[c++]&63;d+=r>=128?String.fromCharCode(r):n}else if(s>=224&&s<240){var o=(s&15)<<12|(i[c++]&63)<<6|i[c++]&63;d+=o>=2048?String.fromCharCode(o):n}else if(s>=240){var a=(s&7)<<18|(i[c++]&63)<<12|(i[c++]&63)<<6|i[c++]&63;a<65536||a>1114111?d+=n:(a-=65536,d+=String.fromCharCode(55296+(a>>10)),d+=String.fromCharCode(56320+(a&1023)))}}return d},t.write=function(i,u,l){for(var d=l,c,s,r=0;r>6|192,u[l++]=c&63|128):(c&64512)===55296&&((s=i.charCodeAt(r+1))&64512)===56320?(c=65536+((c&1023)<<10)+(s&1023),++r,u[l++]=c>>18|240,u[l++]=c>>12&63|128,u[l++]=c>>6&63|128,u[l++]=c&63|128):(u[l++]=c>>12|224,u[l++]=c>>6&63|128,u[l++]=c&63|128);return l-d}}),TO=ae((e,t)=>{"use strict";t.exports=n;function n(i,u,l){var d=l||8192,c=d>>>1,s=null,r=d;return function(o){if(o<1||o>c)return i(o);r+o>d&&(s=i(d),r=0);var a=u.call(s,r,r+=o);return r&7&&(r=(r|7)+1),a}}}),SO=ae((e,t)=>{"use strict";t.exports=i;var n=_n();function i(c,s){this.lo=c>>>0,this.hi=s>>>0}var u=i.zero=new i(0,0);u.toNumber=function(){return 0},u.zzEncode=u.zzDecode=function(){return this},u.length=function(){return 1};var l=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(c){if(c===0)return u;var s=c<0;s&&(c=-c);var r=c>>>0,o=(c-r)/4294967296>>>0;return s&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new i(r,o)},i.from=function(c){if(typeof c=="number")return i.fromNumber(c);if(n.isString(c))if(n.Long)c=n.Long.fromString(c);else return i.fromNumber(parseInt(c,10));return c.low||c.high?new i(c.low>>>0,c.high>>>0):u},i.prototype.toNumber=function(c){if(!c&&this.hi>>>31){var s=~this.lo+1>>>0,r=~this.hi>>>0;return s||(r=r+1>>>0),-(s+r*4294967296)}return this.lo+this.hi*4294967296},i.prototype.toLong=function(c){return n.Long?new n.Long(this.lo|0,this.hi|0,!!c):{low:this.lo|0,high:this.hi|0,unsigned:!!c}};var d=String.prototype.charCodeAt;i.fromHash=function(c){return c===l?u:new i((d.call(c,0)|d.call(c,1)<<8|d.call(c,2)<<16|d.call(c,3)<<24)>>>0,(d.call(c,4)|d.call(c,5)<<8|d.call(c,6)<<16|d.call(c,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var c=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^c)>>>0,this.lo=(this.lo<<1^c)>>>0,this},i.prototype.zzDecode=function(){var c=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^c)>>>0,this.hi=(this.hi>>>1^c)>>>0,this},i.prototype.length=function(){var c=this.lo,s=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?s===0?c<16384?c<128?1:2:c<2097152?3:4:s<16384?s<128?5:6:s<2097152?7:8:r<128?9:10}}),IO=ae((e,t)=>{(function(n,i){function u(l){return l.default||l}typeof define=="function"&&define.amd?define([],function(){var l={};return i(l),u(l)}):typeof e=="object"?(i(e),typeof t=="object"&&(t.exports=u(e))):(function(){var l={};i(l),n.Long=u(l)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:e,function(n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=null;try{i=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function u(v,R,H){this.low=v|0,this.high=R|0,this.unsigned=!!H}u.prototype.__isLong__,Object.defineProperty(u.prototype,"__isLong__",{value:!0});function l(v){return(v&&v.__isLong__)===!0}function d(v){var R=Math.clz32(v&-v);return v?31-R:R}u.isLong=l;var c={},s={};function r(v,R){var H,L,V;return R?(v>>>=0,(V=0<=v&&v<256)&&(L=s[v],L)?L:(H=a(v,0,!0),V&&(s[v]=H),H)):(v|=0,(V=-128<=v&&v<128)&&(L=c[v],L)?L:(H=a(v,v<0?-1:0,!1),V&&(c[v]=H),H))}u.fromInt=r;function o(v,R){if(isNaN(v))return R?A:O;if(R){if(v<0)return A;if(v>=y)return J}else{if(v<=-T)return q;if(v+1>=T)return G}return v<0?o(-v,R).neg():a(v%w|0,v/w|0,R)}u.fromNumber=o;function a(v,R,H){return new u(v,R,H)}u.fromBits=a;var p=Math.pow;function h(v,R,H){if(v.length===0)throw Error("empty string");if(typeof R=="number"?(H=R,R=!1):R=!!R,v==="NaN"||v==="Infinity"||v==="+Infinity"||v==="-Infinity")return R?A:O;if(H=H||10,H<2||360)throw Error("interior hyphen");if(L===0)return h(v.substring(1),R,H).neg();for(var V=o(p(H,8)),K=O,B=0;B>>0:this.low},C.toNumber=function(){return this.unsigned?(this.high>>>0)*w+(this.low>>>0):this.high*w+(this.low>>>0)},C.toString=function(v){if(v=v||10,v<2||36>>0,N=Y.toString(v);if(K=te,K.isZero())return N+B;for(;N.length<6;)N="0"+N;B=""+N+B}},C.getHighBits=function(){return this.high},C.getHighBitsUnsigned=function(){return this.high>>>0},C.getLowBits=function(){return this.low},C.getLowBitsUnsigned=function(){return this.low>>>0},C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(q)?64:this.neg().getNumBitsAbs();for(var v=this.high!=0?this.high:this.low,R=31;R>0&&(v&1<>21;return v?this.unsigned?!1:v===-1&&!(this.low===0&&this.high===-2097152):!0},C.isZero=function(){return this.high===0&&this.low===0},C.eqz=C.isZero,C.isNegative=function(){return!this.unsigned&&this.high<0},C.isPositive=function(){return this.unsigned||this.high>=0},C.isOdd=function(){return(this.low&1)===1},C.isEven=function(){return(this.low&1)===0},C.equals=function(v){return l(v)||(v=m(v)),this.unsigned!==v.unsigned&&this.high>>>31===1&&v.high>>>31===1?!1:this.high===v.high&&this.low===v.low},C.eq=C.equals,C.notEquals=function(v){return!this.eq(v)},C.neq=C.notEquals,C.ne=C.notEquals,C.lessThan=function(v){return this.comp(v)<0},C.lt=C.lessThan,C.lessThanOrEqual=function(v){return this.comp(v)<=0},C.lte=C.lessThanOrEqual,C.le=C.lessThanOrEqual,C.greaterThan=function(v){return this.comp(v)>0},C.gt=C.greaterThan,C.greaterThanOrEqual=function(v){return this.comp(v)>=0},C.gte=C.greaterThanOrEqual,C.ge=C.greaterThanOrEqual,C.compare=function(v){if(l(v)||(v=m(v)),this.eq(v))return 0;var R=this.isNegative(),H=v.isNegative();return R&&!H?-1:!R&&H?1:this.unsigned?v.high>>>0>this.high>>>0||v.high===this.high&&v.low>>>0>this.low>>>0?-1:1:this.sub(v).isNegative()?-1:1},C.comp=C.compare,C.negate=function(){return!this.unsigned&&this.eq(q)?q:this.not().add(P)},C.neg=C.negate,C.add=function(v){l(v)||(v=m(v));var R=this.high>>>16,H=this.high&65535,L=this.low>>>16,V=this.low&65535,K=v.high>>>16,B=v.high&65535,te=v.low>>>16,Y=v.low&65535,N=0,X=0,W=0,re=0;return re+=V+Y,W+=re>>>16,re&=65535,W+=L+te,X+=W>>>16,W&=65535,X+=H+B,N+=X>>>16,X&=65535,N+=R+K,N&=65535,a(W<<16|re,N<<16|X,this.unsigned)},C.subtract=function(v){return l(v)||(v=m(v)),this.add(v.neg())},C.sub=C.subtract,C.multiply=function(v){if(this.isZero())return this;if(l(v)||(v=m(v)),i){var R=i.mul(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}if(v.isZero())return this.unsigned?A:O;if(this.eq(q))return v.isOdd()?q:O;if(v.eq(q))return this.isOdd()?q:O;if(this.isNegative())return v.isNegative()?this.neg().mul(v.neg()):this.neg().mul(v).neg();if(v.isNegative())return this.mul(v.neg()).neg();if(this.lt(S)&&v.lt(S))return o(this.toNumber()*v.toNumber(),this.unsigned);var H=this.high>>>16,L=this.high&65535,V=this.low>>>16,K=this.low&65535,B=v.high>>>16,te=v.high&65535,Y=v.low>>>16,N=v.low&65535,X=0,W=0,re=0,le=0;return le+=K*N,re+=le>>>16,le&=65535,re+=V*N,W+=re>>>16,re&=65535,re+=K*Y,W+=re>>>16,re&=65535,W+=L*N,X+=W>>>16,W&=65535,W+=V*Y,X+=W>>>16,W&=65535,W+=K*te,X+=W>>>16,W&=65535,X+=H*N+L*Y+V*te+K*B,X&=65535,a(re<<16|le,X<<16|W,this.unsigned)},C.mul=C.multiply,C.divide=function(v){if(l(v)||(v=m(v)),v.isZero())throw Error("division by zero");if(i){if(!this.unsigned&&this.high===-2147483648&&v.low===-1&&v.high===-1)return this;var R=(this.unsigned?i.div_u:i.div_s)(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?A:O;var H,L,V;if(this.unsigned){if(v.unsigned||(v=v.toUnsigned()),v.gt(this))return A;if(v.gt(this.shru(1)))return I;V=A}else{if(this.eq(q)){if(v.eq(P)||v.eq(z))return q;if(v.eq(q))return P;var K=this.shr(1);return H=K.div(v).shl(1),H.eq(O)?v.isNegative()?P:z:(L=this.sub(v.mul(H)),V=H.add(L.div(v)),V)}else if(v.eq(q))return this.unsigned?A:O;if(this.isNegative())return v.isNegative()?this.neg().div(v.neg()):this.neg().div(v).neg();if(v.isNegative())return this.div(v.neg()).neg();V=O}for(L=this;L.gte(v);){H=Math.max(1,Math.floor(L.toNumber()/v.toNumber()));for(var B=Math.ceil(Math.log(H)/Math.LN2),te=B<=48?1:p(2,B-48),Y=o(H),N=Y.mul(v);N.isNegative()||N.gt(L);)H-=te,Y=o(H,this.unsigned),N=Y.mul(v);Y.isZero()&&(Y=P),V=V.add(Y),L=L.sub(N)}return V},C.div=C.divide,C.modulo=function(v){if(l(v)||(v=m(v)),i){var R=(this.unsigned?i.rem_u:i.rem_s)(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}return this.sub(this.div(v).mul(v))},C.mod=C.modulo,C.rem=C.modulo,C.not=function(){return a(~this.low,~this.high,this.unsigned)},C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},C.clz=C.countLeadingZeros,C.countTrailingZeros=function(){return this.low?d(this.low):d(this.high)+32},C.ctz=C.countTrailingZeros,C.and=function(v){return l(v)||(v=m(v)),a(this.low&v.low,this.high&v.high,this.unsigned)},C.or=function(v){return l(v)||(v=m(v)),a(this.low|v.low,this.high|v.high,this.unsigned)},C.xor=function(v){return l(v)||(v=m(v)),a(this.low^v.low,this.high^v.high,this.unsigned)},C.shiftLeft=function(v){return l(v)&&(v=v.toInt()),(v&=63)===0?this:v<32?a(this.low<>>32-v,this.unsigned):a(0,this.low<>>v|this.high<<32-v,this.high>>v,this.unsigned):a(this.high>>v-32,this.high>=0?0:-1,this.unsigned)},C.shr=C.shiftRight,C.shiftRightUnsigned=function(v){return l(v)&&(v=v.toInt()),(v&=63)===0?this:v<32?a(this.low>>>v|this.high<<32-v,this.high>>>v,this.unsigned):v===32?a(this.high,0,this.unsigned):a(this.high>>>v-32,0,this.unsigned)},C.shru=C.shiftRightUnsigned,C.shr_u=C.shiftRightUnsigned,C.rotateLeft=function(v){var R;return l(v)&&(v=v.toInt()),(v&=63)===0?this:v===32?a(this.high,this.low,this.unsigned):v<32?(R=32-v,a(this.low<>>R,this.high<>>R,this.unsigned)):(v-=32,R=32-v,a(this.high<>>R,this.low<>>R,this.unsigned))},C.rotl=C.rotateLeft,C.rotateRight=function(v){var R;return l(v)&&(v=v.toInt()),(v&=63)===0?this:v===32?a(this.high,this.low,this.unsigned):v<32?(R=32-v,a(this.high<>>v,this.low<>>v,this.unsigned)):(v-=32,R=32-v,a(this.low<>>v,this.high<>>v,this.unsigned))},C.rotr=C.rotateRight,C.toSigned=function(){return this.unsigned?a(this.low,this.high,!1):this},C.toUnsigned=function(){return this.unsigned?this:a(this.low,this.high,!0)},C.toBytes=function(v){return v?this.toBytesLE():this.toBytesBE()},C.toBytesLE=function(){var v=this.high,R=this.low;return[R&255,R>>>8&255,R>>>16&255,R>>>24,v&255,v>>>8&255,v>>>16&255,v>>>24]},C.toBytesBE=function(){var v=this.high,R=this.low;return[v>>>24,v>>>16&255,v>>>8&255,v&255,R>>>24,R>>>16&255,R>>>8&255,R&255]},u.fromBytes=function(v,R,H){return H?u.fromBytesLE(v,R):u.fromBytesBE(v,R)},u.fromBytesLE=function(v,R){return new u(v[0]|v[1]<<8|v[2]<<16|v[3]<<24,v[4]|v[5]<<8|v[6]<<16|v[7]<<24,R)},u.fromBytesBE=function(v,R){return new u(v[4]<<24|v[5]<<16|v[6]<<8|v[7],v[0]<<24|v[1]<<16|v[2]<<8|v[3],R)},typeof BigInt=="function"&&(u.fromBigInt=function(v,R){var H=Number(BigInt.asIntN(32,v)),L=Number(BigInt.asIntN(32,v>>BigInt(32)));return a(H,L,R)},u.fromValue=function(v,R){return typeof v=="bigint"?u.fromBigInt(v,R):m(v,R)},C.toBigInt=function(){var v=BigInt(this.low>>>0),R=BigInt(this.unsigned?this.high>>>0:this.high);return R<{"use strict";var t=e;t.asPromise=yO(),t.base64=wO(),t.EventEmitter=_O(),t.float=vO(),t.inquire=xO(),t.utf8=$O(),t.pool=TO(),t.LongBits=SO();function n(l){return l==="__proto__"||l==="prototype"||l==="constructor"}t.isUnsafeProperty=n,t.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node),t.global=t.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||e,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(l){return typeof l=="number"&&isFinite(l)&&Math.floor(l)===l},t.isString=function(l){return typeof l=="string"||l instanceof String},t.isObject=function(l){return l&&typeof l=="object"},t.isset=t.isSet=function(l,d){var c=l[d];return c!=null&&Object.hasOwnProperty.call(l,d)?typeof c!="object"||(Array.isArray(c)?c.length:Object.keys(c).length)>0:!1},t.Buffer=(function(){try{var l=t.global.Buffer;return l.prototype.utf8Write?l:null}catch{return null}})(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(l){return typeof l=="number"?t.Buffer?t._Buffer_allocUnsafe(l):new t.Array(l):t.Buffer?t._Buffer_from(l):typeof Uint8Array>"u"?l:new Uint8Array(l)},t.Array=typeof Uint8Array<"u"?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||(function(){try{var l=IO();return l&&l.isLong?l:null}catch{return null}})(),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(l){return l?t.LongBits.from(l).toHash():t.LongBits.zeroHash},t.longFromHash=function(l,d){var c=t.LongBits.fromHash(l);return t.Long?t.Long.fromBits(c.lo,c.hi,d):c.toNumber(!!d)};function i(l){var d=typeof arguments[arguments.length-1]=="boolean",c=d?arguments.length-1:arguments.length;d=d&&arguments[arguments.length-1];for(var s=1;s-1;--r)if(d[s[r]]===1&&this[s[r]]!==void 0&&this[s[r]]!==null)return s[r]}},t.oneOfSetter=function(l){return function(d){for(var c=0;c{"use strict";t.exports=o;var n=_n(),i,u=n.LongBits,l=n.base64,d=n.utf8;function c(y,T,S){this.fn=y,this.len=T,this.next=void 0,this.val=S}function s(){}function r(y){this.head=y.head,this.tail=y.tail,this.len=y.len,this.next=y.states}function o(){this.len=0,this.head=new c(s,0,0),this.tail=this.head,this.states=null}var a=function(){return n.Buffer?function(){return(o.create=function(){return new i})()}:function(){return new o}};o.create=a(),o.alloc=function(y){return new n.Array(y)},n.Array!==Array&&(o.alloc=n.pool(o.alloc,n.Array.prototype.subarray)),o.prototype._push=function(y,T,S){return this.tail=this.tail.next=new c(y,T,S),this.len+=T,this};function p(y,T,S){T[S]=y&255}function h(y,T,S){for(;y>127;)T[S++]=y&127|128,y>>>=7;T[S]=y}function m(y,T){this.len=y,this.next=void 0,this.val=T}m.prototype=Object.create(c.prototype),m.prototype.fn=h,o.prototype.uint32=function(y){return this.len+=(this.tail=this.tail.next=new m((y=y>>>0)<128?1:y<16384?2:y<2097152?3:y<268435456?4:5,y)).len,this},o.prototype.int32=function(y){return(y|=0)<0?this._push(g,10,u.fromNumber(y)):this.uint32(y)},o.prototype.sint32=function(y){return this.uint32((y<<1^y>>31)>>>0)};function g(y,T,S){for(var O=y.lo,A=y.hi;A;)T[S++]=O&127|128,O=(O>>>7|A<<25)>>>0,A>>>=7;for(;O>127;)T[S++]=O&127|128,O=O>>>7;T[S++]=O}o.prototype.uint64=function(y){var T=u.from(y);return this._push(g,T.length(),T)},o.prototype.int64=o.prototype.uint64,o.prototype.sint64=function(y){var T=u.from(y).zzEncode();return this._push(g,T.length(),T)},o.prototype.bool=function(y){return this._push(p,1,y?1:0)};function _(y,T,S){T[S]=y&255,T[S+1]=y>>>8&255,T[S+2]=y>>>16&255,T[S+3]=y>>>24}o.prototype.fixed32=function(y){return this._push(_,4,y>>>0)},o.prototype.sfixed32=o.prototype.fixed32,o.prototype.fixed64=function(y){var T=u.from(y);return this._push(_,4,T.lo)._push(_,4,T.hi)},o.prototype.sfixed64=o.prototype.fixed64,o.prototype.float=function(y){return this._push(n.float.writeFloatLE,4,y)},o.prototype.double=function(y){return this._push(n.float.writeDoubleLE,8,y)};var w=n.Array.prototype.set?function(y,T,S){T.set(y,S)}:function(y,T,S){for(var O=0;O>>0;if(!T)return this._push(p,1,0);if(n.isString(y)){var S=o.alloc(T=l.length(y));l.decode(y,S,0),y=S}return this.uint32(T)._push(w,T,y)},o.prototype.string=function(y){var T=d.length(y);return T?this.uint32(T)._push(d.write,T,y):this._push(p,1,0)},o.prototype.fork=function(){return this.states=new r(this),this.head=this.tail=new c(s,0,0),this.len=0,this},o.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(s,0,0),this.len=0),this},o.prototype.ldelim=function(){var y=this.head,T=this.tail,S=this.len;return this.reset().uint32(S),S&&(this.tail.next=y.next,this.tail=T,this.len+=S),this},o.prototype.finish=function(){for(var y=this.head.next,T=this.constructor.alloc(this.len),S=0;y;)y.fn(y.val,T,S),S+=y.len,y=y.next;return T},o._configure=function(y){i=y,o.create=a(),i._configure()}}),OO=ae((e,t)=>{"use strict";t.exports=u;var n=yw();(u.prototype=Object.create(n.prototype)).constructor=u;var i=_n();function u(){n.call(this)}u._configure=function(){u.alloc=i._Buffer_allocUnsafe,u.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&i.Buffer.prototype.set.name==="set"?function(d,c,s){c.set(d,s)}:function(d,c,s){if(d.copy)d.copy(c,s,0,d.length);else for(var r=0;r>>0;return this.uint32(c),c&&this._push(u.writeBytesBuffer,c,d),this};function l(d,c,s){d.length<40?i.utf8.write(d,c,s):c.utf8Write?c.utf8Write(d,s):c.write(d,s)}u.prototype.string=function(d){var c=i.Buffer.byteLength(d);return this.uint32(c),c&&this._push(l,c,d),this},u._configure()}),ww=ae((e,t)=>{"use strict";t.exports=c;var n=_n(),i,u=n.LongBits,l=n.utf8;function d(h,m){return RangeError("index out of range: "+h.pos+" + "+(m||1)+" > "+h.len)}function c(h){this.buf=h,this.pos=0,this.len=h.length}var s=typeof Uint8Array<"u"?function(h){if(h instanceof Uint8Array||Array.isArray(h))return new c(h);throw Error("illegal buffer")}:function(h){if(Array.isArray(h))return new c(h);throw Error("illegal buffer")},r=function(){return n.Buffer?function(h){return(c.create=function(m){return n.Buffer.isBuffer(m)?new i(m):s(m)})(h)}:s};c.create=r(),c.prototype._slice=n.Array.prototype.subarray||n.Array.prototype.slice,c.prototype.uint32=(function(){var h=4294967295;return function(){if(h=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(h=(h|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return h;if((this.pos+=5)>this.len)throw this.pos=this.len,d(this,10);return h}})(),c.prototype.int32=function(){return this.uint32()|0},c.prototype.sint32=function(){var h=this.uint32();return h>>>1^-(h&1)|0};function o(){var h=new u(0,0),m=0;if(this.len-this.pos>4){for(;m<4;++m)if(h.lo=(h.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h;if(h.lo=(h.lo|(this.buf[this.pos]&127)<<28)>>>0,h.hi=(h.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return h;m=0}else{for(;m<3;++m){if(this.pos>=this.len)throw d(this);if(h.lo=(h.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}return h.lo=(h.lo|(this.buf[this.pos++]&127)<>>0,h}if(this.len-this.pos>4){for(;m<5;++m)if(h.hi=(h.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}else for(;m<5;++m){if(this.pos>=this.len)throw d(this);if(h.hi=(h.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}throw Error("invalid varint encoding")}c.prototype.bool=function(){return this.uint32()!==0};function a(h,m){return(h[m-4]|h[m-3]<<8|h[m-2]<<16|h[m-1]<<24)>>>0}c.prototype.fixed32=function(){if(this.pos+4>this.len)throw d(this,4);return a(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw d(this,4);return a(this.buf,this.pos+=4)|0};function p(){if(this.pos+8>this.len)throw d(this,8);return new u(a(this.buf,this.pos+=4),a(this.buf,this.pos+=4))}c.prototype.float=function(){if(this.pos+4>this.len)throw d(this,4);var h=n.float.readFloatLE(this.buf,this.pos);return this.pos+=4,h},c.prototype.double=function(){if(this.pos+8>this.len)throw d(this,4);var h=n.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,h},c.prototype.bytes=function(){var h=this.uint32(),m=this.pos,g=this.pos+h;if(g>this.len)throw d(this,h);if(this.pos+=h,Array.isArray(this.buf))return this.buf.slice(m,g);if(m===g){var _=n.Buffer;return _?_.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,m,g)},c.prototype.string=function(){var h=this.bytes();return l.read(h,0,h.length)},c.prototype.skip=function(h){if(typeof h=="number"){if(this.pos+h>this.len)throw d(this,h);this.pos+=h}else do if(this.pos>=this.len)throw d(this);while(this.buf[this.pos++]&128);return this},c.recursionLimit=n.recursionLimit,c.prototype.skipType=function(h,m){if(m===void 0&&(m=0),m>c.recursionLimit)throw Error("maximum nesting depth exceeded");switch(h){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(h=this.uint32()&7)!==4;)this.skipType(h,m+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+h+" at offset "+this.pos)}return this},c._configure=function(h){i=h,c.create=r(),i._configure();var m=n.Long?"toLong":"toNumber";n.merge(c.prototype,{int64:function(){return o.call(this)[m](!1)},uint64:function(){return o.call(this)[m](!0)},sint64:function(){return o.call(this).zzDecode()[m](!1)},fixed64:function(){return p.call(this)[m](!0)},sfixed64:function(){return p.call(this)[m](!1)}})}}),EO=ae((e,t)=>{"use strict";t.exports=u;var n=ww();(u.prototype=Object.create(n.prototype)).constructor=u;var i=_n();function u(l){n.call(this,l)}u._configure=function(){i.Buffer&&(u.prototype._slice=i.Buffer.prototype.slice)},u.prototype.string=function(){var l=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+l,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+l,this.len))},u._configure()}),AO=ae((e,t)=>{"use strict";t.exports=i;var n=_n();(i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i;function i(u,l,d){if(typeof u!="function")throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=u,this.requestDelimited=!!l,this.responseDelimited=!!d}i.prototype.rpcCall=function u(l,d,c,s,r){if(!s)throw TypeError("request must be specified");var o=this;if(!r)return n.asPromise(u,o,l,d,c,s);if(!o.rpcImpl){setTimeout(function(){r(Error("already ended"))},0);return}try{return o.rpcImpl(l,d[o.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(a,p){if(a)return o.emit("error",a,l),r(a);if(p===null){o.end(!0);return}if(!(p instanceof c))try{p=c[o.responseDelimited?"decodeDelimited":"decode"](p)}catch(h){return o.emit("error",h,l),r(h)}return o.emit("data",p,l),r(null,p)})}catch(a){o.emit("error",a,l),setTimeout(function(){r(a)},0);return}},i.prototype.end=function(u){return this.rpcImpl&&(u||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}}),kO=ae(e=>{"use strict";var t=e;t.Service=AO()}),PO=ae((e,t)=>{"use strict";t.exports=Object.create(null)}),CO=ae(e=>{"use strict";var t=e;t.build="minimal",t.Writer=yw(),t.BufferWriter=OO(),t.Reader=ww(),t.BufferReader=EO(),t.util=_n(),t.rpc=kO(),t.roots=PO(),t.configure=n;function n(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}n()}),RO=ae((e,t)=>{"use strict";t.exports=CO()}),Ni=ae((e,t)=>{"use strict";var n=RO(),i=n.Reader,u=n.Writer,l=n.util,d=n.roots.default||(n.roots.default={});d.onnx=(function(){var c={};return c.Version=(function(){var s={},r=Object.create(s);return r[s[0]="_START_VERSION"]=0,r[s[1]="IR_VERSION_2017_10_10"]=1,r[s[2]="IR_VERSION_2017_10_30"]=2,r[s[3]="IR_VERSION_2017_11_3"]=3,r[s[4]="IR_VERSION_2019_1_22"]=4,r[s[5]="IR_VERSION_2019_3_18"]=5,r[s[6]="IR_VERSION_2019_9_19"]=6,r[s[7]="IR_VERSION_2020_5_8"]=7,r[s[8]="IR_VERSION_2021_7_30"]=8,r[s[9]="IR_VERSION"]=9,r})(),c.AttributeProto=(function(){function s(r){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparseTensors=[],this.typeProtos=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.name=r.string();break}case 21:{p.refAttrName=r.string();break}case 13:{p.docString=r.string();break}case 20:{p.type=r.int32();break}case 2:{p.f=r.float();break}case 3:{p.i=r.int64();break}case 4:{p.s=r.bytes();break}case 5:{p.t=d.onnx.TensorProto.decode(r,r.uint32());break}case 6:{p.g=d.onnx.GraphProto.decode(r,r.uint32());break}case 22:{p.sparseTensor=d.onnx.SparseTensorProto.decode(r,r.uint32());break}case 14:{p.tp=d.onnx.TypeProto.decode(r,r.uint32());break}case 7:{if(p.floats&&p.floats.length||(p.floats=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.i.high>>>0).toNumber())),r.s!=null&&(typeof r.s=="string"?l.base64.decode(r.s,o.s=l.newBuffer(l.base64.length(r.s)),0):r.s.length>=0&&(o.s=r.s)),r.t!=null){if(typeof r.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");o.t=d.onnx.TensorProto.fromObject(r.t)}if(r.g!=null){if(typeof r.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");o.g=d.onnx.GraphProto.fromObject(r.g)}if(r.sparseTensor!=null){if(typeof r.sparseTensor!="object")throw TypeError(".onnx.AttributeProto.sparseTensor: object expected");o.sparseTensor=d.onnx.SparseTensorProto.fromObject(r.sparseTensor)}if(r.tp!=null){if(typeof r.tp!="object")throw TypeError(".onnx.AttributeProto.tp: object expected");o.tp=d.onnx.TypeProto.fromObject(r.tp)}if(r.floats){if(!Array.isArray(r.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");o.floats=[];for(var a=0;a>>0,r.ints[a].high>>>0).toNumber())}if(r.strings){if(!Array.isArray(r.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");o.strings=[];for(var a=0;a=0&&(o.strings[a]=r.strings[a])}if(r.tensors){if(!Array.isArray(r.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");o.tensors=[];for(var a=0;a>>0,r.i.high>>>0).toNumber():r.i),r.s!=null&&r.hasOwnProperty("s")&&(a.s=o.bytes===String?l.base64.encode(r.s,0,r.s.length):o.bytes===Array?Array.prototype.slice.call(r.s):r.s),r.t!=null&&r.hasOwnProperty("t")&&(a.t=d.onnx.TensorProto.toObject(r.t,o)),r.g!=null&&r.hasOwnProperty("g")&&(a.g=d.onnx.GraphProto.toObject(r.g,o)),r.floats&&r.floats.length){a.floats=[];for(var h=0;h>>0,r.ints[h].high>>>0).toNumber():r.ints[h]}if(r.strings&&r.strings.length){a.strings=[];for(var h=0;h>>3){case 1:{p.name=r.string();break}case 2:{p.type=d.onnx.TypeProto.decode(r,r.uint32());break}case 3:{p.docString=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!l.isString(r.name))return"name: string expected";if(r.type!=null&&r.hasOwnProperty("type")){var o=d.onnx.TypeProto.verify(r.type);if(o)return"type."+o}return r.docString!=null&&r.hasOwnProperty("docString")&&!l.isString(r.docString)?"docString: string expected":null},s.fromObject=function(r){if(r instanceof d.onnx.ValueInfoProto)return r;var o=new d.onnx.ValueInfoProto;if(r.name!=null&&(o.name=String(r.name)),r.type!=null){if(typeof r.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");o.type=d.onnx.TypeProto.fromObject(r.type)}return r.docString!=null&&(o.docString=String(r.docString)),o},s.toObject=function(r,o){o||(o={});var a={};return o.defaults&&(a.name="",a.type=null,a.docString=""),r.name!=null&&r.hasOwnProperty("name")&&(a.name=r.name),r.type!=null&&r.hasOwnProperty("type")&&(a.type=d.onnx.TypeProto.toObject(r.type,o)),r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.ValueInfoProto"},s})(),c.NodeProto=(function(){function s(r){if(this.input=[],this.output=[],this.attribute=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.input&&p.input.length||(p.input=[]),p.input.push(r.string());break}case 2:{p.output&&p.output.length||(p.output=[]),p.output.push(r.string());break}case 3:{p.name=r.string();break}case 4:{p.opType=r.string();break}case 7:{p.domain=r.string();break}case 5:{p.attribute&&p.attribute.length||(p.attribute=[]),p.attribute.push(d.onnx.AttributeProto.decode(r,r.uint32()));break}case 6:{p.docString=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var o=0;o>>3){case 1:{p.initialization=d.onnx.GraphProto.decode(r,r.uint32());break}case 2:{p.algorithm=d.onnx.GraphProto.decode(r,r.uint32());break}case 3:{p.initializationBinding&&p.initializationBinding.length||(p.initializationBinding=[]),p.initializationBinding.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 4:{p.updateBinding&&p.updateBinding.length||(p.updateBinding=[]),p.updateBinding.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.initialization!=null&&r.hasOwnProperty("initialization")){var o=d.onnx.GraphProto.verify(r.initialization);if(o)return"initialization."+o}if(r.algorithm!=null&&r.hasOwnProperty("algorithm")){var o=d.onnx.GraphProto.verify(r.algorithm);if(o)return"algorithm."+o}if(r.initializationBinding!=null&&r.hasOwnProperty("initializationBinding")){if(!Array.isArray(r.initializationBinding))return"initializationBinding: array expected";for(var a=0;a>>3){case 1:{p.irVersion=r.int64();break}case 8:{p.opsetImport&&p.opsetImport.length||(p.opsetImport=[]),p.opsetImport.push(d.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 2:{p.producerName=r.string();break}case 3:{p.producerVersion=r.string();break}case 4:{p.domain=r.string();break}case 5:{p.modelVersion=r.int64();break}case 6:{p.docString=r.string();break}case 7:{p.graph=d.onnx.GraphProto.decode(r,r.uint32());break}case 14:{p.metadataProps&&p.metadataProps.length||(p.metadataProps=[]),p.metadataProps.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 20:{p.trainingInfo&&p.trainingInfo.length||(p.trainingInfo=[]),p.trainingInfo.push(d.onnx.TrainingInfoProto.decode(r,r.uint32()));break}case 25:{p.functions&&p.functions.length||(p.functions=[]),p.functions.push(d.onnx.FunctionProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.irVersion!=null&&r.hasOwnProperty("irVersion")&&!l.isInteger(r.irVersion)&&!(r.irVersion&&l.isInteger(r.irVersion.low)&&l.isInteger(r.irVersion.high)))return"irVersion: integer|Long expected";if(r.opsetImport!=null&&r.hasOwnProperty("opsetImport")){if(!Array.isArray(r.opsetImport))return"opsetImport: array expected";for(var o=0;o>>0,r.irVersion.high>>>0).toNumber())),r.opsetImport){if(!Array.isArray(r.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");o.opsetImport=[];for(var a=0;a>>0,r.modelVersion.high>>>0).toNumber())),r.docString!=null&&(o.docString=String(r.docString)),r.graph!=null){if(typeof r.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");o.graph=d.onnx.GraphProto.fromObject(r.graph)}if(r.metadataProps){if(!Array.isArray(r.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");o.metadataProps=[];for(var a=0;a>>0,r.irVersion.high>>>0).toNumber():r.irVersion),r.producerName!=null&&r.hasOwnProperty("producerName")&&(a.producerName=r.producerName),r.producerVersion!=null&&r.hasOwnProperty("producerVersion")&&(a.producerVersion=r.producerVersion),r.domain!=null&&r.hasOwnProperty("domain")&&(a.domain=r.domain),r.modelVersion!=null&&r.hasOwnProperty("modelVersion")&&(typeof r.modelVersion=="number"?a.modelVersion=o.longs===String?String(r.modelVersion):r.modelVersion:a.modelVersion=o.longs===String?l.Long.prototype.toString.call(r.modelVersion):o.longs===Number?new l.LongBits(r.modelVersion.low>>>0,r.modelVersion.high>>>0).toNumber():r.modelVersion),r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),r.graph!=null&&r.hasOwnProperty("graph")&&(a.graph=d.onnx.GraphProto.toObject(r.graph,o)),r.opsetImport&&r.opsetImport.length){a.opsetImport=[];for(var h=0;h>>3){case 1:{p.key=r.string();break}case 2:{p.value=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){return typeof r!="object"||r===null?"object expected":r.key!=null&&r.hasOwnProperty("key")&&!l.isString(r.key)?"key: string expected":r.value!=null&&r.hasOwnProperty("value")&&!l.isString(r.value)?"value: string expected":null},s.fromObject=function(r){if(r instanceof d.onnx.StringStringEntryProto)return r;var o=new d.onnx.StringStringEntryProto;return r.key!=null&&(o.key=String(r.key)),r.value!=null&&(o.value=String(r.value)),o},s.toObject=function(r,o){o||(o={});var a={};return o.defaults&&(a.key="",a.value=""),r.key!=null&&r.hasOwnProperty("key")&&(a.key=r.key),r.value!=null&&r.hasOwnProperty("value")&&(a.value=r.value),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.StringStringEntryProto"},s})(),c.TensorAnnotation=(function(){function s(r){if(this.quantParameterTensorNames=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.tensorName=r.string();break}case 2:{p.quantParameterTensorNames&&p.quantParameterTensorNames.length||(p.quantParameterTensorNames=[]),p.quantParameterTensorNames.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.tensorName!=null&&r.hasOwnProperty("tensorName")&&!l.isString(r.tensorName))return"tensorName: string expected";if(r.quantParameterTensorNames!=null&&r.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(r.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var o=0;o>>3){case 1:{p.node&&p.node.length||(p.node=[]),p.node.push(d.onnx.NodeProto.decode(r,r.uint32()));break}case 2:{p.name=r.string();break}case 5:{p.initializer&&p.initializer.length||(p.initializer=[]),p.initializer.push(d.onnx.TensorProto.decode(r,r.uint32()));break}case 15:{p.sparseInitializer&&p.sparseInitializer.length||(p.sparseInitializer=[]),p.sparseInitializer.push(d.onnx.SparseTensorProto.decode(r,r.uint32()));break}case 10:{p.docString=r.string();break}case 11:{p.input&&p.input.length||(p.input=[]),p.input.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 12:{p.output&&p.output.length||(p.output=[]),p.output.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 13:{p.valueInfo&&p.valueInfo.length||(p.valueInfo=[]),p.valueInfo.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 14:{p.quantizationAnnotation&&p.quantizationAnnotation.length||(p.quantizationAnnotation=[]),p.quantizationAnnotation.push(d.onnx.TensorAnnotation.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.node!=null&&r.hasOwnProperty("node")){if(!Array.isArray(r.node))return"node: array expected";for(var o=0;o>>3){case 1:{if(p.dims&&p.dims.length||(p.dims=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[a].high>>>0).toNumber())}if(r.dataType!=null&&(o.dataType=r.dataType|0),r.segment!=null){if(typeof r.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");o.segment=d.onnx.TensorProto.Segment.fromObject(r.segment)}if(r.floatData){if(!Array.isArray(r.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");o.floatData=[];for(var a=0;a=0&&(o.stringData[a]=r.stringData[a])}if(r.int64Data){if(!Array.isArray(r.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");o.int64Data=[];for(var a=0;a>>0,r.int64Data[a].high>>>0).toNumber())}if(r.name!=null&&(o.name=String(r.name)),r.docString!=null&&(o.docString=String(r.docString)),r.rawData!=null&&(typeof r.rawData=="string"?l.base64.decode(r.rawData,o.rawData=l.newBuffer(l.base64.length(r.rawData)),0):r.rawData.length>=0&&(o.rawData=r.rawData)),r.externalData){if(!Array.isArray(r.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");o.externalData=[];for(var a=0;a>>0,r.uint64Data[a].high>>>0).toNumber(!0))}return o},s.toObject=function(r,o){o||(o={});var a={};if((o.arrays||o.defaults)&&(a.dims=[],a.floatData=[],a.int32Data=[],a.stringData=[],a.int64Data=[],a.doubleData=[],a.uint64Data=[],a.externalData=[]),o.defaults&&(a.dataType=0,a.segment=null,a.name="",o.bytes===String?a.rawData="":(a.rawData=[],o.bytes!==Array&&(a.rawData=l.newBuffer(a.rawData))),a.docString="",a.dataLocation=o.enums===String?"DEFAULT":0),r.dims&&r.dims.length){a.dims=[];for(var p=0;p>>0,r.dims[p].high>>>0).toNumber():r.dims[p]}if(r.dataType!=null&&r.hasOwnProperty("dataType")&&(a.dataType=r.dataType),r.segment!=null&&r.hasOwnProperty("segment")&&(a.segment=d.onnx.TensorProto.Segment.toObject(r.segment,o)),r.floatData&&r.floatData.length){a.floatData=[];for(var p=0;p>>0,r.int64Data[p].high>>>0).toNumber():r.int64Data[p]}if(r.name!=null&&r.hasOwnProperty("name")&&(a.name=r.name),r.rawData!=null&&r.hasOwnProperty("rawData")&&(a.rawData=o.bytes===String?l.base64.encode(r.rawData,0,r.rawData.length):o.bytes===Array?Array.prototype.slice.call(r.rawData):r.rawData),r.doubleData&&r.doubleData.length){a.doubleData=[];for(var p=0;p>>0,r.uint64Data[p].high>>>0).toNumber(!0):r.uint64Data[p]}if(r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),r.externalData&&r.externalData.length){a.externalData=[];for(var p=0;p>>3){case 1:{h.begin=o.int64();break}case 2:{h.end=o.int64();break}default:o.skipType(m&7);break}}return h},r.decodeDelimited=function(o){return o instanceof i||(o=new i(o)),this.decode(o,o.uint32())},r.verify=function(o){return typeof o!="object"||o===null?"object expected":o.begin!=null&&o.hasOwnProperty("begin")&&!l.isInteger(o.begin)&&!(o.begin&&l.isInteger(o.begin.low)&&l.isInteger(o.begin.high))?"begin: integer|Long expected":o.end!=null&&o.hasOwnProperty("end")&&!l.isInteger(o.end)&&!(o.end&&l.isInteger(o.end.low)&&l.isInteger(o.end.high))?"end: integer|Long expected":null},r.fromObject=function(o){if(o instanceof d.onnx.TensorProto.Segment)return o;var a=new d.onnx.TensorProto.Segment;return o.begin!=null&&(l.Long?(a.begin=l.Long.fromValue(o.begin)).unsigned=!1:typeof o.begin=="string"?a.begin=parseInt(o.begin,10):typeof o.begin=="number"?a.begin=o.begin:typeof o.begin=="object"&&(a.begin=new l.LongBits(o.begin.low>>>0,o.begin.high>>>0).toNumber())),o.end!=null&&(l.Long?(a.end=l.Long.fromValue(o.end)).unsigned=!1:typeof o.end=="string"?a.end=parseInt(o.end,10):typeof o.end=="number"?a.end=o.end:typeof o.end=="object"&&(a.end=new l.LongBits(o.end.low>>>0,o.end.high>>>0).toNumber())),a},r.toObject=function(o,a){a||(a={});var p={};if(a.defaults){if(l.Long){var h=new l.Long(0,0,!1);p.begin=a.longs===String?h.toString():a.longs===Number?h.toNumber():h}else p.begin=a.longs===String?"0":0;if(l.Long){var h=new l.Long(0,0,!1);p.end=a.longs===String?h.toString():a.longs===Number?h.toNumber():h}else p.end=a.longs===String?"0":0}return o.begin!=null&&o.hasOwnProperty("begin")&&(typeof o.begin=="number"?p.begin=a.longs===String?String(o.begin):o.begin:p.begin=a.longs===String?l.Long.prototype.toString.call(o.begin):a.longs===Number?new l.LongBits(o.begin.low>>>0,o.begin.high>>>0).toNumber():o.begin),o.end!=null&&o.hasOwnProperty("end")&&(typeof o.end=="number"?p.end=a.longs===String?String(o.end):o.end:p.end=a.longs===String?l.Long.prototype.toString.call(o.end):a.longs===Number?new l.LongBits(o.end.low>>>0,o.end.high>>>0).toNumber():o.end),p},r.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},r.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TensorProto.Segment"},r})(),s.DataLocation=(function(){var r={},o=Object.create(r);return o[r[0]="DEFAULT"]=0,o[r[1]="EXTERNAL"]=1,o})(),s})(),c.SparseTensorProto=(function(){function s(r){if(this.dims=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.values=d.onnx.TensorProto.decode(r,r.uint32());break}case 2:{p.indices=d.onnx.TensorProto.decode(r,r.uint32());break}case 3:{if(p.dims&&p.dims.length||(p.dims=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[a].high>>>0).toNumber())}return o},s.toObject=function(r,o){o||(o={});var a={};if((o.arrays||o.defaults)&&(a.dims=[]),o.defaults&&(a.values=null,a.indices=null),r.values!=null&&r.hasOwnProperty("values")&&(a.values=d.onnx.TensorProto.toObject(r.values,o)),r.indices!=null&&r.hasOwnProperty("indices")&&(a.indices=d.onnx.TensorProto.toObject(r.indices,o)),r.dims&&r.dims.length){a.dims=[];for(var p=0;p>>0,r.dims[p].high>>>0).toNumber():r.dims[p]}return a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.SparseTensorProto"},s})(),c.TensorShapeProto=(function(){function s(r){if(this.dim=[],r)for(var o=Object.keys(r),a=0;a>>3===1?(p.dim&&p.dim.length||(p.dim=[]),p.dim.push(d.onnx.TensorShapeProto.Dimension.decode(r,r.uint32()))):r.skipType(h&7)}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.dim!=null&&r.hasOwnProperty("dim")){if(!Array.isArray(r.dim))return"dim: array expected";for(var o=0;o>>3){case 1:{m.dimValue=a.int64();break}case 2:{m.dimParam=a.string();break}case 3:{m.denotation=a.string();break}default:a.skipType(g&7);break}}return m},r.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},r.verify=function(a){if(typeof a!="object"||a===null)return"object expected";var p={};if(a.dimValue!=null&&a.hasOwnProperty("dimValue")&&(p.value=1,!l.isInteger(a.dimValue)&&!(a.dimValue&&l.isInteger(a.dimValue.low)&&l.isInteger(a.dimValue.high))))return"dimValue: integer|Long expected";if(a.dimParam!=null&&a.hasOwnProperty("dimParam")){if(p.value===1)return"value: multiple values";if(p.value=1,!l.isString(a.dimParam))return"dimParam: string expected"}return a.denotation!=null&&a.hasOwnProperty("denotation")&&!l.isString(a.denotation)?"denotation: string expected":null},r.fromObject=function(a){if(a instanceof d.onnx.TensorShapeProto.Dimension)return a;var p=new d.onnx.TensorShapeProto.Dimension;return a.dimValue!=null&&(l.Long?(p.dimValue=l.Long.fromValue(a.dimValue)).unsigned=!1:typeof a.dimValue=="string"?p.dimValue=parseInt(a.dimValue,10):typeof a.dimValue=="number"?p.dimValue=a.dimValue:typeof a.dimValue=="object"&&(p.dimValue=new l.LongBits(a.dimValue.low>>>0,a.dimValue.high>>>0).toNumber())),a.dimParam!=null&&(p.dimParam=String(a.dimParam)),a.denotation!=null&&(p.denotation=String(a.denotation)),p},r.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.denotation=""),a.dimValue!=null&&a.hasOwnProperty("dimValue")&&(typeof a.dimValue=="number"?h.dimValue=p.longs===String?String(a.dimValue):a.dimValue:h.dimValue=p.longs===String?l.Long.prototype.toString.call(a.dimValue):p.longs===Number?new l.LongBits(a.dimValue.low>>>0,a.dimValue.high>>>0).toNumber():a.dimValue,p.oneofs&&(h.value="dimValue")),a.dimParam!=null&&a.hasOwnProperty("dimParam")&&(h.dimParam=a.dimParam,p.oneofs&&(h.value="dimParam")),a.denotation!=null&&a.hasOwnProperty("denotation")&&(h.denotation=a.denotation),h},r.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},r.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TensorShapeProto.Dimension"},r})(),s})(),c.TypeProto=(function(){function s(o){if(o)for(var a=Object.keys(o),p=0;p>>3){case 1:{h.tensorType=d.onnx.TypeProto.Tensor.decode(o,o.uint32());break}case 4:{h.sequenceType=d.onnx.TypeProto.Sequence.decode(o,o.uint32());break}case 5:{h.mapType=d.onnx.TypeProto.Map.decode(o,o.uint32());break}case 9:{h.optionalType=d.onnx.TypeProto.Optional.decode(o,o.uint32());break}case 8:{h.sparseTensorType=d.onnx.TypeProto.SparseTensor.decode(o,o.uint32());break}case 6:{h.denotation=o.string();break}default:o.skipType(m&7);break}}return h},s.decodeDelimited=function(o){return o instanceof i||(o=new i(o)),this.decode(o,o.uint32())},s.verify=function(o){if(typeof o!="object"||o===null)return"object expected";var a={};if(o.tensorType!=null&&o.hasOwnProperty("tensorType")){a.value=1;{var p=d.onnx.TypeProto.Tensor.verify(o.tensorType);if(p)return"tensorType."+p}}if(o.sequenceType!=null&&o.hasOwnProperty("sequenceType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Sequence.verify(o.sequenceType);if(p)return"sequenceType."+p}}if(o.mapType!=null&&o.hasOwnProperty("mapType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Map.verify(o.mapType);if(p)return"mapType."+p}}if(o.optionalType!=null&&o.hasOwnProperty("optionalType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Optional.verify(o.optionalType);if(p)return"optionalType."+p}}if(o.sparseTensorType!=null&&o.hasOwnProperty("sparseTensorType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.SparseTensor.verify(o.sparseTensorType);if(p)return"sparseTensorType."+p}}return o.denotation!=null&&o.hasOwnProperty("denotation")&&!l.isString(o.denotation)?"denotation: string expected":null},s.fromObject=function(o){if(o instanceof d.onnx.TypeProto)return o;var a=new d.onnx.TypeProto;if(o.tensorType!=null){if(typeof o.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");a.tensorType=d.onnx.TypeProto.Tensor.fromObject(o.tensorType)}if(o.sequenceType!=null){if(typeof o.sequenceType!="object")throw TypeError(".onnx.TypeProto.sequenceType: object expected");a.sequenceType=d.onnx.TypeProto.Sequence.fromObject(o.sequenceType)}if(o.mapType!=null){if(typeof o.mapType!="object")throw TypeError(".onnx.TypeProto.mapType: object expected");a.mapType=d.onnx.TypeProto.Map.fromObject(o.mapType)}if(o.optionalType!=null){if(typeof o.optionalType!="object")throw TypeError(".onnx.TypeProto.optionalType: object expected");a.optionalType=d.onnx.TypeProto.Optional.fromObject(o.optionalType)}if(o.sparseTensorType!=null){if(typeof o.sparseTensorType!="object")throw TypeError(".onnx.TypeProto.sparseTensorType: object expected");a.sparseTensorType=d.onnx.TypeProto.SparseTensor.fromObject(o.sparseTensorType)}return o.denotation!=null&&(a.denotation=String(o.denotation)),a},s.toObject=function(o,a){a||(a={});var p={};return a.defaults&&(p.denotation=""),o.tensorType!=null&&o.hasOwnProperty("tensorType")&&(p.tensorType=d.onnx.TypeProto.Tensor.toObject(o.tensorType,a),a.oneofs&&(p.value="tensorType")),o.sequenceType!=null&&o.hasOwnProperty("sequenceType")&&(p.sequenceType=d.onnx.TypeProto.Sequence.toObject(o.sequenceType,a),a.oneofs&&(p.value="sequenceType")),o.mapType!=null&&o.hasOwnProperty("mapType")&&(p.mapType=d.onnx.TypeProto.Map.toObject(o.mapType,a),a.oneofs&&(p.value="mapType")),o.denotation!=null&&o.hasOwnProperty("denotation")&&(p.denotation=o.denotation),o.sparseTensorType!=null&&o.hasOwnProperty("sparseTensorType")&&(p.sparseTensorType=d.onnx.TypeProto.SparseTensor.toObject(o.sparseTensorType,a),a.oneofs&&(p.value="sparseTensorType")),o.optionalType!=null&&o.hasOwnProperty("optionalType")&&(p.optionalType=d.onnx.TypeProto.Optional.toObject(o.optionalType,a),a.oneofs&&(p.value="optionalType")),p},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TypeProto"},s.Tensor=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.elemType=a.int32();break}case 2:{m.shape=d.onnx.TensorShapeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")&&!l.isInteger(a.elemType))return"elemType: integer expected";if(a.shape!=null&&a.hasOwnProperty("shape")){var p=d.onnx.TensorShapeProto.verify(a.shape);if(p)return"shape."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Tensor)return a;var p=new d.onnx.TypeProto.Tensor;if(a.elemType!=null&&(p.elemType=a.elemType|0),a.shape!=null){if(typeof a.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");p.shape=d.onnx.TensorShapeProto.fromObject(a.shape)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=0,h.shape=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=a.elemType),a.shape!=null&&a.hasOwnProperty("shape")&&(h.shape=d.onnx.TensorShapeProto.toObject(a.shape,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Tensor"},o})(),s.Sequence=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3===1?m.elemType=d.onnx.TypeProto.decode(a,a.uint32()):a.skipType(g&7)}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")){var p=d.onnx.TypeProto.verify(a.elemType);if(p)return"elemType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Sequence)return a;var p=new d.onnx.TypeProto.Sequence;if(a.elemType!=null){if(typeof a.elemType!="object")throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected");p.elemType=d.onnx.TypeProto.fromObject(a.elemType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=d.onnx.TypeProto.toObject(a.elemType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Sequence"},o})(),s.Map=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.keyType=a.int32();break}case 2:{m.valueType=d.onnx.TypeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.keyType!=null&&a.hasOwnProperty("keyType")&&!l.isInteger(a.keyType))return"keyType: integer expected";if(a.valueType!=null&&a.hasOwnProperty("valueType")){var p=d.onnx.TypeProto.verify(a.valueType);if(p)return"valueType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Map)return a;var p=new d.onnx.TypeProto.Map;if(a.keyType!=null&&(p.keyType=a.keyType|0),a.valueType!=null){if(typeof a.valueType!="object")throw TypeError(".onnx.TypeProto.Map.valueType: object expected");p.valueType=d.onnx.TypeProto.fromObject(a.valueType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.keyType=0,h.valueType=null),a.keyType!=null&&a.hasOwnProperty("keyType")&&(h.keyType=a.keyType),a.valueType!=null&&a.hasOwnProperty("valueType")&&(h.valueType=d.onnx.TypeProto.toObject(a.valueType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Map"},o})(),s.Optional=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3===1?m.elemType=d.onnx.TypeProto.decode(a,a.uint32()):a.skipType(g&7)}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")){var p=d.onnx.TypeProto.verify(a.elemType);if(p)return"elemType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Optional)return a;var p=new d.onnx.TypeProto.Optional;if(a.elemType!=null){if(typeof a.elemType!="object")throw TypeError(".onnx.TypeProto.Optional.elemType: object expected");p.elemType=d.onnx.TypeProto.fromObject(a.elemType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=d.onnx.TypeProto.toObject(a.elemType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Optional"},o})(),s.SparseTensor=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.elemType=a.int32();break}case 2:{m.shape=d.onnx.TensorShapeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")&&!l.isInteger(a.elemType))return"elemType: integer expected";if(a.shape!=null&&a.hasOwnProperty("shape")){var p=d.onnx.TensorShapeProto.verify(a.shape);if(p)return"shape."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.SparseTensor)return a;var p=new d.onnx.TypeProto.SparseTensor;if(a.elemType!=null&&(p.elemType=a.elemType|0),a.shape!=null){if(typeof a.shape!="object")throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected");p.shape=d.onnx.TensorShapeProto.fromObject(a.shape)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=0,h.shape=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=a.elemType),a.shape!=null&&a.hasOwnProperty("shape")&&(h.shape=d.onnx.TensorShapeProto.toObject(a.shape,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.SparseTensor"},o})(),s})(),c.OperatorSetIdProto=(function(){function s(r){if(r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.domain=r.string();break}case 2:{p.version=r.int64();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){return typeof r!="object"||r===null?"object expected":r.domain!=null&&r.hasOwnProperty("domain")&&!l.isString(r.domain)?"domain: string expected":r.version!=null&&r.hasOwnProperty("version")&&!l.isInteger(r.version)&&!(r.version&&l.isInteger(r.version.low)&&l.isInteger(r.version.high))?"version: integer|Long expected":null},s.fromObject=function(r){if(r instanceof d.onnx.OperatorSetIdProto)return r;var o=new d.onnx.OperatorSetIdProto;return r.domain!=null&&(o.domain=String(r.domain)),r.version!=null&&(l.Long?(o.version=l.Long.fromValue(r.version)).unsigned=!1:typeof r.version=="string"?o.version=parseInt(r.version,10):typeof r.version=="number"?o.version=r.version:typeof r.version=="object"&&(o.version=new l.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber())),o},s.toObject=function(r,o){o||(o={});var a={};if(o.defaults)if(a.domain="",l.Long){var p=new l.Long(0,0,!1);a.version=o.longs===String?p.toString():o.longs===Number?p.toNumber():p}else a.version=o.longs===String?"0":0;return r.domain!=null&&r.hasOwnProperty("domain")&&(a.domain=r.domain),r.version!=null&&r.hasOwnProperty("version")&&(typeof r.version=="number"?a.version=o.longs===String?String(r.version):r.version:a.version=o.longs===String?l.Long.prototype.toString.call(r.version):o.longs===Number?new l.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber():r.version),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.OperatorSetIdProto"},s})(),c.OperatorStatus=(function(){var s={},r=Object.create(s);return r[s[0]="EXPERIMENTAL"]=0,r[s[1]="STABLE"]=1,r})(),c.FunctionProto=(function(){function s(r){if(this.input=[],this.output=[],this.attribute=[],this.attributeProto=[],this.node=[],this.opsetImport=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.name=r.string();break}case 4:{p.input&&p.input.length||(p.input=[]),p.input.push(r.string());break}case 5:{p.output&&p.output.length||(p.output=[]),p.output.push(r.string());break}case 6:{p.attribute&&p.attribute.length||(p.attribute=[]),p.attribute.push(r.string());break}case 11:{p.attributeProto&&p.attributeProto.length||(p.attributeProto=[]),p.attributeProto.push(d.onnx.AttributeProto.decode(r,r.uint32()));break}case 7:{p.node&&p.node.length||(p.node=[]),p.node.push(d.onnx.NodeProto.decode(r,r.uint32()));break}case 8:{p.docString=r.string();break}case 9:{p.opsetImport&&p.opsetImport.length||(p.opsetImport=[]),p.opsetImport.push(d.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 10:{p.domain=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!l.isString(r.name))return"name: string expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var o=0;o{"use strict";k0(),Le=be(Ni()),Ln(),_i=class{static arraysEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n1&&o>1)return;c[d-s]=Math.max(r,o)}return c}static index(t,n){let i=new Array(n.length);return vi.fillIndex(t,n,i),i}static fillIndex(t,n,i){let u=t.length-n.length;for(let l=0;l=0;y--)r[y]=_%d[y],_=Math.floor(_/d[y]);m||(vi.fillIndex(r,t.dims,o),p=t.get(o)),g||(vi.fillIndex(r,n.dims,a),h=n.get(a)),s.set(r,i(p,h))}}return s}}static isValidBroadcast(t,n){let i=t.length,u=n.length;if(i>u)return!1;for(let l=1;l<=i;l++)if(t[i-l]!==1&&t[i-l]!==n[u-l])return!1;return!0}static getBroadcastDims(t,n){let i=t.length,u=[];for(let l=0;l1&&c===1&&u.unshift(d)}return u}},_w=class{static getShapeOfGemmResult(e,t,n,i,u){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,d,c;t?(l=e[1],d=e[0]):(l=e[0],d=e[1]);let s=-1;if(i?(c=n[0],s=1):(c=n[1],s=0),n[s]!==d)throw new Error("dimension mismatch");if(l<=0||c<=0||d<=0)throw new Error("invalid shape specified");if(u&&!Qt.isValidBroadcast(u,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,d]}},wt=class ol{static tensorDataTypeFromProto(t){switch(t){case Le.onnx.TensorProto.DataType.INT8:return"int8";case Le.onnx.TensorProto.DataType.UINT8:return"uint8";case Le.onnx.TensorProto.DataType.BOOL:return"bool";case Le.onnx.TensorProto.DataType.INT16:return"int16";case Le.onnx.TensorProto.DataType.UINT16:return"uint16";case Le.onnx.TensorProto.DataType.INT32:return"int32";case Le.onnx.TensorProto.DataType.UINT32:return"uint32";case Le.onnx.TensorProto.DataType.FLOAT:return"float32";case Le.onnx.TensorProto.DataType.DOUBLE:return"float64";case Le.onnx.TensorProto.DataType.STRING:return"string";case Le.onnx.TensorProto.DataType.INT64:return"int32";case Le.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${Le.onnx.TensorProto.DataType[t]}`)}}static tensorDataTypeStringToEnum(t){switch(t){case"int8":return Le.onnx.TensorProto.DataType.INT8;case"uint8":return Le.onnx.TensorProto.DataType.UINT8;case"bool":return Le.onnx.TensorProto.DataType.BOOL;case"int16":return Le.onnx.TensorProto.DataType.INT16;case"uint16":return Le.onnx.TensorProto.DataType.UINT16;case"int32":return Le.onnx.TensorProto.DataType.INT32;case"uint32":return Le.onnx.TensorProto.DataType.UINT32;case"float32":return Le.onnx.TensorProto.DataType.FLOAT;case"float64":return Le.onnx.TensorProto.DataType.DOUBLE;case"string":return Le.onnx.TensorProto.DataType.STRING;case"int64":return Le.onnx.TensorProto.DataType.INT64;case"uint64":return Le.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${t}`)}}static tensorDimsFromProto(t){return t.map(n=>mn.isLong(n)?n.toNumber():n)}static tensorValueTypeFromProto(t){return{tensorType:ol.tensorDataTypeFromProto(t.elemType),shape:{dims:ol.tensorDimsFromProto(t.shape.dim.map(n=>n.dimValue))}}}static tensorDimsFromORTFormat(t){let n=[];for(let i=0;it.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Sr.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Sr.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let u=1;for(let l=n;l=0;--u)i[u]=i[u+1]*t[u+1];return i}static transpose(t){return t.slice().reverse()}static indicesToOffset(t,n,i){i===void 0&&(i=t.length);let u=0;for(let l=0;l=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n))}static incrementIndex(t,n,i){if(n.length===0||t.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(i===void 0)i=n.length;else if(i<=0||i>n.length)throw new Error("Incorrect axis to increment on");for(let u=i-1;u>=0&&(t[u]++,!(t[u]=t.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");u[s]=t[s]}else u[s]=n[s];d*=u[s]}}let c=Sr.size(t);if(l!==-1){if(c%d!==0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t}] Output shape: [${n}]`);u[l]=c/d}else if(d!==c)throw new Error("reshapedDims and originalDims don't have matching sizes");return u}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((u,l)=>u+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,u)=>i===n[u])}static validateDimsAndCalcSize(t){if(t.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let n=1;for(let i of t){if(!Number.isInteger(i))throw new TypeError(`Invalid shape: ${i} is not an integer`);if(i<0||i>2147483647)throw new TypeError(`Invalid shape: length ${i} is not allowed`);n*=i}return n}static flattenShape(t,n){n<0&&(n+=t.length);let i=t.reduce((l,d)=>l*d,1),u=t.slice(n).reduce((l,d)=>l*d,1);return[i/u,u]}static squeezeShape(t,n){let i=new Array;n=Sr.normalizeAxes(n,t.length);for(let u=0;u=0;if(l&&t[u]!==1)throw new Error("squeeze an axis of size different than 1");(n.length===0&&t[u]>1||n.length>0&&!l)&&i.push(t[u])}return i}static unsqueezeShape(t,n){let i=new Array(t.length+n.length);i.fill(0);for(let l=0;l=i.length)throw new Error("'axes' has an out of range axis");if(i[d]!==0)throw new Error("'axes' has a duplicate axis");i[d]=1}let u=0;for(let l=0;l=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c=i[c]||d[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,u,l,d){if(d){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let c=0;c=i+u&&(d-=1)),d}static adjustPadAndReturnShape(t,n,i,u,l,d,c,s,r=0){let o=i*(u-1)+1;if(s&&s!=="NOTSET")switch(s){case"VALID":return l[d]=0,l[c]=0,Ir.computeOutputSize(t-o,n,t,0,r);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let a=(Math.floor((t+n-1)/n)-1)*n+u-t;return l[d]=Math.floor(s==="SAME_LOWER"?(a+1)/2:a/2),l[c]=a-l[d],Ir.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}default:throw new Error("Unsupported AutoPad type")}else return Ir.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}},Ci=-34028234663852886e22,Ri=34028234663852886e22});function DO(e){switch(e){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${e}`)}}function ch(e){switch(e){case ve.onnx.TensorProto.DataType.UINT8:case ve.onnx.TensorProto.DataType.INT8:case ve.onnx.TensorProto.DataType.BOOL:return 1;case ve.onnx.TensorProto.DataType.UINT16:case ve.onnx.TensorProto.DataType.INT16:return 2;case ve.onnx.TensorProto.DataType.FLOAT:case ve.onnx.TensorProto.DataType.INT32:case ve.onnx.TensorProto.DataType.UINT32:return 4;case ve.onnx.TensorProto.DataType.INT64:case ve.onnx.TensorProto.DataType.DOUBLE:case ve.onnx.TensorProto.DataType.UINT64:return 8;default:throw new Error(`cannot calculate sizeof() on type ${ve.onnx.TensorProto.DataType[e]}`)}}function MO(e,t){return new(xw(t))(e)}function xw(e){switch(e){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw new Error("unspecified error")}}function sl(e,t){if(t===ve.onnx.TensorProto.DataType.INT64||t===No.TensorDataType.INT64){if(e.greaterThanOrEqual(2147483648)||e.lessThan(-2147483648))throw new TypeError("int64 is not supported")}else if(t===ve.onnx.TensorProto.DataType.UINT32||t===No.TensorDataType.UINT32||t===ve.onnx.TensorProto.DataType.UINT64||t===No.TensorDataType.UINT64){if(e.greaterThanOrEqual(4294967296)||e.lessThan(0))throw new TypeError("uint64 is not supported")}else throw new TypeError(`not a LONG type: ${ve.onnx.TensorProto.DataType[t]}`);return e.toNumber()}function ph(e,t,n){switch(t){case ve.onnx.TensorProto.DataType.BOOL:case ve.onnx.TensorProto.DataType.UINT8:return e.getUint8(n);case ve.onnx.TensorProto.DataType.INT8:return e.getInt8(n);case ve.onnx.TensorProto.DataType.UINT16:return e.getUint16(n,!0);case ve.onnx.TensorProto.DataType.INT16:return e.getInt16(n,!0);case ve.onnx.TensorProto.DataType.FLOAT:return e.getFloat32(n,!0);case ve.onnx.TensorProto.DataType.INT32:return e.getInt32(n,!0);case ve.onnx.TensorProto.DataType.UINT32:return e.getUint32(n,!0);case ve.onnx.TensorProto.DataType.INT64:return sl(mn.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!1),t);case ve.onnx.TensorProto.DataType.DOUBLE:return e.getFloat64(n,!0);case ve.onnx.TensorProto.DataType.UINT64:return sl(mn.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!0),t);default:throw new Error(`cannot read from DataView for type ${ve.onnx.TensorProto.DataType[t]}`)}}var hh,ve,xt,Ln=D(()=>{"use strict";hh=be(B3()),k0(),ns(),ve=be(Ni()),Me(),xt=class zo{constructor(t,n,i,u,l,d=hh.Guid.create()){this.dims=t,this.type=n,this.dataProvider=i,this.asyncDataProvider=u,this.cache=l,this.dataId=d,this.size=ye.validateDimsAndCalcSize(t);let c=this.size,s=i===void 0&&u===void 0&&l===void 0;if(l!==void 0&&l.length!==c)throw new RangeError("Input dims doesn't match data length.");if(n==="string"){if(l!==void 0&&(!Array.isArray(l)||!l.every(r=>typeof r=="string")))throw new TypeError("cache should be a string array");s&&(this.cache=new Array(c))}else{if(l!==void 0){let r=xw(n);if(!(l instanceof r))throw new TypeError(`cache should be type ${r.name}`)}if(s){let r=new ArrayBuffer(c*DO(n));this.cache=MO(r,n)}}}get data(){if(this.cache===void 0){let t=this.dataProvider(this.dataId);if(t.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=t}return this.cache}get stringData(){if(this.type!=="string")throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if(this.type!=="string")return this.data;throw new TypeError("type cannot be non-number (string)")}get(t){return this.data[ye.indicesToOffset(t,this.strides)]}set(t,n){this.data[ye.indicesToOffset(t,this.strides)]=n}async getData(){return this.cache===void 0&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=ye.computeStrides(this.dims)),this._strides}static fromProto(t){if(!t)throw new Error("cannot construct Value from an empty tensor");let n=wt.tensorDataTypeFromProto(t.dataType),i=wt.tensorDimsFromProto(t.dims),u=new zo(i,n);if(n==="string")t.stringData.forEach((l,d)=>{u.data[d]=nl(l)});else if(t.rawData&&typeof t.rawData.byteLength=="number"&&t.rawData.byteLength>0){let l=u.data,d=new DataView(t.rawData.buffer,t.rawData.byteOffset,t.rawData.byteLength),c=ch(t.dataType),s=t.rawData.byteLength/c;if(t.rawData.byteLength%c!==0)throw new Error("invalid buffer length");if(l.length!==s)throw new Error("buffer length mismatch");for(let r=0;r0){let l=u.data,d=new DataView(t.rawDataArray().buffer,t.rawDataArray().byteOffset,t.rawDataLength()),c=ch(t.dataType()),s=t.rawDataLength()/c;if(t.rawDataLength()%c!==0)throw new Error("invalid buffer length");if(l.length!==s)throw new Error("buffer length mismatch");for(let r=0;rthis.isTimerResultAvailable(e)),this.getTimerResult(e)}async createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n=e,i=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),i===null?t=()=>!0:t=()=>{let u=n.clientWaitSync(i,0,0);return u===n.ALREADY_SIGNALED||u===n.CONDITION_SATISFIED},{query:i,isFencePassed:t}}async pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=AA(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}async addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&await fh(()=>(this.pollItems(),this.itemsToPoll.length===0))}}});function Qv(e){let t;if((!e||e==="webgl2")&&"webgl2"in sn?t=sn.webgl2:(!e||e==="webgl")&&"webgl"in sn&&(t=sn.webgl),!t)try{let i=CA();t=ym(i,e)}catch{let i=PA();t=ym(i,e)}e=e||t.version===1?"webgl":"webgl2";let n=t.gl;return sn[e]=t,n.isContextLost()?(delete sn[e],Qv(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),t)}function ym(e,t){let n={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1},i,u=n;if((!t||t==="webgl2")&&(i=e.getContext("webgl2",u),i))try{return new Il(i,2)}catch(l){Je.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${l}`)}if((!t||t==="webgl")&&(i=e.getContext("webgl",u)||e.getContext("experimental-webgl",u),i))try{return new Il(i,1)}catch(l){Je.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${l}`)}throw new Error("WebGL is not supported")}function PA(){if(typeof document>"u")throw new TypeError("failed to create canvas: document is not supported");let e=document.createElement("canvas");return e.width=1,e.height=1,e}function CA(){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}var sn,RA=D(()=>{"use strict";qt(),kA(),sn={}}),ex,DA=D(()=>{"use strict";dt(),qt(),EA(),RA(),ex=class{get contextId(){return me.webgl.contextId}set contextId(e){me.webgl.contextId=e}get matmulMaxBatchSize(){return me.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(e){me.webgl.matmulMaxBatchSize=e}get textureCacheMode(){return me.webgl.textureCacheMode}set textureCacheMode(e){me.webgl.textureCacheMode=e}get pack(){return me.webgl.pack}set pack(e){me.webgl.pack=e}get async(){return me.webgl.async}set async(e){me.webgl.async=e}initialize(){try{return this.glContext=Qv(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),Je.setWithEnv(me),me.webgl.context||Object.defineProperty(me.webgl,"context",{value:this.glContext.gl}),Je.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(e){return Je.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${e}`),!1}}createSessionHandler(e){return new Jv(this,e)}dispose(){this.glContext.dispose()}}});async function tx(e){if(e){let t=typeof e=="string"?[e]:e;for(let n of t){let i=ed.get(n);if(i)return i;let u=await MA(n);if(u)return u}}else return tx(["webgl"]);throw new Error("no available backend to use")}async function MA(e){let t=rx;if(typeof t[e]<"u"&&NA(t[e])){let n=t[e],i=n.initialize();if(typeof i=="object"&&"then"in i&&(i=await i),i)return ed.set(e,n),n}}function NA(e){let t=e;return"initialize"in t&&typeof t.initialize=="function"&&"createSessionHandler"in t&&typeof t.createSessionHandler=="function"&&"dispose"in t&&typeof t.dispose=="function"}var ed,rx,zA=D(()=>{"use strict";DA(),ed=new Map,rx={webgl:new ex}}),wm,nx,BA=D(()=>{"use strict";qt(),wm=class{constructor(e,t){this.op=e,this.node=t}},nx=class{constructor(e,t,n){this.graph=e,this.profiler=n,this.initialize(t)}initialize(e){this.profiler.event("session","ExecutionPlan.initialize",()=>{let t=this.graph.getNodes();if(t.length!==e.length)throw new Error("The size of nodes and OPs do not match.");this._ops=e.map((n,i)=>new wm(n,t[i])),this.reset(),this._starter=[],this._ops.forEach((n,i)=>{let u=!0;for(let l of n.node.inputs)if(!this._values[l]&&this.graph.getInputIndices().indexOf(l)===-1){u=!1;break}u&&this._starter.push(i)})})}reset(){this._values=this.graph.getValues().map(e=>e.tensor)}async execute(e,t){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();let n=e.createInferenceHandler(),i=this.graph.getInputIndices();if(t.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${t.length} expected: ${i.length}`);t.forEach((r,o)=>{let a=i[o];this._values[a]=r});let u=this._starter.slice(0),l=this.graph.getValues(),d=this.graph.getNodes(),c=0;for(;cthis._values[g]);if(a.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${o.node}`);let p=a;Je.verbose("ExecPlan",`Running op:${o.node.name} (${p.map((g,_)=>`'${o.node.inputs[_]}': ${g.type}[${g.dims.join(",")}]`).join(", ")})`);let h=await this.profiler.event("node",o.node.name,async()=>o.op.impl(n,p,o.op.context));if(h.length!==o.node.outputs.length)throw new Error("the size of output does not match model definition.");h.forEach((g,_)=>{let w=o.node.outputs[_];if(this._values[w])throw new Error(`output [${w}] already has value: op:${o.node.name}`);this._values[w]=g});let m=new Set;h.forEach((g,_)=>{let w=o.node.outputs[_];for(let y of l[w].to){let T=d[y],S=!0;for(let O of T.inputs)if(!this._values[O]){S=!1;break}S&&m.add(y)}}),u.push(...m)}let s=[];for(let r=0;r{"use strict";ns(),Se=be(Ni()),Ln(),Me(),Ol=class Ti{constructor(t){if(this._attributes=new Map,t!=null){for(let n of t)n instanceof Se.onnx.AttributeProto?this._attributes.set(n.name,[Ti.getValue(n),Ti.getType(n)]):n instanceof rl.Attribute&&this._attributes.set(n.name(),[Ti.getValue(n),Ti.getType(n)]);if(this._attributes.sizext.fromProto(u));if(t instanceof rl.Attribute)return i.map(u=>xt.fromOrtTensor(u))}return n===Se.onnx.AttributeProto.AttributeType.STRING&&t instanceof Se.onnx.AttributeProto?nl(i):n===Se.onnx.AttributeProto.AttributeType.STRINGS&&t instanceof Se.onnx.AttributeProto?i.map(nl):i}static getValueNoCheck(t){return t instanceof Se.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(t):this.getValueNoCheckFromOrtFormat(t)}static getValueNoCheckFromOnnxFormat(t){switch(t.type){case Se.onnx.AttributeProto.AttributeType.FLOAT:return t.f;case Se.onnx.AttributeProto.AttributeType.INT:return t.i;case Se.onnx.AttributeProto.AttributeType.STRING:return t.s;case Se.onnx.AttributeProto.AttributeType.TENSOR:return t.t;case Se.onnx.AttributeProto.AttributeType.GRAPH:return t.g;case Se.onnx.AttributeProto.AttributeType.FLOATS:return t.floats;case Se.onnx.AttributeProto.AttributeType.INTS:return t.ints;case Se.onnx.AttributeProto.AttributeType.STRINGS:return t.strings;case Se.onnx.AttributeProto.AttributeType.TENSORS:return t.tensors;case Se.onnx.AttributeProto.AttributeType.GRAPHS:return t.graphs;default:throw new Error(`unsupported attribute type: ${Se.onnx.AttributeProto.AttributeType[t.type]}`)}}static getValueNoCheckFromOrtFormat(t){switch(t.type()){case jt.AttributeType.FLOAT:return t.f();case jt.AttributeType.INT:return t.i();case jt.AttributeType.STRING:return t.s();case jt.AttributeType.TENSOR:return t.t();case jt.AttributeType.GRAPH:return t.g();case jt.AttributeType.FLOATS:return t.floatsArray();case jt.AttributeType.INTS:{let n=[];for(let i=0;i{"use strict";FA(),ns(),Ba=be(Ni()),Ln(),Me(),El={from:(e,t)=>new _m(e,t)},nr=class{constructor(e){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,e&&(this.type=wt.tensorValueTypeFromProto(e.type.tensorType))}get from(){return this._from}get to(){return this._to}},Fa=class{constructor(e,t){e instanceof Ba.onnx.NodeProto?(this.name=e.name,this.opType=e.opType,this.attributes=new Ol(e.attribute)):e instanceof mw.Node&&(this.name=t??e.name(),this.opType=e.opType(),this.attributes=new Ol(wt.tensorAttributesFromORTFormat(e))),this.inputs=[],this.outputs=[],this.executeNode=!0}},_m=class{constructor(e,t){if(!e)throw new TypeError("graph is empty");this.buildGraph(e),this.transformGraph(t),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(e){if(e instanceof Ba.onnx.GraphProto)this.buildGraphFromOnnxFormat(e);else if(e instanceof hw.Graph)this.buildGraphFromOrtFormat(e);else throw new TypeError("Graph type is not supported.")}buildGraphFromOnnxFormat(e){let t=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let n=new Map;if(!e.input)throw new Error("missing information in graph: input");let i=[];for(let u of e.input){if(t.has(u.name))throw new Error(`duplicated input name: ${u.name}`);let l=this._allData.push(new nr(u))-1;t.set(u.name,l),i.push(u.name)}if(!e.initializer)throw new Error("missing information in graph: initializer");for(let u of e.initializer){let l=t.get(u.name);if(l===void 0){let d=new nr;d.type={shape:{dims:wt.tensorDimsFromProto(u.dims)},tensorType:wt.tensorDataTypeFromProto(u.dataType)},l=this._allData.push(d)-1,t.set(u.name,l)}this._allData[l]._from=-1,this._allData[l].tensor=xt.fromProto(u)}for(let u=0;u"u"&&(s=this._allData.push(new nr)-1,t.set(c,s)),l.outputs.push(s),this._allData[s]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${s}`);if(this._allData[s]._from=u,d.opType==="Constant"){if(!d.attribute||d.attribute.length!==1||!d.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!d.output||d.output.length!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");l.outputs.pop(),l.executeNode=!1,this._allData[s]._from=-1,this._allData[s].tensor=xt.fromProto(d.attribute[0].t)}}}for(let u=0;u"u"){if(c===""&&(d.input.length===3||d.input.length===4)&&d.opType==="Resize")continue;throw new Error(`unrecognized input '${c}' for node: ${d.name}`)}l.inputs.push(s),this._allData[s]._to.push(u)}}return!0}buildGraphFromOrtFormat(e){let t=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let n=new Map,i=[];for(let u=0;u"u"&&(r=this._allData.push(new nr)-1,t.set(s,r)),l.outputs.push(r),this._allData[r]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${r}`);if(this._allData[r]._from=u,d.opType()==="Constant"){if(d.attributesLength()!==1||!d.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(d.outputsLength()!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");l.outputs.pop(),l.executeNode=!1,this._allData[r]._from=-1,this._allData[r].tensor=xt.fromOrtTensor(d.attributes(0).t())}}}for(let u=0;u"u")throw new Error(`unrecognized input '${s}' for node: ${d.name()}`);l.inputs.push(r),this._allData[r]._to.push(u)}}}checkIsAcyclic(){let e=new Set;this._allInputIndices.forEach(i=>{this._allData[i]._to.forEach(u=>{e.add(u)})});let t=Array.from(e),n=new Array(this._nodes.length).fill("white");for(;t.length>0;){let i=t.pop();n[i]==="gray"?n[i]="black":(t.push(i),n[i]="gray",this._nodes[i].outputs.forEach(u=>{let l=this._allData[u];if(typeof l.tensor<"u")throw new Error("node outputs should not be initialized");if(l._from!==i)throw new Error("from property of the Value object doesn't match index of Node being processed");l._to.forEach(d=>{if(n[d]==="gray")throw new Error("model graph is cyclic");n[d]==="white"&&t.push(d)})}))}}transformGraph(e){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),e&&e.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let e=0,t=new Array(this._nodes.length,0),n=0;for(let i=0;i{this._allData[u]._from=-2});this._nodes.splice(n,this._nodes.length-n);for(let i=0;i=0)u._to[l]=t[u._to[l]];else throw new Error("Trying to update a removed node")}e=0;for(let i=0;i0){let u=-1;this._allData[i].from!==void 0&&this._allData[i].from!==-1?(u=this._nodes[this._allData[i].from].outputs.indexOf(i+e),u!==-1&&(this._nodes[this._allData[i].from].outputs[u]=i)):(u=this._allInputIndices.indexOf(i+e),u!==-1&&(this._allInputIndices[u]=i)),this._allData[i].to.forEach(l=>{u=this._nodes[l].inputs.indexOf(i+e),u!==-1&&(this._nodes[l].inputs[u]=i)}),this._allData[i].to.length===0&&(u=this._allOutputIndices.indexOf(i+e),u!==-1&&(this._allOutputIndices[u]=i))}}}deleteNode(e){let t=this._nodes[e];if(t.outputs.length>1){for(let d=1;d0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}t.executeNode=!1;let n=t.inputs[0],i=t.outputs[0],u=this._allData[i].to;for(let d=0;d0)for(let d of u){let c=this._nodes[d].inputs.indexOf(i);if(c===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[d].inputs[c]=n,this._allData[n].to.push(d)}}removeAllDropoutNodes(){let e=0;for(let t of this._nodes){if(t.opType==="Dropout"){if(t.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(t.outputs.length!==1&&t.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(t.outputs.length===2&&this._allData[t.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(e)}e++}}removeAllIdentityNodes(){let e=0;for(let t of this._nodes)t.opType==="Identity"&&this.deleteNode(e),e++}isActivation(e){switch(e.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(let e of this._nodes)if(e.opType==="Conv"){let t=this._allData[e.outputs[0]]._to;if(t.length===1&&this.isActivation(this._nodes[t[0]])){let n=this._nodes[t[0]];if(n.opType==="Clip")if(n.inputs.length===1)try{e.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch{e.attributes.set("activation_params","floats",[Ci,Ri])}else if(n.inputs.length>=3&&this._allData[n.inputs[1]].tensor!==void 0&&this._allData[n.inputs[2]].tensor!==void 0)e.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]]);else continue;e.attributes.set("activation","string",n.opType),this.deleteNode(t[0])}}}}}),vm,xm,ix,jA=D(()=>{"use strict";vm=be(De()),LA(),ns(),xm=be(Ni()),Me(),ix=class{constructor(){}load(e,t,n){let i;if(!n)try{this.loadFromOnnxFormat(e,t);return}catch(u){if(n!==void 0)throw u;i=u}try{this.loadFromOrtFormat(e,t)}catch(u){throw n!==void 0?u:new Error(`Failed to load model as ONNX format: ${i} as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e);if(Yt.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map(i=>({domain:i.domain,version:Yt.longToNumber(i.version)})),this._graph=El.from(n.graph,t)}loadFromOrtFormat(e,t){let n=new vm.ByteBuffer(e),i=fw.InferenceSession.getRootAsInferenceSession(n).model();if(Yt.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let u=0;u{"use strict";zA(),BA(),qt(),jA(),ox=class{constructor(e={}){this._initialized=!1,this.backendHint=e.backendHint,this.profiler=A0.create(e.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(e,t,n){await this.profiler.event("session","Session.loadModel",async()=>{let i=await tx(this.backendHint);if(this.sessionHandler=i.createSessionHandler(this.context),this._model=new ix,typeof e=="string"){let u=e.endsWith(".ort");{let l=await(await fetch(e)).arrayBuffer();this.initialize(new Uint8Array(l),u)}}else if(ArrayBuffer.isView(e))this.initialize(e);else{let u=new Uint8Array(e,t||0,n||e.byteLength);this.initialize(u)}})}initialize(e,t){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{let n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(e,n,t),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new nx(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(e){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{let t=this.normalizeAndValidateInputs(e),n=await this._executionPlan.execute(this.sessionHandler,t);return this.createOutput(n)})}normalizeAndValidateInputs(e){let t=this._model.graph.getInputNames();if(Array.isArray(e)){if(e.length!==t.length)throw new Error(`incorrect input array length: expected ${t.length} but got ${e.length}`)}else{if(e.size!==t.length)throw new Error(`incorrect input map size: expected ${t.length} but got ${e.size}`);let n=new Array(e.size),i=0;for(let u=0;u{"use strict";dt(),Ln(),sx=class{constructor(e){this.session=e,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}get inputMetadata(){throw new Error("Getting model metadata is not supported in webgl backend.")}get outputMetadata(){throw new Error("Getting model metadata is not supported in webgl backend.")}async dispose(){}async run(e,t,n){let i=new Map;for(let d in e)if(Object.hasOwnProperty.call(e,d)){let c=e[d];i.set(d,new xt(c.dims,c.type,void 0,void 0,c.data))}let u=await this.session.run(i),l={};return u.forEach((d,c)=>{l[c]=new vt(d.type,d.data,d.dims)}),l}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}}),ax={};wn(ax,{onnxjsBackend:()=>ux});var $m,ux,qA=D(()=>{"use strict";UA(),VA(),$m=class{async init(){}async createInferenceSessionHandler(e,t){let n=new ox(t);return typeof e=="string"?await n.loadModel(e):await n.loadModel(e),new sx(n)}},ux=new $m}),td=D(()=>{"use strict"}),lx={};wn(lx,{default:()=>dx});var La,ja,dx,GA=D(()=>{"use strict";y$(),vn(),rd(),La="ort-wasm-proxy-worker",ja=globalThis.self?.name===La,ja&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":nd(n.wasm).then(()=>{_d(n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:u}=n;vd(u,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=n,u=Yo(i);postMessage({type:t,out:u});break}case"create":{let{model:i,options:u}=n;xd(i,u).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":$d(n),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:u,inputs:l,outputIndices:d,options:c}=n;Td(i,u,l,d,new Array(d.length).fill(null),c).then(s=>{s.some(r=>r[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:s},Id([...l,...s]))},s=>{postMessage({type:t,err:s})});break}case"end-profiling":Sd(n),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),dx=ja?null:e=>new Worker(e??yt,{type:"module",name:La})}),cx={};wn(cx,{default:()=>px});async function Tm(e={}){var t=e,n=!!globalThis.window,i=!!globalThis.WorkerGlobalScope,u=i&&self.name?.startsWith("em-pthread");t.mountExternalData=(f,b)=>{f.startsWith("./")&&(f=f.substring(2)),(t.Yc||(t.Yc=new Map)).set(f,b)},t.unmountExternalData=()=>{delete t.Yc,delete t.Zd,delete t.Yd,delete t.$d},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let l=f=>async(...b)=>{try{if(t.Xc)throw Error("Session already started");let $=t.Xc={Kd:b[0],errors:[]},x=await f(...b);if(t.Xc!==$)throw Error("Session mismatch");t.dd?.flush();let E=$.errors;if(0M),0{if(f==="webgpu"){[t.dd,t.Ad,t.Ed,t.ed,t.Dd,t.$b,t.Fd,t.Hd,t.Bd,t.Cd,t.Gd]=b;let $=t.dd;t.jsepRegisterBuffer=(x,E,k,M)=>$.registerBuffer(x,E,k,M),t.jsepGetBuffer=x=>$.getBuffer(x),t.jsepCreateDownloader=(x,E,k)=>$.createDownloader(x,E,k),t.jsepOnCreateSession=x=>{$.onCreateSession(x)},t.jsepOnReleaseSession=x=>{$.onReleaseSession(x)},t.jsepOnRunStart=x=>$.onRunStart(x),t.Id=(x,E)=>{$.upload(x,E)}}else if(f==="webnn"){let $=b[0];[t.Sd,t.sd,t.webnnEnsureTensor,t.td,t.webnnDownloadTensor,t.Rd,t.webnnEnableTraceEvent]=b.slice(1),t.webnnReleaseTensorId=t.sd,t.webnnUploadTensor=t.td,t.webnnRegisterMLContext=t.Rd,t.webnnOnRunStart=x=>$.onRunStart(x),t.webnnOnRunEnd=$.onRunEnd.bind($),t.webnnOnReleaseSession=x=>{$.onReleaseSession(x)},t.webnnCreateMLTensorDownloader=(x,E)=>$.createMLTensorDownloader(x,E),t.webnnRegisterMLTensor=(x,E,k,M)=>$.registerMLTensor(x,E,k,M),t.webnnCreateMLContext=x=>$.createMLContext(x),t.webnnRegisterGraphInput=$.registerGraphInput.bind($),t.webnnIsGraphInput=$.isGraphInput.bind($),t.webnnRegisterGraphOutput=$.registerGraphOutput.bind($),t.webnnIsGraphOutput=$.isGraphOutput.bind($),t.webnnCreateTemporaryTensor=$.createTemporaryTensor.bind($),t.webnnIsGraphInputOutputTypeSupported=$.isGraphInputOutputTypeSupported.bind($)}};let d=()=>{let f=b=>(...$)=>{let x=Wt;return $=b(...$),Wt!=x?new Promise((E,k)=>{Ks={resolve:E,reject:k}}):$};(()=>{for(let b of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[b]=f(t[b])})(),l!==void 0&&(t._OrtRun=l(t._OrtRun),t._OrtRunWithBinding=l(t._OrtRunWithBinding)),d=void 0};t.asyncInit=()=>{d?.()};var c,s,r=(f,b)=>{throw b},o=import.meta.url,a="";if(n||i){try{a=new URL(".",o).href}catch{}i&&(s=f=>{var b=new XMLHttpRequest;return b.open("GET",f,!1),b.responseType="arraybuffer",b.send(null),new Uint8Array(b.response)}),c=async f=>{if(P(f))return new Promise(($,x)=>{var E=new XMLHttpRequest;E.open("GET",f,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?$(E.response):x(E.status)},E.onerror=x,E.send(null)});var b=await fetch(f,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url)}}var p,h,m,g,_,w,y=console.log.bind(console),T=console.error.bind(console),S=y,O=T,A=!1,P=f=>f.startsWith("file://");function I(){hr.buffer!=J.buffer&&Y()}if(u){let f=function(b){try{var $=b.data,x=$.Sc;if(x==="load"){let E=[];self.onmessage=k=>E.push(k),w=()=>{postMessage({Sc:"loaded"});for(let k of E)f(k);self.onmessage=f};for(let k of $.xd)t[k]&&!t[k].proxy||(t[k]=(...M)=>{postMessage({Sc:"callHandler",vd:k,args:M})},k=="print"&&(S=t[k]),k=="printErr"&&(O=t[k]));hr=$.Od,Y(),h=$.Pd,ne(),bo()}else if(x==="run"){(function(E){var k=(I(),R)[E+52>>>2>>>0];E=(I(),R)[E+56>>>2>>>0],mp(k,k-E),we(k)})($.Rc),Qs($.Rc,0,0,1,0,0),gc(),Gs($.Rc),G||(lp(),G=!0);try{oS($.Md,$.bd)}catch(E){if(E!="unwind")throw E}}else $.target!=="setimmediate"&&(x==="checkMailbox"?G&&lo():x&&(O(`worker: received unknown command ${x}`),O($)))}catch(E){throw dp(),E}};var z=f,G=!1;self.onunhandledrejection=b=>{throw b.reason||b},self.onmessage=f}var J,q,C,ee,v,R,H,L,V,K,B,te=!1;function Y(){var f=hr.buffer;t.HEAP8=J=new Int8Array(f),C=new Int16Array(f),t.HEAPU8=q=new Uint8Array(f),ee=new Uint16Array(f),t.HEAP32=v=new Int32Array(f),t.HEAPU32=R=new Uint32Array(f),H=new Float32Array(f),L=new Float64Array(f),V=new BigInt64Array(f),K=new BigUint64Array(f)}function N(){te=!0,u?w():rr.sb()}function X(f){throw O(f="Aborted("+f+")"),A=!0,f=new WebAssembly.RuntimeError(f+". Build with -sASSERTIONS for more info."),_?.(f),f}function W(){return{a:{ma:kI,hb:AI,g:sS,J:aS,f:uS,o:lS,i:dS,$:cS,b:pS,S:hS,Ia:xc,n:fS,aa:Ic,Ya:Oc,Ea:Ec,Ga:Ac,Za:kc,Wa:Pc,Pa:Cc,Va:Rc,ka:Dc,Fa:Mc,Ca:Nc,Xa:zc,Da:Bc,cb:mS,fa:bS,xa:yS,va:_S,ea:xS,N:$S,H:TS,wa:SS,_:CS,ya:RS,Sa:DS,Aa:NS,Ja:zS,ta:BS,ga:FS,Ra:Gs,$a:LS,Q:qS,r:XS,c:Vs,ib:ZS,y:YS,M:JS,D:QS,l:eI,s:Hc,jb:tI,I:rI,R:nI,j:iI,u:oI,q:sI,k:aI,Ma:uI,Na:lI,Oa:dI,Ka:Zc,La:Yc,ua:Jc,eb:pI,bb:mI,v:gI,ba:bI,ha:yI,ab:hI,V:wI,_a:_I,Ba:vI,F:cI,T:xI,la:mo,za:TI,gb:$I,fb:SI,Ta:rp,Ua:np,Ha:zr,U:ip,ja:op,Qa:sp,ia:ap,lb:p3,na:a3,mb:c3,oa:s3,G:ZI,e:DI,t:CI,w:PI,B:qI,nb:n3,Z:r3,x:zI,pa:i3,X:u3,ca:t3,ob:e3,pb:QI,O:GI,qa:JI,qb:YI,L:KI,Y:o3,d:RI,A:NI,m:MI,kb:h3,p:FI,z:LI,C:BI,E:jI,K:HI,ra:XI,P:l3,da:WI,W:d3,rb:VI,sa:UI,h:OI,a:hr,db:ht}}}async function ne(){function f(x,E){var k=rr=x.exports;x={};for(let[M,U]of Object.entries(k))typeof U=="function"?(k=jS(U),x[M]=k):x[M]=U;return rr=x,rr=(function(){var M=rr,U=re=>ge=>re(ge)>>>0,Q=re=>()=>re()>>>0;return(M=Object.assign({},M)).tb=U(M.tb),M.Xb=Q(M.Xb),M.Zb=U(M.Zb),M.lc=U(M.lc),M.mc=Q(M.mc),M.qc=U(M.qc),M})(),fc.push(rr._b),up=(x=rr).tb,lp=x.ub,t._OrtInit=x.vb,t._OrtGetLastError=x.wb,t._OrtCreateSessionOptions=x.xb,t._OrtAppendExecutionProvider=x.yb,t._OrtAddFreeDimensionOverride=x.zb,t._OrtAddSessionConfigEntry=x.Ab,t._OrtReleaseSessionOptions=x.Bb,t._OrtCreateSession=x.Cb,t._OrtReleaseSession=x.Db,t._OrtGetInputOutputCount=x.Eb,t._OrtGetInputOutputMetadata=x.Fb,t._OrtFree=x.Gb,t._OrtCreateTensor=x.Hb,t._OrtGetTensorData=x.Ib,t._OrtReleaseTensor=x.Jb,t._OrtCreateRunOptions=x.Kb,t._OrtAddRunConfigEntry=x.Lb,t._OrtReleaseRunOptions=x.Mb,t._OrtCreateBinding=x.Nb,t._OrtBindInput=x.Ob,t._OrtBindOutput=x.Pb,t._OrtClearBoundOutputs=x.Qb,t._OrtReleaseBinding=x.Rb,t._OrtRunWithBinding=x.Sb,t._OrtRun=x.Tb,t._OrtEndProfiling=x.Ub,t._JsepOutput=x.Vb,t._JsepGetNodeName=x.Wb,go=x.Xb,Kt=t._free=x.Yb,ei=t._malloc=x.Zb,Qs=x.ac,dp=x.bc,cp=x.cc,pp=x.dc,ea=x.ec,hp=x.fc,fp=x.gc,Te=x.hc,ti=x.ic,mp=x.jc,we=x.kc,ta=x.lc,_e=x.mc,gp=x.nc,ra=x.oc,bp=x.pc,yp=x.qc,wp=x.rc,na=x.sc,_p=x.tc,vp=x.uc,xp=x.vc,$p=x.wc,Tp=x.xc,Sp=x.yc,Ip=x.zc,Op=x.Ac,Ep=x.Bc,Ap=x.Cc,kp=x.Dc,Pp=x.Ec,Cp=x.Fc,Rp=x.Gc,Dp=x.Hc,Mp=x.Ic,Np=x.Jc,zp=x.Kc,Bp=x.Lc,Fp=x.Mc,Lp=x.Nc,jp=x.Pc,Up=x.Qc,Vp=x.$c,qp=x.ad,Gp=x.fd,Hp=x.kd,Wp=x.ld,Kp=x.md,Xp=x.nd,Zp=x.od,Yp=x.pd,Jp=x.qd,Qp=x.rd,eh=x.wd,th=x.Ud,rh=x.Vd,nh=x.Wd,ih=x.Xd,h=E,rr}var b,$=W();return t.instantiateWasm?new Promise(x=>{t.instantiateWasm($,(E,k)=>{x(f(E,k))})}):u?f(new WebAssembly.Instance(h,W()),h):(B??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.jsep.wasm",a):a+"ort-wasm-simd-threaded.jsep.wasm":new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url).href,b=await(async function(x){var E=B;if(!p&&!P(E))try{var k=fetch(E,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(k,x)}catch(M){O(`wasm streaming compile failed: ${M}`),O("falling back to ArrayBuffer instantiation")}return(async function(M,U){try{var Q=await(async function(re){if(!p)try{var ge=await c(re);return new Uint8Array(ge)}catch{}if(re==B&&p)re=new Uint8Array(p);else{if(!s)throw"both async and sync fetching of the wasm failed";re=s(re)}return re})(M);return await WebAssembly.instantiate(Q,U)}catch(re){O(`failed to asynchronously prepare wasm: ${re}`),X(re)}})(E,x)})($),f(b.instance,b.module))}class le{name="ExitStatus";constructor(b){this.message=`Program terminated with exit(${b})`,this.status=b}}var ce=f=>{f.terminate(),f.onmessage=()=>{}},xe=[],qe=0,Ve=null,it=f=>{Gt.length==0&&(yc(),bc(Gt[0]));var b=Gt.pop();if(!b)return 6;Jn.push(b),Br[f.Rc]=b,b.Rc=f.Rc;var $={Sc:"run",Md:f.Ld,bd:f.bd,Rc:f.Rc};return b.postMessage($,f.jd),0},Ze=0,$e=(f,b,...$)=>{var x,E=16*$.length,k=_e(),M=ta(E),U=M>>>3;for(x of $)typeof x=="bigint"?((I(),V)[U++>>>0]=1n,(I(),V)[U++>>>0]=x):((I(),V)[U++>>>0]=0n,(I(),L)[U++>>>0]=x);return f=cp(f,0,E,M,b),we(k),f};function ht(f){if(u)return $e(0,1,f);if(m=f,!(0{if(m=f,u)throw It(f),"unwind";ht(f)},Gt=[],Jn=[],fc=[],Br={},mc=f=>{var b=f.Rc;delete Br[b],Gt.push(f),Jn.splice(Jn.indexOf(f),1),f.Rc=0,pp(b)};function gc(){fc.forEach(f=>f())}var bc=f=>new Promise(b=>{f.onmessage=E=>{var k=E.data;if(E=k.Sc,k.Zc&&k.Zc!=go()){var M=Br[k.Zc];M?M.postMessage(k,k.jd):O(`Internal error! Worker sent a message "${E}" to target pthread ${k.Zc}, but that thread no longer exists!`)}else E==="checkMailbox"?lo():E==="spawnThread"?it(k):E==="cleanupThread"?uo(()=>{mc(Br[k.Nd])}):E==="loaded"?(f.loaded=!0,b(f)):k.target==="setimmediate"?f.postMessage(k):E==="uncaughtException"?f.onerror(k.error):E==="callHandler"?t[k.vd](...k.args):E&&O(`worker sent an unknown command ${E}`)},f.onerror=E=>{throw O(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var $,x=[];for($ of[])t.propertyIsEnumerable($)&&x.push($);f.postMessage({Sc:"load",xd:x,Od:hr,Pd:h})});function yc(){var f=new Worker((()=>{let b=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new b("ort.all.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Gt.push(f)}var hr,oS=(f,b)=>{Ze=0,f=na(f,b),0>>=0);return(I(),J)[b.Tc+12>>>0]==0&&(wc(b,!0),so--),_c(b,!1),oo.push(b),yp(f)}var On=0,aS=()=>{Te(0,0);var f=oo.pop();gp(f.cd),On=0};function wc(f,b){b=b?1:0,(I(),J)[f.Tc+12>>>0]=b}function _c(f,b){b=b?1:0,(I(),J)[f.Tc+13>>>0]=b}class Fs{constructor(b){this.cd=b,this.Tc=b-24}}var Ls=f=>{var b=On;if(!b)return ti(0),0;var $=new Fs(b);(I(),R)[$.Tc+16>>>2>>>0]=b;var x=(I(),R)[$.Tc+4>>>2>>>0];if(!x)return ti(0),b;for(var E of f){if(E===0||E===x)break;if(bp(E,x,$.Tc+16))return ti(E),b}return ti(x),b};function uS(){return Ls([])}function lS(f){return Ls([f>>>0])}function dS(f,b,$,x){return Ls([f>>>0,b>>>0,$>>>0,x>>>0])}var cS=()=>{var f=oo.pop();f||X("no exception to throw");var b=f.cd;throw(I(),J)[f.Tc+13>>>0]==0&&(oo.push(f),_c(f,!0),wc(f,!1),so++),ra(b),On=b};function pS(f,b,$){var x=new Fs(f>>>=0);throw b>>>=0,$>>>=0,(I(),R)[x.Tc+16>>>2>>>0]=0,(I(),R)[x.Tc+4>>>2>>>0]=b,(I(),R)[x.Tc+8>>>2>>>0]=$,ra(f),so++,On=f}var hS=()=>so;function vc(f,b,$,x){return u?$e(2,1,f,b,$,x):xc(f,b,$,x)}function xc(f,b,$,x){if(f>>>=0,b>>>=0,$>>>=0,x>>>=0,!globalThis.SharedArrayBuffer)return 6;var E=[];return u&&E.length===0?vc(f,b,$,x):(f={Ld:$,Rc:f,bd:x,jd:E},u?(f.Sc="spawnThread",postMessage(f,E),0):it(f))}function fS(f){throw On||=f>>>0,On}var $c=globalThis.TextDecoder&&new TextDecoder,Tc=(f,b,$,x)=>{if($=b+$,x)return $;for(;f[b]&&!(b>=$);)++b;return b},Sc=(f,b=0,$,x)=>{if(16<($=Tc(f,b>>>=0,$,x))-b&&f.buffer&&$c)return $c.decode(f.buffer instanceof ArrayBuffer?f.subarray(b,$):f.slice(b,$));for(x="";b<$;){var E=f[b++];if(128&E){var k=63&f[b++];if((224&E)==192)x+=String.fromCharCode((31&E)<<6|k);else{var M=63&f[b++];65536>(E=(240&E)==224?(15&E)<<12|k<<6|M:(7&E)<<18|k<<12|M<<6|63&f[b++])?x+=String.fromCharCode(E):(E-=65536,x+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else x+=String.fromCharCode(E)}return x},et=(f,b,$)=>(f>>>=0)?Sc((I(),q),f,b,$):"";function Ic(f,b,$){return u?$e(3,1,f,b,$):0}function Oc(f,b){if(u)return $e(4,1,f,b)}function Ec(f,b){if(u)return $e(5,1,f,b)}function Ac(f,b,$){if(u)return $e(6,1,f,b,$)}function kc(f,b,$){return u?$e(7,1,f,b,$):0}function Pc(f,b){if(u)return $e(8,1,f,b)}function Cc(f,b,$){if(u)return $e(9,1,f,b,$)}function Rc(f,b,$,x){if(u)return $e(10,1,f,b,$,x)}function Dc(f,b,$,x){if(u)return $e(11,1,f,b,$,x)}function Mc(f,b,$,x){if(u)return $e(12,1,f,b,$,x)}function Nc(f){if(u)return $e(13,1,f)}function zc(f,b){if(u)return $e(14,1,f,b)}function Bc(f,b,$){if(u)return $e(15,1,f,b,$)}var mS=()=>X(""),Ht=f=>{f>>>=0;for(var b="";;){var $=(I(),q)[f++>>>0];if(!$)return b;b+=String.fromCharCode($)}},js={},Us={},gS={},En=class extends Error{constructor(f){super(f),this.name="BindingError"}};function tr(f,b,$={}){return(function(x,E,k={}){var M=E.name;if(!x)throw new En(`type "${M}" must have a positive integer typeid pointer`);if(Us.hasOwnProperty(x)){if(k.yd)return;throw new En(`Cannot register type '${M}' twice`)}Us[x]=E,delete gS[x],js.hasOwnProperty(x)&&(E=js[x],delete js[x],E.forEach(U=>U()))})(f,b,$)}var Fc=(f,b,$)=>{switch(b){case 1:return $?x=>(I(),J)[x>>>0]:x=>(I(),q)[x>>>0];case 2:return $?x=>(I(),C)[x>>>1>>>0]:x=>(I(),ee)[x>>>1>>>0];case 4:return $?x=>(I(),v)[x>>>2>>>0]:x=>(I(),R)[x>>>2>>>0];case 8:return $?x=>(I(),V)[x>>>3>>>0]:x=>(I(),K)[x>>>3>>>0];default:throw new TypeError(`invalid integer width (${b}): ${f}`)}};function bS(f,b,$,x,E){f>>>=0,$>>>=0,b=Ht(b>>>0);let k=M=>M;if(x=x===0n){let M=8*$;k=U=>BigInt.asUintN(M,U),E=k(E)}tr(f,{name:b,Oc:k,Vc:(M,U)=>(typeof U=="number"&&(U=BigInt(U)),U),Uc:Fc(b,$,!x),Wc:null})}function yS(f,b,$,x){tr(f>>>=0,{name:b=Ht(b>>>0),Oc:function(E){return!!E},Vc:function(E,k){return k?$:x},Uc:function(E){return this.Oc((I(),q)[E>>>0])},Wc:null})}var Lc=[],Fr=[0,1,,1,null,1,!0,1,!1,1];function Vs(f){9<(f>>>=0)&&--Fr[f+1]===0&&(Fr[f]=void 0,Lc.push(f))}var Ot=f=>{if(!f)throw new En(`Cannot use deleted val. handle = ${f}`);return Fr[f]},Mt=f=>{switch(f){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let b=Lc.pop()||Fr.length;return Fr[b]=f,Fr[b+1]=1,b}};function qs(f){return this.Oc((I(),R)[f>>>2>>>0])}var wS={name:"emscripten::val",Oc:f=>{var b=Ot(f);return Vs(f),b},Vc:(f,b)=>Mt(b),Uc:qs,Wc:null};function _S(f){return tr(f>>>0,wS)}var vS=(f,b)=>{switch(b){case 4:return function($){return this.Oc((I(),H)[$>>>2>>>0])};case 8:return function($){return this.Oc((I(),L)[$>>>3>>>0])};default:throw new TypeError(`invalid float width (${b}): ${f}`)}};function xS(f,b,$){$>>>=0,tr(f>>>=0,{name:b=Ht(b>>>0),Oc:x=>x,Vc:(x,E)=>E,Uc:vS(b,$),Wc:null})}function $S(f,b,$,x,E){f>>>=0,$>>>=0,b=Ht(b>>>0);let k=U=>U;if(x===0){var M=32-8*$;k=U=>U<>>M,E=k(E)}tr(f,{name:b,Oc:k,Vc:(U,Q)=>Q,Uc:Fc(b,$,x!==0),Wc:null})}function TS(f,b,$){function x(k){var M=(I(),R)[k>>>2>>>0];return k=(I(),R)[k+4>>>2>>>0],new E((I(),J).buffer,k,M)}var E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];tr(f>>>=0,{name:$=Ht($>>>0),Oc:x,Uc:x},{yd:!0})}var fr=(f,b,$)=>{var x=(I(),q);if(b>>>=0,0<$){var E=b;$=b+$-1;for(var k=0;k=M){if(b>=$)break;x[b++>>>0]=M}else if(2047>=M){if(b+1>=$)break;x[b++>>>0]=192|M>>6,x[b++>>>0]=128|63&M}else if(65535>=M){if(b+2>=$)break;x[b++>>>0]=224|M>>12,x[b++>>>0]=128|M>>6&63,x[b++>>>0]=128|63&M}else{if(b+3>=$)break;x[b++>>>0]=240|M>>18,x[b++>>>0]=128|M>>12&63,x[b++>>>0]=128|M>>6&63,x[b++>>>0]=128|63&M,k++}}x[b>>>0]=0,f=b-E}else f=0;return f},ao=f=>{for(var b=0,$=0;$=x?b++:2047>=x?b+=2:55296<=x&&57343>=x?(b+=4,++$):b+=3}return b};function SS(f,b){tr(f>>>=0,{name:b=Ht(b>>>0),Oc($){var x=(I(),R)[$>>>2>>>0];return x=et($+4,x,!0),Kt($),x},Vc($,x){x instanceof ArrayBuffer&&(x=new Uint8Array(x));var E=typeof x=="string";if(!(E||ArrayBuffer.isView(x)&&x.BYTES_PER_ELEMENT==1))throw new En("Cannot pass non-string to std::string");var k=E?ao(x):x.length,M=ei(4+k+1),U=M+4;return(I(),R)[M>>>2>>>0]=k,E?fr(x,U,k+1):(I(),q).set(x,U>>>0),$!==null&&$.push(Kt,M),M},Uc:qs,Wc($){Kt($)}})}var jc=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,IS=(f,b,$)=>{if(f>>>=1,16<(b=Tc((I(),ee),f,b/2,$))-f&&jc)return jc.decode((I(),ee).slice(f,b));for($="";f>>0];$+=String.fromCharCode(x)}return $},OS=(f,b,$)=>{if($??=2147483647,2>$)return 0;var x=b;$=($-=2)<2*f.length?$/2:f.length;for(var E=0;E<$;++E){var k=f.charCodeAt(E);(I(),C)[b>>>1>>>0]=k,b+=2}return(I(),C)[b>>>1>>>0]=0,b-x},ES=f=>2*f.length,AS=(f,b,$)=>{var x="";f>>>=2;for(var E=0;!(E>=b/4);E++){var k=(I(),R)[f+E>>>0];if(!k&&!$)break;x+=String.fromCodePoint(k)}return x},kS=(f,b,$)=>{if(b>>>=0,$??=2147483647,4>$)return 0;var x=b;$=x+$-4;for(var E=0;E>>2>>>0]=k,(b+=4)+4>$)break}return(I(),v)[b>>>2>>>0]=0,b-x},PS=f=>{for(var b=0,$=0;$>>=0,b>>>=0,$=Ht($>>>=0),b===2)var x=IS,E=OS,k=ES;else x=AS,E=kS,k=PS;tr(f,{name:$,Oc:M=>{var U=(I(),R)[M>>>2>>>0];return U=x(M+4,U*b,!0),Kt(M),U},Vc:(M,U)=>{if(typeof U!="string")throw new En(`Cannot pass non-string to C++ string type ${$}`);var Q=k(U),re=ei(4+Q+b);return(I(),R)[re>>>2>>>0]=Q/b,E(U,re+4,Q+b),M!==null&&M.push(Kt,re),re},Uc:qs,Wc(M){Kt(M)}})}function RS(f,b){tr(f>>>=0,{zd:!0,name:b=Ht(b>>>0),Oc:()=>{},Vc:()=>{}})}function DS(f){Qs(f>>>0,!i,1,!n,131072,!1),gc()}var uo=f=>{if(!A)try{if(f(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Gs(f){f>>>=0,MS||(Atomics.waitAsync((I(),v),f>>>2,f).value.then(lo),f+=128,Atomics.store((I(),v),f>>>2,1))}var lo=()=>uo(()=>{var f=go();f&&(Gs(f),fp())});function NS(f,b){(f>>>=0)==b>>>0?setTimeout(lo):u?postMessage({Zc:f,Sc:"checkMailbox"}):(f=Br[f])&&f.postMessage({Sc:"checkMailbox"})}var Hs=[];function zS(f,b,$,x,E){for(b>>>=0,E>>>=0,Hs.length=0,$=E>>>3,x=E+x>>>3;$>>0]?(I(),V)[$++>>>0]:(I(),L)[$++>>>0],Hs.push(k)}return(b?ia[b]:EI[f])(...Hs)}var BS=()=>{Ze=0};function FS(f){f>>>=0,u?postMessage({Sc:"cleanupThread",Nd:f}):mc(Br[f])}function LS(f){}var co=f=>{try{f()}catch(b){X(b)}};function jS(f){var b=(...$)=>{po.push(f);try{return f(...$)}finally{A||(po.pop(),Wt&&mr===1&&po.length===0&&(mr=0,Ze+=1,co(rh),typeof Fibers<"u"&&Fibers.be()))}};return qc.set(f,b),b}var mr=0,Wt=null,Uc=0,po=[],Ws=new Map,Vc=new Map,qc=new Map,US=0,Ks=null,VS=[],Gc=f=>(function(b){if(!A){if(mr===0){var $=!1,x=!1;b((E=0)=>{if(!A&&(Uc=E,$=!0,x)){mr=2,co(()=>nh(Wt)),typeof MainLoop<"u"&&MainLoop.ud&&MainLoop.resume(),E=!1;try{var k=(function(){var Q=(I(),v)[Wt+8>>>2>>>0];return Q=Vc.get(Q),Q=qc.get(Q),--Ze,Q()})()}catch(Q){k=Q,E=!0}var M=!1;if(!Wt){var U=Ks;U&&(Ks=null,(E?U.reject:U.resolve)(k),M=!0)}if(E&&!M)throw k}}),x=!0,$||(mr=1,Wt=(function(){var E=ei(65548),k=E+12;if((I(),R)[E>>>2>>>0]=k,(I(),R)[E+4>>>2>>>0]=k+65536,k=po[0],!Ws.has(k)){var M=US++;Ws.set(k,M),Vc.set(M,k)}return k=Ws.get(k),(I(),v)[E+8>>>2>>>0]=k,E})(),typeof MainLoop<"u"&&MainLoop.ud&&MainLoop.pause(),co(()=>th(Wt)))}else mr===2?(mr=0,co(ih),Kt(Wt),Wt=null,VS.forEach(uo)):X(`invalid state: ${mr}`);return Uc}})(b=>{f().then(b)});function qS(f){return f>>>=0,Gc(async()=>{var b=await Ot(f);return Mt(b)})}var Xs=[],GS=f=>{var b=Xs.length;return Xs.push(f),b},HS=(f,b)=>{for(var $=Array(f),x=0;x>>2>>>0],M=Us[k];if(M===void 0)throw f=`parameter ${x}`,k=up(k),b=Ht(k),Kt(k),new En(`${f} has unknown type ${b}`);$[E]=M}return $},WS=(f,b,$)=>{var x=[];return f=f(x,$),x.length&&((I(),R)[b>>>2>>>0]=Mt(x)),f},KS={},ho=f=>{var b=KS[f];return b===void 0?Ht(f):b};function XS(f,b,$){var[x,...E]=HS(f,b>>>0);b=x.Vc.bind(x);var k=E.map(Q=>Q.Uc.bind(Q));f--;var M={toValue:Ot};switch(f=k.map((Q,re)=>{var ge=`argFromPtr${re}`;return M[ge]=Q,`${ge}(args${re?"+"+8*re:""})`}),$){case 0:var U="toValue(handle)";break;case 2:U="new (toValue(handle))";break;case 3:U="";break;case 1:M.getStringOrSymbol=ho,U="toValue(handle)[getStringOrSymbol(methodName)]"}return U+=`(${f})`,x.zd||(M.toReturnWire=b,M.emval_returnValue=WS,U=`return emval_returnValue(toReturnWire, destructorsRef, ${U})`),U=`return function (handle, methodName, destructorsRef, args) { +`))}return x}finally{t.Xc=null}};t.jsepInit=(f,b)=>{if(f==="webgpu"){[t.dd,t.Ad,t.Ed,t.ed,t.Dd,t.$b,t.Fd,t.Hd,t.Bd,t.Cd,t.Gd]=b;let $=t.dd;t.jsepRegisterBuffer=(x,E,k,M)=>$.registerBuffer(x,E,k,M),t.jsepGetBuffer=x=>$.getBuffer(x),t.jsepCreateDownloader=(x,E,k)=>$.createDownloader(x,E,k),t.jsepOnCreateSession=x=>{$.onCreateSession(x)},t.jsepOnReleaseSession=x=>{$.onReleaseSession(x)},t.jsepOnRunStart=x=>$.onRunStart(x),t.Id=(x,E)=>{$.upload(x,E)}}else if(f==="webnn"){let $=b[0];[t.Sd,t.sd,t.webnnEnsureTensor,t.td,t.webnnDownloadTensor,t.Rd,t.webnnEnableTraceEvent]=b.slice(1),t.webnnReleaseTensorId=t.sd,t.webnnUploadTensor=t.td,t.webnnRegisterMLContext=t.Rd,t.webnnOnRunStart=x=>$.onRunStart(x),t.webnnOnRunEnd=$.onRunEnd.bind($),t.webnnOnReleaseSession=x=>{$.onReleaseSession(x)},t.webnnCreateMLTensorDownloader=(x,E)=>$.createMLTensorDownloader(x,E),t.webnnRegisterMLTensor=(x,E,k,M)=>$.registerMLTensor(x,E,k,M),t.webnnCreateMLContext=x=>$.createMLContext(x),t.webnnRegisterGraphInput=$.registerGraphInput.bind($),t.webnnIsGraphInput=$.isGraphInput.bind($),t.webnnRegisterGraphOutput=$.registerGraphOutput.bind($),t.webnnIsGraphOutput=$.isGraphOutput.bind($),t.webnnCreateTemporaryTensor=$.createTemporaryTensor.bind($),t.webnnIsGraphInputOutputTypeSupported=$.isGraphInputOutputTypeSupported.bind($)}};let d=()=>{let f=b=>(...$)=>{let x=Wt;return $=b(...$),Wt!=x?new Promise((E,k)=>{Ks={resolve:E,reject:k}}):$};(()=>{for(let b of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[b]=f(t[b])})(),l!==void 0&&(t._OrtRun=l(t._OrtRun),t._OrtRunWithBinding=l(t._OrtRunWithBinding)),d=void 0};t.asyncInit=()=>{d?.()};var c,s,r=(f,b)=>{throw b},o=import.meta.url,a="";if(n||i){try{a=new URL(".",o).href}catch{}i&&(s=f=>{var b=new XMLHttpRequest;return b.open("GET",f,!1),b.responseType="arraybuffer",b.send(null),new Uint8Array(b.response)}),c=async f=>{if(P(f))return new Promise(($,x)=>{var E=new XMLHttpRequest;E.open("GET",f,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?$(E.response):x(E.status)},E.onerror=x,E.send(null)});var b=await fetch(f,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url)}}var p,h,m,g,_,w,y=console.log.bind(console),T=console.error.bind(console),S=y,O=T,A=!1,P=f=>f.startsWith("file://");function I(){hr.buffer!=J.buffer&&Y()}if(u){let f=function(b){try{var $=b.data,x=$.Sc;if(x==="load"){let E=[];self.onmessage=k=>E.push(k),w=()=>{postMessage({Sc:"loaded"});for(let k of E)f(k);self.onmessage=f};for(let k of $.xd)t[k]&&!t[k].proxy||(t[k]=(...M)=>{postMessage({Sc:"callHandler",vd:k,args:M})},k=="print"&&(S=t[k]),k=="printErr"&&(O=t[k]));hr=$.Od,Y(),h=$.Pd,re(),bo()}else if(x==="run"){(function(E){var k=(I(),R)[E+52>>>2>>>0];E=(I(),R)[E+56>>>2>>>0],mp(k,k-E),we(k)})($.Rc),Qs($.Rc,0,0,1,0,0),gc(),Gs($.Rc),G||(lp(),G=!0);try{oS($.Md,$.bd)}catch(E){if(E!="unwind")throw E}}else $.target!=="setimmediate"&&(x==="checkMailbox"?G&&lo():x&&(O(`worker: received unknown command ${x}`),O($)))}catch(E){throw dp(),E}};var z=f,G=!1;self.onunhandledrejection=b=>{throw b.reason||b},self.onmessage=f}var J,q,C,ee,v,R,H,L,V,K,B,te=!1;function Y(){var f=hr.buffer;t.HEAP8=J=new Int8Array(f),C=new Int16Array(f),t.HEAPU8=q=new Uint8Array(f),ee=new Uint16Array(f),t.HEAP32=v=new Int32Array(f),t.HEAPU32=R=new Uint32Array(f),H=new Float32Array(f),L=new Float64Array(f),V=new BigInt64Array(f),K=new BigUint64Array(f)}function N(){te=!0,u?w():rr.sb()}function X(f){throw O(f="Aborted("+f+")"),A=!0,f=new WebAssembly.RuntimeError(f+". Build with -sASSERTIONS for more info."),_?.(f),f}function W(){return{a:{ma:kI,hb:AI,g:sS,J:aS,f:uS,o:lS,i:dS,$:cS,b:pS,S:hS,Ia:xc,n:fS,aa:Ic,Ya:Oc,Ea:Ec,Ga:Ac,Za:kc,Wa:Pc,Pa:Cc,Va:Rc,ka:Dc,Fa:Mc,Ca:Nc,Xa:zc,Da:Bc,cb:mS,fa:bS,xa:yS,va:_S,ea:xS,N:$S,H:TS,wa:SS,_:CS,ya:RS,Sa:DS,Aa:NS,Ja:zS,ta:BS,ga:FS,Ra:Gs,$a:LS,Q:qS,r:XS,c:Vs,ib:ZS,y:YS,M:JS,D:QS,l:eI,s:Hc,jb:tI,I:rI,R:nI,j:iI,u:oI,q:sI,k:aI,Ma:uI,Na:lI,Oa:dI,Ka:Zc,La:Yc,ua:Jc,eb:pI,bb:mI,v:gI,ba:bI,ha:yI,ab:hI,V:wI,_a:_I,Ba:vI,F:cI,T:xI,la:mo,za:TI,gb:$I,fb:SI,Ta:rp,Ua:np,Ha:zr,U:ip,ja:op,Qa:sp,ia:ap,lb:p3,na:a3,mb:c3,oa:s3,G:ZI,e:DI,t:CI,w:PI,B:qI,nb:n3,Z:r3,x:zI,pa:i3,X:u3,ca:t3,ob:e3,pb:QI,O:GI,qa:JI,qb:YI,L:KI,Y:o3,d:RI,A:NI,m:MI,kb:h3,p:FI,z:LI,C:BI,E:jI,K:HI,ra:XI,P:l3,da:WI,W:d3,rb:VI,sa:UI,h:OI,a:hr,db:ht}}}async function re(){function f(x,E){var k=rr=x.exports;x={};for(let[M,U]of Object.entries(k))typeof U=="function"?(k=jS(U),x[M]=k):x[M]=U;return rr=x,rr=(function(){var M=rr,U=ne=>ge=>ne(ge)>>>0,Q=ne=>()=>ne()>>>0;return(M=Object.assign({},M)).tb=U(M.tb),M.Xb=Q(M.Xb),M.Zb=U(M.Zb),M.lc=U(M.lc),M.mc=Q(M.mc),M.qc=U(M.qc),M})(),fc.push(rr._b),up=(x=rr).tb,lp=x.ub,t._OrtInit=x.vb,t._OrtGetLastError=x.wb,t._OrtCreateSessionOptions=x.xb,t._OrtAppendExecutionProvider=x.yb,t._OrtAddFreeDimensionOverride=x.zb,t._OrtAddSessionConfigEntry=x.Ab,t._OrtReleaseSessionOptions=x.Bb,t._OrtCreateSession=x.Cb,t._OrtReleaseSession=x.Db,t._OrtGetInputOutputCount=x.Eb,t._OrtGetInputOutputMetadata=x.Fb,t._OrtFree=x.Gb,t._OrtCreateTensor=x.Hb,t._OrtGetTensorData=x.Ib,t._OrtReleaseTensor=x.Jb,t._OrtCreateRunOptions=x.Kb,t._OrtAddRunConfigEntry=x.Lb,t._OrtReleaseRunOptions=x.Mb,t._OrtCreateBinding=x.Nb,t._OrtBindInput=x.Ob,t._OrtBindOutput=x.Pb,t._OrtClearBoundOutputs=x.Qb,t._OrtReleaseBinding=x.Rb,t._OrtRunWithBinding=x.Sb,t._OrtRun=x.Tb,t._OrtEndProfiling=x.Ub,t._JsepOutput=x.Vb,t._JsepGetNodeName=x.Wb,go=x.Xb,Kt=t._free=x.Yb,ei=t._malloc=x.Zb,Qs=x.ac,dp=x.bc,cp=x.cc,pp=x.dc,ea=x.ec,hp=x.fc,fp=x.gc,Te=x.hc,ti=x.ic,mp=x.jc,we=x.kc,ta=x.lc,_e=x.mc,gp=x.nc,ra=x.oc,bp=x.pc,yp=x.qc,wp=x.rc,na=x.sc,_p=x.tc,vp=x.uc,xp=x.vc,$p=x.wc,Tp=x.xc,Sp=x.yc,Ip=x.zc,Op=x.Ac,Ep=x.Bc,Ap=x.Cc,kp=x.Dc,Pp=x.Ec,Cp=x.Fc,Rp=x.Gc,Dp=x.Hc,Mp=x.Ic,Np=x.Jc,zp=x.Kc,Bp=x.Lc,Fp=x.Mc,Lp=x.Nc,jp=x.Pc,Up=x.Qc,Vp=x.$c,qp=x.ad,Gp=x.fd,Hp=x.kd,Wp=x.ld,Kp=x.md,Xp=x.nd,Zp=x.od,Yp=x.pd,Jp=x.qd,Qp=x.rd,eh=x.wd,th=x.Ud,rh=x.Vd,nh=x.Wd,ih=x.Xd,h=E,rr}var b,$=W();return t.instantiateWasm?new Promise(x=>{t.instantiateWasm($,(E,k)=>{x(f(E,k))})}):u?f(new WebAssembly.Instance(h,W()),h):(B??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.jsep.wasm",a):a+"ort-wasm-simd-threaded.jsep.wasm":new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url).href,b=await(async function(x){var E=B;if(!p&&!P(E))try{var k=fetch(E,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(k,x)}catch(M){O(`wasm streaming compile failed: ${M}`),O("falling back to ArrayBuffer instantiation")}return(async function(M,U){try{var Q=await(async function(ne){if(!p)try{var ge=await c(ne);return new Uint8Array(ge)}catch{}if(ne==B&&p)ne=new Uint8Array(p);else{if(!s)throw"both async and sync fetching of the wasm failed";ne=s(ne)}return ne})(M);return await WebAssembly.instantiate(Q,U)}catch(ne){O(`failed to asynchronously prepare wasm: ${ne}`),X(ne)}})(E,x)})($),f(b.instance,b.module))}class le{name="ExitStatus";constructor(b){this.message=`Program terminated with exit(${b})`,this.status=b}}var ce=f=>{f.terminate(),f.onmessage=()=>{}},xe=[],qe=0,Ve=null,it=f=>{Gt.length==0&&(yc(),bc(Gt[0]));var b=Gt.pop();if(!b)return 6;Jn.push(b),Br[f.Rc]=b,b.Rc=f.Rc;var $={Sc:"run",Md:f.Ld,bd:f.bd,Rc:f.Rc};return b.postMessage($,f.jd),0},Ze=0,$e=(f,b,...$)=>{var x,E=16*$.length,k=_e(),M=ta(E),U=M>>>3;for(x of $)typeof x=="bigint"?((I(),V)[U++>>>0]=1n,(I(),V)[U++>>>0]=x):((I(),V)[U++>>>0]=0n,(I(),L)[U++>>>0]=x);return f=cp(f,0,E,M,b),we(k),f};function ht(f){if(u)return $e(0,1,f);if(m=f,!(0{if(m=f,u)throw It(f),"unwind";ht(f)},Gt=[],Jn=[],fc=[],Br={},mc=f=>{var b=f.Rc;delete Br[b],Gt.push(f),Jn.splice(Jn.indexOf(f),1),f.Rc=0,pp(b)};function gc(){fc.forEach(f=>f())}var bc=f=>new Promise(b=>{f.onmessage=E=>{var k=E.data;if(E=k.Sc,k.Zc&&k.Zc!=go()){var M=Br[k.Zc];M?M.postMessage(k,k.jd):O(`Internal error! Worker sent a message "${E}" to target pthread ${k.Zc}, but that thread no longer exists!`)}else E==="checkMailbox"?lo():E==="spawnThread"?it(k):E==="cleanupThread"?uo(()=>{mc(Br[k.Nd])}):E==="loaded"?(f.loaded=!0,b(f)):k.target==="setimmediate"?f.postMessage(k):E==="uncaughtException"?f.onerror(k.error):E==="callHandler"?t[k.vd](...k.args):E&&O(`worker sent an unknown command ${E}`)},f.onerror=E=>{throw O(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var $,x=[];for($ of[])t.propertyIsEnumerable($)&&x.push($);f.postMessage({Sc:"load",xd:x,Od:hr,Pd:h})});function yc(){var f=new Worker((()=>{let b=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new b("ort.all.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Gt.push(f)}var hr,oS=(f,b)=>{Ze=0,f=na(f,b),0>>=0);return(I(),J)[b.Tc+12>>>0]==0&&(wc(b,!0),so--),_c(b,!1),oo.push(b),yp(f)}var On=0,aS=()=>{Te(0,0);var f=oo.pop();gp(f.cd),On=0};function wc(f,b){b=b?1:0,(I(),J)[f.Tc+12>>>0]=b}function _c(f,b){b=b?1:0,(I(),J)[f.Tc+13>>>0]=b}class Fs{constructor(b){this.cd=b,this.Tc=b-24}}var Ls=f=>{var b=On;if(!b)return ti(0),0;var $=new Fs(b);(I(),R)[$.Tc+16>>>2>>>0]=b;var x=(I(),R)[$.Tc+4>>>2>>>0];if(!x)return ti(0),b;for(var E of f){if(E===0||E===x)break;if(bp(E,x,$.Tc+16))return ti(E),b}return ti(x),b};function uS(){return Ls([])}function lS(f){return Ls([f>>>0])}function dS(f,b,$,x){return Ls([f>>>0,b>>>0,$>>>0,x>>>0])}var cS=()=>{var f=oo.pop();f||X("no exception to throw");var b=f.cd;throw(I(),J)[f.Tc+13>>>0]==0&&(oo.push(f),_c(f,!0),wc(f,!1),so++),ra(b),On=b};function pS(f,b,$){var x=new Fs(f>>>=0);throw b>>>=0,$>>>=0,(I(),R)[x.Tc+16>>>2>>>0]=0,(I(),R)[x.Tc+4>>>2>>>0]=b,(I(),R)[x.Tc+8>>>2>>>0]=$,ra(f),so++,On=f}var hS=()=>so;function vc(f,b,$,x){return u?$e(2,1,f,b,$,x):xc(f,b,$,x)}function xc(f,b,$,x){if(f>>>=0,b>>>=0,$>>>=0,x>>>=0,!globalThis.SharedArrayBuffer)return 6;var E=[];return u&&E.length===0?vc(f,b,$,x):(f={Ld:$,Rc:f,bd:x,jd:E},u?(f.Sc="spawnThread",postMessage(f,E),0):it(f))}function fS(f){throw On||=f>>>0,On}var $c=globalThis.TextDecoder&&new TextDecoder,Tc=(f,b,$,x)=>{if($=b+$,x)return $;for(;f[b]&&!(b>=$);)++b;return b},Sc=(f,b=0,$,x)=>{if(16<($=Tc(f,b>>>=0,$,x))-b&&f.buffer&&$c)return $c.decode(f.buffer instanceof ArrayBuffer?f.subarray(b,$):f.slice(b,$));for(x="";b<$;){var E=f[b++];if(128&E){var k=63&f[b++];if((224&E)==192)x+=String.fromCharCode((31&E)<<6|k);else{var M=63&f[b++];65536>(E=(240&E)==224?(15&E)<<12|k<<6|M:(7&E)<<18|k<<12|M<<6|63&f[b++])?x+=String.fromCharCode(E):(E-=65536,x+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else x+=String.fromCharCode(E)}return x},et=(f,b,$)=>(f>>>=0)?Sc((I(),q),f,b,$):"";function Ic(f,b,$){return u?$e(3,1,f,b,$):0}function Oc(f,b){if(u)return $e(4,1,f,b)}function Ec(f,b){if(u)return $e(5,1,f,b)}function Ac(f,b,$){if(u)return $e(6,1,f,b,$)}function kc(f,b,$){return u?$e(7,1,f,b,$):0}function Pc(f,b){if(u)return $e(8,1,f,b)}function Cc(f,b,$){if(u)return $e(9,1,f,b,$)}function Rc(f,b,$,x){if(u)return $e(10,1,f,b,$,x)}function Dc(f,b,$,x){if(u)return $e(11,1,f,b,$,x)}function Mc(f,b,$,x){if(u)return $e(12,1,f,b,$,x)}function Nc(f){if(u)return $e(13,1,f)}function zc(f,b){if(u)return $e(14,1,f,b)}function Bc(f,b,$){if(u)return $e(15,1,f,b,$)}var mS=()=>X(""),Ht=f=>{f>>>=0;for(var b="";;){var $=(I(),q)[f++>>>0];if(!$)return b;b+=String.fromCharCode($)}},js={},Us={},gS={},En=class extends Error{constructor(f){super(f),this.name="BindingError"}};function tr(f,b,$={}){return(function(x,E,k={}){var M=E.name;if(!x)throw new En(`type "${M}" must have a positive integer typeid pointer`);if(Us.hasOwnProperty(x)){if(k.yd)return;throw new En(`Cannot register type '${M}' twice`)}Us[x]=E,delete gS[x],js.hasOwnProperty(x)&&(E=js[x],delete js[x],E.forEach(U=>U()))})(f,b,$)}var Fc=(f,b,$)=>{switch(b){case 1:return $?x=>(I(),J)[x>>>0]:x=>(I(),q)[x>>>0];case 2:return $?x=>(I(),C)[x>>>1>>>0]:x=>(I(),ee)[x>>>1>>>0];case 4:return $?x=>(I(),v)[x>>>2>>>0]:x=>(I(),R)[x>>>2>>>0];case 8:return $?x=>(I(),V)[x>>>3>>>0]:x=>(I(),K)[x>>>3>>>0];default:throw new TypeError(`invalid integer width (${b}): ${f}`)}};function bS(f,b,$,x,E){f>>>=0,$>>>=0,b=Ht(b>>>0);let k=M=>M;if(x=x===0n){let M=8*$;k=U=>BigInt.asUintN(M,U),E=k(E)}tr(f,{name:b,Oc:k,Vc:(M,U)=>(typeof U=="number"&&(U=BigInt(U)),U),Uc:Fc(b,$,!x),Wc:null})}function yS(f,b,$,x){tr(f>>>=0,{name:b=Ht(b>>>0),Oc:function(E){return!!E},Vc:function(E,k){return k?$:x},Uc:function(E){return this.Oc((I(),q)[E>>>0])},Wc:null})}var Lc=[],Fr=[0,1,,1,null,1,!0,1,!1,1];function Vs(f){9<(f>>>=0)&&--Fr[f+1]===0&&(Fr[f]=void 0,Lc.push(f))}var Ot=f=>{if(!f)throw new En(`Cannot use deleted val. handle = ${f}`);return Fr[f]},Mt=f=>{switch(f){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let b=Lc.pop()||Fr.length;return Fr[b]=f,Fr[b+1]=1,b}};function qs(f){return this.Oc((I(),R)[f>>>2>>>0])}var wS={name:"emscripten::val",Oc:f=>{var b=Ot(f);return Vs(f),b},Vc:(f,b)=>Mt(b),Uc:qs,Wc:null};function _S(f){return tr(f>>>0,wS)}var vS=(f,b)=>{switch(b){case 4:return function($){return this.Oc((I(),H)[$>>>2>>>0])};case 8:return function($){return this.Oc((I(),L)[$>>>3>>>0])};default:throw new TypeError(`invalid float width (${b}): ${f}`)}};function xS(f,b,$){$>>>=0,tr(f>>>=0,{name:b=Ht(b>>>0),Oc:x=>x,Vc:(x,E)=>E,Uc:vS(b,$),Wc:null})}function $S(f,b,$,x,E){f>>>=0,$>>>=0,b=Ht(b>>>0);let k=U=>U;if(x===0){var M=32-8*$;k=U=>U<>>M,E=k(E)}tr(f,{name:b,Oc:k,Vc:(U,Q)=>Q,Uc:Fc(b,$,x!==0),Wc:null})}function TS(f,b,$){function x(k){var M=(I(),R)[k>>>2>>>0];return k=(I(),R)[k+4>>>2>>>0],new E((I(),J).buffer,k,M)}var E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];tr(f>>>=0,{name:$=Ht($>>>0),Oc:x,Uc:x},{yd:!0})}var fr=(f,b,$)=>{var x=(I(),q);if(b>>>=0,0<$){var E=b;$=b+$-1;for(var k=0;k=M){if(b>=$)break;x[b++>>>0]=M}else if(2047>=M){if(b+1>=$)break;x[b++>>>0]=192|M>>6,x[b++>>>0]=128|63&M}else if(65535>=M){if(b+2>=$)break;x[b++>>>0]=224|M>>12,x[b++>>>0]=128|M>>6&63,x[b++>>>0]=128|63&M}else{if(b+3>=$)break;x[b++>>>0]=240|M>>18,x[b++>>>0]=128|M>>12&63,x[b++>>>0]=128|M>>6&63,x[b++>>>0]=128|63&M,k++}}x[b>>>0]=0,f=b-E}else f=0;return f},ao=f=>{for(var b=0,$=0;$=x?b++:2047>=x?b+=2:55296<=x&&57343>=x?(b+=4,++$):b+=3}return b};function SS(f,b){tr(f>>>=0,{name:b=Ht(b>>>0),Oc($){var x=(I(),R)[$>>>2>>>0];return x=et($+4,x,!0),Kt($),x},Vc($,x){x instanceof ArrayBuffer&&(x=new Uint8Array(x));var E=typeof x=="string";if(!(E||ArrayBuffer.isView(x)&&x.BYTES_PER_ELEMENT==1))throw new En("Cannot pass non-string to std::string");var k=E?ao(x):x.length,M=ei(4+k+1),U=M+4;return(I(),R)[M>>>2>>>0]=k,E?fr(x,U,k+1):(I(),q).set(x,U>>>0),$!==null&&$.push(Kt,M),M},Uc:qs,Wc($){Kt($)}})}var jc=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,IS=(f,b,$)=>{if(f>>>=1,16<(b=Tc((I(),ee),f,b/2,$))-f&&jc)return jc.decode((I(),ee).slice(f,b));for($="";f>>0];$+=String.fromCharCode(x)}return $},OS=(f,b,$)=>{if($??=2147483647,2>$)return 0;var x=b;$=($-=2)<2*f.length?$/2:f.length;for(var E=0;E<$;++E){var k=f.charCodeAt(E);(I(),C)[b>>>1>>>0]=k,b+=2}return(I(),C)[b>>>1>>>0]=0,b-x},ES=f=>2*f.length,AS=(f,b,$)=>{var x="";f>>>=2;for(var E=0;!(E>=b/4);E++){var k=(I(),R)[f+E>>>0];if(!k&&!$)break;x+=String.fromCodePoint(k)}return x},kS=(f,b,$)=>{if(b>>>=0,$??=2147483647,4>$)return 0;var x=b;$=x+$-4;for(var E=0;E>>2>>>0]=k,(b+=4)+4>$)break}return(I(),v)[b>>>2>>>0]=0,b-x},PS=f=>{for(var b=0,$=0;$>>=0,b>>>=0,$=Ht($>>>=0),b===2)var x=IS,E=OS,k=ES;else x=AS,E=kS,k=PS;tr(f,{name:$,Oc:M=>{var U=(I(),R)[M>>>2>>>0];return U=x(M+4,U*b,!0),Kt(M),U},Vc:(M,U)=>{if(typeof U!="string")throw new En(`Cannot pass non-string to C++ string type ${$}`);var Q=k(U),ne=ei(4+Q+b);return(I(),R)[ne>>>2>>>0]=Q/b,E(U,ne+4,Q+b),M!==null&&M.push(Kt,ne),ne},Uc:qs,Wc(M){Kt(M)}})}function RS(f,b){tr(f>>>=0,{zd:!0,name:b=Ht(b>>>0),Oc:()=>{},Vc:()=>{}})}function DS(f){Qs(f>>>0,!i,1,!n,131072,!1),gc()}var uo=f=>{if(!A)try{if(f(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Gs(f){f>>>=0,MS||(Atomics.waitAsync((I(),v),f>>>2,f).value.then(lo),f+=128,Atomics.store((I(),v),f>>>2,1))}var lo=()=>uo(()=>{var f=go();f&&(Gs(f),fp())});function NS(f,b){(f>>>=0)==b>>>0?setTimeout(lo):u?postMessage({Zc:f,Sc:"checkMailbox"}):(f=Br[f])&&f.postMessage({Sc:"checkMailbox"})}var Hs=[];function zS(f,b,$,x,E){for(b>>>=0,E>>>=0,Hs.length=0,$=E>>>3,x=E+x>>>3;$>>0]?(I(),V)[$++>>>0]:(I(),L)[$++>>>0],Hs.push(k)}return(b?ia[b]:EI[f])(...Hs)}var BS=()=>{Ze=0};function FS(f){f>>>=0,u?postMessage({Sc:"cleanupThread",Nd:f}):mc(Br[f])}function LS(f){}var co=f=>{try{f()}catch(b){X(b)}};function jS(f){var b=(...$)=>{po.push(f);try{return f(...$)}finally{A||(po.pop(),Wt&&mr===1&&po.length===0&&(mr=0,Ze+=1,co(rh),typeof Fibers<"u"&&Fibers.be()))}};return qc.set(f,b),b}var mr=0,Wt=null,Uc=0,po=[],Ws=new Map,Vc=new Map,qc=new Map,US=0,Ks=null,VS=[],Gc=f=>(function(b){if(!A){if(mr===0){var $=!1,x=!1;b((E=0)=>{if(!A&&(Uc=E,$=!0,x)){mr=2,co(()=>nh(Wt)),typeof MainLoop<"u"&&MainLoop.ud&&MainLoop.resume(),E=!1;try{var k=(function(){var Q=(I(),v)[Wt+8>>>2>>>0];return Q=Vc.get(Q),Q=qc.get(Q),--Ze,Q()})()}catch(Q){k=Q,E=!0}var M=!1;if(!Wt){var U=Ks;U&&(Ks=null,(E?U.reject:U.resolve)(k),M=!0)}if(E&&!M)throw k}}),x=!0,$||(mr=1,Wt=(function(){var E=ei(65548),k=E+12;if((I(),R)[E>>>2>>>0]=k,(I(),R)[E+4>>>2>>>0]=k+65536,k=po[0],!Ws.has(k)){var M=US++;Ws.set(k,M),Vc.set(M,k)}return k=Ws.get(k),(I(),v)[E+8>>>2>>>0]=k,E})(),typeof MainLoop<"u"&&MainLoop.ud&&MainLoop.pause(),co(()=>th(Wt)))}else mr===2?(mr=0,co(ih),Kt(Wt),Wt=null,VS.forEach(uo)):X(`invalid state: ${mr}`);return Uc}})(b=>{f().then(b)});function qS(f){return f>>>=0,Gc(async()=>{var b=await Ot(f);return Mt(b)})}var Xs=[],GS=f=>{var b=Xs.length;return Xs.push(f),b},HS=(f,b)=>{for(var $=Array(f),x=0;x>>2>>>0],M=Us[k];if(M===void 0)throw f=`parameter ${x}`,k=up(k),b=Ht(k),Kt(k),new En(`${f} has unknown type ${b}`);$[E]=M}return $},WS=(f,b,$)=>{var x=[];return f=f(x,$),x.length&&((I(),R)[b>>>2>>>0]=Mt(x)),f},KS={},ho=f=>{var b=KS[f];return b===void 0?Ht(f):b};function XS(f,b,$){var[x,...E]=HS(f,b>>>0);b=x.Vc.bind(x);var k=E.map(Q=>Q.Uc.bind(Q));f--;var M={toValue:Ot};switch(f=k.map((Q,ne)=>{var ge=`argFromPtr${ne}`;return M[ge]=Q,`${ge}(args${ne?"+"+8*ne:""})`}),$){case 0:var U="toValue(handle)";break;case 2:U="new (toValue(handle))";break;case 3:U="";break;case 1:M.getStringOrSymbol=ho,U="toValue(handle)[getStringOrSymbol(methodName)]"}return U+=`(${f})`,x.zd||(M.toReturnWire=b,M.emval_returnValue=WS,U=`return emval_returnValue(toReturnWire, destructorsRef, ${U})`),U=`return function (handle, methodName, destructorsRef, args) { ${U} }`,$=new Function(Object.keys(M),U)(...Object.values(M)),U=`methodCaller<(${E.map(Q=>Q.name)}) => ${x.name}>`,GS(Object.defineProperty($,"name",{value:U}))}function ZS(f,b){return b>>>=0,(f=Ot(f>>>0))==Ot(b)}function YS(f){return(f>>>=0)?(f=ho(f),Mt(globalThis[f])):Mt(globalThis)}function JS(f){return f=ho(f>>>0),Mt(t[f])}function QS(f,b){return b>>>=0,f=Ot(f>>>0),b=Ot(b),Mt(f[b])}function eI(f){9<(f>>>=0)&&(Fr[f+1]+=1)}function Hc(f,b,$,x,E){return Xs[f>>>0](b>>>0,$>>>0,x>>>0,E>>>0)}function tI(f,b,$,x,E){return Hc(f>>>0,b>>>0,$>>>0,x>>>0,E>>>0)}function rI(){return Mt([])}function nI(f){f=Ot(f>>>0);for(var b=Array(f.length),$=0;$>>0))}function oI(){return Mt({})}function sI(f){for(var b=Ot(f>>>=0);b.length;){var $=b.pop();b.pop()($)}Vs(f)}function aI(f,b,$){b>>>=0,$>>>=0,f=Ot(f>>>0),b=Ot(b),$=Ot($),f[b]=$}function uI(f,b){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),(I(),v)[b>>>2>>>0]=f.getUTCSeconds(),(I(),v)[b+4>>>2>>>0]=f.getUTCMinutes(),(I(),v)[b+8>>>2>>>0]=f.getUTCHours(),(I(),v)[b+12>>>2>>>0]=f.getUTCDate(),(I(),v)[b+16>>>2>>>0]=f.getUTCMonth(),(I(),v)[b+20>>>2>>>0]=f.getUTCFullYear()-1900,(I(),v)[b+24>>>2>>>0]=f.getUTCDay(),f=(f.getTime()-Date.UTC(f.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(I(),v)[b+28>>>2>>>0]=f}var Wc=f=>f%4==0&&(f%100!=0||f%400==0),Kc=[0,31,60,91,121,152,182,213,244,274,305,335],Xc=[0,31,59,90,120,151,181,212,243,273,304,334];function lI(f,b){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),(I(),v)[b>>>2>>>0]=f.getSeconds(),(I(),v)[b+4>>>2>>>0]=f.getMinutes(),(I(),v)[b+8>>>2>>>0]=f.getHours(),(I(),v)[b+12>>>2>>>0]=f.getDate(),(I(),v)[b+16>>>2>>>0]=f.getMonth(),(I(),v)[b+20>>>2>>>0]=f.getFullYear()-1900,(I(),v)[b+24>>>2>>>0]=f.getDay();var $=(Wc(f.getFullYear())?Kc:Xc)[f.getMonth()]+f.getDate()-1|0;(I(),v)[b+28>>>2>>>0]=$,(I(),v)[b+36>>>2>>>0]=-60*f.getTimezoneOffset(),$=new Date(f.getFullYear(),6,1).getTimezoneOffset();var x=new Date(f.getFullYear(),0,1).getTimezoneOffset();f=0|($!=x&&f.getTimezoneOffset()==Math.min(x,$)),(I(),v)[b+32>>>2>>>0]=f}function dI(f){f>>>=0;var b=new Date((I(),v)[f+20>>>2>>>0]+1900,(I(),v)[f+16>>>2>>>0],(I(),v)[f+12>>>2>>>0],(I(),v)[f+8>>>2>>>0],(I(),v)[f+4>>>2>>>0],(I(),v)[f>>>2>>>0],0),$=(I(),v)[f+32>>>2>>>0],x=b.getTimezoneOffset(),E=new Date(b.getFullYear(),6,1).getTimezoneOffset(),k=new Date(b.getFullYear(),0,1).getTimezoneOffset(),M=Math.min(k,E);return 0>$?(I(),v)[f+32>>>2>>>0]=+(E!=k&&M==x):0<$!=(M==x)&&(E=Math.max(k,E),b.setTime(b.getTime()+6e4*((0<$?M:E)-x))),(I(),v)[f+24>>>2>>>0]=b.getDay(),$=(Wc(b.getFullYear())?Kc:Xc)[b.getMonth()]+b.getDate()-1|0,(I(),v)[f+28>>>2>>>0]=$,(I(),v)[f>>>2>>>0]=b.getSeconds(),(I(),v)[f+4>>>2>>>0]=b.getMinutes(),(I(),v)[f+8>>>2>>>0]=b.getHours(),(I(),v)[f+12>>>2>>>0]=b.getDate(),(I(),v)[f+16>>>2>>>0]=b.getMonth(),(I(),v)[f+20>>>2>>>0]=b.getYear(),f=b.getTime(),BigInt(isNaN(f)?-1:f/1e3)}function Zc(f,b,$,x,E,k,M){return u?$e(16,1,f,b,$,x,E,k,M):-52}function Yc(f,b,$,x,E,k){if(u)return $e(17,1,f,b,$,x,E,k)}var Qn={},cI=()=>performance.timeOrigin+performance.now();function Jc(f,b){if(u)return $e(18,1,f,b);if(Qn[f]&&(clearTimeout(Qn[f].id),delete Qn[f]),!b)return 0;var $=setTimeout(()=>{delete Qn[f],uo(()=>hp(f,performance.timeOrigin+performance.now()))},b);return Qn[f]={id:$,ae:b},0}function pI(f,b,$,x){f>>>=0,b>>>=0,$>>>=0,x>>>=0;var E=new Date().getFullYear(),k=new Date(E,0,1).getTimezoneOffset();E=new Date(E,6,1).getTimezoneOffset();var M=Math.max(k,E);(I(),R)[f>>>2>>>0]=60*M,(I(),v)[b>>>2>>>0]=+(k!=E),f=(b=U=>{var Q=Math.abs(U);return`UTC${0<=U?"-":"+"}${String(Math.floor(Q/60)).padStart(2,"0")}${String(Q%60).padStart(2,"0")}`})(k),b=b(E),EDate.now(),fI=1;function mI(f,b,$){if($>>>=0,!(0<=f&&3>=f))return 28;if(f===0)f=Date.now();else{if(!fI)return 52;f=performance.timeOrigin+performance.now()}return f=Math.round(1e6*f),(I(),V)[$>>>3>>>0]=BigInt(f),0}var Zs=[],Qc=(f,b)=>{Zs.length=0;for(var $;$=(I(),q)[f++>>>0];){var x=$!=105;b+=(x&=$!=112)&&b%8?4:0,Zs.push($==112?(I(),R)[b>>>2>>>0]:$==106?(I(),V)[b>>>3>>>0]:$==105?(I(),v)[b>>>2>>>0]:(I(),L)[b>>>3>>>0]),b+=x?8:4}return Zs};function gI(f,b,$){return f>>>=0,b=Qc(b>>>0,$>>>0),ia[f](...b)}function bI(f,b,$){return f>>>=0,b=Qc(b>>>0,$>>>0),ia[f](...b)}var yI=()=>{};function wI(f,b){return O(et(f>>>0,b>>>0))}var _I=()=>{throw Ze+=1,"unwind"};function vI(){return 4294901760}var xI=()=>navigator.hardwareConcurrency,Lr={},fo=f=>{var b;return(b=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(f))?+b[1]:(b=/:(\d+):\d+(?:\)|$)/.exec(f))?2147483648|+b[1]:0},ep=f=>{for(var b of f)(f=fo(b))&&(Lr[f]=b)};function $I(){var f=Error().stack.toString().split(` `);return f[0]=="Error"&&f.shift(),ep(f),Lr.gd=fo(f[3]),Lr.Jd=f,Lr.gd}function mo(f){if(!(f=Lr[f>>>0]))return 0;var b;if(b=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(f))f=b[1];else if(b=/^\s+at (.*) \(.*\)$/.exec(f))f=b[1];else{if(!(b=/^(.+?)@/.exec(f)))return 0;f=b[1]}Kt(mo.hd??0),b=ao(f)+1;var $=ei(b);return $&&fr(f,$,b),mo.hd=$,mo.hd}function TI(f){f>>>=0;var b=(I(),q).length;if(f<=b||4294901760=$;$*=2){var x=b*(1+.2/$);x=Math.min(x,f+100663296);e:{x=(Math.min(4294901760,65536*Math.ceil(Math.max(f,x)/65536))-hr.buffer.byteLength+65535)/65536|0;try{hr.grow(x),Y();var E=1;break e}catch{}E=void 0}if(E)return!0}return!1}function SI(f,b,$){if(f>>>=0,b>>>=0,Lr.gd==f)var x=Lr.Jd;else(x=Error().stack.toString().split(` -`))[0]=="Error"&&x.shift(),ep(x);for(var E=3;x[E]&&fo(x[E])!=f;)++E;for(f=0;f<$&&x[f+E];++f)(I(),v)[b+4*f>>>2>>>0]=fo(x[f+E]);return f}var Ys,Js={},tp=()=>{if(!Ys){var f,b={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(f in Js)Js[f]===void 0?delete b[f]:b[f]=Js[f];var $=[];for(f in b)$.push(`${f}=${b[f]}`);Ys=$}return Ys};function rp(f,b){if(u)return $e(19,1,f,b);f>>>=0,b>>>=0;var $,x=0,E=0;for($ of tp()){var k=b+x;(I(),R)[f+E>>>2>>>0]=k,x+=fr($,k,1/0)+1,E+=4}return 0}function np(f,b){if(u)return $e(20,1,f,b);f>>>=0,b>>>=0;var $=tp();for(var x of((I(),R)[f>>>2>>>0]=$.length,f=0,$))f+=ao(x)+1;return(I(),R)[b>>>2>>>0]=f,0}function ip(f){return u?$e(21,1,f):52}function op(f,b,$,x){return u?$e(22,1,f,b,$,x):52}function sp(f,b,$,x){return u?$e(23,1,f,b,$,x):70}var II=[null,[],[]];function ap(f,b,$,x){if(u)return $e(24,1,f,b,$,x);b>>>=0,$>>>=0,x>>>=0;for(var E=0,k=0;k<$;k++){var M=(I(),R)[b>>>2>>>0],U=(I(),R)[b+4>>>2>>>0];b+=8;for(var Q=0;Q>>0],Oe=II[re];ge===0||ge===10?((re===1?S:O)(Sc(Oe)),Oe.length=0):Oe.push(ge)}E+=U}return(I(),R)[x>>>2>>>0]=E,0}function OI(f){return f>>>0}u||(function(){for(var f=t.numThreads-1;f--;)yc();xe.push(async()=>{var b=(async function(){if(!u)return Promise.all(Gt.map(bc))})();qe++,await b,--qe==0&&Ve&&(b=Ve,Ve=null,b())})})(),u||(hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Y()),t.wasmBinary&&(p=t.wasmBinary),t.stackSave=()=>_e(),t.stackRestore=f=>we(f),t.stackAlloc=f=>ta(f),t.setValue=function(f,b,$="i8"){switch($.endsWith("*")&&($="*"),$){case"i1":case"i8":(I(),J)[f>>>0]=b;break;case"i16":(I(),C)[f>>>1>>>0]=b;break;case"i32":(I(),v)[f>>>2>>>0]=b;break;case"i64":(I(),V)[f>>>3>>>0]=BigInt(b);break;case"float":(I(),H)[f>>>2>>>0]=b;break;case"double":(I(),L)[f>>>3>>>0]=b;break;case"*":(I(),R)[f>>>2>>>0]=b;break;default:X(`invalid type for setValue: ${$}`)}},t.getValue=function(f,b="i8"){switch(b.endsWith("*")&&(b="*"),b){case"i1":case"i8":return(I(),J)[f>>>0];case"i16":return(I(),C)[f>>>1>>>0];case"i32":return(I(),v)[f>>>2>>>0];case"i64":return(I(),V)[f>>>3>>>0];case"float":return(I(),H)[f>>>2>>>0];case"double":return(I(),L)[f>>>3>>>0];case"*":return(I(),R)[f>>>2>>>0];default:X(`invalid type for getValue: ${b}`)}},t.UTF8ToString=et,t.stringToUTF8=fr,t.lengthBytesUTF8=ao;var up,lp,go,Kt,ei,Qs,dp,cp,pp,ea,hp,fp,Te,ti,mp,we,ta,_e,gp,ra,bp,yp,wp,na,_p,vp,xp,$p,Tp,Sp,Ip,Op,Ep,Ap,kp,Pp,Cp,Rp,Dp,Mp,Np,zp,Bp,Fp,Lp,jp,Up,Vp,qp,Gp,Hp,Wp,Kp,Xp,Zp,Yp,Jp,Qp,eh,th,rh,nh,ih,rr,EI=[ht,It,vc,Ic,Oc,Ec,Ac,kc,Pc,Cc,Rc,Dc,Mc,Nc,zc,Bc,Zc,Yc,Jc,rp,np,ip,op,sp,ap],ia={1055492:(f,b,$,x,E)=>{if(t===void 0||!t.Yc)return 1;if((f=et(Number(f>>>0))).startsWith("./")&&(f=f.substring(2)),!(f=t.Yc.get(f)))return 2;if(b=Number(b>>>0),$=Number($>>>0),x=Number(x>>>0),b+$>f.byteLength)return 3;try{let k=f.subarray(b,b+$);switch(E){case 0:(I(),q).set(k,x>>>0);break;case 1:t.Qd?t.Qd(x,k):t.Id(x,k);break;default:return 4}return 0}catch{return 4}},1056316:(f,b,$)=>{t.td(f,(I(),q).subarray(b>>>0,b+$>>>0))},1056380:()=>t.Sd(),1056422:f=>{t.sd(f)},1056459:()=>{t.Bd()},1056490:()=>{t.Cd()},1056519:()=>{t.Gd()},1056544:f=>t.Ad(f),1056577:f=>t.Ed(f),1056609:(f,b,$)=>{t.ed(Number(f),Number(b),Number($),!0)},1056672:(f,b,$)=>{t.ed(Number(f),Number(b),Number($))},1056729:()=>typeof wasmOffsetConverter<"u",1056786:f=>{t.$b("Abs",f,void 0)},1056837:f=>{t.$b("Neg",f,void 0)},1056888:f=>{t.$b("Floor",f,void 0)},1056941:f=>{t.$b("Ceil",f,void 0)},1056993:f=>{t.$b("Reciprocal",f,void 0)},1057051:f=>{t.$b("Sqrt",f,void 0)},1057103:f=>{t.$b("Exp",f,void 0)},1057154:f=>{t.$b("Erf",f,void 0)},1057205:f=>{t.$b("Sigmoid",f,void 0)},1057260:(f,b,$)=>{t.$b("HardSigmoid",f,{alpha:b,beta:$})},1057339:f=>{t.$b("HardSwish",f,void 0)},1057396:f=>{t.$b("Log",f,void 0)},1057447:f=>{t.$b("Sin",f,void 0)},1057498:f=>{t.$b("Cos",f,void 0)},1057549:f=>{t.$b("Tan",f,void 0)},1057600:f=>{t.$b("Asin",f,void 0)},1057652:f=>{t.$b("Acos",f,void 0)},1057704:f=>{t.$b("Atan",f,void 0)},1057756:f=>{t.$b("Sinh",f,void 0)},1057808:f=>{t.$b("Cosh",f,void 0)},1057860:f=>{t.$b("Asinh",f,void 0)},1057913:f=>{t.$b("Acosh",f,void 0)},1057966:f=>{t.$b("Atanh",f,void 0)},1058019:f=>{t.$b("Tanh",f,void 0)},1058071:f=>{t.$b("Not",f,void 0)},1058122:(f,b,$)=>{t.$b("Clip",f,{min:b,max:$})},1058191:f=>{t.$b("Clip",f,void 0)},1058243:(f,b)=>{t.$b("Elu",f,{alpha:b})},1058301:f=>{t.$b("Gelu",f,void 0)},1058353:f=>{t.$b("Relu",f,void 0)},1058405:(f,b)=>{t.$b("LeakyRelu",f,{alpha:b})},1058469:(f,b)=>{t.$b("ThresholdedRelu",f,{alpha:b})},1058539:(f,b)=>{t.$b("Cast",f,{to:b})},1058597:f=>{t.$b("Add",f,void 0)},1058648:f=>{t.$b("Sub",f,void 0)},1058699:f=>{t.$b("Mul",f,void 0)},1058750:f=>{t.$b("Div",f,void 0)},1058801:f=>{t.$b("Pow",f,void 0)},1058852:f=>{t.$b("Equal",f,void 0)},1058905:f=>{t.$b("Greater",f,void 0)},1058960:f=>{t.$b("GreaterOrEqual",f,void 0)},1059022:f=>{t.$b("Less",f,void 0)},1059074:f=>{t.$b("LessOrEqual",f,void 0)},1059133:(f,b,$,x,E)=>{t.$b("ReduceMean",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059308:(f,b,$,x,E)=>{t.$b("ReduceMax",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059482:(f,b,$,x,E)=>{t.$b("ReduceMin",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059656:(f,b,$,x,E)=>{t.$b("ReduceProd",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059831:(f,b,$,x,E)=>{t.$b("ReduceSum",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060005:(f,b,$,x,E)=>{t.$b("ReduceL1",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060178:(f,b,$,x,E)=>{t.$b("ReduceL2",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060351:(f,b,$,x,E)=>{t.$b("ReduceLogSum",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060528:(f,b,$,x,E)=>{t.$b("ReduceSumSquare",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060708:(f,b,$,x,E)=>{t.$b("ReduceLogSumExp",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060888:f=>{t.$b("Where",f,void 0)},1060941:(f,b,$)=>{t.$b("Transpose",f,{perm:b?Array.from((I(),v).subarray(Number(b)>>>0,Number($)>>>0)):[]})},1061065:(f,b,$,x)=>{t.$b("DepthToSpace",f,{blocksize:b,mode:et($),format:x?"NHWC":"NCHW"})},1061198:(f,b,$,x)=>{t.$b("DepthToSpace",f,{blocksize:b,mode:et($),format:x?"NHWC":"NCHW"})},1061331:(f,b,$,x)=>{t.$b("DFT",f,{axis:b,inverse:$,onesided:x})},1061423:(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe,gr)=>{t.$b("ConvTranspose",f,{format:Q?"NHWC":"NCHW",autoPad:b,dilations:[$],group:x,kernelShape:[E],pads:[k,M],strides:[U],wIsConst:()=>!!(I(),J)[re>>>0],outputPadding:ge?Array.from((I(),v).subarray(Number(ge)>>>0,Number(Oe)>>>0)):[],outputShape:Ne?Array.from((I(),v).subarray(Number(Ne)>>>0,Number(Fe)>>>0)):[],activation:et(gr)})},1061856:(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe)=>{t.$b("ConvTranspose",f,{format:U?"NHWC":"NCHW",autoPad:b,dilations:Array.from((I(),v).subarray(Number($)>>>0,(Number($)>>>0)+2>>>0)),group:x,kernelShape:Array.from((I(),v).subarray(Number(E)>>>0,(Number(E)>>>0)+2>>>0)),pads:Array.from((I(),v).subarray(Number(k)>>>0,(Number(k)>>>0)+4>>>0)),strides:Array.from((I(),v).subarray(Number(M)>>>0,(Number(M)>>>0)+2>>>0)),wIsConst:()=>!!(I(),J)[Q>>>0],outputPadding:re?Array.from((I(),v).subarray(Number(re)>>>0,Number(ge)>>>0)):[],outputShape:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[],activation:et(Fe)})},1062517:(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe,gr)=>{t.$b("ConvTranspose",f,{format:Q?"NHWC":"NCHW",autoPad:b,dilations:[$],group:x,kernelShape:[E],pads:[k,M],strides:[U],wIsConst:()=>!!(I(),J)[re>>>0],outputPadding:ge?Array.from((I(),v).subarray(Number(ge)>>>0,Number(Oe)>>>0)):[],outputShape:Ne?Array.from((I(),v).subarray(Number(Ne)>>>0,Number(Fe)>>>0)):[],activation:et(gr)})},1062950:(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe)=>{t.$b("ConvTranspose",f,{format:U?"NHWC":"NCHW",autoPad:b,dilations:Array.from((I(),v).subarray(Number($)>>>0,(Number($)>>>0)+2>>>0)),group:x,kernelShape:Array.from((I(),v).subarray(Number(E)>>>0,(Number(E)>>>0)+2>>>0)),pads:Array.from((I(),v).subarray(Number(k)>>>0,(Number(k)>>>0)+4>>>0)),strides:Array.from((I(),v).subarray(Number(M)>>>0,(Number(M)>>>0)+2>>>0)),wIsConst:()=>!!(I(),J)[Q>>>0],outputPadding:re?Array.from((I(),v).subarray(Number(re)>>>0,Number(ge)>>>0)):[],outputShape:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[],activation:et(Fe)})},1063611:(f,b)=>{t.$b("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},1063702:(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe)=>{t.$b("AveragePool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:re?Array.from((I(),v).subarray(Number(re)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1064181:(f,b)=>{t.$b("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},1064272:(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe)=>{t.$b("AveragePool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:re?Array.from((I(),v).subarray(Number(re)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1064751:(f,b)=>{t.$b("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},1064838:(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe)=>{t.$b("MaxPool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:re?Array.from((I(),v).subarray(Number(re)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1065313:(f,b)=>{t.$b("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},1065400:(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe)=>{t.$b("MaxPool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:re?Array.from((I(),v).subarray(Number(re)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1065875:(f,b,$,x,E)=>{t.$b("Gemm",f,{alpha:b,beta:$,transA:x,transB:E})},1065979:f=>{t.$b("MatMul",f,void 0)},1066033:(f,b,$,x)=>{t.$b("ArgMax",f,{keepDims:!!b,selectLastIndex:!!$,axis:x})},1066141:(f,b,$,x)=>{t.$b("ArgMin",f,{keepDims:!!b,selectLastIndex:!!$,axis:x})},1066249:(f,b)=>{t.$b("Softmax",f,{axis:b})},1066312:(f,b)=>{t.$b("Concat",f,{axis:b})},1066372:(f,b,$,x,E)=>{t.$b("Split",f,{axis:b,numOutputs:$,splitSizes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1066528:f=>{t.$b("Expand",f,void 0)},1066582:(f,b)=>{t.$b("Gather",f,{axis:Number(b)})},1066653:(f,b)=>{t.$b("GatherElements",f,{axis:Number(b)})},1066732:(f,b)=>{t.$b("GatherND",f,{batch_dims:Number(b)})},1066811:(f,b,$,x,E,k,M,U,Q,re,ge)=>{t.$b("Resize",f,{antialias:b,axes:$?Array.from((I(),v).subarray(Number($)>>>0,Number(x)>>>0)):[],coordinateTransformMode:et(E),cubicCoeffA:k,excludeOutside:M,extrapolationValue:U,keepAspectRatioPolicy:et(Q),mode:et(re),nearestMode:et(ge)})},1067173:(f,b,$,x,E,k,M)=>{t.$b("Slice",f,{starts:b?Array.from((I(),v).subarray(Number(b)>>>0,Number($)>>>0)):[],ends:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[],axes:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[]})},1067437:f=>{t.$b("Tile",f,void 0)},1067489:(f,b,$)=>{t.$b("InstanceNormalization",f,{epsilon:b,format:$?"NHWC":"NCHW"})},1067603:(f,b,$)=>{t.$b("InstanceNormalization",f,{epsilon:b,format:$?"NHWC":"NCHW"})},1067717:f=>{t.$b("Range",f,void 0)},1067770:(f,b)=>{t.$b("Einsum",f,{equation:et(b)})},1067851:(f,b,$,x,E)=>{t.$b("Pad",f,{mode:b,value:$,pads:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1067994:(f,b,$,x,E,k)=>{t.$b("BatchNormalization",f,{epsilon:b,momentum:$,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},1068163:(f,b,$,x,E,k)=>{t.$b("BatchNormalization",f,{epsilon:b,momentum:$,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},1068332:(f,b,$)=>{t.$b("CumSum",f,{exclusive:Number(b),reverse:Number($)})},1068429:(f,b,$)=>{t.$b("DequantizeLinear",f,{axis:b,blockSize:$})},1068519:(f,b,$,x,E)=>{t.$b("GridSample",f,{align_corners:b,mode:et($),padding_mode:et(x),format:E?"NHWC":"NCHW"})},1068689:(f,b,$,x,E)=>{t.$b("GridSample",f,{align_corners:b,mode:et($),padding_mode:et(x),format:E?"NHWC":"NCHW"})},1068859:(f,b)=>{t.$b("ScatterND",f,{reduction:et(b)})},1068944:(f,b,$,x,E,k,M,U,Q)=>{t.$b("Attention",f,{numHeads:b,isUnidirectional:$,maskFilterValue:x,scale:E,doRotary:k,qkvHiddenSizes:M?Array.from((I(),v).subarray(Number(U)>>>0,Number(U)+M>>>0)):[],pastPresentShareBuffer:!!Q})},1069216:f=>{t.$b("BiasAdd",f,void 0)},1069271:f=>{t.$b("BiasSplitGelu",f,void 0)},1069332:f=>{t.$b("FastGelu",f,void 0)},1069388:(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe,gr,oa)=>{t.$b("Conv",f,{format:Oe?"NHWC":"NCHW",auto_pad:b,dilations:$?Array.from((I(),v).subarray(Number($)>>>0,Number(x)>>>0)):[],group:E,kernel_shape:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],pads:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],strides:re?Array.from((I(),v).subarray(Number(re)>>>0,Number(ge)>>>0)):[],w_is_const:()=>!!(I(),J)[Number(Ne)>>>0],activation:et(Fe),activation_params:gr?Array.from((I(),H).subarray(Number(gr)>>>0,Number(oa)>>>0)):[]})},1069972:f=>{t.$b("Gelu",f,void 0)},1070024:(f,b,$,x,E,k,M,U,Q)=>{t.$b("GroupQueryAttention",f,{numHeads:b,kvNumHeads:$,scale:x,softcap:E,doRotary:k,rotaryInterleaved:M,smoothSoftmax:U,localWindowSize:Q})},1070241:(f,b,$,x)=>{t.$b("LayerNormalization",f,{axis:b,epsilon:$,simplified:!!x})},1070352:(f,b,$,x)=>{t.$b("LayerNormalization",f,{axis:b,epsilon:$,simplified:!!x})},1070463:(f,b,$,x,E,k)=>{t.$b("MatMulNBits",f,{k:b,n:$,accuracyLevel:x,bits:E,blockSize:k})},1070590:(f,b,$,x,E,k)=>{t.$b("MultiHeadAttention",f,{numHeads:b,isUnidirectional:$,maskFilterValue:x,scale:E,doRotary:k})},1070749:(f,b)=>{t.$b("QuickGelu",f,{alpha:b})},1070813:(f,b,$,x,E)=>{t.$b("RotaryEmbedding",f,{interleaved:!!b,numHeads:$,rotaryEmbeddingDim:x,scale:E})},1070952:(f,b,$)=>{t.$b("SkipLayerNormalization",f,{epsilon:b,simplified:!!$})},1071054:(f,b,$)=>{t.$b("SkipLayerNormalization",f,{epsilon:b,simplified:!!$})},1071156:(f,b,$,x)=>{t.$b("GatherBlockQuantized",f,{gatherAxis:b,quantizeAxis:$,blockSize:x})},1071277:f=>{t.Fd(f)},1071311:(f,b)=>t.Hd(Number(f),Number(b),t.Xc.Kd,t.Xc.errors)};function AI(f,b,$){return Gc(async()=>{await t.Dd(Number(f),Number(b),Number($))})}function kI(){return typeof wasmOffsetConverter<"u"}function PI(f,b,$,x){var E=_e();try{return Op(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function CI(f,b,$){var x=_e();try{return $p(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function RI(f){var b=_e();try{_p(f)}catch($){if(we(b),$!==$+0)throw $;Te(1,0)}}function DI(f,b){var $=_e();try{return na(f,b)}catch(x){if(we($),x!==x+0)throw x;Te(1,0)}}function MI(f,b,$){var x=_e();try{wp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function NI(f,b){var $=_e();try{Ep(f,b)}catch(x){if(we($),x!==x+0)throw x;Te(1,0)}}function zI(f,b,$,x,E,k,M){var U=_e();try{return Sp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function BI(f,b,$,x,E,k){var M=_e();try{vp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function FI(f,b,$,x){var E=_e();try{Ip(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function LI(f,b,$,x,E){var k=_e();try{xp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function jI(f,b,$,x,E,k,M){var U=_e();try{kp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function UI(f,b,$,x,E,k,M){var U=_e();try{Pp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function VI(f,b,$,x,E,k,M,U){var Q=_e();try{Mp(f,b,$,x,E,k,M,U)}catch(re){if(we(Q),re!==re+0)throw re;Te(1,0)}}function qI(f,b,$,x,E){var k=_e();try{return Ap(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function GI(f,b,$){var x=_e();try{return Np(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function HI(f,b,$,x,E,k,M,U){var Q=_e();try{zp(f,b,$,x,E,k,M,U)}catch(re){if(we(Q),re!==re+0)throw re;Te(1,0)}}function WI(f,b,$,x,E,k,M,U,Q,re,ge,Oe){var Ne=_e();try{Cp(f,b,$,x,E,k,M,U,Q,re,ge,Oe)}catch(Fe){if(we(Ne),Fe!==Fe+0)throw Fe;Te(1,0)}}function KI(f,b,$){var x=_e();try{return Bp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;return Te(1,0),0n}}function XI(f,b,$,x,E,k,M,U,Q){var re=_e();try{Tp(f,b,$,x,E,k,M,U,Q)}catch(ge){if(we(re),ge!==ge+0)throw ge;Te(1,0)}}function ZI(f){var b=_e();try{return Fp(f)}catch($){if(we(b),$!==$+0)throw $;Te(1,0)}}function YI(f,b){var $=_e();try{return eh(f,b)}catch(x){if(we($),x!==x+0)throw x;return Te(1,0),0n}}function JI(f){var b=_e();try{return Lp(f)}catch($){if(we(b),$!==$+0)throw $;return Te(1,0),0n}}function QI(f,b,$,x){var E=_e();try{return Hp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function e3(f,b,$,x,E){var k=_e();try{return Wp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function t3(f,b,$,x,E,k){var M=_e();try{return Kp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function r3(f,b,$,x,E,k){var M=_e();try{return Rp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function n3(f,b,$,x,E,k){var M=_e();try{return Xp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function i3(f,b,$,x,E,k,M,U){var Q=_e();try{return Dp(f,b,$,x,E,k,M,U)}catch(re){if(we(Q),re!==re+0)throw re;Te(1,0)}}function o3(f,b,$,x,E){var k=_e();try{return Zp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;return Te(1,0),0n}}function s3(f,b,$,x){var E=_e();try{return Yp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function a3(f,b,$,x){var E=_e();try{return Jp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function u3(f,b,$,x,E,k,M,U,Q,re,ge,Oe){var Ne=_e();try{return Qp(f,b,$,x,E,k,M,U,Q,re,ge,Oe)}catch(Fe){if(we(Ne),Fe!==Fe+0)throw Fe;Te(1,0)}}function l3(f,b,$,x,E,k,M,U,Q,re,ge){var Oe=_e();try{qp(f,b,$,x,E,k,M,U,Q,re,ge)}catch(Ne){if(we(Oe),Ne!==Ne+0)throw Ne;Te(1,0)}}function d3(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe,gr,oa){var f3=_e();try{Gp(f,b,$,x,E,k,M,U,Q,re,ge,Oe,Ne,Fe,gr,oa)}catch(sa){if(we(f3),sa!==sa+0)throw sa;Te(1,0)}}function c3(f,b,$){var x=_e();try{return jp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function p3(f,b,$){var x=_e();try{return Up(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function h3(f,b,$,x){var E=_e();try{Vp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function bo(){if(0{g=f,_=b})}var px,Sm,HA=D(()=>{"use strict";px=Tm,Sm=globalThis.self?.name?.startsWith("em-pthread"),Sm&&Tm()}),Ua,Al,Im,yt,hx,$o,Om,Em,Va,Am,qa,fx,Ga,mx,rd=D(()=>{"use strict";td(),Ua=typeof location>"u"?void 0:location.origin,Al=import.meta.url>"file:"&&import.meta.url<"file;",Im=()=>{if(Al){let e=URL;return new URL(new e("ort.all.bundle.min.mjs",import.meta.url).href,Ua).href}return import.meta.url},yt=Im(),hx=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},$o=(e,t)=>{try{let n=t??yt;return(n?new URL(e,n):new URL(e)).origin===Ua}catch{return!1}},Om=(e,t)=>{let n=t??yt;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Em=(e,t)=>`${t??"./"}${e}`,Va=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Am=async e=>(await import(e)).default,qa=(GA(),Nn(lx)).default,fx=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if($o(yt))return[void 0,qa()];let e=await Va(yt);return[e,qa(e)]},Ga=(HA(),Nn(cx)).default,mx=async(e,t,n,i)=>{let u=Ga&&!(e||t);if(u)if(yt)u=$o(yt)||i&&!n;else if(i&&!n)u=!0;else throw new Error("cannot determine the script source URL.");if(u)return[void 0,Ga];{let l="ort-wasm-simd-threaded.jsep.mjs",d=e??Om(l,t),c=n&&d&&!$o(d,t),s=c?await Va(d):d??Em(l,t);return[c?s:void 0,await Am(s)]}}}),Ha,To,li,Wa,km,Pm,Cm,nd,Be,vn=D(()=>{"use strict";rd(),To=!1,li=!1,Wa=!1,km=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Pm=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Cm=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},nd=async e=>{if(To)return Promise.resolve();if(li)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Wa)throw new Error("previous call to 'initializeWebAssembly()' failed.");li=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Cm())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Pm())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=km();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let u=e.wasmPaths,l=typeof u=="string"?u:void 0,d=u?.mjs,c=d?.href??d,s=u?.wasm,r=s?.href??s,o=e.wasmBinary,[a,p]=await mx(c,l,n>1,!!o||!!r),h=!1,m=[];if(t>0&&m.push(new Promise(g=>{setTimeout(()=>{h=!0,g()},t)})),m.push(new Promise((g,_)=>{let w={numThreads:n};if(o)w.wasmBinary=o,w.locateFile=y=>y;else if(r||l)w.locateFile=y=>r??l+y;else if(c&&c.indexOf("blob:")!==0)w.locateFile=y=>new URL(y,c).href;else if(a){let y=hx();y&&(w.locateFile=T=>y+T)}p(w).then(y=>{li=!1,To=!0,Ha=y,g(),a&&URL.revokeObjectURL(a)},y=>{li=!1,Wa=!0,_(y)})})),await Promise.race(m),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Be=()=>{if(To&&Ha)return Ha;throw new Error("WebAssembly is not initialized yet.")}}),Ut,Go,Re,id=D(()=>{"use strict";vn(),Ut=(e,t)=>{let n=Be(),i=n.lengthBytesUTF8(e)+1,u=n._malloc(i);return n.stringToUTF8(e,u,i),t.push(u),u},Go=(e,t,n,i)=>{if(typeof e=="object"&&e!==null){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([u,l])=>{let d=t?t+u:u;if(typeof l=="object")Go(l,d+".",n,i);else if(typeof l=="string"||typeof l=="number")i(d,l.toString());else if(typeof l=="boolean")i(d,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},Re=e=>{let t=Be(),n=t.stackSave();try{let i=t.PTR_SIZE,u=t.stackAlloc(2*i);t._OrtGetLastError(u,u+i);let l=Number(t.getValue(u,i===4?"i32":"i64")),d=t.getValue(u+i,"*"),c=d?t.UTF8ToString(d):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(n)}}}),gx,WA=D(()=>{"use strict";vn(),id(),gx=e=>{let t=Be(),n=0,i=[],u=e||{};try{if(e?.logSeverityLevel===void 0)u.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)u.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(u.terminate=!1);let l=0;return e?.tag!==void 0&&(l=Ut(e.tag,i)),n=t._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,l),n===0&&Re("Can't create run options."),e?.extra!==void 0&&Go(e.extra,"",new WeakSet,(d,c)=>{let s=Ut(d,i),r=Ut(c,i);t._OrtAddRunConfigEntry(n,s,r)!==0&&Re(`Can't set a run config entry: ${d} - ${c}.`)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseRunOptions(n),i.forEach(d=>t._free(d)),l}}}),Rm,Dm,Mm,qr,Nm,bx,KA=D(()=>{"use strict";vn(),id(),Rm=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Dm=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Mm=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},qr=(e,t,n,i)=>{let u=Ut(t,i),l=Ut(n,i);Be()._OrtAddSessionConfigEntry(e,u,l)!==0&&Re(`Can't set a session config entry: ${t} - ${n}.`)},Nm=async(e,t,n)=>{let i=t.executionProviders;for(let u of i){let l=typeof u=="string"?u:u.name,d=[];switch(l){case"webnn":if(l="WEBNN",qr(e,"session.disable_quant_qdq","1",n),qr(e,"session.disable_qdq_constant_folding","1",n),typeof u!="string"){let a=u?.deviceType;a&&qr(e,"deviceType",a,n)}break;case"webgpu":if(l="JS",typeof u!="string"){let a=u;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);qr(e,"preferredLayout",a.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let c=Ut(l,n),s=d.length,r=0,o=0;if(s>0){r=Be()._malloc(s*Be().PTR_SIZE),n.push(r),o=Be()._malloc(s*Be().PTR_SIZE),n.push(o);for(let a=0;a{let t=Be(),n=0,i=[],u=e||{};Mm(u);try{let l=Rm(u.graphOptimizationLevel??"all"),d=Dm(u.executionMode??"sequential"),c=typeof u.logId=="string"?Ut(u.logId,i):0,s=u.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw new Error(`log severity level is not valid: ${s}`);let r=u.logVerbosityLevel??0;if(!Number.isInteger(r)||r<0||r>4)throw new Error(`log verbosity level is not valid: ${r}`);let o=typeof u.optimizedModelFilePath=="string"?Ut(u.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(l,!!u.enableCpuMemArena,!!u.enableMemPattern,d,!!u.enableProfiling,0,c,s,r,o),n===0&&Re("Can't create session options."),u.executionProviders&&await Nm(n,u,i),u.enableGraphCapture!==void 0){if(typeof u.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${u.enableGraphCapture}`);qr(n,"enableGraphCapture",u.enableGraphCapture.toString(),i)}if(u.freeDimensionOverrides)for(let[a,p]of Object.entries(u.freeDimensionOverrides)){if(typeof a!="string")throw new Error(`free dimension override name must be a string: ${a}`);if(typeof p!="number"||!Number.isInteger(p)||p<0)throw new Error(`free dimension override value must be a non-negative integer: ${p}`);let h=Ut(a,i);t._OrtAddFreeDimensionOverride(n,h,p)!==0&&Re(`Can't set a free dimension override: ${a} - ${p}.`)}return u.extra!==void 0&&Go(u.extra,"",new WeakSet,(a,p)=>{qr(n,a,p,i)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&Re("Can't release session options."),i.forEach(d=>t._free(d)),l}}}),dn,sr,cn,ss,Ho,od,sd,kl,de=D(()=>{"use strict";dn=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},sr=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},cn=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((u,l)=>u*l,1);return n>0?Math.ceil(i*n):void 0},ss=e=>{switch(e){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Ho=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},od=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",sd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",kl=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),ad,yx=D(()=>{"use strict";td(),ad=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),i=n?parseInt(n,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let u=t.body.getReader(),l;try{l=new ArrayBuffer(i)}catch(c){if(c instanceof RangeError){let s=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:s,maximum:s}).buffer}else throw c}let d=0;for(;;){let{done:c,value:s}=await u.read();if(c)break;let r=s.byteLength;new Uint8Array(l,d,r).set(s),d+=r}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),zm,Bm,Fm,Lm,ud,jm,Ie,ur=D(()=>{"use strict";de(),zm=["V","I","W","E","F"],Bm=(e,t)=>{console.log(`[${zm[e]},${new Date().toISOString()}]${t}`)},ud=(e,t)=>{Fm=e,Lm=t},jm=(e,t)=>{let n=Ho(e),i=Ho(Fm);n>=i&&Bm(n,typeof t=="function"?t():t)},Ie=(...e)=>{Lm&&jm(...e)}}),Um,Bn,F,Wo,wx,_x,vx,pe=D(()=>{"use strict";Um=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Bn=class{static calcShape(e,t,n=!1){let i=e.length,u=t.length;if(i===0)return t;if(u===0)return e;let l=Math.max(e.length,t.length),d=new Array(l);if(n){if(i<2||u<2)return;let c=Um.calcMatMulShape([e[i-2],e[i-1]],[t[u-2],t[u-1]]);if(c===void 0)return;[d[l-2],d[l-1]]=c}for(let c=n?3:1;c<=l;c++){let s=i-c<0?1:e[i-c],r=u-c<0?1:t[u-c];if(s!==r&&s>1&&r>1)return;let o=Math.max(s,r);if(s&&r)d[l-c]=Math.max(s,r);else{if(o>1)return;d[l-c]=0}}return d}static isValidBroadcast(e,t){let n=e.length,i=t.length;if(n>i)return!1;for(let u=1;u<=n;u++)if(e[n-u]!==1&&e[n-u]!==t[i-u])return!1;return!0}},F=class Bo{static size(t){return Bo.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,n=4){let i=t.length;if(i===0)return[];let u=new Array(i),l=i-1;for(;l>=0;){if(t[l]%n===0){u[l]=t[l]/n;break}if(n%t[l]!==0)throw new Error("cannot convert shape");u[l]=1,n/=t[l],l--}for(l--;l>=0;l--)u[l]=t[l];return u}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Bo.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Bo.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let u=1;for(let l=n;l=0;--u)i[u]=i[u+1]*t[u+1];return i}static normalizeAxis(t,n){if(t<-n&&t>=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n??t.length))}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((u,l)=>u+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,u)=>i===n[u])}},Wo=class Er{static adjustPoolAttributes(t,n,i,u,l,d){if(!t&&i.length!==n.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c=i[c]||d[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,u,l,d,c){if(c){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let s=0;s=i+u&&(d-=1)),d}static adjustPadAndReturnShape(t,n,i,u,l,d,c,s,r=0){let o=i*(u-1)+1;if(s&&s!=="NOTSET")switch(s){case"VALID":return l[d]=0,l[c]=0,Er.computeOutputSize(t-o,n,t,0,r);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let a=(Math.floor((t+n-1)/n)-1)*n+u-t;return l[d]=Math.floor(s==="SAME_LOWER"?(a+1)/2:a/2),l[c]=a-l[d],Er.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}default:throw new Error("Unsupported AutoPad type")}else return Er.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}},wx=class{static getShapeOfGemmResult(e,t,n,i,u){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,d,c;t?(l=e[1],d=e[0]):(l=e[0],d=e[1]);let s=-1;if(i?(c=n[0],s=1):(c=n[1],s=0),n[s]!==d)throw new Error("dimension mismatch");if(l<=0||c<=0||d<=0)throw new Error("invalid shape specified");if(u&&!Bn.isValidBroadcast(u,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,d]}},_x=-34028234663852886e22,vx=34028234663852886e22}),ld,xx=D(()=>{"use strict";de(),ld=(e,t)=>new(ss(t))(e)}),Ka,Vm,Xa,qm,Za,Gm,Ya,Ja,Qa,Hm,$x,XA=D(()=>{"use strict";de(),ur(),Ka=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Vm=(e,t)=>{if(t==="int32")return e;let n=Ka.get(t);if(!n)throw new Error(`WebNN backend does not support data type: ${t}`);let i=n/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let u=e.byteLength/i,l=new(ss(t))(e.buffer,e.byteOffset,u);switch(t){case"int64":case"uint64":{let d=new Int32Array(u);for(let c=0;c2147483647n||s<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");d[c]=Number(s)}return new Uint8Array(d.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(c=>c>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let d=Int32Array.from(l,Number);return new Uint8Array(d.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Xa=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let n=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case"int64":{let u=BigInt64Array.from(i,BigInt);return new Uint8Array(u.buffer)}case"uint64":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let u=BigUint64Array.from(i,BigInt);return new Uint8Array(u.buffer)}case"int8":{if(i.some(l=>l<-128||l>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let u=Int8Array.from(i,Number);return new Uint8Array(u.buffer)}case"uint8":{if(i.some(u=>u<0||u>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(i,Number)}case"uint32":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let u=Uint32Array.from(i,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},qm=1,Za=()=>qm++,Gm=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Ya=(e,t)=>{let n=Ka.get(e);if(!n)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,u)=>i*u)*n/8):0},Ja=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:i,dataType:u,shape:l,fallbackDataType:d}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=i,this.dataType=u,this.tensorShape=l,this.fallbackDataType=d}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Ya(this.dataType,this.tensorShape)}destroy(){Ie("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Xa(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return new Uint8Array(n).buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((i,u)=>i===n[u])}setIsDataConverted(e){this.isDataConverted=e}},Qa=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,i){let u=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),d;if(!l?.input.dataTypes.includes(t)){if(d=Gm.get(t),!d||l?.input.dataTypes.includes(d))throw new Error(`WebNN backend does not support data type: ${t}`);Ie("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${d}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(u,t,n))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==Ya(t,n))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,c,!0,!0,d),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=Vm(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Ie("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Xa(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Hm=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Za();return this.tensorTrackersById.set(e,new Qa(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,i,u){Ie("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${i}, copyOld: ${u}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,n,i,u)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){Ie("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,i){let u=this.getMLContext(e),l=Za(),d=new Ja({sessionId:e,context:u,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(l,new Qa(this,d)),this.externalTensors.add(d),l}async getCachedTensor(e,t,n,i,u,l,d){let c=this.getMLContext(e);for(let[r,o]of this.freeTensors.entries())if(o.canReuseTensor(c,t,n)){Ie("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${d?`fallbackDataType: ${d},`:""} shape: ${n}`);let a=this.freeTensors.splice(r,1)[0];return a.sessionId=e,a}Ie("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${d?`fallbackDataType: ${d},`:""} shape: ${n}}`);let s=await c.createTensor({dataType:d??t,shape:n,dimensions:n,usage:i,writable:u,readable:l});return new Ja({sessionId:e,context:c,tensor:s,dataType:t,shape:n,fallbackDataType:d})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},$x=(...e)=>new Hm(...e)}),di,Wm,Tx,ZA=D(()=>{"use strict";de(),vn(),xx(),XA(),ur(),di=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Wm=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),i=Object.keys(t).sort();return n.length===i.length&&n.every((u,l)=>u===i[l]&&e[u]===t[u])},Tx=class{constructor(e){this.tensorManager=$x(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,ud(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Ie("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Ie("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let n of t)Ie("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${n}}`),this.tensorManager.releaseTensorId(n);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let n=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let n=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(n=>Wm(n.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:n}),n}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(u=>u.mlContext===t);i!==-1&&this.mlContextCache.splice(i,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Ie("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,i,u){let l=di.get(n);if(!l)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,u)}async createTemporaryTensor(e,t,n){Ie("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let i=di.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let u=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,u,i,n,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(u):this.temporarySessionTensorIds.set(e,[u]),u}uploadTensor(e,t){if(!Be().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ie("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return ld(n,t)}}registerMLTensor(e,t,n,i){let u=di.get(n);if(!u)throw new Error(`Unsupported ONNX data type: ${n}`);let l=this.tensorManager.registerTensor(e,t,u,i);return Ie("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${u}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let i=di.get(dn(t)),u=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:n?!!u?.input.dataTypes.includes(i):!!u?.output.dataTypes.includes(i)}flush(){}}}),dd=D(()=>{"use strict"}),eu,So,Io,Km,Xm,tu,Pl,Zm,Sx,YA=D(()=>{"use strict";ur(),dd(),eu=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),So=[],Io=e=>Math.ceil(Number(e)/16)*16,Km=e=>{for(let t=0;tXm++,Pl=async(e,t,n,i)=>{let u=Io(n),l=e.device.createBuffer({size:u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=e.getCommandEncoder();e.endComputePass(),d.copyBufferToBuffer(t,0,l,0,u),e.flush(),await l.mapAsync(GPUMapMode.READ);let c=l.getMappedRange();if(i){let s=i();return s.set(new Uint8Array(c,0,n)),s}else return new Uint8Array(c.slice(0,n))}finally{l.destroy()}},Zm=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of eu)So.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,i=t.byteOffset,u=t.byteLength,l=Io(u),d=this.storageCache.get(e);if(!d)throw new Error("gpu data for uploading does not exist");if(Number(d.originalSize)!==u)throw new Error(`inconsistent data size. gpu data size=${d.originalSize}, data size=${u}`);if(l===u&&i%4===0)this.backend.device.queue.writeBuffer(d.gpuData.buffer,0,n,i,u);else{let c=new Uint8Array(l);c.set(t),this.backend.device.queue.writeBuffer(d.gpuData.buffer,0,c,0,l)}Ie("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(t);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let u=Io(n.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(n.gpuData.buffer,0,i.gpuData.buffer,0,u)}registerExternalBuffer(e,t,n){let i;if(n){if(i=n[0],e===n[1])return Ie("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. +`))[0]=="Error"&&x.shift(),ep(x);for(var E=3;x[E]&&fo(x[E])!=f;)++E;for(f=0;f<$&&x[f+E];++f)(I(),v)[b+4*f>>>2>>>0]=fo(x[f+E]);return f}var Ys,Js={},tp=()=>{if(!Ys){var f,b={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(f in Js)Js[f]===void 0?delete b[f]:b[f]=Js[f];var $=[];for(f in b)$.push(`${f}=${b[f]}`);Ys=$}return Ys};function rp(f,b){if(u)return $e(19,1,f,b);f>>>=0,b>>>=0;var $,x=0,E=0;for($ of tp()){var k=b+x;(I(),R)[f+E>>>2>>>0]=k,x+=fr($,k,1/0)+1,E+=4}return 0}function np(f,b){if(u)return $e(20,1,f,b);f>>>=0,b>>>=0;var $=tp();for(var x of((I(),R)[f>>>2>>>0]=$.length,f=0,$))f+=ao(x)+1;return(I(),R)[b>>>2>>>0]=f,0}function ip(f){return u?$e(21,1,f):52}function op(f,b,$,x){return u?$e(22,1,f,b,$,x):52}function sp(f,b,$,x){return u?$e(23,1,f,b,$,x):70}var II=[null,[],[]];function ap(f,b,$,x){if(u)return $e(24,1,f,b,$,x);b>>>=0,$>>>=0,x>>>=0;for(var E=0,k=0;k<$;k++){var M=(I(),R)[b>>>2>>>0],U=(I(),R)[b+4>>>2>>>0];b+=8;for(var Q=0;Q>>0],Oe=II[ne];ge===0||ge===10?((ne===1?S:O)(Sc(Oe)),Oe.length=0):Oe.push(ge)}E+=U}return(I(),R)[x>>>2>>>0]=E,0}function OI(f){return f>>>0}u||(function(){for(var f=t.numThreads-1;f--;)yc();xe.push(async()=>{var b=(async function(){if(!u)return Promise.all(Gt.map(bc))})();qe++,await b,--qe==0&&Ve&&(b=Ve,Ve=null,b())})})(),u||(hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Y()),t.wasmBinary&&(p=t.wasmBinary),t.stackSave=()=>_e(),t.stackRestore=f=>we(f),t.stackAlloc=f=>ta(f),t.setValue=function(f,b,$="i8"){switch($.endsWith("*")&&($="*"),$){case"i1":case"i8":(I(),J)[f>>>0]=b;break;case"i16":(I(),C)[f>>>1>>>0]=b;break;case"i32":(I(),v)[f>>>2>>>0]=b;break;case"i64":(I(),V)[f>>>3>>>0]=BigInt(b);break;case"float":(I(),H)[f>>>2>>>0]=b;break;case"double":(I(),L)[f>>>3>>>0]=b;break;case"*":(I(),R)[f>>>2>>>0]=b;break;default:X(`invalid type for setValue: ${$}`)}},t.getValue=function(f,b="i8"){switch(b.endsWith("*")&&(b="*"),b){case"i1":case"i8":return(I(),J)[f>>>0];case"i16":return(I(),C)[f>>>1>>>0];case"i32":return(I(),v)[f>>>2>>>0];case"i64":return(I(),V)[f>>>3>>>0];case"float":return(I(),H)[f>>>2>>>0];case"double":return(I(),L)[f>>>3>>>0];case"*":return(I(),R)[f>>>2>>>0];default:X(`invalid type for getValue: ${b}`)}},t.UTF8ToString=et,t.stringToUTF8=fr,t.lengthBytesUTF8=ao;var up,lp,go,Kt,ei,Qs,dp,cp,pp,ea,hp,fp,Te,ti,mp,we,ta,_e,gp,ra,bp,yp,wp,na,_p,vp,xp,$p,Tp,Sp,Ip,Op,Ep,Ap,kp,Pp,Cp,Rp,Dp,Mp,Np,zp,Bp,Fp,Lp,jp,Up,Vp,qp,Gp,Hp,Wp,Kp,Xp,Zp,Yp,Jp,Qp,eh,th,rh,nh,ih,rr,EI=[ht,It,vc,Ic,Oc,Ec,Ac,kc,Pc,Cc,Rc,Dc,Mc,Nc,zc,Bc,Zc,Yc,Jc,rp,np,ip,op,sp,ap],ia={1055492:(f,b,$,x,E)=>{if(t===void 0||!t.Yc)return 1;if((f=et(Number(f>>>0))).startsWith("./")&&(f=f.substring(2)),!(f=t.Yc.get(f)))return 2;if(b=Number(b>>>0),$=Number($>>>0),x=Number(x>>>0),b+$>f.byteLength)return 3;try{let k=f.subarray(b,b+$);switch(E){case 0:(I(),q).set(k,x>>>0);break;case 1:t.Qd?t.Qd(x,k):t.Id(x,k);break;default:return 4}return 0}catch{return 4}},1056316:(f,b,$)=>{t.td(f,(I(),q).subarray(b>>>0,b+$>>>0))},1056380:()=>t.Sd(),1056422:f=>{t.sd(f)},1056459:()=>{t.Bd()},1056490:()=>{t.Cd()},1056519:()=>{t.Gd()},1056544:f=>t.Ad(f),1056577:f=>t.Ed(f),1056609:(f,b,$)=>{t.ed(Number(f),Number(b),Number($),!0)},1056672:(f,b,$)=>{t.ed(Number(f),Number(b),Number($))},1056729:()=>typeof wasmOffsetConverter<"u",1056786:f=>{t.$b("Abs",f,void 0)},1056837:f=>{t.$b("Neg",f,void 0)},1056888:f=>{t.$b("Floor",f,void 0)},1056941:f=>{t.$b("Ceil",f,void 0)},1056993:f=>{t.$b("Reciprocal",f,void 0)},1057051:f=>{t.$b("Sqrt",f,void 0)},1057103:f=>{t.$b("Exp",f,void 0)},1057154:f=>{t.$b("Erf",f,void 0)},1057205:f=>{t.$b("Sigmoid",f,void 0)},1057260:(f,b,$)=>{t.$b("HardSigmoid",f,{alpha:b,beta:$})},1057339:f=>{t.$b("HardSwish",f,void 0)},1057396:f=>{t.$b("Log",f,void 0)},1057447:f=>{t.$b("Sin",f,void 0)},1057498:f=>{t.$b("Cos",f,void 0)},1057549:f=>{t.$b("Tan",f,void 0)},1057600:f=>{t.$b("Asin",f,void 0)},1057652:f=>{t.$b("Acos",f,void 0)},1057704:f=>{t.$b("Atan",f,void 0)},1057756:f=>{t.$b("Sinh",f,void 0)},1057808:f=>{t.$b("Cosh",f,void 0)},1057860:f=>{t.$b("Asinh",f,void 0)},1057913:f=>{t.$b("Acosh",f,void 0)},1057966:f=>{t.$b("Atanh",f,void 0)},1058019:f=>{t.$b("Tanh",f,void 0)},1058071:f=>{t.$b("Not",f,void 0)},1058122:(f,b,$)=>{t.$b("Clip",f,{min:b,max:$})},1058191:f=>{t.$b("Clip",f,void 0)},1058243:(f,b)=>{t.$b("Elu",f,{alpha:b})},1058301:f=>{t.$b("Gelu",f,void 0)},1058353:f=>{t.$b("Relu",f,void 0)},1058405:(f,b)=>{t.$b("LeakyRelu",f,{alpha:b})},1058469:(f,b)=>{t.$b("ThresholdedRelu",f,{alpha:b})},1058539:(f,b)=>{t.$b("Cast",f,{to:b})},1058597:f=>{t.$b("Add",f,void 0)},1058648:f=>{t.$b("Sub",f,void 0)},1058699:f=>{t.$b("Mul",f,void 0)},1058750:f=>{t.$b("Div",f,void 0)},1058801:f=>{t.$b("Pow",f,void 0)},1058852:f=>{t.$b("Equal",f,void 0)},1058905:f=>{t.$b("Greater",f,void 0)},1058960:f=>{t.$b("GreaterOrEqual",f,void 0)},1059022:f=>{t.$b("Less",f,void 0)},1059074:f=>{t.$b("LessOrEqual",f,void 0)},1059133:(f,b,$,x,E)=>{t.$b("ReduceMean",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059308:(f,b,$,x,E)=>{t.$b("ReduceMax",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059482:(f,b,$,x,E)=>{t.$b("ReduceMin",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059656:(f,b,$,x,E)=>{t.$b("ReduceProd",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059831:(f,b,$,x,E)=>{t.$b("ReduceSum",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060005:(f,b,$,x,E)=>{t.$b("ReduceL1",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060178:(f,b,$,x,E)=>{t.$b("ReduceL2",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060351:(f,b,$,x,E)=>{t.$b("ReduceLogSum",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060528:(f,b,$,x,E)=>{t.$b("ReduceSumSquare",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060708:(f,b,$,x,E)=>{t.$b("ReduceLogSumExp",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060888:f=>{t.$b("Where",f,void 0)},1060941:(f,b,$)=>{t.$b("Transpose",f,{perm:b?Array.from((I(),v).subarray(Number(b)>>>0,Number($)>>>0)):[]})},1061065:(f,b,$,x)=>{t.$b("DepthToSpace",f,{blocksize:b,mode:et($),format:x?"NHWC":"NCHW"})},1061198:(f,b,$,x)=>{t.$b("DepthToSpace",f,{blocksize:b,mode:et($),format:x?"NHWC":"NCHW"})},1061331:(f,b,$,x)=>{t.$b("DFT",f,{axis:b,inverse:$,onesided:x})},1061423:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr)=>{t.$b("ConvTranspose",f,{format:Q?"NHWC":"NCHW",autoPad:b,dilations:[$],group:x,kernelShape:[E],pads:[k,M],strides:[U],wIsConst:()=>!!(I(),J)[ne>>>0],outputPadding:ge?Array.from((I(),v).subarray(Number(ge)>>>0,Number(Oe)>>>0)):[],outputShape:Ne?Array.from((I(),v).subarray(Number(Ne)>>>0,Number(Fe)>>>0)):[],activation:et(gr)})},1061856:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("ConvTranspose",f,{format:U?"NHWC":"NCHW",autoPad:b,dilations:Array.from((I(),v).subarray(Number($)>>>0,(Number($)>>>0)+2>>>0)),group:x,kernelShape:Array.from((I(),v).subarray(Number(E)>>>0,(Number(E)>>>0)+2>>>0)),pads:Array.from((I(),v).subarray(Number(k)>>>0,(Number(k)>>>0)+4>>>0)),strides:Array.from((I(),v).subarray(Number(M)>>>0,(Number(M)>>>0)+2>>>0)),wIsConst:()=>!!(I(),J)[Q>>>0],outputPadding:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],outputShape:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[],activation:et(Fe)})},1062517:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr)=>{t.$b("ConvTranspose",f,{format:Q?"NHWC":"NCHW",autoPad:b,dilations:[$],group:x,kernelShape:[E],pads:[k,M],strides:[U],wIsConst:()=>!!(I(),J)[ne>>>0],outputPadding:ge?Array.from((I(),v).subarray(Number(ge)>>>0,Number(Oe)>>>0)):[],outputShape:Ne?Array.from((I(),v).subarray(Number(Ne)>>>0,Number(Fe)>>>0)):[],activation:et(gr)})},1062950:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("ConvTranspose",f,{format:U?"NHWC":"NCHW",autoPad:b,dilations:Array.from((I(),v).subarray(Number($)>>>0,(Number($)>>>0)+2>>>0)),group:x,kernelShape:Array.from((I(),v).subarray(Number(E)>>>0,(Number(E)>>>0)+2>>>0)),pads:Array.from((I(),v).subarray(Number(k)>>>0,(Number(k)>>>0)+4>>>0)),strides:Array.from((I(),v).subarray(Number(M)>>>0,(Number(M)>>>0)+2>>>0)),wIsConst:()=>!!(I(),J)[Q>>>0],outputPadding:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],outputShape:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[],activation:et(Fe)})},1063611:(f,b)=>{t.$b("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},1063702:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("AveragePool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1064181:(f,b)=>{t.$b("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},1064272:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("AveragePool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1064751:(f,b)=>{t.$b("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},1064838:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("MaxPool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1065313:(f,b)=>{t.$b("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},1065400:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("MaxPool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1065875:(f,b,$,x,E)=>{t.$b("Gemm",f,{alpha:b,beta:$,transA:x,transB:E})},1065979:f=>{t.$b("MatMul",f,void 0)},1066033:(f,b,$,x)=>{t.$b("ArgMax",f,{keepDims:!!b,selectLastIndex:!!$,axis:x})},1066141:(f,b,$,x)=>{t.$b("ArgMin",f,{keepDims:!!b,selectLastIndex:!!$,axis:x})},1066249:(f,b)=>{t.$b("Softmax",f,{axis:b})},1066312:(f,b)=>{t.$b("Concat",f,{axis:b})},1066372:(f,b,$,x,E)=>{t.$b("Split",f,{axis:b,numOutputs:$,splitSizes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1066528:f=>{t.$b("Expand",f,void 0)},1066582:(f,b)=>{t.$b("Gather",f,{axis:Number(b)})},1066653:(f,b)=>{t.$b("GatherElements",f,{axis:Number(b)})},1066732:(f,b)=>{t.$b("GatherND",f,{batch_dims:Number(b)})},1066811:(f,b,$,x,E,k,M,U,Q,ne,ge)=>{t.$b("Resize",f,{antialias:b,axes:$?Array.from((I(),v).subarray(Number($)>>>0,Number(x)>>>0)):[],coordinateTransformMode:et(E),cubicCoeffA:k,excludeOutside:M,extrapolationValue:U,keepAspectRatioPolicy:et(Q),mode:et(ne),nearestMode:et(ge)})},1067173:(f,b,$,x,E,k,M)=>{t.$b("Slice",f,{starts:b?Array.from((I(),v).subarray(Number(b)>>>0,Number($)>>>0)):[],ends:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[],axes:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[]})},1067437:f=>{t.$b("Tile",f,void 0)},1067489:(f,b,$)=>{t.$b("InstanceNormalization",f,{epsilon:b,format:$?"NHWC":"NCHW"})},1067603:(f,b,$)=>{t.$b("InstanceNormalization",f,{epsilon:b,format:$?"NHWC":"NCHW"})},1067717:f=>{t.$b("Range",f,void 0)},1067770:(f,b)=>{t.$b("Einsum",f,{equation:et(b)})},1067851:(f,b,$,x,E)=>{t.$b("Pad",f,{mode:b,value:$,pads:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1067994:(f,b,$,x,E,k)=>{t.$b("BatchNormalization",f,{epsilon:b,momentum:$,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},1068163:(f,b,$,x,E,k)=>{t.$b("BatchNormalization",f,{epsilon:b,momentum:$,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},1068332:(f,b,$)=>{t.$b("CumSum",f,{exclusive:Number(b),reverse:Number($)})},1068429:(f,b,$)=>{t.$b("DequantizeLinear",f,{axis:b,blockSize:$})},1068519:(f,b,$,x,E)=>{t.$b("GridSample",f,{align_corners:b,mode:et($),padding_mode:et(x),format:E?"NHWC":"NCHW"})},1068689:(f,b,$,x,E)=>{t.$b("GridSample",f,{align_corners:b,mode:et($),padding_mode:et(x),format:E?"NHWC":"NCHW"})},1068859:(f,b)=>{t.$b("ScatterND",f,{reduction:et(b)})},1068944:(f,b,$,x,E,k,M,U,Q)=>{t.$b("Attention",f,{numHeads:b,isUnidirectional:$,maskFilterValue:x,scale:E,doRotary:k,qkvHiddenSizes:M?Array.from((I(),v).subarray(Number(U)>>>0,Number(U)+M>>>0)):[],pastPresentShareBuffer:!!Q})},1069216:f=>{t.$b("BiasAdd",f,void 0)},1069271:f=>{t.$b("BiasSplitGelu",f,void 0)},1069332:f=>{t.$b("FastGelu",f,void 0)},1069388:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr,oa)=>{t.$b("Conv",f,{format:Oe?"NHWC":"NCHW",auto_pad:b,dilations:$?Array.from((I(),v).subarray(Number($)>>>0,Number(x)>>>0)):[],group:E,kernel_shape:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],pads:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],strides:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],w_is_const:()=>!!(I(),J)[Number(Ne)>>>0],activation:et(Fe),activation_params:gr?Array.from((I(),H).subarray(Number(gr)>>>0,Number(oa)>>>0)):[]})},1069972:f=>{t.$b("Gelu",f,void 0)},1070024:(f,b,$,x,E,k,M,U,Q)=>{t.$b("GroupQueryAttention",f,{numHeads:b,kvNumHeads:$,scale:x,softcap:E,doRotary:k,rotaryInterleaved:M,smoothSoftmax:U,localWindowSize:Q})},1070241:(f,b,$,x)=>{t.$b("LayerNormalization",f,{axis:b,epsilon:$,simplified:!!x})},1070352:(f,b,$,x)=>{t.$b("LayerNormalization",f,{axis:b,epsilon:$,simplified:!!x})},1070463:(f,b,$,x,E,k)=>{t.$b("MatMulNBits",f,{k:b,n:$,accuracyLevel:x,bits:E,blockSize:k})},1070590:(f,b,$,x,E,k)=>{t.$b("MultiHeadAttention",f,{numHeads:b,isUnidirectional:$,maskFilterValue:x,scale:E,doRotary:k})},1070749:(f,b)=>{t.$b("QuickGelu",f,{alpha:b})},1070813:(f,b,$,x,E)=>{t.$b("RotaryEmbedding",f,{interleaved:!!b,numHeads:$,rotaryEmbeddingDim:x,scale:E})},1070952:(f,b,$)=>{t.$b("SkipLayerNormalization",f,{epsilon:b,simplified:!!$})},1071054:(f,b,$)=>{t.$b("SkipLayerNormalization",f,{epsilon:b,simplified:!!$})},1071156:(f,b,$,x)=>{t.$b("GatherBlockQuantized",f,{gatherAxis:b,quantizeAxis:$,blockSize:x})},1071277:f=>{t.Fd(f)},1071311:(f,b)=>t.Hd(Number(f),Number(b),t.Xc.Kd,t.Xc.errors)};function AI(f,b,$){return Gc(async()=>{await t.Dd(Number(f),Number(b),Number($))})}function kI(){return typeof wasmOffsetConverter<"u"}function PI(f,b,$,x){var E=_e();try{return Op(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function CI(f,b,$){var x=_e();try{return $p(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function RI(f){var b=_e();try{_p(f)}catch($){if(we(b),$!==$+0)throw $;Te(1,0)}}function DI(f,b){var $=_e();try{return na(f,b)}catch(x){if(we($),x!==x+0)throw x;Te(1,0)}}function MI(f,b,$){var x=_e();try{wp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function NI(f,b){var $=_e();try{Ep(f,b)}catch(x){if(we($),x!==x+0)throw x;Te(1,0)}}function zI(f,b,$,x,E,k,M){var U=_e();try{return Sp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function BI(f,b,$,x,E,k){var M=_e();try{vp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function FI(f,b,$,x){var E=_e();try{Ip(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function LI(f,b,$,x,E){var k=_e();try{xp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function jI(f,b,$,x,E,k,M){var U=_e();try{kp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function UI(f,b,$,x,E,k,M){var U=_e();try{Pp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function VI(f,b,$,x,E,k,M,U){var Q=_e();try{Mp(f,b,$,x,E,k,M,U)}catch(ne){if(we(Q),ne!==ne+0)throw ne;Te(1,0)}}function qI(f,b,$,x,E){var k=_e();try{return Ap(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function GI(f,b,$){var x=_e();try{return Np(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function HI(f,b,$,x,E,k,M,U){var Q=_e();try{zp(f,b,$,x,E,k,M,U)}catch(ne){if(we(Q),ne!==ne+0)throw ne;Te(1,0)}}function WI(f,b,$,x,E,k,M,U,Q,ne,ge,Oe){var Ne=_e();try{Cp(f,b,$,x,E,k,M,U,Q,ne,ge,Oe)}catch(Fe){if(we(Ne),Fe!==Fe+0)throw Fe;Te(1,0)}}function KI(f,b,$){var x=_e();try{return Bp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;return Te(1,0),0n}}function XI(f,b,$,x,E,k,M,U,Q){var ne=_e();try{Tp(f,b,$,x,E,k,M,U,Q)}catch(ge){if(we(ne),ge!==ge+0)throw ge;Te(1,0)}}function ZI(f){var b=_e();try{return Fp(f)}catch($){if(we(b),$!==$+0)throw $;Te(1,0)}}function YI(f,b){var $=_e();try{return eh(f,b)}catch(x){if(we($),x!==x+0)throw x;return Te(1,0),0n}}function JI(f){var b=_e();try{return Lp(f)}catch($){if(we(b),$!==$+0)throw $;return Te(1,0),0n}}function QI(f,b,$,x){var E=_e();try{return Hp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function e3(f,b,$,x,E){var k=_e();try{return Wp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function t3(f,b,$,x,E,k){var M=_e();try{return Kp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function r3(f,b,$,x,E,k){var M=_e();try{return Rp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function n3(f,b,$,x,E,k){var M=_e();try{return Xp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function i3(f,b,$,x,E,k,M,U){var Q=_e();try{return Dp(f,b,$,x,E,k,M,U)}catch(ne){if(we(Q),ne!==ne+0)throw ne;Te(1,0)}}function o3(f,b,$,x,E){var k=_e();try{return Zp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;return Te(1,0),0n}}function s3(f,b,$,x){var E=_e();try{return Yp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function a3(f,b,$,x){var E=_e();try{return Jp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function u3(f,b,$,x,E,k,M,U,Q,ne,ge,Oe){var Ne=_e();try{return Qp(f,b,$,x,E,k,M,U,Q,ne,ge,Oe)}catch(Fe){if(we(Ne),Fe!==Fe+0)throw Fe;Te(1,0)}}function l3(f,b,$,x,E,k,M,U,Q,ne,ge){var Oe=_e();try{qp(f,b,$,x,E,k,M,U,Q,ne,ge)}catch(Ne){if(we(Oe),Ne!==Ne+0)throw Ne;Te(1,0)}}function d3(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr,oa){var f3=_e();try{Gp(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr,oa)}catch(sa){if(we(f3),sa!==sa+0)throw sa;Te(1,0)}}function c3(f,b,$){var x=_e();try{return jp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function p3(f,b,$){var x=_e();try{return Up(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function h3(f,b,$,x){var E=_e();try{Vp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function bo(){if(0{g=f,_=b})}var px,Sm,HA=D(()=>{"use strict";px=Tm,Sm=globalThis.self?.name?.startsWith("em-pthread"),Sm&&Tm()}),Ua,Al,Im,yt,hx,$o,Om,Em,Va,Am,qa,fx,Ga,mx,rd=D(()=>{"use strict";td(),Ua=typeof location>"u"?void 0:location.origin,Al=import.meta.url>"file:"&&import.meta.url<"file;",Im=()=>{if(Al){let e=URL;return new URL(new e("ort.all.bundle.min.mjs",import.meta.url).href,Ua).href}return import.meta.url},yt=Im(),hx=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},$o=(e,t)=>{try{let n=t??yt;return(n?new URL(e,n):new URL(e)).origin===Ua}catch{return!1}},Om=(e,t)=>{let n=t??yt;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Em=(e,t)=>`${t??"./"}${e}`,Va=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Am=async e=>(await import(e)).default,qa=(GA(),Nn(lx)).default,fx=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if($o(yt))return[void 0,qa()];let e=await Va(yt);return[e,qa(e)]},Ga=(HA(),Nn(cx)).default,mx=async(e,t,n,i)=>{let u=Ga&&!(e||t);if(u)if(yt)u=$o(yt)||i&&!n;else if(i&&!n)u=!0;else throw new Error("cannot determine the script source URL.");if(u)return[void 0,Ga];{let l="ort-wasm-simd-threaded.jsep.mjs",d=e??Om(l,t),c=n&&d&&!$o(d,t),s=c?await Va(d):d??Em(l,t);return[c?s:void 0,await Am(s)]}}}),Ha,To,li,Wa,km,Pm,Cm,nd,Be,vn=D(()=>{"use strict";rd(),To=!1,li=!1,Wa=!1,km=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Pm=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Cm=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},nd=async e=>{if(To)return Promise.resolve();if(li)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Wa)throw new Error("previous call to 'initializeWebAssembly()' failed.");li=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Cm())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Pm())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=km();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let u=e.wasmPaths,l=typeof u=="string"?u:void 0,d=u?.mjs,c=d?.href??d,s=u?.wasm,r=s?.href??s,o=e.wasmBinary,[a,p]=await mx(c,l,n>1,!!o||!!r),h=!1,m=[];if(t>0&&m.push(new Promise(g=>{setTimeout(()=>{h=!0,g()},t)})),m.push(new Promise((g,_)=>{let w={numThreads:n};if(o)w.wasmBinary=o,w.locateFile=y=>y;else if(r||l)w.locateFile=y=>r??l+y;else if(c&&c.indexOf("blob:")!==0)w.locateFile=y=>new URL(y,c).href;else if(a){let y=hx();y&&(w.locateFile=T=>y+T)}p(w).then(y=>{li=!1,To=!0,Ha=y,g(),a&&URL.revokeObjectURL(a)},y=>{li=!1,Wa=!0,_(y)})})),await Promise.race(m),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Be=()=>{if(To&&Ha)return Ha;throw new Error("WebAssembly is not initialized yet.")}}),Ut,Go,Re,id=D(()=>{"use strict";vn(),Ut=(e,t)=>{let n=Be(),i=n.lengthBytesUTF8(e)+1,u=n._malloc(i);return n.stringToUTF8(e,u,i),t.push(u),u},Go=(e,t,n,i)=>{if(typeof e=="object"&&e!==null){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([u,l])=>{let d=t?t+u:u;if(typeof l=="object")Go(l,d+".",n,i);else if(typeof l=="string"||typeof l=="number")i(d,l.toString());else if(typeof l=="boolean")i(d,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},Re=e=>{let t=Be(),n=t.stackSave();try{let i=t.PTR_SIZE,u=t.stackAlloc(2*i);t._OrtGetLastError(u,u+i);let l=Number(t.getValue(u,i===4?"i32":"i64")),d=t.getValue(u+i,"*"),c=d?t.UTF8ToString(d):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(n)}}}),gx,WA=D(()=>{"use strict";vn(),id(),gx=e=>{let t=Be(),n=0,i=[],u=e||{};try{if(e?.logSeverityLevel===void 0)u.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)u.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(u.terminate=!1);let l=0;return e?.tag!==void 0&&(l=Ut(e.tag,i)),n=t._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,l),n===0&&Re("Can't create run options."),e?.extra!==void 0&&Go(e.extra,"",new WeakSet,(d,c)=>{let s=Ut(d,i),r=Ut(c,i);t._OrtAddRunConfigEntry(n,s,r)!==0&&Re(`Can't set a run config entry: ${d} - ${c}.`)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseRunOptions(n),i.forEach(d=>t._free(d)),l}}}),Rm,Dm,Mm,qr,Nm,bx,KA=D(()=>{"use strict";vn(),id(),Rm=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Dm=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Mm=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},qr=(e,t,n,i)=>{let u=Ut(t,i),l=Ut(n,i);Be()._OrtAddSessionConfigEntry(e,u,l)!==0&&Re(`Can't set a session config entry: ${t} - ${n}.`)},Nm=async(e,t,n)=>{let i=t.executionProviders;for(let u of i){let l=typeof u=="string"?u:u.name,d=[];switch(l){case"webnn":if(l="WEBNN",qr(e,"session.disable_quant_qdq","1",n),qr(e,"session.disable_qdq_constant_folding","1",n),typeof u!="string"){let a=u?.deviceType;a&&qr(e,"deviceType",a,n)}break;case"webgpu":if(l="JS",typeof u!="string"){let a=u;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);qr(e,"preferredLayout",a.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let c=Ut(l,n),s=d.length,r=0,o=0;if(s>0){r=Be()._malloc(s*Be().PTR_SIZE),n.push(r),o=Be()._malloc(s*Be().PTR_SIZE),n.push(o);for(let a=0;a{let t=Be(),n=0,i=[],u=e||{};Mm(u);try{let l=Rm(u.graphOptimizationLevel??"all"),d=Dm(u.executionMode??"sequential"),c=typeof u.logId=="string"?Ut(u.logId,i):0,s=u.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw new Error(`log severity level is not valid: ${s}`);let r=u.logVerbosityLevel??0;if(!Number.isInteger(r)||r<0||r>4)throw new Error(`log verbosity level is not valid: ${r}`);let o=typeof u.optimizedModelFilePath=="string"?Ut(u.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(l,!!u.enableCpuMemArena,!!u.enableMemPattern,d,!!u.enableProfiling,0,c,s,r,o),n===0&&Re("Can't create session options."),u.executionProviders&&await Nm(n,u,i),u.enableGraphCapture!==void 0){if(typeof u.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${u.enableGraphCapture}`);qr(n,"enableGraphCapture",u.enableGraphCapture.toString(),i)}if(u.freeDimensionOverrides)for(let[a,p]of Object.entries(u.freeDimensionOverrides)){if(typeof a!="string")throw new Error(`free dimension override name must be a string: ${a}`);if(typeof p!="number"||!Number.isInteger(p)||p<0)throw new Error(`free dimension override value must be a non-negative integer: ${p}`);let h=Ut(a,i);t._OrtAddFreeDimensionOverride(n,h,p)!==0&&Re(`Can't set a free dimension override: ${a} - ${p}.`)}return u.extra!==void 0&&Go(u.extra,"",new WeakSet,(a,p)=>{qr(n,a,p,i)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&Re("Can't release session options."),i.forEach(d=>t._free(d)),l}}}),dn,sr,cn,ss,Ho,od,sd,kl,de=D(()=>{"use strict";dn=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},sr=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},cn=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((u,l)=>u*l,1);return n>0?Math.ceil(i*n):void 0},ss=e=>{switch(e){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Ho=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},od=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",sd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",kl=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),ad,yx=D(()=>{"use strict";td(),ad=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),i=n?parseInt(n,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let u=t.body.getReader(),l;try{l=new ArrayBuffer(i)}catch(c){if(c instanceof RangeError){let s=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:s,maximum:s}).buffer}else throw c}let d=0;for(;;){let{done:c,value:s}=await u.read();if(c)break;let r=s.byteLength;new Uint8Array(l,d,r).set(s),d+=r}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),zm,Bm,Fm,Lm,ud,jm,Ie,ur=D(()=>{"use strict";de(),zm=["V","I","W","E","F"],Bm=(e,t)=>{console.log(`[${zm[e]},${new Date().toISOString()}]${t}`)},ud=(e,t)=>{Fm=e,Lm=t},jm=(e,t)=>{let n=Ho(e),i=Ho(Fm);n>=i&&Bm(n,typeof t=="function"?t():t)},Ie=(...e)=>{Lm&&jm(...e)}}),Um,Bn,F,Wo,wx,_x,vx,pe=D(()=>{"use strict";Um=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Bn=class{static calcShape(e,t,n=!1){let i=e.length,u=t.length;if(i===0)return t;if(u===0)return e;let l=Math.max(e.length,t.length),d=new Array(l);if(n){if(i<2||u<2)return;let c=Um.calcMatMulShape([e[i-2],e[i-1]],[t[u-2],t[u-1]]);if(c===void 0)return;[d[l-2],d[l-1]]=c}for(let c=n?3:1;c<=l;c++){let s=i-c<0?1:e[i-c],r=u-c<0?1:t[u-c];if(s!==r&&s>1&&r>1)return;let o=Math.max(s,r);if(s&&r)d[l-c]=Math.max(s,r);else{if(o>1)return;d[l-c]=0}}return d}static isValidBroadcast(e,t){let n=e.length,i=t.length;if(n>i)return!1;for(let u=1;u<=n;u++)if(e[n-u]!==1&&e[n-u]!==t[i-u])return!1;return!0}},F=class Bo{static size(t){return Bo.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,n=4){let i=t.length;if(i===0)return[];let u=new Array(i),l=i-1;for(;l>=0;){if(t[l]%n===0){u[l]=t[l]/n;break}if(n%t[l]!==0)throw new Error("cannot convert shape");u[l]=1,n/=t[l],l--}for(l--;l>=0;l--)u[l]=t[l];return u}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Bo.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Bo.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let u=1;for(let l=n;l=0;--u)i[u]=i[u+1]*t[u+1];return i}static normalizeAxis(t,n){if(t<-n&&t>=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n??t.length))}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((u,l)=>u+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,u)=>i===n[u])}},Wo=class Er{static adjustPoolAttributes(t,n,i,u,l,d){if(!t&&i.length!==n.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c=i[c]||d[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,u,l,d,c){if(c){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let s=0;s=i+u&&(d-=1)),d}static adjustPadAndReturnShape(t,n,i,u,l,d,c,s,r=0){let o=i*(u-1)+1;if(s&&s!=="NOTSET")switch(s){case"VALID":return l[d]=0,l[c]=0,Er.computeOutputSize(t-o,n,t,0,r);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let a=(Math.floor((t+n-1)/n)-1)*n+u-t;return l[d]=Math.floor(s==="SAME_LOWER"?(a+1)/2:a/2),l[c]=a-l[d],Er.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}default:throw new Error("Unsupported AutoPad type")}else return Er.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}},wx=class{static getShapeOfGemmResult(e,t,n,i,u){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,d,c;t?(l=e[1],d=e[0]):(l=e[0],d=e[1]);let s=-1;if(i?(c=n[0],s=1):(c=n[1],s=0),n[s]!==d)throw new Error("dimension mismatch");if(l<=0||c<=0||d<=0)throw new Error("invalid shape specified");if(u&&!Bn.isValidBroadcast(u,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,d]}},_x=-34028234663852886e22,vx=34028234663852886e22}),ld,xx=D(()=>{"use strict";de(),ld=(e,t)=>new(ss(t))(e)}),Ka,Vm,Xa,qm,Za,Gm,Ya,Ja,Qa,Hm,$x,XA=D(()=>{"use strict";de(),ur(),Ka=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Vm=(e,t)=>{if(t==="int32")return e;let n=Ka.get(t);if(!n)throw new Error(`WebNN backend does not support data type: ${t}`);let i=n/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let u=e.byteLength/i,l=new(ss(t))(e.buffer,e.byteOffset,u);switch(t){case"int64":case"uint64":{let d=new Int32Array(u);for(let c=0;c2147483647n||s<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");d[c]=Number(s)}return new Uint8Array(d.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(c=>c>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let d=Int32Array.from(l,Number);return new Uint8Array(d.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Xa=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let n=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case"int64":{let u=BigInt64Array.from(i,BigInt);return new Uint8Array(u.buffer)}case"uint64":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let u=BigUint64Array.from(i,BigInt);return new Uint8Array(u.buffer)}case"int8":{if(i.some(l=>l<-128||l>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let u=Int8Array.from(i,Number);return new Uint8Array(u.buffer)}case"uint8":{if(i.some(u=>u<0||u>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(i,Number)}case"uint32":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let u=Uint32Array.from(i,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},qm=1,Za=()=>qm++,Gm=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Ya=(e,t)=>{let n=Ka.get(e);if(!n)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,u)=>i*u)*n/8):0},Ja=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:i,dataType:u,shape:l,fallbackDataType:d}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=i,this.dataType=u,this.tensorShape=l,this.fallbackDataType=d}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Ya(this.dataType,this.tensorShape)}destroy(){Ie("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Xa(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return new Uint8Array(n).buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((i,u)=>i===n[u])}setIsDataConverted(e){this.isDataConverted=e}},Qa=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,i){let u=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),d;if(!l?.input.dataTypes.includes(t)){if(d=Gm.get(t),!d||l?.input.dataTypes.includes(d))throw new Error(`WebNN backend does not support data type: ${t}`);Ie("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${d}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(u,t,n))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==Ya(t,n))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,c,!0,!0,d),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=Vm(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Ie("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Xa(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Hm=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Za();return this.tensorTrackersById.set(e,new Qa(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,i,u){Ie("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${i}, copyOld: ${u}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,n,i,u)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){Ie("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,i){let u=this.getMLContext(e),l=Za(),d=new Ja({sessionId:e,context:u,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(l,new Qa(this,d)),this.externalTensors.add(d),l}async getCachedTensor(e,t,n,i,u,l,d){let c=this.getMLContext(e);for(let[r,o]of this.freeTensors.entries())if(o.canReuseTensor(c,t,n)){Ie("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${d?`fallbackDataType: ${d},`:""} shape: ${n}`);let a=this.freeTensors.splice(r,1)[0];return a.sessionId=e,a}Ie("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${d?`fallbackDataType: ${d},`:""} shape: ${n}}`);let s=await c.createTensor({dataType:d??t,shape:n,dimensions:n,usage:i,writable:u,readable:l});return new Ja({sessionId:e,context:c,tensor:s,dataType:t,shape:n,fallbackDataType:d})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},$x=(...e)=>new Hm(...e)}),di,Wm,Tx,ZA=D(()=>{"use strict";de(),vn(),xx(),XA(),ur(),di=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Wm=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),i=Object.keys(t).sort();return n.length===i.length&&n.every((u,l)=>u===i[l]&&e[u]===t[u])},Tx=class{constructor(e){this.tensorManager=$x(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,ud(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Ie("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Ie("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let n of t)Ie("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${n}}`),this.tensorManager.releaseTensorId(n);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let n=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let n=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(n=>Wm(n.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:n}),n}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(u=>u.mlContext===t);i!==-1&&this.mlContextCache.splice(i,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Ie("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,i,u){let l=di.get(n);if(!l)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,u)}async createTemporaryTensor(e,t,n){Ie("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let i=di.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let u=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,u,i,n,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(u):this.temporarySessionTensorIds.set(e,[u]),u}uploadTensor(e,t){if(!Be().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ie("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return ld(n,t)}}registerMLTensor(e,t,n,i){let u=di.get(n);if(!u)throw new Error(`Unsupported ONNX data type: ${n}`);let l=this.tensorManager.registerTensor(e,t,u,i);return Ie("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${u}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let i=di.get(dn(t)),u=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:n?!!u?.input.dataTypes.includes(i):!!u?.output.dataTypes.includes(i)}flush(){}}}),dd=D(()=>{"use strict"}),eu,So,Io,Km,Xm,tu,Pl,Zm,Sx,YA=D(()=>{"use strict";ur(),dd(),eu=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),So=[],Io=e=>Math.ceil(Number(e)/16)*16,Km=e=>{for(let t=0;tXm++,Pl=async(e,t,n,i)=>{let u=Io(n),l=e.device.createBuffer({size:u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=e.getCommandEncoder();e.endComputePass(),d.copyBufferToBuffer(t,0,l,0,u),e.flush(),await l.mapAsync(GPUMapMode.READ);let c=l.getMappedRange();if(i){let s=i();return s.set(new Uint8Array(c,0,n)),s}else return new Uint8Array(c.slice(0,n))}finally{l.destroy()}},Zm=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of eu)So.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,i=t.byteOffset,u=t.byteLength,l=Io(u),d=this.storageCache.get(e);if(!d)throw new Error("gpu data for uploading does not exist");if(Number(d.originalSize)!==u)throw new Error(`inconsistent data size. gpu data size=${d.originalSize}, data size=${u}`);if(l===u&&i%4===0)this.backend.device.queue.writeBuffer(d.gpuData.buffer,0,n,i,u);else{let c=new Uint8Array(l);c.set(t),this.backend.device.queue.writeBuffer(d.gpuData.buffer,0,c,0,l)}Ie("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(t);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let u=Io(n.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(n.gpuData.buffer,0,i.gpuData.buffer,0,u)}registerExternalBuffer(e,t,n){let i;if(n){if(i=n[0],e===n[1])return Ie("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`)}else i=tu();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),Ie("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Ie("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=Km(e),i,u=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,l=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(u||l){let c=(u?this.freeBuffers:this.freeUniformBuffers).get(n);c?c.length>0?i=c.pop():i=this.backend.device.createBuffer({size:n,usage:t}):i=this.backend.device.createBuffer({size:n,usage:t})}else i=this.backend.device.createBuffer({size:n,usage:t});let d={id:tu(),type:0,buffer:i};return this.storageCache.set(d.id,{gpuData:d,originalSize:Number(e)}),Ie("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${d.id}`),d}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,n=this.storageCache.get(t);if(!n){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Ie("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw new Error("data does not exist");await Pl(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=eu.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Ie("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Sx=(...e)=>new Zm(...e)}),Ym,ke,He=D(()=>{"use strict";Ym=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},ke=e=>new Ym(e)}),Fn,Oo,nt,rt,ue,Ge,Cl,Mn,kr,se,ci,j,oe,Ix,cd,Jm,Ox,he=D(()=>{"use strict";de(),pe(),Fn=64,Oo=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},nt=(e,t=1)=>{let n=Oo(e,t);return typeof n=="string"?n:n[0]},rt=(e,t=1)=>{let n=Oo(e,t);return typeof n=="string"?n:n[1]},ue=(...e)=>{let t=[];return e.forEach(n=>{n.length!==0&&t.push({type:12,data:n},{type:12,data:F.computeStrides(n)})}),t},Ge=e=>e%4===0?4:e%2===0?2:1,Cl=(e="f32",t,n="0")=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,Mn=(e,t,n)=>e==="f32"?n:t===1?`f32(${n})`:`vec${t}(${n})`,kr=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,se=(e,t,n,i)=>e.startsWith("uniforms.")&&n>4?typeof t=="string"?i==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:i==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,ci=(e,t,n,i,u)=>{let l=typeof n=="number",d=l?n:n.length,c=[...new Array(d).keys()],s=d<2?"u32":d<=4?`vec${d}`:`array`,r=Oo(t,u),o=typeof r=="string"?r:r[1],a=typeof r=="string"?r:r[0],p={indices:s,value:o,storage:a,tensor:t},h=B=>typeof B=="string"?B:`${B}u`,m={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=l?"uniforms.":"",_=`${g}${e}_shape`,w=`${g}${e}_strides`,y="";for(let B=0;B u32 { a_data${N>0?N:""}[j${N>0?N:""}] = ${z.getByOffset(`input_offset${N>0?N:""}`)}; input_offset${N>0?N:""}++; } - `;for(let ne=0;ne> ${N*16}u; let byte_lo = half_word & 0xFFu; @@ -3824,8 +3824,8 @@ fn calculateOutputIndex(index: u32) -> u32 { }`:`b_value_lower = unpack4xU8((b_value >> ${X}u) & b_mask); b_value_upper = unpack4xU8((b_value >> ${W}u) & b_mask);`} b_quantized_values = ${H}(${Array.from({length:4},(le,ce)=>`${R}(b_value_lower[${ce}]), ${R}(b_value_upper[${ce}])`).join(", ")}); - b_dequantized_values = ${a===1?`${H}(${Array.from({length:8},(le,ce)=>`(b_quantized_values[${ce}] - ${C?`zero_point${ne}`:"zero_point"}) * scale${ne}`).join(", ")});`:`(b_quantized_values - ${H}(${Array(8).fill(`${C?`zero_point${ne}`:"zero_point"}`).join(",")})) * scale${ne};`}; - workgroup_shared[local_id.x * ${g} + ${Math.floor(ne/h)}]${h>1?`[${ne%h}]`:""} += ${Array.from({length:8/a},(le,ce)=>`${a===1?`a_data${N>0?N:""}[${ce}] * b_dequantized_values[${ce}]`:`dot(a_data${N>0?N:""}[${ce}], b_dequantized_values[${ce}])`}`).join(" + ")}; + b_dequantized_values = ${a===1?`${H}(${Array.from({length:8},(le,ce)=>`(b_quantized_values[${ce}] - ${C?`zero_point${re}`:"zero_point"}) * scale${re}`).join(", ")});`:`(b_quantized_values - ${H}(${Array(8).fill(`${C?`zero_point${re}`:"zero_point"}`).join(",")})) * scale${re};`}; + workgroup_shared[local_id.x * ${g} + ${Math.floor(re/h)}]${h>1?`[${re%h}]`:""} += ${Array.from({length:8/a},(le,ce)=>`${a===1?`a_data${N>0?N:""}[${ce}] * b_dequantized_values[${ce}]`:`dot(a_data${N>0?N:""}[${ce}], b_dequantized_values[${ce}])`}`).join(" + ")}; `}return Y},B=()=>{let Y=` var col_index = col * ${h}; ${C?` @@ -3954,9 +3954,9 @@ fn calculateOutputIndex(index: u32) -> u32 { let b_value_upper = unpack4xU8((spread_word >> 2u) & 0x03030303u);`:` let b_value_lower = unpack4xU8((b_value >> ${X}u) & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> ${W}u) & 0x0F0F0F0Fu);`} - let b_quantized_values = mat2x4<${K}>(${Array.from({length:4},(ne,le)=>`${K}(b_value_lower[${le}]), ${K}(b_value_upper[${le}])`).join(", ")}); + let b_quantized_values = mat2x4<${K}>(${Array.from({length:4},(re,le)=>`${K}(b_value_lower[${le}]), ${K}(b_value_upper[${le}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${K}>(${Array(8).fill("zero_point").join(",")})) * scale; - inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(ne,le)=>`${`dot(a_data${le}, b_dequantized_values[${le}])`}`).join(" + ")}; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(re,le)=>`${`dot(a_data${le}, b_dequantized_values[${le}])`}`).join(" + ")}; } word_offset += ${8/a};`}return Y})()} } @@ -4693,7 +4693,7 @@ fn calculateOutputIndex(index: u32) -> u32 { }`},e0=e=>{let t=e[1].dims,n=e[2].dims,i=e[0].dims,u=e[1].dataType,l=!(F.areEqual(t,n)&&F.areEqual(n,i)),d=t,c=F.size(t);if(l){let r=Bn.calcShape(Bn.calcShape(t,n,!1),i,!1);if(!r)throw new Error("Can't perform where op on the given tensors");d=r,c=F.size(d)}let s=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:r=>Qy(r,e,d,l,u),getRunData:()=>({outputs:[{dims:d,dataType:u}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:s},...ue(i,t,n,d)]})}},d$=e=>{e.compute(e0(e.inputs))}}),c$,Lk=D(()=>{"use strict";QA(),hd(),ek(),tk(),rk(),nk(),ik(),lk(),ck(),pk(),hk(),fk(),mk(),gk(),bk(),yk(),wk(),_k(),vk(),xk(),$k(),Tk(),Sk(),Ik(),Ok(),Ek(),k2(),Ak(),kk(),Pk(),Ck(),Rk(),pd(),Dk(),M2(),Mk(),Nk(),zk(),R2(),Bk(),Cr(),fd(),Fk(),c$=new Map([["Abs",[t1]],["Acos",[r1]],["Acosh",[n1]],["Add",[B1]],["ArgMax",[Yx,Dl]],["ArgMin",[Zx,Dl]],["Asin",[i1]],["Asinh",[o1]],["Atan",[s1]],["Atanh",[a1]],["Attention",[Jx]],["AveragePool",[q2,V2]],["BatchNormalization",[Qx]],["BiasAdd",[e1]],["BiasSplitGelu",[z1]],["Cast",[l1,u1]],["Ceil",[c1]],["Clip",[d1]],["Concat",[K1,X1]],["Conv",[Ll,Fl]],["ConvTranspose",[o2,i2]],["Cos",[p1]],["Cosh",[h1]],["CumSum",[s2,a2]],["DepthToSpace",[u2,l2]],["DequantizeLinear",[Y2,J2]],["DFT",[d2,c2]],["Div",[F1]],["Einsum",[p2,h2]],["Elu",[f1,Si]],["Equal",[L1]],["Erf",[m1]],["Exp",[g1]],["Expand",[f2]],["FastGelu",[m2]],["Floor",[b1]],["FusedConv",[Ll,Fl]],["Gather",[b2,g2]],["GatherElements",[$2,x2]],["GatherBlockQuantized",[_2,v2]],["GatherND",[y2,w2]],["Gelu",[y1]],["Gemm",[S2,T2]],["GlobalAveragePool",[H2,G2]],["GlobalMaxPool",[Z2,X2]],["Greater",[q1]],["GreaterOrEqual",[H1]],["GridSample",[I2,O2]],["GroupQueryAttention",[N2]],["HardSigmoid",[I1,S1]],["HardSwish",[O1]],["InstanceNormalization",[z2]],["LayerNormalization",[B2]],["LeakyRelu",[w1,Si]],["Less",[G1]],["LessOrEqual",[W1]],["Log",[M1]],["MatMul",[F2]],["MatMulNBits",[L2,j2]],["MaxPool",[W2,K2]],["Mul",[j1]],["MultiHeadAttention",[A2,E2]],["Neg",[v1]],["Not",[_1]],["Pad",[U2]],["Pow",[U1]],["QuickGelu",[N1,Si]],["Range",[Q2]],["Reciprocal",[x1]],["ReduceMin",[Gx]],["ReduceMean",[Lx]],["ReduceMax",[qx]],["ReduceSum",[Wx]],["ReduceProd",[Hx]],["ReduceL1",[jx]],["ReduceL2",[Ux]],["ReduceLogSum",[Xx]],["ReduceLogSumExp",[Vx]],["ReduceSumSquare",[Kx]],["Relu",[$1]],["Resize",[r$,n$]],["RotaryEmbedding",[D2]],["ScatterND",[t$,e$]],["Sigmoid",[T1]],["Sin",[E1]],["Sinh",[A1]],["Slice",[o$,s$]],["SkipLayerNormalization",[i$]],["Split",[P2,C2]],["Sqrt",[k1]],["Softmax",[a$,u$]],["Sub",[V1]],["Tan",[P1]],["Tanh",[C1]],["ThresholdedRelu",[D1,Si]],["Tile",[l$]],["Transpose",[Ex,Ax]],["Where",[d$]]])}),p$,jk=D(()=>{"use strict";dt(),ur(),he(),p$=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,i,u){Jt(e.programInfo.name);let l=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let c=[];for(let r of t)c.push({binding:c.length,resource:{buffer:r.buffer}});for(let r of n)c.push({binding:c.length,resource:{buffer:r.buffer}});u&&c.push({binding:c.length,resource:u});let s=l.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:c,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let r={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:s,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(r)}d.setPipeline(e.computePipeline),d.setBindGroup(0,s),d.dispatchWorkgroups(...i),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Vt(e.programInfo.name)}dispose(){}build(e,t){Jt(e.name);let n=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(r=>{n.features.has(r.feature)&&i.push(`enable ${r.extension};`)});let u=Ox(t,this.backend.device.limits),l=e.getShaderSource(u),d=`${i.join(` `)} ${u.additionalImplementations} -${l}`,c=n.createShaderModule({code:d,label:e.name});Ie("verbose",()=>`[WebGPU] ${e.name} shader code: ${d}`);let s=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return Vt(e.name),{programInfo:e,computePipeline:s,uniformVariablesInfo:u.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,n=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,u=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=u&&n<=u&&i<=u)return[t,n,i];let l=t*n*i,d=Math.ceil(Math.sqrt(l));if(d>u){if(d=Math.ceil(Math.cbrt(l)),d>u)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),h$={};wn(h$,{WebGpuBackend:()=>f$});var t0,r0,n0,f$,Uk=D(()=>{"use strict";dt(),de(),ur(),xx(),YA(),Lk(),jk(),t0=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let i=0;i{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+n+`:${t0(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},n0=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},f$=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},u=c=>t.features.has(c)&&n.push(c)&&!0;u("chromium-experimental-timestamp-query-inside-passes")||u("timestamp-query"),u("shader-f16"),u("subgroups"),this.device=await t.requestDevice(i);let l=t,d=t.info??(typeof l.requestAdapterInfo=="function"?await l.requestAdapterInfo():void 0);this.adapterInfo=new n0(d),this.gpuDataManager=Sx(this),this.programManager=new p$(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ud(e.logLevel,!!e.debug),this.device.onuncapturederror=c=>{c.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${c.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Jt(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=p);let m=Number(p-this.queryTimeBase),g=Number(h-this.queryTimeBase);if(!Number.isSafeInteger(m)||!Number.isSafeInteger(g))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:o.map(_=>({dims:_.dims,dataType:sr(_.dataType)})),outputsMetadata:a.map(_=>({dims:_.dims,dataType:sr(_.dataType)})),kernelId:l,kernelType:c,kernelName:s,programName:r,startTime:m,endTime:g});else{let _="";o.forEach((y,T)=>{_+=`input[${T}]: [${y.dims}] | ${sr(y.dataType)}, `});let w="";a.forEach((y,T)=>{w+=`output[${T}]: [${y.dims}] | ${sr(y.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${s}|${r}" ${_}${w}start time: ${m} ns, execution time: ${g-m} ns`)}Lo("GPU",`${r}::${p}::${h}`)}e.unmap(),this.pendingQueries.delete(e)}),Vt()}run(e,t,n,i,u,l){Jt(e.name);let d=[];for(let y=0;yT):n;if(o.length!==c.length)throw new Error(`Output size ${o.length} must be equal to ${c.length}.`);let a=[],p=[];for(let y=0;y=l)throw new Error(`Invalid output index: ${o[y]}`);if(o[y]===-3)continue;let T=o[y]===-1,S=o[y]===-2,O=T||S?u(c[y].dataType,c[y].dims):i(o[y],c[y].dataType,c[y].dims);if(a.push(O),O.data===0)continue;let A=this.gpuDataManager.get(O.data);if(!A)throw new Error(`no GPU data for output: ${O.data}`);if(T&&this.temporaryData.push(A),S){let P=this.kernelPersistentData.get(this.currentKernelId);P||(P=[],this.kernelPersistentData.set(this.currentKernelId,P)),P.push(A)}p.push(A)}if(d.length!==t.length||p.length!==a.length){if(p.length===0)return Vt(e.name),a;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let h;if(r){let y=0,T=[];r.forEach(P=>{let I=typeof P.data=="number"?[P.data]:P.data;if(I.length===0)return;let z=P.type===10?2:4,G,J;P.type===10?(J=I.length>4?16:I.length>2?8:I.length*z,G=I.length>4?16:z*I.length):(J=I.length<=2?I.length*z:16,G=16),y=Math.ceil(y/J)*J,T.push(y);let q=P.type===10?8:4;y+=I.length>4?Math.ceil(I.length/q)*G:I.length*z});let S=16;y=Math.ceil(y/S)*S;let O=new ArrayBuffer(y);r.forEach((P,I)=>{let z=T[I],G=typeof P.data=="number"?[P.data]:P.data;if(P.type===6)new Int32Array(O,z,G.length).set(G);else if(P.type===12)new Uint32Array(O,z,G.length).set(G);else if(P.type===10)new Uint16Array(O,z,G.length).set(G);else if(P.type===1)new Float32Array(O,z,G.length).set(G);else throw new Error(`Unsupported uniform type: ${sr(P.type)}`)});let A=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(A.buffer,0,O,0,y),this.gpuDataManager.release(A.id),h={offset:0,size:y,buffer:A.buffer}}let m=this.programManager.normalizeDispatchGroupSize(s),g=m[1]===1&&m[2]===1,_=r0(e,t,g),w=this.programManager.getArtifact(_);if(w||(w=this.programManager.build(e,m),this.programManager.setArtifact(_,w),Ie("info",()=>`[artifact] key: ${_}, programName: ${e.name}`)),r&&w.uniformVariablesInfo){if(r.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${r.length} in program "${w.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${e.name}" (key=${_}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:t,outputTensorViews:a};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(w,d,p,m,h),Vt(e.name),a}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,i){let u=c$.get(e);if(!u)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:u[0],attributes:[u[1],n]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let n of t)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let u=i.kernelType,l=i.kernelName,d=i.kernelEntry,c=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${u}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),Ie("info",()=>`[WebGPU] Start to run kernel "[${u}] ${l}"...`);let s=this.env.debug;this.temporaryData=[];try{return s&&this.device.pushErrorScope("validation"),d(t,c[1]),0}catch(r){return n.push(Promise.resolve(`[WebGPU] Kernel "[${u}] ${l}" failed. ${r}`)),1}finally{s&&n.push(this.device.popErrorScope().then(r=>r?`GPU validation error for kernel "[${u}] ${l}": ${r.message}`:null));for(let r of this.temporaryData)this.gpuDataManager.release(r.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,i){let u=this.sessionExternalDataMapping.get(e);u||(u=new Map,this.sessionExternalDataMapping.set(e,u));let l=u.get(t),d=this.gpuDataManager.registerExternalBuffer(n,i,l);return u.set(t,[d,n]),d}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let i=await Pl(this,e,t);return ld(i.buffer,n)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Ie("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Ie("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ie("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let i=0;i=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),m$={};wn(m$,{init:()=>g$});var Ro,i0,g$,Vk=D(()=>{"use strict";de(),ur(),pe(),ZA(),Ro=class b${constructor(t,n,i,u){this.module=t,this.dataType=n,this.data=i,this.dims=u}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(F.size(t)!==F.size(this.dims))throw new Error("Invalid new shape");return new b$(this.module,this.dataType,this.data,t)}},i0=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,u=n/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*u++,l));let d=Number(e.getValue(i*u++,l));this.outputCount=Number(e.getValue(i*u++,l)),this.customDataOffset=Number(e.getValue(i*u++,"*")),this.customDataSize=Number(e.getValue(i*u++,l));let c=[];for(let s=0;stypeof d=="number"?this.inputs[d]:d)??this.inputs,i=t?.outputs??[],u=(d,c,s)=>new Ro(this.module,c,this.output(d,s),s),l=(d,c)=>{let s=cn(d,c);if(!s)throw new Error(`Unsupported data type: ${d}`);let r=s>0?this.backend.gpuDataManager.create(s).id:0;return new Ro(this.module,d,r,c)};return this.backend.run(e,n,i,u,l,this.outputCount)}output(e,t){let n=this.module.stackSave();try{let i=this.module.PTR_SIZE,u=i===4?"i32":"i64",l=this.module.stackAlloc((1+t.length)*i);this.module.setValue(l,t.length,u);for(let d=0;d{let u=t.jsepInit;if(!u)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let l=(Uk(),Nn(h$)).WebGpuBackend,d=new l;await d.initialize(n,i),u("webgpu",[d,c=>d.alloc(Number(c)),c=>d.free(c),(c,s,r,o=!1)=>{if(o)Ie("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(s)}, size=${Number(r)}`),d.memcpy(Number(c),Number(s));else{Ie("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(s)}, size=${Number(r)}`);let a=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(r));d.upload(Number(s),a)}},async(c,s,r)=>{Ie("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${c}, dataOffset=${s}, size=${r}`),await d.download(Number(c),()=>t.HEAPU8.subarray(Number(s)>>>0,Number(s+r)>>>0))},(c,s,r)=>d.createKernel(c,Number(s),r,t.UTF8ToString(t._JsepGetNodeName(Number(s)))),c=>d.releaseKernel(c),(c,s,r,o)=>{Ie("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${c}, contextDataOffset=${s}`);let a=new i0(t,d,Number(s));return d.computeKernel(Number(c),a,o)},()=>d.captureBegin(),()=>d.captureEnd(),()=>d.replay()])}else{let l=new Tx(n);u("webnn",[l,()=>l.reserveTensorId(),d=>l.releaseTensorId(d),async(d,c,s,r,o)=>l.ensureTensor(d,c,s,r,o),(d,c)=>{l.uploadTensor(d,c)},async(d,c)=>l.downloadTensor(d,c),(d,c)=>l.registerMLContext(d,c),!!n.trace])}}}),o0,_d,vd,_r,s0,Du,Yo,xd,$d,Mu,Td,Sd,Id,y$=D(()=>{"use strict";dt(),WA(),KA(),de(),vn(),id(),yx(),o0=(e,t)=>{Be()._OrtInit(e,t)!==0&&Re("Can't initialize onnxruntime.")},_d=async e=>{o0(e.wasm.numThreads,Ho(e.logLevel))},vd=async(e,t)=>{Be().asyncInit?.();let n=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let u=e.webgpu.forceFallbackAdapter;if(u!==void 0&&typeof u!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${u}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:u}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let i=(Vk(),Nn(m$)).init;t==="webgpu"&&await i("webgpu",Be(),e,n),t==="webnn"&&await i("webnn",Be(),e)}},_r=new Map,s0=e=>{let t=Be(),n=t.stackSave();try{let i=t.PTR_SIZE,u=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,u,u+i)!==0&&Re("Can't get session input/output count.");let l=i===4?"i32":"i64";return[Number(t.getValue(u,l)),Number(t.getValue(u+i,l))]}finally{t.stackRestore(n)}},Du=(e,t)=>{let n=Be(),i=n.stackSave(),u=0;try{let l=n.PTR_SIZE,d=n.stackAlloc(2*l);n._OrtGetInputOutputMetadata(e,t,d,d+l)!==0&&Re("Can't get session input/output metadata.");let c=Number(n.getValue(d,"*"));u=Number(n.getValue(d+l,"*"));let s=n.HEAP32[u/4];if(s===0)return[c,0];let r=n.HEAPU32[u/4+1],o=[];for(let a=0;a{let t=Be(),n=t._malloc(e.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},xd=async(e,t)=>{let n,i,u=Be();Array.isArray(e)?[n,i]=e:e.buffer===u.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=Yo(e);let l=0,d=0,c=0,s=[],r=[],o=[];try{if([d,s]=await bx(t),t?.externalData&&u.mountExternalData){let S=[];for(let O of t.externalData){let A=typeof O=="string"?O:O.path,P=typeof O=="string"?O:O.data;S.push(ad(P).then(I=>{u.mountExternalData(A,I)}))}await Promise.all(S)}for(let S of t?.executionProviders??[])if((typeof S=="string"?S:S.name)==="webnn"){if(u.shouldTransferToMLTensor=!1,typeof S!="string"){let O=S,A=O?.context,P=O?.gpuDevice,I=O?.deviceType,z=O?.powerPreference;A?u.currentContext=A:P?u.currentContext=await u.webnnCreateMLContext(P):u.currentContext=await u.webnnCreateMLContext({deviceType:I,powerPreference:z})}else u.currentContext=await u.webnnCreateMLContext();break}l=await u._OrtCreateSession(n,i,d),u.webgpuOnCreateSession?.(l),l===0&&Re("Can't create a session."),u.jsepOnCreateSession?.(),u.currentContext&&(u.webnnRegisterMLContext(l,u.currentContext),u.currentContext=void 0,u.shouldTransferToMLTensor=!0);let[a,p]=s0(l),h=!!t?.enableGraphCapture,m=[],g=[],_=[],w=[],y=[];for(let S=0;SS==="gpu-buffer"||S==="ml-tensor"||S==="ml-tensor-cpu-output")&&(c=u._OrtCreateBinding(l),c===0&&Re("Can't create IO binding."),T={handle:c,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map(S=>S==="ml-tensor-cpu-output"?"ml-tensor":S).map(S=>kl(S))}),_r.set(l,[l,r,o,T,h,!1]),[l,m,g,_,w]}catch(a){throw r.forEach(p=>u._OrtFree(p)),o.forEach(p=>u._OrtFree(p)),c!==0&&u._OrtReleaseBinding(c)!==0&&Re("Can't release IO binding."),l!==0&&u._OrtReleaseSession(l)!==0&&Re("Can't release session."),a}finally{u._free(n),d!==0&&u._OrtReleaseSessionOptions(d)!==0&&Re("Can't release session options."),s.forEach(a=>u._free(a)),u.unmountExternalData?.()}},$d=e=>{let t=Be(),n=_r.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,u,l,d,c]=n;d&&(c&&t._OrtClearBoundOutputs(d.handle)!==0&&Re("Can't clear bound outputs."),t._OrtReleaseBinding(d.handle)!==0&&Re("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),u.forEach(s=>t._OrtFree(s)),l.forEach(s=>t._OrtFree(s)),t._OrtReleaseSession(i)!==0&&Re("Can't release session."),_r.delete(e)},Mu=async(e,t,n,i,u,l,d=!1)=>{if(!e){t.push(0);return}let c=Be(),s=c.PTR_SIZE,r=e[0],o=e[1],a=e[3],p=a,h,m;if(r==="string"&&(a==="gpu-buffer"||a==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(d&&a!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(a==="gpu-buffer"){let w=e[2].gpuBuffer;m=cn(dn(r),o);{let y=c.jsepRegisterBuffer;if(!y)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=y(i,l,w,m)}}else if(a==="ml-tensor"){let w=e[2].mlTensor;m=cn(dn(r),o);let y=c.webnnRegisterMLTensor;if(!y)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=y(i,w,dn(r),o)}else{let w=e[2];if(Array.isArray(w)){m=s*w.length,h=c._malloc(m),n.push(h);for(let y=0;yc.setValue(_+T*s,y,s===4?"i32":"i64"));let w=c._OrtCreateTensor(dn(r),h,m,_,o.length,kl(p));w===0&&Re(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(w)}finally{c.stackRestore(g)}},Td=async(e,t,n,i,u,l)=>{let d=Be(),c=d.PTR_SIZE,s=_r.get(e);if(!s)throw new Error(`cannot run inference. invalid session id: ${e}`);let r=s[0],o=s[1],a=s[2],p=s[3],h=s[4],m=s[5],g=t.length,_=i.length,w=0,y=[],T=[],S=[],O=[],A=[],P=d.stackSave(),I=d.stackAlloc(g*c),z=d.stackAlloc(g*c),G=d.stackAlloc(_*c),J=d.stackAlloc(_*c);try{[w,y]=gx(l),hn("wasm prepareInputOutputTensor");for(let v=0;vce*xe,1);K=sr(Y);let le=p?.outputPreferredLocations[i[v]];if(K==="string"){if(le==="gpu-buffer"||le==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ce=[];for(let xe=0;xe0){let ce=d.jsepGetBuffer;if(!ce)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=ce(B),qe=cn(Y,ne);if(qe===void 0||!od(K))throw new Error(`Unsupported data type: ${K}`);V=!0,C.push([K,W,{gpuBuffer:xe,download:d.jsepCreateDownloader(xe,qe,K),dispose:()=>{d._OrtReleaseTensor(R)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(le==="ml-tensor"&&ne>0){let ce=d.webnnEnsureTensor,xe=d.webnnIsGraphInputOutputTypeSupported;if(!ce||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(cn(Y,ne)===void 0||!sd(K))throw new Error(`Unsupported data type: ${K}`);if(!xe(e,K,!1))throw new Error(`preferredLocation "ml-tensor" for ${K} output is not supported by current WebNN Context.`);let qe=await ce(e,B,Y,W,!1);V=!0,C.push([K,W,{mlTensor:qe,download:d.webnnCreateMLTensorDownloader(B,K),dispose:()=>{d.webnnReleaseTensorId(B),d._OrtReleaseTensor(R)}},"ml-tensor"])}else if(le==="ml-tensor-cpu-output"&&ne>0){let ce=d.webnnCreateMLTensorDownloader(B,K)(),xe=C.length;V=!0,ee.push((async()=>{let qe=[xe,await ce];return d.webnnReleaseTensorId(B),d._OrtReleaseTensor(R),qe})()),C.push([K,W,[],"cpu"])}else{let ce=ss(K),xe=new ce(ne);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(d.HEAPU8.subarray(B,B+xe.byteLength)),C.push([K,W,xe,"cpu"])}}finally{d.stackRestore(H),K==="string"&&B&&d._free(B),V||d._OrtReleaseTensor(R)}}p&&!h&&(d._OrtClearBoundOutputs(p.handle)!==0&&Re("Can't clear bound outputs."),_r.set(e,[r,o,a,p,h,!1]));for(let[v,R]of await Promise.all(ee))C[v][2]=R;return fn("wasm ProcessOutputTensor"),C}finally{d.webnnOnRunEnd?.(r),d.stackRestore(P),T.forEach(q=>d._OrtReleaseTensor(q)),S.forEach(q=>d._OrtReleaseTensor(q)),O.forEach(q=>d._free(q)),w!==0&&d._OrtReleaseRunOptions(w),y.forEach(q=>d._free(q))}},Sd=e=>{let t=Be(),n=_r.get(e);if(!n)throw new Error("invalid session id");let i=n[0],u=t._OrtEndProfiling(i);u===0&&Re("Can't get an profile file name."),t._OrtFree(u)},Id=e=>{let t=[];for(let n of e){let i=n[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),vr,At,An,bi,yi,Do,Nu,Mo,Wr,Kr,a0,w$,_$,v$,x$,$$,T$,S$,I$=D(()=>{"use strict";dt(),y$(),vn(),rd(),vr=()=>!!me.wasm.proxy&&typeof document<"u",An=!1,bi=!1,yi=!1,Mo=new Map,Wr=(e,t)=>{let n=Mo.get(e);n?n.push(t):Mo.set(e,[t])},Kr=()=>{if(An||!bi||yi||!At)throw new Error("worker not ready")},a0=e=>{switch(e.data.type){case"init-wasm":An=!1,e.data.err?(yi=!0,Nu[1](e.data.err)):(bi=!0,Nu[0]()),Do&&(URL.revokeObjectURL(Do),Do=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Mo.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},w$=async()=>{if(!bi){if(An)throw new Error("multiple calls to 'initWasm()' detected.");if(yi)throw new Error("previous call to 'initWasm()' failed.");if(An=!0,vr())return new Promise((e,t)=>{At?.terminate(),fx().then(([n,i])=>{try{At=i,At.onerror=l=>t(l),At.onmessage=a0,Nu=[e,t];let u={type:"init-wasm",in:me};!u.in.wasm.wasmPaths&&(n||Al)&&(u.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url).href}),At.postMessage(u),Do=n}catch(u){t(u)}},t)});try{await nd(me.wasm),await _d(me),bi=!0}catch(e){throw yi=!0,e}finally{An=!1}}},_$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:me}};At.postMessage(i)});await vd(me,e)},v$=async e=>vr()?(Kr(),new Promise((t,n)=>{Wr("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};At.postMessage(i,[e.buffer])})):Yo(e),x$=async(e,t)=>{if(vr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Kr(),new Promise((n,i)=>{Wr("create",[n,i]);let u={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),At.postMessage(u,l)})}else return xd(e,t)},$$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("release",[t,n]);let i={type:"release",in:e};At.postMessage(i)});$d(e)},T$=async(e,t,n,i,u,l)=>{if(vr()){if(n.some(d=>d[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(u.some(d=>d))throw new Error("pre-allocated output tensor is not supported for proxy.");return Kr(),new Promise((d,c)=>{Wr("run",[d,c]);let s=n,r={type:"run",in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:i,options:l}};At.postMessage(r,Id(s))})}else return Td(e,t,n,i,u,l)},S$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("end-profiling",[t,n]);let i={type:"end-profiling",in:e};At.postMessage(i)});Sd(e)}}),zu,u0,O$,qk=D(()=>{"use strict";dt(),I$(),de(),td(),yx(),zu=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},u0=e=>{switch(e[3]){case"cpu":return new vt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!od(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:u}=e[2];return vt.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:u})}case"ml-tensor":{let t=e[0];if(!sd(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:u}=e[2];return vt.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:u})}default:throw new Error(`invalid data location: ${e[3]}`)}},O$=class{async fetchModelAndCopyToWasmMemory(e){return v$(await ad(e))}async loadModel(e,t){Jt();let n;typeof e=="string"?n=await this.fetchModelAndCopyToWasmMemory(e):n=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await x$(n,t),Vt()}async dispose(){return $$(this.sessionId)}async run(e,t,n){Jt();let i=[],u=[];Object.entries(e).forEach(a=>{let p=a[0],h=a[1],m=this.inputNames.indexOf(p);if(m===-1)throw new Error(`invalid input '${p}'`);i.push(h),u.push(m)});let l=[],d=[];Object.entries(t).forEach(a=>{let p=a[0],h=a[1],m=this.outputNames.indexOf(p);if(m===-1)throw new Error(`invalid output '${p}'`);l.push(h),d.push(m)});let c=i.map((a,p)=>zu(a,()=>`input "${this.inputNames[u[p]]}"`)),s=l.map((a,p)=>a?zu(a,()=>`output "${this.outputNames[d[p]]}"`):null),r=await T$(this.sessionId,u,c,d,s,n),o={};for(let a=0;aVl,initializeFlags:()=>Ul,wasmBackend:()=>A$});var Ul,Vl,A$,Gk=D(()=>{"use strict";dt(),I$(),qk(),Ul=()=>{(typeof me.wasm.initTimeout!="number"||me.wasm.initTimeout<0)&&(me.wasm.initTimeout=0);let e=me.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),me.wasm.simd=!1),typeof me.wasm.proxy!="boolean"&&(me.wasm.proxy=!1),typeof me.wasm.trace!="boolean"&&(me.wasm.trace=!1),typeof me.wasm.numThreads!="number"||!Number.isInteger(me.wasm.numThreads)||me.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)me.wasm.numThreads=1;else{let t=typeof navigator>"u"?Bu("node:os").cpus().length:navigator.hardwareConcurrency;me.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Vl=class{async init(e){Ul(),await w$(),await _$(e)}async createInferenceSessionHandler(e,t){let n=new O$;return await n.loadModel(e,t),n}},A$=new Vl});dt();dt();dt();var Hk="1.29.0";{let e=(qA(),Nn(ax)).onnxjsBackend;pn("webgl",e,-10)}{let e=(Gk(),Nn(E$)).wasmBackend;pn("webgpu",e,5),pn("webnn",e,5),pn("cpu",e,10),pn("wasm",e,10)}Object.defineProperty(me.versions,"web",{value:Hk,enumerable:!0});function k$(){return me.versions.web??""}function P$(e={}){me.wasm.numThreads=e.wasmThreads??1,e.wasmPaths!==void 0&&(me.wasm.wasmPaths=e.wasmPaths)}var as=[];function Od(){let e=as;return as=[],e}async function us(e,t,n){for(let i of t){let u=null;try{let l=performance.now();u=await Qo.create(e.slice().buffer,{executionProviders:[i]});let d=performance.now();if(await n(u))return{session:u,ep:i,createMs:d-l,firstRunMs:performance.now()-d};as.push(`${i}: the model does not have the inputs and outputs the release describes`)}catch(l){as.push(`${i}: ${l instanceof Error?l.message:String(l)}`.slice(0,300))}await u?.release().catch(()=>{})}return null}function qn(e,t){return new vt("float32",e,t)}function Ed(e){return{cx:e.x+e.width/2,cy:e.y+e.height/2,w:e.width,h:e.height,angle:0}}function Gn(e,t){let n=Math.max(e.x,t.x),i=Math.max(e.y,t.y),u=Math.min(e.x+e.width,t.x+t.width),l=Math.min(e.y+e.height,t.y+t.height);if(u<=n||l<=i)return 0;let d=(u-n)*(l-i);return d/(e.width*e.height+t.width*t.height-d)}function Ad(e,t,n,i){let u=[...e].sort((d,c)=>n(c)-n(d)),l=[];for(let d of u){let c=t(d);l.every(s=>Gn(c,t(s))O&&(O=P,S=A)}O>=l&&(c.push(w),s.push(O),r.push(S))}let o=c.length;if(o===0)return[];let a=new Float32Array(o),p=new Float32Array(o),h=new Float32Array(o),m=new Float32Array(o);for(let w=0;wy).sort((w,y)=>s[y]-s[w]||w-y),_=[];for(;g.length>0;){let w=g[0];if(_.push(w),g.length===1)break;let y=Qe(Qe(h[w]-a[w])*Qe(m[w]-p[w])),T=[];for(let S=1;S{let y={x:a[w]/n,y:p[w]/n,width:Qe(h[w]-a[w])/n,height:Qe(m[w]-p[w])/n};return{aabb:y,rect:Ed(y),score:s[w],cls:r[w]}})}function ls(e,t,n,i=Hn){let u=Math.trunc(Math.max(0,e.x)),l=Math.trunc(Math.max(0,e.y)),d=Math.trunc(Math.min(t,e.x+e.width)),c=Math.trunc(Math.min(n,e.y+e.height));return d-u>=i&&c-l>=i}function R$(e,t,n,i,u,l=kd,d=Hn){return C$(e,t,n,l).filter(c=>ls(c.aabb,i,u,d))}function Xk(e,t,n,i,u){let l=i/t,d=u/n;return[Math.max(0,e.x*l),Math.max(0,e.y*d),Math.min(i,(e.x+e.width)*l),Math.min(u,(e.y+e.height)*d)]}function D$(e,t){let n=e.aabb;if(n.x>=0&&n.y>=0&&n.x+n.width<=t.width&&n.y+n.height<=t.height)return e;let[i,u,l,d]=Xk(n,t.width,t.height,t.width,t.height),c={x:i,y:u,width:Math.max(0,l-i),height:Math.max(0,d-u)};return{...e,aabb:c,rect:Ed(c)}}function M$(e,t=Rr){let n=[],i=[];for(let u of e)(u.cls===t?n:i).push(u);return{faces:n,others:i}}function Zk(e){return e<0&&(e=-e),e<1?1-e:0}function N$(e,t){let n=e/t,i=n<1?1:n,u=i,l=Math.ceil(u)*2+1,d=new Int32Array(t*2),c=new Int32Array(t*l),s=new Float64Array(l);for(let r=0;re&&(m=e),m-=h;for(let g=0;g>22;return t<0?0:t>255?255:t}var z$="",Pd=null,Cd=null;function Yk(e,t,n,i){let u=`${e}x${t}>${n}x${i}`;return(u!==z$||!Pd||!Cd)&&(Pd=N$(e,n),Cd=N$(t,i),z$=u),{h:Pd,v:Cd}}function cs(e,t,n,i,u){let{h:l,v:d}=Yk(t,n,i,u),c=i!==t,s=u!==n,r,o;if(c){let w=s?d.bounds[0]:0,T=(s?d.bounds[u*2-2]+d.bounds[u*2-1]:n)-w;o=w,r=new Uint8Array(i*T*3);let{ksize:S,bounds:O,kk:A}=l;for(let P=0;P.5?t+1:n<.5||t%2===0?t:t+1}function Rd(e,t,n=ps){let i=Math.min(n.height/t,n.width/e);return{ratio:i,width:B$(e*i),height:B$(t*i)}}function Jk(e,t,n,i=ps){let u=Rd(t,n,i),l=cs(e,t,n,u.width,u.height),d=new Uint8Array(i.width*i.height*3).fill(i.pad);for(let c=0;c{let o=(await s.run({[n.inputName]:qn(new Float32Array(3*u*l),[1,3,l,u])}))[n.outputName]?.dims??[];return o.length===3&&o[0]===1&&o[1]===n.anchors&&o[2]===d});return c?new e(c.session,c.ep,n,{createMs:c.createMs,firstRunMs:c.firstRunMs}):null}async propose(t){let{letterbox:n,inputName:i,outputName:u,decode:l,minCropPx:d}=this.settings,c=performance.now(),{tensor:s,ratio:r}=Dd(t.data,t.width,t.height,n),o=performance.now(),a=await this.session.run({[i]:qn(s,[1,3,n.height,n.width])});return this.lastTimings={preprocessMs:o-c,inferMs:performance.now()-o},R$(a[u].data,this.columns,r,t.width,t.height,l,d)}async release(){await this.session.release().catch(()=>{})}};var Qk=32;async function eP(e,t,n,i,u=Qk){if(n<=u)return e(t,n);let l=t.length/n,d=new Float32Array(n*i);for(let c=0;c(await d.run({[n.inputName]:qn(new Float32Array(3*u*u),[1,3,u,u])}))[n.outputName]?.data.length===n.dim);return l?new e(l.session,l.ep,n,{createMs:l.createMs,firstRunMs:l.firstRunMs}):null}async embedBatch(t,n){return eP((i,u)=>this.run(i,u),t,n,this.settings.dim)}async run(t,n){let{inputName:i,outputName:u,inputSize:l,dim:d}=this.settings,s=(await this.session.run({[i]:qn(t,[n,3,l,l])}))[u].data;if(s.length!==n*d)throw new Error(`unexpected embedding size ${s.length} for ${n} crops`);return s}async release(){await this.session.release().catch(()=>{})}};var tP=["orb","akaze","sift"];var rP={orb:[["scaleFactor",1.2,!1],["nLevels",8,!0],["edgeThreshold",15,!0],["patchSize",15,!0],["fastThreshold",10,!0]],akaze:[["threshold",.001,!1],["nOctaves",4,!0],["nOctaveLayers",4,!0]],sift:[["nOctaveLayers",3,!0],["contrastThreshold",.04,!1],["edgeThreshold",10,!1],["sigma",1.6,!1]]},RD=Object.fromEntries(tP.map(e=>[e,Object.fromEntries(rP[e].map(([t,n])=>[t,n]))])),DD=Object.freeze({seed:0,features:{type:"orb",maxFeatures:300,artLongSide:320,mask:[],params:{}},crop:{longSide:320,maxFeatures:500},candidates:{embeddingTopK:5,voteTopN:0},vote:{matcher:"bf",ratio:.8,lshTables:12,lshKeySize:20,lshProbes:2,kdTrees:4,checks:64},match:{ratio:.8},ransac:{model:"homography",method:"ransac",threshold:6,maxIters:2e3,confidence:.995,minAreaRatio:.25,maxAreaRatio:4},fusion:{weight:.1,minInliers:8,fullInliers:30,penalty:0,baseline:"none",reorder:!0},gate:{belowAccept:!1,sources:null}}),nP=["features","crop","candidates","vote","match","ransac","fusion","gate"],MD=["index","seed",...nP];var zD=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function F$(e,t,n){let i=new Float64Array(e);for(let u of t){let l=u.fused-u.cosine;for(let d of n(u.cardId))i[d]=i[d]+l}return i}var iP=10n;function oP(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let n=t.getUint32(0),i=t.getUint32(4),u=n>>>31?-1n:1n,l=n>>>20&2047,d=BigInt(n&1048575)<<32n|BigInt(i),c;return l===0?c=-1074:(d|=1n<<52n,c=l-1075),{mantissa:u*d,exponent:c}}function Ui(e,t){if(!Number.isFinite(e)||e===0)return e;let{mantissa:n,exponent:i}=oP(e),u=n<0n,d=(u?-n:n)*iP**BigInt(t),c=1n;i>=0?d<<=BigInt(i):c<<=BigInt(-i);let s=d/c,o=2n*(d-s*c);if((o>c||o===c&&s%2n===1n)&&(s+=1n),s===0n)return u?-0:0;let a=`${u?"-":""}${s.toString()}e-${t}`;return Number(a)}function sP(e){return{cardId:e.cardId,cosine:Ui(e.cosine,6),foundBy:e.foundBy,votes:e.votes,matches:e.matches,inliers:e.inliers,evidence:Ui(e.evidence,6),fused:Ui(e.fused,6)}}function L$(e,t){return{before:{topId:e.topId,similarity:Ui(e.similarity,6),margin:Ui(e.margin,6),accepted:e.accepted},candidates:t.candidates.map(sP),...t.debug?{debug:t.debug}:{}}}var aP=23,jD=(1<!n.representative.has(d))??[...u].sort()[0];for(let d of u)i.set(d,`group:${n.representative.get(d)??l}`)}return i}var Wn="file:///";function U$(e){let t=new URL(e,Wn).href.slice(Wn.length);try{return decodeURIComponent(t)}catch{return t}}var V$="busy";var er={full128:{id:"full128",size:128,centerMask:!1,poolVersion:2,crop:"truncate"}};function Md(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(er,e)}function hs(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(!Md(t.id))return null;let n=er[t.id],i=Object.keys(t);return i.length===Object.keys(n).length&&i.every(l=>n[l]===t[l])?t.id:null}function G$(e,t,n,i,u,l){let d=new Float64Array(i*u*3),c=new Uint32Array(i*u);for(let a=0;a0&&(d[a*3]=d[a*3]/p,d[a*3+1]=d[a*3+1]/p,d[a*3+2]=d[a*3+2]/p)}if(l===1||t>=i&&n>=u||t<=0||n<=0)return d;let s=q$(n,u),r=q$(t,i),o=new Float64Array(d.length);for(let a=0;a=0&&!n[l];)l--;let d=u+1;for(;d=0&&(d>=t||u-l<=d-u)?l:d}return i}function fs(e,t,n,i){let u=i.size,l=G$(e,t,n,u,u,i.poolVersion),d=new Float32Array(3*u*u),c=u*u;for(let s=0;s>10&31,s=l&1023;c===0?i[u]=d*s*2**-24:c===31?i[u]=s?NaN:d*(1/0):i[u]=d*(1+s/1024)*2**(c-15)}return i}function lP(e,t){let n;try{n=atob(e)}catch{return null}if(n.length!==t*2)return null;let i=new Uint8Array(n.length);for(let u=0;u0)||!Number.isFinite(u))return!1;for(let l=0;l=Kn.length&&Kn.every((t,n)=>e[n]===t)}function Bd(e){return zd(e)&&e.length>Kn.length?e[Kn.length]:null}function X$(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);if(Bd(t)!==gs||t.lengthtypeof a=="string")||u.entryCount!==d.length)return null;let c=u.artVs;if(c!==void 0&&(!Array.isArray(c)||c.length!==d.length||!c.every(a=>a===null||typeof a=="string")))return null;let s=l.dim,r=Vi+n;if(t.length-r!==d.length*s*2)return null;let o=new Float32Array(d.length*s);for(let a=0;a({x:i+p*s-h*r,y:u+p*r+h*s}))}}function Z$(e,t){let{points:n}=t,i=0;for(let u=0;u0?1:-1;if(i===0)i=p;else if(p!==i)return!1}return!0}function Ld(e,t){let n=null;for(let i of t)Z$(e,i.quad)&&(!n||i.zIndex>=n.zIndex)&&(n=i);return n?n.card:null}function Xn(e){return e<0?0:e>1?1:e}function bs(e,t){let{frameWidth:n,frameHeight:i,names:u}=t;return e.map(l=>{let{aabb:d}=l,c=l.identity?u.get(l.identity):void 0,s=c!==void 0&&l.outline?l.outline:l.rect,r={instanceId:l.instanceId,bounds:{x:Xn(d.x/n),y:Xn(d.y/i),width:Xn(d.width/n),height:Xn(d.height/i)},rotation:(s.angle+45)%90-45,localWidth:Xn(s.w/n),localHeight:Xn(s.h/i),landscape:s.w>s.h,cardId:null,name:null};return l.identity&&c!==void 0&&(r.cardId=l.identity,r.name=c),r})}var J$=["accepted-nms","best-score","detector-score"];function Q$(e){return typeof e=="string"&&J$.includes(e)}var jd="accepted-nms",pP=.5,hP="hover_";function Y$(e){return e.width*e.height}function eT(e,t){let n=t==="accepted-nms"?e.kept:e.proposals.map((u,l)=>l),i=(u,l)=>{let d=e.proposals[u],c=e.proposals[l];if(t==="detector-score")return d.detectorScore!==c.detectorScore?d.detectorScore{let u=e.proposals[n];return{proposal:n,aabb:u.aabb,rect:u.rect,...u.outline?{outline:u.outline}:{},identity:u.accepted?u.displayId:null,score:u.score,zIndex:i+1}})}var ys=class{prev=[];nextId=1;reset(){this.prev=[]}assign(t){let n=new Set,i=t.map((l,d)=>d).sort((l,d)=>t[d].zIndex-t[l].zIndex),u=new Array(t.length);for(let l of i){let d=t[l],c=-1,s=pP;for(let r=0;r=s&&(c<0||o>s)&&(c=r,s=o)}c>=0?(n.add(c),u[l]=this.prev[c].id):u[l]=`${hP}${String(this.nextId++).padStart(4,"0")}`}return this.prev=t.map((l,d)=>({id:u[d],aabb:l.aabb,identity:l.identity})),u}};function ws(e,t,n,i=u=>u){return bs(e.map((l,d)=>({instanceId:t[d],aabb:l.aabb,rect:l.rect,...l.outline?{outline:l.outline}:{},identity:l.identity})),n).map((l,d)=>({...l,zIndex:e[d].zIndex,boxIndex:i(e[d].proposal)}))}var fP={card:null,boxIndex:null,box:null,cardId:null,name:null};function Ud(e,t,n){let i=e.map(l=>({card:l,quad:Fd(l,n),zIndex:l.zIndex??0})),u=Ld(t,i);return u?{card:u,boxIndex:u.boxIndex??null,box:{x:u.bounds.x*n.width,y:u.bounds.y*n.height,width:u.bounds.width*n.width,height:u.bounds.height*n.height},cardId:u.cardId,name:u.name}:fP}var mP="identity-groups";function Vd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.schemaVersion!==1||t.kind!==mP||typeof t.version!="number"||!Number.isInteger(t.version)||!Array.isArray(t.groups)||typeof t.representative!="object"||t.representative===null||Array.isArray(t.representative))return null;let n=new Map,i=[];for(let l of t.groups){if(!Array.isArray(l)||l.length<2)return null;let d=[];for(let c of l){if(typeof c!="string"||c.length===0||n.has(c))return null;n.set(c,i.length),d.push(c)}i.push(d)}let u=new Map;for(let[l,d]of Object.entries(t.representative)){if(typeof d!="string"||l===d)return null;let c=n.get(l);if(c===void 0||n.get(d)!==c)return null;u.set(l,d)}for(let l of i){let d=l.filter(c=>!u.has(c));if(d.length!==1||l.some(c=>u.has(c)&&u.get(c)!==d[0]))return null}return{version:t.version,groups:i,representative:u}}var gP=["name","printing"];function qd(e){return gP.includes(e)}function rT(e,t){return t==="printing"?e.printingOf??e.id:e.name}function nT(e,t){let n=new Map;for(let i of[...new Set(e)].sort(tT)){let u=t.get(i);if(u===void 0)continue;let l=n.get(u);l?l.push(i):n.set(u,[i])}return[...n.values()].filter(i=>i.length>=2).sort((i,u)=>tT(i[0],u[0]))}function tT(e,t){return et?1:0}var Tn=class{rep=new Map;display;constructor(t=null,n,i="representative"){if(this.display=i,!!t)for(let[u,l]of t.representative)i==="representative"&&n&&!n(l)||this.rep.set(u,l)}of(t){return this.rep.get(t)??t}shown(t){return this.display==="best-printing"?t:this.of(t)}get collapsedCount(){return this.rep.size}};var _s=["webgpu","wasm"];function Gd(e,t=e.hover.selection){let n=e.boxes.flatMap((s,r)=>s.face!==null?[r]:[]),i=n.map(s=>e.boxes[s]),u=new Map,l=i.map(s=>{let r=s.face;r.cardId!==null&&r.name!==null&&u.set(r.cardId,r.name);let o={x:s.box[0],y:s.box[1],width:s.box[2],height:s.box[3]};return{aabb:o,rect:{cx:o.x+o.width/2,cy:o.y+o.height/2,w:o.width,h:o.height,angle:0},score:r.similarity,detectorScore:s.score,accepted:r.cardId!==null,displayId:r.cardId??r.topId}}),d=i.flatMap((s,r)=>s.face.kept?[r]:[]),c=qi({proposals:l,kept:d},t);return ws(c,c.map((s,r)=>`${t}_${r}`),{frameWidth:e.frame.width,frameHeight:e.frame.height,names:u},s=>n[s])}function vs(e,t,n,i){let u=i===void 0||i===e.hover.selection?e.hover.cards:Gd(e,i);return Ud(u,{x:t,y:n},e.frame)}var fe=Math.fround,iT=63/88,bP=128,Tt=90,yP=.2,wP=8,_P=.35,vP=.55,xP=.9,$P=Object.freeze({scales:[.95,1,1.05],maxFacesPerFrame:8,budgetMs:1500}),TP=[1,.8824969025845955,.6065306597126334,.32465246735834974,.1353352832366127,.04393693362340742,.011108996538242306],oT=6,SP=fe(fe(180)/fe(Math.PI)),Hd=[fe(.299),fe(.587),fe(.114)];function IP(e){let t=e-90*Math.ceil((e-45)/90);return t<=-45?45:t}function OP(e,t){let n=e%t;return n!==0&&n<0!=t<0?n+t:n}function EP(e,t){let n=e%t;return n===0?0:n<0?fe(n+t):n}function sT(e){let t=Math.floor(e),n=e-t;return n<.5?t:n>.5?t+1:t%2===0?t:t+1}function AP(e,t){let n=e.length,i=Float32Array.from(e).sort(),u=fe(t),l=fe(fe(fe(n*u)+fe(1+fe(u*-1)))-1),d,c;l>=n-1?d=c=n-1:l<0?d=c=0:(d=Math.floor(l),c=d+1);let s=d===c?0:fe(l-d),r=i[d],o=i[c],a=fe(o-r);return s>=.5?fe(o-fe(a*fe(1-s))):fe(r+fe(a*s))}function Wd(e){let{width:t,height:n}=e,i=e.channels??4,u=Math.max(1,Math.ceil(Math.max(n,t)/bP)),l=u===1?n:Math.floor(n/u),d=u===1?t:Math.floor(t/u);if(Math.min(l,d)c[Math.min(l-1,Math.max(0,C))*d+Math.min(d-1,Math.max(0,ee))],o=l-2,a=d-2,p=o*a,h=new Float32Array(p),m=new Float32Array(p),g=new Uint8Array(p),_=new Float32Array(p),w=0,y=0;for(let C=0;Cy&&(y=_[B]))}if(y<=0)return 0;let T=new Float32Array(w);for(let C=0,ee=0;C=S)||!(ee>0))continue;let v=EP(fe(fe(Math.atan2(m[C],h[C]))*SP),90),R=Math.min(Math.trunc(fe(fe(v/90)*Tt)),Tt-1);O[R]=O[R]+ee}let A=new Float64Array(Tt);for(let C=0;CA[P]&&(P=C);let I=A[(P-1+Tt)%Tt],z=A[(P+1)%Tt],G=I-2*A[P]+z,J=G!==0?.5*(I-z)/G:0,q=OP((P+.5+J)*90/Tt,90);return IP(q)}var aT=1;function Kd(e,t,n){let i=Math.abs(n)*(Math.PI/180),u=Math.cos(i),l=Math.sin(i),d=u*u-l*l;if(d>_P){let s=(e*u-t*l)/d,r=(t*u-e*l)/d;if(s>0&&r>0){let o=Math.min(s,r)/Math.max(s,r);if(o>=vP&&o<=xP)return{w:s,h:r,how:"exact"}}}let c=null;for(let s of[iT,1/iT]){let r=s*u+l,o=s*l+u,a=(e*r+t*o)/(r*r+o*o),p=(e-a*r)**2+(t-a*o)**2;(c===null||pw>=0&&w=0&&yuT(e,c,s,l*r,d*r,u))}}function lT(e,t,n){if(Math.abs(e)!["scales","maxFacesPerFrame","budgetMs"].includes(l));if(n.length>0)return`tiltedRetry has unknown key(s) ${n.sort().join(", ")}`;let i=t.scales;if(!Array.isArray(i)||i.length<1||i.length>5||!i.every(l=>typeof l=="number"&&Number.isFinite(l)&&l>=.5&&l<=1.5))return"tiltedRetry.scales must list 1 to 5 numbers from 0.5 to 1.5";let u=l=>typeof l=="number"&&Number.isInteger(l)&&l>=1;return u(t.maxFacesPerFrame)?u(t.budgetMs)?null:"tiltedRetry.budgetMs must be a whole number above 0":"tiltedRetry.maxFacesPerFrame must be a whole number above 0"}var kP=.3;function hT(e,t){let n=Math.max(0,Math.floor(t.x)),i=Math.max(0,Math.floor(t.y)),u=Math.min(e.width,Math.floor(t.x+t.width)),l=Math.min(e.height,Math.floor(t.y+t.height)),d=Math.max(0,u-n),c=Math.max(0,l-i),s=new Uint8ClampedArray(d*c*4);for(let r=0;r=t.tau&&e.margin>=t.delta}function fT(e,t,n){if(lr(e,n)||!n.rotationRetry)return{orientation:0,match:e,retried:!1};let i=[e,...t()],u=-1;for(let l=0;li[u].similarity)&&(u=l);if(u<0){u=0;for(let l=1;li[u].similarity&&(u=l)}return{orientation:u,match:i[u],retried:!0}}function cT(e){let t=[],n=[];return e.forEach((i,u)=>{let l=i.tilted!==void 0&&i.tilted.scale!==null;i.tauPassed&&(i.orientation===0&&!l?t:n).push(u)}),[...t,...n]}function pT(e,t){let n=(t??e.map((i,u)=>u)).filter(i=>e[i].tauPassed);return Ad(n,i=>e[i].aabb,i=>e[i].score,kP)}async function Yd(e,t,n,i,u=Hn,l=null,d=null,c=!1){let s=n.preprocessing,r=n.rule,o=s.size,a=n.dim,p=[],h=[],m=[];for(let N of i){let X=hT(e,N.aabb),{rgba:W,width:ne,height:le}=X;nen.matchScored(w,X*a)),T=[];if(r.rotationRetry)for(let N=0;N[N,X])),O=null;if(T.length>0){let N=new Float32Array(T.length*3*g);for(let X=0;X{let W=S.get(N);if(W===void 0||O===null)throw new Error(`the turned looks of proposal ${N} were not embedded`);return(W*3+X-1)*a},P=h.map((N,X)=>fT(y[X],()=>[1,2,3].map(W=>n.matchScored(O,A(X,W))),r)),I=N=>P[N].orientation===0?{embs:w,off:N*a}:{embs:O,off:A(N,P[N].orientation)},z=new Map,G,J,q=!1;if(l)try{let N=performance.now(),X=[],W=[],ne=[];for(let le=0;le0){let le=await l.verifyBatch(ne,n.bankIds);X.forEach((ce,xe)=>{let qe=le[xe],Ve=W[xe],it=P[ce].match,Ze=F$(Ve,qe.candidates,zr=>n.columnsOf(zr)),$e=l.reorder?n.lookOf(Ze):n.lookWithin(Ze,n.lookOf(Ve).row),{row:ht,...It}=$e;z.set(ce,{match:It,geometric:L$({topId:it.topId,similarity:it.similarity,margin:it.margin,accepted:lr(it,r)},qe)})})}G=performance.now()-N}catch(N){q=!0,J=N,z.clear(),G=void 0}let C=new Map,ee,v,R=!1,H=0;if(d)try{let N=performance.now(),{scales:X,maxFacesPerFrame:W}=d.settings,ne=ce=>z.get(ce)?.match??P[ce].match,le=mT(h.map((ce,xe)=>({aabb:ce.aabb,similarity:P[xe].match.similarity,accepted:lr(ne(xe),r)})),d.focus??null).slice(0,W);if(le.length>0){let ce=[],xe=new Float32Array(le.length*X.length*g);le.forEach((Ve,it)=>{let Ze=m[Ve],{tilt:$e,rects:ht}=Xd(e,h[Ve].aabb,{data:Ze.rgba,width:Ze.width,height:Ze.height},X);ce.push($e),ht.forEach((It,zr)=>{let Gt=fs(It.rgba,It.width,It.height,s);xe.set(ms(Gt,P[Ve].orientation,o),(it*X.length+zr)*g)})}),H=le.length*X.length;let qe=await t.embedBatch(xe,H);le.forEach((Ve,it)=>{let Ze=ne(Ve),$e=null;for(let ht=0;ht$e.match.similarity)&&($e={q:ht,match:It})}C.set(Ve,{match:$e?$e.match:null,evidence:{tilt:ce[it],scale:$e?X[$e.q]:null,before:{topId:Ze.topId,similarity:Ze.similarity,margin:Ze.margin}}})})}ee=performance.now()-N}catch(N){R=!0,v=N,C.clear(),H=0,ee=void 0}let L=new Map,V=N=>{let X=L.get(N);if(X===void 0){let{aabb:W}=h[N],ne=m[N],{tilt:le,w:ce,h:xe}=Zd({data:ne.rgba,width:ne.width,height:ne.height},W.width,W.height);X={cx:W.x+W.width/2,cy:W.y+W.height/2,w:ce,h:xe,angle:le},L.set(N,X)}return X},K=N=>{let X=[];for(let W=0;Wt!==null&&t.x>=d.x&&t.x<=d.x+d.width&&t.y>=d.y&&t.y<=d.y+d.height,i=e.map((d,c)=>c).filter(d=>!e[d].accepted),u=i.filter(d=>n(e[d].aabb)).sort((d,c)=>e[d].aabb.width*e[d].aabb.height-e[c].aabb.width*e[c].aabb.height),l=i.filter(d=>!n(e[d].aabb)).sort((d,c)=>e[c].similarity-e[d].similarity);return[...u,...l]}var $s={tau:.62,delta:.05,rotationRetry:!0},xs=-2,Gi=class{constructor(t,n=$s,i=new Tn){this.bank=t;this.rule=n;this.contract=er[t.preprocessing],this.rowShown=t.ids.map(l=>i.shown(l));let u=new Map;this.rowIdent=new Int32Array(t.ids.length);for(let l=0;lc&&(c=p,s=a)}let r=xs,o=s>=0?this.rowIdent[s]:-1;for(let a=0;ar&&(r=d[a]);return{bestRow:s,best:c,other:r}}matchScored(t,n){let{bestRow:i,best:u,other:l}=this.topAndOther(t,n),d=this.bank.ids[i];return{cardId:u>=this.rule.tau?d:null,similarity:u,topId:d,identity:this.identRep[this.rowIdent[i]],displayId:this.rowShown[i],margin:u-l}}scoreRow(t,n){let{matrix:i,dim:u,ids:l}=this.bank,d=new Float64Array(l.length);for(let c=0;cd);n.sort((l,d)=>t[d]-t[l]);let i=new Set,u=[];for(let l of n){let d=this.bank.ids[l];i.has(d)||(i.add(d),u.push({cardId:d,cosine:t[l]}))}return u}columns=null;columnsOf(t){return this.columns===null&&(this.columns=new Map,this.bank.ids.forEach((n,i)=>{let u=this.columns.get(n);u?u.push(i):this.columns.set(n,[i])})),this.columns.get(t)??[]}bankIdSet=null;get bankIds(){return this.columnsOf(""),this.bankIdSet??=new Set(this.columns.keys()),this.bankIdSet}scored(t,n,i){let u=this.bank.ids[t];return{cardId:n>=this.rule.tau?u:null,similarity:n,topId:u,identity:this.identRep[this.rowIdent[t]],displayId:this.rowShown[t],margin:n-i,row:t}}lookOf(t){let n=0;for(let d=1;dt[n]&&(n=d);let i=this.rowIdent[n],u=xs,l=!1;for(let d=0;du)&&(u=t[d]),l=!0);return this.scored(n,t[n],u)}lookWithin(t,n){let i=this.rowIdent[n],u=-1,l=xs,d=!1;for(let c=0;ct[u])&&(u=c):((!d||t[c]>l)&&(l=t[c]),d=!0);return this.scored(u,t[u],l)}matchPooled(t,n=this.rule.delta){let{bestRow:i,best:u,other:l}=this.topAndOther(t,0),d=u-l;return{cardId:u>=this.rule.tau&&d>=n?this.rowShown[i]:null,similarity:u,margin:d}}};var Hi=class{constructor(t=3){this.k=t;if(!Number.isInteger(t)||t<1)throw new RangeError(`k must be a positive integer, got ${t}`)}k;run=0;misses=0;showing=!1;reset(){this.run=0,this.misses=0,this.showing=!1}observe(t){return t?(this.run+=1,this.misses=0,this.run>=this.k&&(this.showing=!0)):(this.run=0,this.misses+=1,this.misses>=this.k&&(this.showing=!1)),{confirmed:this.showing,consecutive:this.run}}};var PP=.4,CP=2,RP=5,DP=2,MP="track_";function gT(e){let t=e[0].length,n=new Float32Array(t);for(let l of e)for(let d=0;d0))return null;for(let l=0;lu));for(let i of this.tracks){let u=-1,l=PP;for(let d of n){let c=Gn(i.detection.aabb,t[d].aabb);c>l&&(l=c,u=d)}if(u>=0){let d=t[u];i.detection=d,i.misses=0,i.age+=1,i.embeddings.push(d.embedding),i.embeddings.length>RP&&i.embeddings.shift(),n.delete(u)}else i.misses+=1}this.tracks=this.tracks.filter(i=>i.misses<=CP);for(let i of n){let u=t[i];this.tracks.push({instanceId:`${MP}${String(this.nextId++).padStart(4,"0")}`,detection:u,embeddings:[u.embedding],misses:0,age:1})}return this.tracks.filter(i=>i.misses===0).map(i=>({instanceId:i.instanceId,detection:i.detection,identity:i.age>=DP?this.identityOf(i):null}))}};var NP=.25,zP=5;function BP(e,t){if(e===null||t===void 0)return!1;let n=t-e;return n<-NP||n>zP}function FP(e){return[e.x,e.y,e.width,e.height]}var Ki=class{hoverSelection;detector;embedder;recognizer;names;classNames;faceClass;minCropPx;now;tracker;gate=new Hi(3);hoverIds=new ys;heldCards=[];lastVideoTimeSec=null;geometric;geometricFailure=null;tiltedRetry;tiltedFailure=null;constructor(t){this.detector=t.detector,this.embedder=t.embedder,this.names=t.names,this.classNames=t.classNames??["face","back"],this.faceClass=t.faceClass??Rr,this.minCropPx=t.minCropPx??Hn,this.hoverSelection=t.hoverSelection??jd,this.now=t.now??(()=>performance.now()),this.geometric=t.geometric??null,this.tiltedRetry=t.tiltedRetry??null;let n=new Tn(t.identityGroups??null,i=>this.names.has(i),t.identityDisplay??"best-printing");this.recognizer=new Gi(t.bank,t.accept??$s,n),this.tracker=new Wi(i=>this.recognizer.matchPooled(i).cardId)}get size(){return this.recognizer.size}takeGeometricFailure(){let t=this.geometricFailure;return this.geometricFailure=null,t}takeTiltedFailure(){let t=this.tiltedFailure;return this.tiltedFailure=null,t}get tiltedSettings(){return this.tiltedRetry}setTiltedRetry(t){this.tiltedRetry=t,this.tiltedFailure=null}get geometricStage(){return this.geometric}setGeometric(t){this.geometric=t,this.geometricFailure=null}reset(){this.tracker.reset(),this.gate.reset(),this.heldCards=[],this.hoverIds.reset(),this.lastVideoTimeSec=null}async analyze(t,n,i={}){let u=this.now(),l=BP(this.lastVideoTimeSec,n);l&&this.reset(),n!==void 0&&(this.lastVideoTimeSec=n);let d=await this.detector.propose(t),c=this.now()-u,s=d.filter(I=>ls(I.aabb,t.width,t.height,this.minCropPx)).map(I=>D$(I,t)),{faces:r}=M$(s,this.faceClass),o=this.now(),a=this.tiltedRetry&&i.tilted!==!1?{settings:this.tiltedRetry,focus:i.focus??null}:null,p=await Yd(t,this.embedder,this.recognizer,r,this.minCropPx,this.geometric,a,i.rotatedOutlines===!0),h=this.now()-o;if(p.tiltedError!==void 0&&this.tiltedRetry&&(this.tiltedFailure={error:p.tiltedError},this.tiltedRetry=null),p.geometricError!==void 0&&this.geometric&&(this.geometricFailure={stage:this.geometric,error:p.geometricError},this.geometric=null),p.proposals.length!==r.length)throw new Error("pipeline: a valid face box was not recognized");let m={frameWidth:t.width,frameHeight:t.height,names:this.names},g=qi(p,this.hoverSelection),_=r.map(I=>s.indexOf(I)),w=ws(g,this.hoverIds.assign(g),m,I=>_[I]),y=p.base??p,T=y.kept.map(I=>{let z=y.proposals[I];return{aabb:z.aabb,rect:z.rect,cardId:z.topId,embedding:z.embedding,...z.outline?{outline:z.outline}:{}}}),S=this.tracker.update(T),O=T.length>0,A=this.gate.observe(O),P;return A.confirmed?O?(P=bs(S.map(I=>({instanceId:I.instanceId,aabb:I.detection.aabb,rect:I.detection.rect,...I.detection.outline?{outline:I.detection.outline}:{},identity:I.identity})),m),this.heldCards=P):P=this.heldCards:(this.heldCards=[],P=[]),{frame:{width:t.width,height:t.height},boxes:this.boxResults(s,r,p),hover:{selection:this.hoverSelection,cards:w},tracks:{shown:A.confirmed,cards:P},discontinuity:l,retried:p.retried,embeddings:p.embeddings,timings:{detectorMs:c,recognizeMs:h,analyzeMs:this.now()-u,...p.geometricMs!==void 0?{geometricMs:p.geometricMs}:{},...p.tiltedMs!==void 0?{tiltedMs:p.tiltedMs}:{}}}}boxResults(t,n,i){let u=new Map(n.map((d,c)=>[d,c])),l=new Set(i.kept);return t.map(d=>{let c=u.get(d),s=null;if(c!==void 0){let r=i.proposals[c],o=r.accepted&&this.names.has(r.displayId)?r.displayId:null;s={topId:r.topId,topName:this.names.get(r.topId)??null,similarity:r.score,margin:r.margin,look:r.orientation,retried:r.retried,tauPassed:r.tauPassed,accepted:r.accepted,cardId:o,name:o===null?null:this.names.get(o)??null,kept:l.has(c),...r.geometric?{geometric:r.geometric}:{},...r.tilted?{tilted:r.tilted}:{}}}return{box:FP(d.aabb),score:d.score,cls:d.cls,className:this.classNames[d.cls]??String(d.cls),face:s}})}};var bT=1,yT="vision-release",LP=[8,16,32];function wT(e,t){return LP.reduce((n,i)=>n+Math.floor(e/i)*Math.floor(t/i),0)}var jP=/^[0-9a-f]{16}$/,UP=/^[0-9a-f]{64}$/,VP=/^\d+\.\d+\.\d+$/,qP=["schemaVersion","kind","id","game","locale","detector","recognizer","bank","identity","catalog","accept","hover","runtime","tiltedRetry"],_T=["tau","delta","rotationRetry"],Ue=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ft=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,Ji=e=>typeof e=="number"&&Number.isFinite(e),tt=e=>typeof e=="string"&&e.trim()!=="";function GP(e){return!tt(e)||e.includes("\\")||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e)||/[\x00-\x1f\x7f]/.test(e)||/^ | $/.test(e)||e.startsWith("/")?!1:!e.split("/").some(t=>{let n=t.replace(/%2e/gi,".");return n==="."||n===".."})}function Zi(e){return!Ue(e)||!GP(e.path)||typeof e.sha256!="string"||!UP.test(e.sha256)||!ft(e.bytes)?null:{path:e.path,sha256:e.sha256,bytes:e.bytes}}function HP(e){let t=e.input,n=e.decode;if(!Ue(t)||!ft(t.width)||!ft(t.height))return"detector.input must give a width and a height";if(!Ue(n))return"detector.decode must be an object";if(!tt(n.inputName)||!tt(n.outputName))return"detector.decode must name the model's input and output";let i=[["layout","NCHW"],["channels","BGR"],["scale","0-255"],["score","obj * max(cls)"],["class","argmax(cls)"]];for(let[o,a]of i)if(n[o]!==a)return`detector.decode.${o} is not ${JSON.stringify(a)}, the contract this runtime implements`;let u=n.letterbox;if(!Ue(u)||u.width!==t.width||u.height!==t.height)return"detector.decode.letterbox differs from detector.input";if(typeof u.pad!="number"||!Number.isInteger(u.pad)||u.pad<0||u.pad>255)return"detector.decode.letterbox.pad must be a whole number from 0 to 255";let l=[["anchor","top-left"],["resize","pillow-bilinear"],["ratio","min(height / frameHeight, width / frameWidth)"],["size","round(frame * ratio)"]];for(let[o,a]of l)if(u[o]!==a)return`detector.decode.letterbox.${o} is not ${JSON.stringify(a)}`;let d=n.classes;if(!Array.isArray(d)||d.length===0||!d.every(tt)||new Set(d).size!==d.length)return"detector.decode.classes must be a list of distinct class names";if(e.faceClass!==Rr||d[Rr]!=="face")return`detector.faceClass must be ${Rr} and that class must be named "face"`;let c=n.output,s=["cx","cy","w","h","obj",...d.map(o=>`cls_${o}`)];if(!Ue(c)||!Array.isArray(c.columns)||c.columns.length!==s.length||!c.columns.every((o,a)=>o===s[a]))return"detector.decode.output.columns must be cx, cy, w, h, obj and one cls_ per class";if(c.anchors!==wT(t.width,t.height))return`detector.decode.output.anchors must be ${wT(t.width,t.height)} for a ${t.width} x ${t.height} input`;if(!Ji(n.threshold)||!(n.threshold>0&&n.threshold<1))return"detector.decode.threshold must be a number between 0 and 1";if(n.threshold<.01)return`detector.decode.threshold ${n.threshold} is below 0.01, the lowest score at which the detector export checks box parity`;let r=n.nms;return!Ue(r)||!Ji(r.iou)||!(r.iou>0&&r.iou<=1)||r.classAgnostic!==!0||r.greedy!==!0?"detector.decode.nms must give an iou above 0 and at most 1, with classAgnostic and greedy both true":ft(n.maxProposals)?ft(e.minCropPx)?{inputName:n.inputName,outputName:n.outputName,letterbox:{width:t.width,height:t.height,pad:u.pad},anchors:c.anchors,classes:d,decode:{threshold:n.threshold,nmsIou:r.iou,maxProposals:n.maxProposals},faceClass:Rr,minCropPx:e.minCropPx}:"detector.minCropPx must be a whole number above 0":"detector.decode.maxProposals must be a whole number above 0"}function xT(e){let t=A=>({error:A});if(!Ue(e)||e.schemaVersion!==bT||e.kind!==yT)return t(`not a "${yT}" document of schema version ${bT}`);let n=Object.keys(e).filter(A=>!qP.includes(A));if(n.length>0)return t(`unknown key(s) ${n.sort().join(", ")}`);if(typeof e.id!="string"||!jP.test(e.id))return t("id must be 16 lowercase hex digits");if(!tt(e.game)||!tt(e.locale))return t("game and locale must be non-empty strings");let i=e.detector;if(!Ue(i))return t("incomplete release: detector missing (a release is all-or-nothing)");let u=Zi(i);if(!u||!tt(i.version)||!tt(i.weights))return t("detector must pin a file and carry a version and a weights label");if(i.arm!=="yolox")return t(`detector.arm ${JSON.stringify(i.arm)} is not one this runtime implements`);let l=HP(i);if(typeof l=="string")return t(l);let d=e.recognizer;if(!Ue(d))return t("incomplete release: recognizer missing (a release is all-or-nothing)");let c=Zi(d);if(!c||!tt(d.version)||!tt(d.weights)||!ft(d.dim))return t("recognizer must pin a file and carry a version, a weights label and a dim");if(!tt(d.inputName)||!tt(d.outputName))return t("recognizer must name the model's input and output");let s=hs(d.preprocessing);if(s===null)return t(`recognizer.preprocessing is not a contract this runtime implements (known: ${Object.keys(er).join(", ")})`);let r=e.bank;if(!Ue(r))return t("incomplete release: bank missing (a release is all-or-nothing)");let o=Zi(r);if(!o||!ft(r.version)||!ft(r.cardCount)||!ft(r.entryCount))return t("bank must pin a file and carry a version, a cardCount and an entryCount");if(r.aggregation!=="mean")return t('bank.aggregation must be "mean"');let a=e.identity;if(!Ue(a)||!qd(a.level))return t('identity.level must be "name" or "printing"');let p=a.groups,h=Zi(p);if(!h||!Ue(p)||!ft(p.version))return t("incomplete release: identity.groups must pin a file and carry a version");if(a.display!=="best-printing"&&a.display!=="representative")return t(`identity.display ${JSON.stringify(a.display)} is not one of best-printing, representative`);let m=e.catalog,g=Zi(m);if(!g||!Ue(m)||!ft(m.cardCount))return t("incomplete release: catalog must pin a file and carry a cardCount");let _=e.accept;if(!Ue(_))return t("incomplete release: accept missing (a release is all-or-nothing)");if(Object.keys(_).some(A=>!_T.includes(A)))return t(`accept has unknown key(s) (expected ${_T.join(", ")})`);if(!Ji(_.tau)||!(_.tau>0&&_.tau<=1))return t("accept.tau must be a number above 0 and at most 1");if(!Ji(_.delta)||!(_.delta>=0&&_.delta<1))return t("accept.delta must be a number from 0 to below 1");if(typeof _.rotationRetry!="boolean")return t("accept.rotationRetry must be true or false");let w=e.hover;if(!Ue(w)||!Q$(w.selection))return t("hover.selection is not one of accepted-nms, best-score, detector-score");if(!ft(w.maxAgeMs))return t("hover.maxAgeMs must be a whole number above 0");let y=e.runtime;if(!Ue(y)||typeof y.ortWeb!="string"||!VP.test(y.ortWeb))return t("runtime.ortWeb must be an exact version of the form 1.2.3");if(y.wasmThreads!==1)return t("runtime.wasmThreads must be 1");let T=y.executionProviders;if(!Array.isArray(T)||T.length===0||new Set(T).size!==T.length||!T.every(A=>_s.includes(A)))return t(`runtime.executionProviders must list one or more of ${_s.join(", ")}, each once`);let S=y.analysisWidth;if(!Ue(S)||!ft(S.min)||!ft(S.max)||S.min>S.max)return t("runtime.analysisWidth must give whole numbers min <= max above 0");let O=null;if("tiltedRetry"in e){let A=dT(e.tiltedRetry);if(A!==null)return t(A);let P=e.tiltedRetry;O={scales:[...P.scales],maxFacesPerFrame:P.maxFacesPerFrame,budgetMs:P.budgetMs}}return{release:{id:e.id,game:e.game,locale:e.locale,detector:{...u,arm:"yolox",version:i.version,weights:i.weights,settings:l},recognizer:{...c,version:d.version,weights:d.weights,dim:d.dim,inputName:d.inputName,outputName:d.outputName,preprocessing:s},bank:{...o,version:r.version,cardCount:r.cardCount,entryCount:r.entryCount},identity:{level:a.level,groups:{...h,version:p.version},display:a.display},catalog:{...g,cardCount:m.cardCount},accept:{tau:_.tau,delta:_.delta,rotationRetry:_.rotationRetry},hover:{selection:w.selection,maxAgeMs:w.maxAgeMs},runtime:{ortWeb:y.ortWeb,executionProviders:T,wasmThreads:1,analysisWidth:{min:S.min,max:S.max}},tiltedRetry:O}}}function WP(e){let t=0,n=()=>{throw new Error("not JSON")},i=()=>{for(;t`[WebGPU] ${e.name} shader code: ${d}`);let s=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return Vt(e.name),{programInfo:e,computePipeline:s,uniformVariablesInfo:u.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,n=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,u=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=u&&n<=u&&i<=u)return[t,n,i];let l=t*n*i,d=Math.ceil(Math.sqrt(l));if(d>u){if(d=Math.ceil(Math.cbrt(l)),d>u)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),h$={};wn(h$,{WebGpuBackend:()=>f$});var t0,r0,n0,f$,Uk=D(()=>{"use strict";dt(),de(),ur(),xx(),YA(),Lk(),jk(),t0=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let i=0;i{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+n+`:${t0(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},n0=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},f$=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},u=c=>t.features.has(c)&&n.push(c)&&!0;u("chromium-experimental-timestamp-query-inside-passes")||u("timestamp-query"),u("shader-f16"),u("subgroups"),this.device=await t.requestDevice(i);let l=t,d=t.info??(typeof l.requestAdapterInfo=="function"?await l.requestAdapterInfo():void 0);this.adapterInfo=new n0(d),this.gpuDataManager=Sx(this),this.programManager=new p$(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ud(e.logLevel,!!e.debug),this.device.onuncapturederror=c=>{c.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${c.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Jt(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=p);let m=Number(p-this.queryTimeBase),g=Number(h-this.queryTimeBase);if(!Number.isSafeInteger(m)||!Number.isSafeInteger(g))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:o.map(_=>({dims:_.dims,dataType:sr(_.dataType)})),outputsMetadata:a.map(_=>({dims:_.dims,dataType:sr(_.dataType)})),kernelId:l,kernelType:c,kernelName:s,programName:r,startTime:m,endTime:g});else{let _="";o.forEach((y,T)=>{_+=`input[${T}]: [${y.dims}] | ${sr(y.dataType)}, `});let w="";a.forEach((y,T)=>{w+=`output[${T}]: [${y.dims}] | ${sr(y.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${s}|${r}" ${_}${w}start time: ${m} ns, execution time: ${g-m} ns`)}Lo("GPU",`${r}::${p}::${h}`)}e.unmap(),this.pendingQueries.delete(e)}),Vt()}run(e,t,n,i,u,l){Jt(e.name);let d=[];for(let y=0;yT):n;if(o.length!==c.length)throw new Error(`Output size ${o.length} must be equal to ${c.length}.`);let a=[],p=[];for(let y=0;y=l)throw new Error(`Invalid output index: ${o[y]}`);if(o[y]===-3)continue;let T=o[y]===-1,S=o[y]===-2,O=T||S?u(c[y].dataType,c[y].dims):i(o[y],c[y].dataType,c[y].dims);if(a.push(O),O.data===0)continue;let A=this.gpuDataManager.get(O.data);if(!A)throw new Error(`no GPU data for output: ${O.data}`);if(T&&this.temporaryData.push(A),S){let P=this.kernelPersistentData.get(this.currentKernelId);P||(P=[],this.kernelPersistentData.set(this.currentKernelId,P)),P.push(A)}p.push(A)}if(d.length!==t.length||p.length!==a.length){if(p.length===0)return Vt(e.name),a;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let h;if(r){let y=0,T=[];r.forEach(P=>{let I=typeof P.data=="number"?[P.data]:P.data;if(I.length===0)return;let z=P.type===10?2:4,G,J;P.type===10?(J=I.length>4?16:I.length>2?8:I.length*z,G=I.length>4?16:z*I.length):(J=I.length<=2?I.length*z:16,G=16),y=Math.ceil(y/J)*J,T.push(y);let q=P.type===10?8:4;y+=I.length>4?Math.ceil(I.length/q)*G:I.length*z});let S=16;y=Math.ceil(y/S)*S;let O=new ArrayBuffer(y);r.forEach((P,I)=>{let z=T[I],G=typeof P.data=="number"?[P.data]:P.data;if(P.type===6)new Int32Array(O,z,G.length).set(G);else if(P.type===12)new Uint32Array(O,z,G.length).set(G);else if(P.type===10)new Uint16Array(O,z,G.length).set(G);else if(P.type===1)new Float32Array(O,z,G.length).set(G);else throw new Error(`Unsupported uniform type: ${sr(P.type)}`)});let A=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(A.buffer,0,O,0,y),this.gpuDataManager.release(A.id),h={offset:0,size:y,buffer:A.buffer}}let m=this.programManager.normalizeDispatchGroupSize(s),g=m[1]===1&&m[2]===1,_=r0(e,t,g),w=this.programManager.getArtifact(_);if(w||(w=this.programManager.build(e,m),this.programManager.setArtifact(_,w),Ie("info",()=>`[artifact] key: ${_}, programName: ${e.name}`)),r&&w.uniformVariablesInfo){if(r.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${r.length} in program "${w.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${e.name}" (key=${_}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:t,outputTensorViews:a};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(w,d,p,m,h),Vt(e.name),a}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,i){let u=c$.get(e);if(!u)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:u[0],attributes:[u[1],n]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let n of t)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let u=i.kernelType,l=i.kernelName,d=i.kernelEntry,c=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${u}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),Ie("info",()=>`[WebGPU] Start to run kernel "[${u}] ${l}"...`);let s=this.env.debug;this.temporaryData=[];try{return s&&this.device.pushErrorScope("validation"),d(t,c[1]),0}catch(r){return n.push(Promise.resolve(`[WebGPU] Kernel "[${u}] ${l}" failed. ${r}`)),1}finally{s&&n.push(this.device.popErrorScope().then(r=>r?`GPU validation error for kernel "[${u}] ${l}": ${r.message}`:null));for(let r of this.temporaryData)this.gpuDataManager.release(r.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,i){let u=this.sessionExternalDataMapping.get(e);u||(u=new Map,this.sessionExternalDataMapping.set(e,u));let l=u.get(t),d=this.gpuDataManager.registerExternalBuffer(n,i,l);return u.set(t,[d,n]),d}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let i=await Pl(this,e,t);return ld(i.buffer,n)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Ie("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Ie("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ie("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let i=0;i=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),m$={};wn(m$,{init:()=>g$});var Ro,i0,g$,Vk=D(()=>{"use strict";de(),ur(),pe(),ZA(),Ro=class b${constructor(t,n,i,u){this.module=t,this.dataType=n,this.data=i,this.dims=u}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(F.size(t)!==F.size(this.dims))throw new Error("Invalid new shape");return new b$(this.module,this.dataType,this.data,t)}},i0=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,u=n/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*u++,l));let d=Number(e.getValue(i*u++,l));this.outputCount=Number(e.getValue(i*u++,l)),this.customDataOffset=Number(e.getValue(i*u++,"*")),this.customDataSize=Number(e.getValue(i*u++,l));let c=[];for(let s=0;stypeof d=="number"?this.inputs[d]:d)??this.inputs,i=t?.outputs??[],u=(d,c,s)=>new Ro(this.module,c,this.output(d,s),s),l=(d,c)=>{let s=cn(d,c);if(!s)throw new Error(`Unsupported data type: ${d}`);let r=s>0?this.backend.gpuDataManager.create(s).id:0;return new Ro(this.module,d,r,c)};return this.backend.run(e,n,i,u,l,this.outputCount)}output(e,t){let n=this.module.stackSave();try{let i=this.module.PTR_SIZE,u=i===4?"i32":"i64",l=this.module.stackAlloc((1+t.length)*i);this.module.setValue(l,t.length,u);for(let d=0;d{let u=t.jsepInit;if(!u)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let l=(Uk(),Nn(h$)).WebGpuBackend,d=new l;await d.initialize(n,i),u("webgpu",[d,c=>d.alloc(Number(c)),c=>d.free(c),(c,s,r,o=!1)=>{if(o)Ie("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(s)}, size=${Number(r)}`),d.memcpy(Number(c),Number(s));else{Ie("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(s)}, size=${Number(r)}`);let a=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(r));d.upload(Number(s),a)}},async(c,s,r)=>{Ie("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${c}, dataOffset=${s}, size=${r}`),await d.download(Number(c),()=>t.HEAPU8.subarray(Number(s)>>>0,Number(s+r)>>>0))},(c,s,r)=>d.createKernel(c,Number(s),r,t.UTF8ToString(t._JsepGetNodeName(Number(s)))),c=>d.releaseKernel(c),(c,s,r,o)=>{Ie("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${c}, contextDataOffset=${s}`);let a=new i0(t,d,Number(s));return d.computeKernel(Number(c),a,o)},()=>d.captureBegin(),()=>d.captureEnd(),()=>d.replay()])}else{let l=new Tx(n);u("webnn",[l,()=>l.reserveTensorId(),d=>l.releaseTensorId(d),async(d,c,s,r,o)=>l.ensureTensor(d,c,s,r,o),(d,c)=>{l.uploadTensor(d,c)},async(d,c)=>l.downloadTensor(d,c),(d,c)=>l.registerMLContext(d,c),!!n.trace])}}}),o0,_d,vd,_r,s0,Du,Yo,xd,$d,Mu,Td,Sd,Id,y$=D(()=>{"use strict";dt(),WA(),KA(),de(),vn(),id(),yx(),o0=(e,t)=>{Be()._OrtInit(e,t)!==0&&Re("Can't initialize onnxruntime.")},_d=async e=>{o0(e.wasm.numThreads,Ho(e.logLevel))},vd=async(e,t)=>{Be().asyncInit?.();let n=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let u=e.webgpu.forceFallbackAdapter;if(u!==void 0&&typeof u!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${u}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:u}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let i=(Vk(),Nn(m$)).init;t==="webgpu"&&await i("webgpu",Be(),e,n),t==="webnn"&&await i("webnn",Be(),e)}},_r=new Map,s0=e=>{let t=Be(),n=t.stackSave();try{let i=t.PTR_SIZE,u=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,u,u+i)!==0&&Re("Can't get session input/output count.");let l=i===4?"i32":"i64";return[Number(t.getValue(u,l)),Number(t.getValue(u+i,l))]}finally{t.stackRestore(n)}},Du=(e,t)=>{let n=Be(),i=n.stackSave(),u=0;try{let l=n.PTR_SIZE,d=n.stackAlloc(2*l);n._OrtGetInputOutputMetadata(e,t,d,d+l)!==0&&Re("Can't get session input/output metadata.");let c=Number(n.getValue(d,"*"));u=Number(n.getValue(d+l,"*"));let s=n.HEAP32[u/4];if(s===0)return[c,0];let r=n.HEAPU32[u/4+1],o=[];for(let a=0;a{let t=Be(),n=t._malloc(e.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},xd=async(e,t)=>{let n,i,u=Be();Array.isArray(e)?[n,i]=e:e.buffer===u.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=Yo(e);let l=0,d=0,c=0,s=[],r=[],o=[];try{if([d,s]=await bx(t),t?.externalData&&u.mountExternalData){let S=[];for(let O of t.externalData){let A=typeof O=="string"?O:O.path,P=typeof O=="string"?O:O.data;S.push(ad(P).then(I=>{u.mountExternalData(A,I)}))}await Promise.all(S)}for(let S of t?.executionProviders??[])if((typeof S=="string"?S:S.name)==="webnn"){if(u.shouldTransferToMLTensor=!1,typeof S!="string"){let O=S,A=O?.context,P=O?.gpuDevice,I=O?.deviceType,z=O?.powerPreference;A?u.currentContext=A:P?u.currentContext=await u.webnnCreateMLContext(P):u.currentContext=await u.webnnCreateMLContext({deviceType:I,powerPreference:z})}else u.currentContext=await u.webnnCreateMLContext();break}l=await u._OrtCreateSession(n,i,d),u.webgpuOnCreateSession?.(l),l===0&&Re("Can't create a session."),u.jsepOnCreateSession?.(),u.currentContext&&(u.webnnRegisterMLContext(l,u.currentContext),u.currentContext=void 0,u.shouldTransferToMLTensor=!0);let[a,p]=s0(l),h=!!t?.enableGraphCapture,m=[],g=[],_=[],w=[],y=[];for(let S=0;SS==="gpu-buffer"||S==="ml-tensor"||S==="ml-tensor-cpu-output")&&(c=u._OrtCreateBinding(l),c===0&&Re("Can't create IO binding."),T={handle:c,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map(S=>S==="ml-tensor-cpu-output"?"ml-tensor":S).map(S=>kl(S))}),_r.set(l,[l,r,o,T,h,!1]),[l,m,g,_,w]}catch(a){throw r.forEach(p=>u._OrtFree(p)),o.forEach(p=>u._OrtFree(p)),c!==0&&u._OrtReleaseBinding(c)!==0&&Re("Can't release IO binding."),l!==0&&u._OrtReleaseSession(l)!==0&&Re("Can't release session."),a}finally{u._free(n),d!==0&&u._OrtReleaseSessionOptions(d)!==0&&Re("Can't release session options."),s.forEach(a=>u._free(a)),u.unmountExternalData?.()}},$d=e=>{let t=Be(),n=_r.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,u,l,d,c]=n;d&&(c&&t._OrtClearBoundOutputs(d.handle)!==0&&Re("Can't clear bound outputs."),t._OrtReleaseBinding(d.handle)!==0&&Re("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),u.forEach(s=>t._OrtFree(s)),l.forEach(s=>t._OrtFree(s)),t._OrtReleaseSession(i)!==0&&Re("Can't release session."),_r.delete(e)},Mu=async(e,t,n,i,u,l,d=!1)=>{if(!e){t.push(0);return}let c=Be(),s=c.PTR_SIZE,r=e[0],o=e[1],a=e[3],p=a,h,m;if(r==="string"&&(a==="gpu-buffer"||a==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(d&&a!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(a==="gpu-buffer"){let w=e[2].gpuBuffer;m=cn(dn(r),o);{let y=c.jsepRegisterBuffer;if(!y)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=y(i,l,w,m)}}else if(a==="ml-tensor"){let w=e[2].mlTensor;m=cn(dn(r),o);let y=c.webnnRegisterMLTensor;if(!y)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=y(i,w,dn(r),o)}else{let w=e[2];if(Array.isArray(w)){m=s*w.length,h=c._malloc(m),n.push(h);for(let y=0;yc.setValue(_+T*s,y,s===4?"i32":"i64"));let w=c._OrtCreateTensor(dn(r),h,m,_,o.length,kl(p));w===0&&Re(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(w)}finally{c.stackRestore(g)}},Td=async(e,t,n,i,u,l)=>{let d=Be(),c=d.PTR_SIZE,s=_r.get(e);if(!s)throw new Error(`cannot run inference. invalid session id: ${e}`);let r=s[0],o=s[1],a=s[2],p=s[3],h=s[4],m=s[5],g=t.length,_=i.length,w=0,y=[],T=[],S=[],O=[],A=[],P=d.stackSave(),I=d.stackAlloc(g*c),z=d.stackAlloc(g*c),G=d.stackAlloc(_*c),J=d.stackAlloc(_*c);try{[w,y]=gx(l),hn("wasm prepareInputOutputTensor");for(let v=0;vce*xe,1);K=sr(Y);let le=p?.outputPreferredLocations[i[v]];if(K==="string"){if(le==="gpu-buffer"||le==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ce=[];for(let xe=0;xe0){let ce=d.jsepGetBuffer;if(!ce)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=ce(B),qe=cn(Y,re);if(qe===void 0||!od(K))throw new Error(`Unsupported data type: ${K}`);V=!0,C.push([K,W,{gpuBuffer:xe,download:d.jsepCreateDownloader(xe,qe,K),dispose:()=>{d._OrtReleaseTensor(R)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(le==="ml-tensor"&&re>0){let ce=d.webnnEnsureTensor,xe=d.webnnIsGraphInputOutputTypeSupported;if(!ce||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(cn(Y,re)===void 0||!sd(K))throw new Error(`Unsupported data type: ${K}`);if(!xe(e,K,!1))throw new Error(`preferredLocation "ml-tensor" for ${K} output is not supported by current WebNN Context.`);let qe=await ce(e,B,Y,W,!1);V=!0,C.push([K,W,{mlTensor:qe,download:d.webnnCreateMLTensorDownloader(B,K),dispose:()=>{d.webnnReleaseTensorId(B),d._OrtReleaseTensor(R)}},"ml-tensor"])}else if(le==="ml-tensor-cpu-output"&&re>0){let ce=d.webnnCreateMLTensorDownloader(B,K)(),xe=C.length;V=!0,ee.push((async()=>{let qe=[xe,await ce];return d.webnnReleaseTensorId(B),d._OrtReleaseTensor(R),qe})()),C.push([K,W,[],"cpu"])}else{let ce=ss(K),xe=new ce(re);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(d.HEAPU8.subarray(B,B+xe.byteLength)),C.push([K,W,xe,"cpu"])}}finally{d.stackRestore(H),K==="string"&&B&&d._free(B),V||d._OrtReleaseTensor(R)}}p&&!h&&(d._OrtClearBoundOutputs(p.handle)!==0&&Re("Can't clear bound outputs."),_r.set(e,[r,o,a,p,h,!1]));for(let[v,R]of await Promise.all(ee))C[v][2]=R;return fn("wasm ProcessOutputTensor"),C}finally{d.webnnOnRunEnd?.(r),d.stackRestore(P),T.forEach(q=>d._OrtReleaseTensor(q)),S.forEach(q=>d._OrtReleaseTensor(q)),O.forEach(q=>d._free(q)),w!==0&&d._OrtReleaseRunOptions(w),y.forEach(q=>d._free(q))}},Sd=e=>{let t=Be(),n=_r.get(e);if(!n)throw new Error("invalid session id");let i=n[0],u=t._OrtEndProfiling(i);u===0&&Re("Can't get an profile file name."),t._OrtFree(u)},Id=e=>{let t=[];for(let n of e){let i=n[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),vr,At,An,bi,yi,Do,Nu,Mo,Wr,Kr,a0,w$,_$,v$,x$,$$,T$,S$,I$=D(()=>{"use strict";dt(),y$(),vn(),rd(),vr=()=>!!me.wasm.proxy&&typeof document<"u",An=!1,bi=!1,yi=!1,Mo=new Map,Wr=(e,t)=>{let n=Mo.get(e);n?n.push(t):Mo.set(e,[t])},Kr=()=>{if(An||!bi||yi||!At)throw new Error("worker not ready")},a0=e=>{switch(e.data.type){case"init-wasm":An=!1,e.data.err?(yi=!0,Nu[1](e.data.err)):(bi=!0,Nu[0]()),Do&&(URL.revokeObjectURL(Do),Do=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Mo.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},w$=async()=>{if(!bi){if(An)throw new Error("multiple calls to 'initWasm()' detected.");if(yi)throw new Error("previous call to 'initWasm()' failed.");if(An=!0,vr())return new Promise((e,t)=>{At?.terminate(),fx().then(([n,i])=>{try{At=i,At.onerror=l=>t(l),At.onmessage=a0,Nu=[e,t];let u={type:"init-wasm",in:me};!u.in.wasm.wasmPaths&&(n||Al)&&(u.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url).href}),At.postMessage(u),Do=n}catch(u){t(u)}},t)});try{await nd(me.wasm),await _d(me),bi=!0}catch(e){throw yi=!0,e}finally{An=!1}}},_$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:me}};At.postMessage(i)});await vd(me,e)},v$=async e=>vr()?(Kr(),new Promise((t,n)=>{Wr("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};At.postMessage(i,[e.buffer])})):Yo(e),x$=async(e,t)=>{if(vr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Kr(),new Promise((n,i)=>{Wr("create",[n,i]);let u={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),At.postMessage(u,l)})}else return xd(e,t)},$$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("release",[t,n]);let i={type:"release",in:e};At.postMessage(i)});$d(e)},T$=async(e,t,n,i,u,l)=>{if(vr()){if(n.some(d=>d[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(u.some(d=>d))throw new Error("pre-allocated output tensor is not supported for proxy.");return Kr(),new Promise((d,c)=>{Wr("run",[d,c]);let s=n,r={type:"run",in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:i,options:l}};At.postMessage(r,Id(s))})}else return Td(e,t,n,i,u,l)},S$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("end-profiling",[t,n]);let i={type:"end-profiling",in:e};At.postMessage(i)});Sd(e)}}),zu,u0,O$,qk=D(()=>{"use strict";dt(),I$(),de(),td(),yx(),zu=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},u0=e=>{switch(e[3]){case"cpu":return new vt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!od(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:u}=e[2];return vt.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:u})}case"ml-tensor":{let t=e[0];if(!sd(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:u}=e[2];return vt.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:u})}default:throw new Error(`invalid data location: ${e[3]}`)}},O$=class{async fetchModelAndCopyToWasmMemory(e){return v$(await ad(e))}async loadModel(e,t){Jt();let n;typeof e=="string"?n=await this.fetchModelAndCopyToWasmMemory(e):n=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await x$(n,t),Vt()}async dispose(){return $$(this.sessionId)}async run(e,t,n){Jt();let i=[],u=[];Object.entries(e).forEach(a=>{let p=a[0],h=a[1],m=this.inputNames.indexOf(p);if(m===-1)throw new Error(`invalid input '${p}'`);i.push(h),u.push(m)});let l=[],d=[];Object.entries(t).forEach(a=>{let p=a[0],h=a[1],m=this.outputNames.indexOf(p);if(m===-1)throw new Error(`invalid output '${p}'`);l.push(h),d.push(m)});let c=i.map((a,p)=>zu(a,()=>`input "${this.inputNames[u[p]]}"`)),s=l.map((a,p)=>a?zu(a,()=>`output "${this.outputNames[d[p]]}"`):null),r=await T$(this.sessionId,u,c,d,s,n),o={};for(let a=0;aVl,initializeFlags:()=>Ul,wasmBackend:()=>A$});var Ul,Vl,A$,Gk=D(()=>{"use strict";dt(),I$(),qk(),Ul=()=>{(typeof me.wasm.initTimeout!="number"||me.wasm.initTimeout<0)&&(me.wasm.initTimeout=0);let e=me.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),me.wasm.simd=!1),typeof me.wasm.proxy!="boolean"&&(me.wasm.proxy=!1),typeof me.wasm.trace!="boolean"&&(me.wasm.trace=!1),typeof me.wasm.numThreads!="number"||!Number.isInteger(me.wasm.numThreads)||me.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)me.wasm.numThreads=1;else{let t=typeof navigator>"u"?Bu("node:os").cpus().length:navigator.hardwareConcurrency;me.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Vl=class{async init(e){Ul(),await w$(),await _$(e)}async createInferenceSessionHandler(e,t){let n=new O$;return await n.loadModel(e,t),n}},A$=new Vl});dt();dt();dt();var Hk="1.29.0";{let e=(qA(),Nn(ax)).onnxjsBackend;pn("webgl",e,-10)}{let e=(Gk(),Nn(E$)).wasmBackend;pn("webgpu",e,5),pn("webnn",e,5),pn("cpu",e,10),pn("wasm",e,10)}Object.defineProperty(me.versions,"web",{value:Hk,enumerable:!0});function k$(){return me.versions.web??""}function P$(e={}){me.wasm.numThreads=e.wasmThreads??1,e.wasmPaths!==void 0&&(me.wasm.wasmPaths=e.wasmPaths)}var as=[];function Od(){let e=as;return as=[],e}async function us(e,t,n){for(let i of t){let u=null;try{let l=performance.now();u=await Qo.create(e.slice().buffer,{executionProviders:[i]});let d=performance.now();if(await n(u))return{session:u,ep:i,createMs:d-l,firstRunMs:performance.now()-d};as.push(`${i}: the model does not have the inputs and outputs the release describes`)}catch(l){as.push(`${i}: ${l instanceof Error?l.message:String(l)}`.slice(0,300))}await u?.release().catch(()=>{})}return null}function qn(e,t){return new vt("float32",e,t)}function Ed(e){return{cx:e.x+e.width/2,cy:e.y+e.height/2,w:e.width,h:e.height,angle:0}}function Gn(e,t){let n=Math.max(e.x,t.x),i=Math.max(e.y,t.y),u=Math.min(e.x+e.width,t.x+t.width),l=Math.min(e.y+e.height,t.y+t.height);if(u<=n||l<=i)return 0;let d=(u-n)*(l-i);return d/(e.width*e.height+t.width*t.height-d)}function Ad(e,t,n,i){let u=[...e].sort((d,c)=>n(c)-n(d)),l=[];for(let d of u){let c=t(d);l.every(s=>Gn(c,t(s))O&&(O=P,S=A)}O>=l&&(c.push(w),s.push(O),r.push(S))}let o=c.length;if(o===0)return[];let a=new Float32Array(o),p=new Float32Array(o),h=new Float32Array(o),m=new Float32Array(o);for(let w=0;wy).sort((w,y)=>s[y]-s[w]||w-y),_=[];for(;g.length>0;){let w=g[0];if(_.push(w),g.length===1)break;let y=Qe(Qe(h[w]-a[w])*Qe(m[w]-p[w])),T=[];for(let S=1;S{let y={x:a[w]/n,y:p[w]/n,width:Qe(h[w]-a[w])/n,height:Qe(m[w]-p[w])/n};return{aabb:y,rect:Ed(y),score:s[w],cls:r[w]}})}function ls(e,t,n,i=Hn){let u=Math.trunc(Math.max(0,e.x)),l=Math.trunc(Math.max(0,e.y)),d=Math.trunc(Math.min(t,e.x+e.width)),c=Math.trunc(Math.min(n,e.y+e.height));return d-u>=i&&c-l>=i}function R$(e,t,n,i,u,l=kd,d=Hn){return C$(e,t,n,l).filter(c=>ls(c.aabb,i,u,d))}function Xk(e,t,n,i,u){let l=i/t,d=u/n;return[Math.max(0,e.x*l),Math.max(0,e.y*d),Math.min(i,(e.x+e.width)*l),Math.min(u,(e.y+e.height)*d)]}function D$(e,t){let n=e.aabb;if(n.x>=0&&n.y>=0&&n.x+n.width<=t.width&&n.y+n.height<=t.height)return e;let[i,u,l,d]=Xk(n,t.width,t.height,t.width,t.height),c={x:i,y:u,width:Math.max(0,l-i),height:Math.max(0,d-u)};return{...e,aabb:c,rect:Ed(c)}}function M$(e,t=Rr){let n=[],i=[];for(let u of e)(u.cls===t?n:i).push(u);return{faces:n,others:i}}function Zk(e){return e<0&&(e=-e),e<1?1-e:0}function N$(e,t){let n=e/t,i=n<1?1:n,u=i,l=Math.ceil(u)*2+1,d=new Int32Array(t*2),c=new Int32Array(t*l),s=new Float64Array(l);for(let r=0;re&&(m=e),m-=h;for(let g=0;g>22;return t<0?0:t>255?255:t}var z$="",Pd=null,Cd=null;function Yk(e,t,n,i){let u=`${e}x${t}>${n}x${i}`;return(u!==z$||!Pd||!Cd)&&(Pd=N$(e,n),Cd=N$(t,i),z$=u),{h:Pd,v:Cd}}function cs(e,t,n,i,u){let{h:l,v:d}=Yk(t,n,i,u),c=i!==t,s=u!==n,r,o;if(c){let w=s?d.bounds[0]:0,T=(s?d.bounds[u*2-2]+d.bounds[u*2-1]:n)-w;o=w,r=new Uint8Array(i*T*3);let{ksize:S,bounds:O,kk:A}=l;for(let P=0;P.5?t+1:n<.5||t%2===0?t:t+1}function Rd(e,t,n=ps){let i=Math.min(n.height/t,n.width/e);return{ratio:i,width:B$(e*i),height:B$(t*i)}}function Jk(e,t,n,i=ps){let u=Rd(t,n,i),l=cs(e,t,n,u.width,u.height),d=new Uint8Array(i.width*i.height*3).fill(i.pad);for(let c=0;c{let o=(await s.run({[n.inputName]:qn(new Float32Array(3*u*l),[1,3,l,u])}))[n.outputName]?.dims??[];return o.length===3&&o[0]===1&&o[1]===n.anchors&&o[2]===d});return c?new e(c.session,c.ep,n,{createMs:c.createMs,firstRunMs:c.firstRunMs}):null}async propose(t){let{letterbox:n,inputName:i,outputName:u,decode:l,minCropPx:d}=this.settings,c=performance.now(),{tensor:s,ratio:r}=Dd(t.data,t.width,t.height,n),o=performance.now(),a=await this.session.run({[i]:qn(s,[1,3,n.height,n.width])});return this.lastTimings={preprocessMs:o-c,inferMs:performance.now()-o},R$(a[u].data,this.columns,r,t.width,t.height,l,d)}async release(){await this.session.release().catch(()=>{})}};var Qk=32;async function eP(e,t,n,i,u=Qk){if(n<=u)return e(t,n);let l=t.length/n,d=new Float32Array(n*i);for(let c=0;c(await d.run({[n.inputName]:qn(new Float32Array(3*u*u),[1,3,u,u])}))[n.outputName]?.data.length===n.dim);return l?new e(l.session,l.ep,n,{createMs:l.createMs,firstRunMs:l.firstRunMs}):null}async embedBatch(t,n){return eP((i,u)=>this.run(i,u),t,n,this.settings.dim)}async run(t,n){let{inputName:i,outputName:u,inputSize:l,dim:d}=this.settings,s=(await this.session.run({[i]:qn(t,[n,3,l,l])}))[u].data;if(s.length!==n*d)throw new Error(`unexpected embedding size ${s.length} for ${n} crops`);return s}async release(){await this.session.release().catch(()=>{})}};var tP=["orb","akaze","sift"];var rP={orb:[["scaleFactor",1.2,!1],["nLevels",8,!0],["edgeThreshold",15,!0],["patchSize",15,!0],["fastThreshold",10,!0]],akaze:[["threshold",.001,!1],["nOctaves",4,!0],["nOctaveLayers",4,!0]],sift:[["nOctaveLayers",3,!0],["contrastThreshold",.04,!1],["edgeThreshold",10,!1],["sigma",1.6,!1]]},DD=Object.fromEntries(tP.map(e=>[e,Object.fromEntries(rP[e].map(([t,n])=>[t,n]))])),MD=Object.freeze({seed:0,features:{type:"orb",maxFeatures:300,artLongSide:320,mask:[],params:{}},crop:{longSide:320,maxFeatures:500},candidates:{embeddingTopK:5,voteTopN:0},vote:{matcher:"bf",ratio:.8,lshTables:12,lshKeySize:20,lshProbes:2,kdTrees:4,checks:64},match:{ratio:.8},ransac:{model:"homography",method:"ransac",threshold:6,maxIters:2e3,confidence:.995,minAreaRatio:.25,maxAreaRatio:4},fusion:{weight:.1,minInliers:8,fullInliers:30,penalty:0,baseline:"none",reorder:!0},gate:{belowAccept:!1,sources:null}}),nP=["features","crop","candidates","vote","match","ransac","fusion","gate"],ND=["index","seed",...nP];var BD=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function F$(e,t,n){let i=new Float64Array(e);for(let u of t){let l=u.fused-u.cosine;for(let d of n(u.cardId))i[d]=i[d]+l}return i}var iP=10n;function oP(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let n=t.getUint32(0),i=t.getUint32(4),u=n>>>31?-1n:1n,l=n>>>20&2047,d=BigInt(n&1048575)<<32n|BigInt(i),c;return l===0?c=-1074:(d|=1n<<52n,c=l-1075),{mantissa:u*d,exponent:c}}function Ui(e,t){if(!Number.isFinite(e)||e===0)return e;let{mantissa:n,exponent:i}=oP(e),u=n<0n,d=(u?-n:n)*iP**BigInt(t),c=1n;i>=0?d<<=BigInt(i):c<<=BigInt(-i);let s=d/c,o=2n*(d-s*c);if((o>c||o===c&&s%2n===1n)&&(s+=1n),s===0n)return u?-0:0;let a=`${u?"-":""}${s.toString()}e-${t}`;return Number(a)}function sP(e){return{cardId:e.cardId,cosine:Ui(e.cosine,6),foundBy:e.foundBy,votes:e.votes,matches:e.matches,inliers:e.inliers,evidence:Ui(e.evidence,6),fused:Ui(e.fused,6)}}function L$(e,t){return{before:{topId:e.topId,similarity:Ui(e.similarity,6),margin:Ui(e.margin,6),accepted:e.accepted},candidates:t.candidates.map(sP),...t.debug?{debug:t.debug}:{}}}var aP=23,UD=(1<!n.representative.has(d))??[...u].sort()[0];for(let d of u)i.set(d,`group:${n.representative.get(d)??l}`)}return i}var Wn="file:///";function U$(e){let t=new URL(e,Wn).href.slice(Wn.length);try{return decodeURIComponent(t)}catch{return t}}var V$="busy";var er={full128:{id:"full128",size:128,centerMask:!1,poolVersion:2,crop:"truncate"}};function Md(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(er,e)}function hs(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(!Md(t.id))return null;let n=er[t.id],i=Object.keys(t);return i.length===Object.keys(n).length&&i.every(l=>n[l]===t[l])?t.id:null}function G$(e,t,n,i,u,l){let d=new Float64Array(i*u*3),c=new Uint32Array(i*u);for(let a=0;a0&&(d[a*3]=d[a*3]/p,d[a*3+1]=d[a*3+1]/p,d[a*3+2]=d[a*3+2]/p)}if(l===1||t>=i&&n>=u||t<=0||n<=0)return d;let s=q$(n,u),r=q$(t,i),o=new Float64Array(d.length);for(let a=0;a=0&&!n[l];)l--;let d=u+1;for(;d=0&&(d>=t||u-l<=d-u)?l:d}return i}function fs(e,t,n,i){let u=i.size,l=G$(e,t,n,u,u,i.poolVersion),d=new Float32Array(3*u*u),c=u*u;for(let s=0;s>10&31,s=l&1023;c===0?i[u]=d*s*2**-24:c===31?i[u]=s?NaN:d*(1/0):i[u]=d*(1+s/1024)*2**(c-15)}return i}function lP(e,t){let n;try{n=atob(e)}catch{return null}if(n.length!==t*2)return null;let i=new Uint8Array(n.length);for(let u=0;u0)||!Number.isFinite(u))return!1;for(let l=0;l=Kn.length&&Kn.every((t,n)=>e[n]===t)}function Bd(e){return zd(e)&&e.length>Kn.length?e[Kn.length]:null}function X$(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);if(Bd(t)!==gs||t.lengthtypeof a=="string")||u.entryCount!==d.length)return null;let c=u.artVs;if(c!==void 0&&(!Array.isArray(c)||c.length!==d.length||!c.every(a=>a===null||typeof a=="string")))return null;let s=l.dim,r=Vi+n;if(t.length-r!==d.length*s*2)return null;let o=new Float32Array(d.length*s);for(let a=0;a({x:i+p*s-h*r,y:u+p*r+h*s}))}}function Z$(e,t){let{points:n}=t,i=0;for(let u=0;u0?1:-1;if(i===0)i=p;else if(p!==i)return!1}return!0}function Ld(e,t){let n=null;for(let i of t)Z$(e,i.quad)&&(!n||i.zIndex>=n.zIndex)&&(n=i);return n?n.card:null}function Xn(e){return e<0?0:e>1?1:e}function bs(e,t){let{frameWidth:n,frameHeight:i,names:u}=t;return e.map(l=>{let{aabb:d}=l,c=l.identity?u.get(l.identity):void 0,s=c!==void 0&&l.outline?l.outline:l.rect,r={instanceId:l.instanceId,bounds:{x:Xn(d.x/n),y:Xn(d.y/i),width:Xn(d.width/n),height:Xn(d.height/i)},rotation:(s.angle+45)%90-45,localWidth:Xn(s.w/n),localHeight:Xn(s.h/i),landscape:s.w>s.h,cardId:null,name:null};return l.identity&&c!==void 0&&(r.cardId=l.identity,r.name=c),r})}var J$=["accepted-nms","best-score","detector-score"];function Q$(e){return typeof e=="string"&&J$.includes(e)}var jd="accepted-nms",pP=.5,hP="hover_";function Y$(e){return e.width*e.height}function eT(e,t){let n=t==="accepted-nms"?e.kept:e.proposals.map((u,l)=>l),i=(u,l)=>{let d=e.proposals[u],c=e.proposals[l];if(t==="detector-score")return d.detectorScore!==c.detectorScore?d.detectorScore{let u=e.proposals[n];return{proposal:n,aabb:u.aabb,rect:u.rect,...u.outline?{outline:u.outline}:{},identity:u.accepted?u.displayId:null,score:u.score,zIndex:i+1}})}var ys=class{prev=[];nextId=1;reset(){this.prev=[]}assign(t){let n=new Set,i=t.map((l,d)=>d).sort((l,d)=>t[d].zIndex-t[l].zIndex),u=new Array(t.length);for(let l of i){let d=t[l],c=-1,s=pP;for(let r=0;r=s&&(c<0||o>s)&&(c=r,s=o)}c>=0?(n.add(c),u[l]=this.prev[c].id):u[l]=`${hP}${String(this.nextId++).padStart(4,"0")}`}return this.prev=t.map((l,d)=>({id:u[d],aabb:l.aabb,identity:l.identity})),u}};function ws(e,t,n,i=u=>u){return bs(e.map((l,d)=>({instanceId:t[d],aabb:l.aabb,rect:l.rect,...l.outline?{outline:l.outline}:{},identity:l.identity})),n).map((l,d)=>({...l,zIndex:e[d].zIndex,boxIndex:i(e[d].proposal)}))}var fP={card:null,boxIndex:null,box:null,cardId:null,name:null};function Ud(e,t,n){let i=e.map(l=>({card:l,quad:Fd(l,n),zIndex:l.zIndex??0})),u=Ld(t,i);return u?{card:u,boxIndex:u.boxIndex??null,box:{x:u.bounds.x*n.width,y:u.bounds.y*n.height,width:u.bounds.width*n.width,height:u.bounds.height*n.height},cardId:u.cardId,name:u.name}:fP}var mP="identity-groups";function Vd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.schemaVersion!==1||t.kind!==mP||typeof t.version!="number"||!Number.isInteger(t.version)||!Array.isArray(t.groups)||typeof t.representative!="object"||t.representative===null||Array.isArray(t.representative))return null;let n=new Map,i=[];for(let l of t.groups){if(!Array.isArray(l)||l.length<2)return null;let d=[];for(let c of l){if(typeof c!="string"||c.length===0||n.has(c))return null;n.set(c,i.length),d.push(c)}i.push(d)}let u=new Map;for(let[l,d]of Object.entries(t.representative)){if(typeof d!="string"||l===d)return null;let c=n.get(l);if(c===void 0||n.get(d)!==c)return null;u.set(l,d)}for(let l of i){let d=l.filter(c=>!u.has(c));if(d.length!==1||l.some(c=>u.has(c)&&u.get(c)!==d[0]))return null}return{version:t.version,groups:i,representative:u}}var gP=["name","printing"];function qd(e){return gP.includes(e)}function rT(e,t){return t==="printing"?e.printingOf??e.id:e.name}function nT(e,t){let n=new Map;for(let i of[...new Set(e)].sort(tT)){let u=t.get(i);if(u===void 0)continue;let l=n.get(u);l?l.push(i):n.set(u,[i])}return[...n.values()].filter(i=>i.length>=2).sort((i,u)=>tT(i[0],u[0]))}function tT(e,t){return et?1:0}var Tn=class{rep=new Map;display;constructor(t=null,n,i="representative"){if(this.display=i,!!t)for(let[u,l]of t.representative)i==="representative"&&n&&!n(l)||this.rep.set(u,l)}of(t){return this.rep.get(t)??t}shown(t){return this.display==="best-printing"?t:this.of(t)}get collapsedCount(){return this.rep.size}};var _s=["webgpu","wasm"];function Gd(e,t=e.hover.selection){let n=e.boxes.flatMap((s,r)=>s.face!==null?[r]:[]),i=n.map(s=>e.boxes[s]),u=new Map,l=i.map(s=>{let r=s.face;r.cardId!==null&&r.name!==null&&u.set(r.cardId,r.name);let o={x:s.box[0],y:s.box[1],width:s.box[2],height:s.box[3]};return{aabb:o,rect:{cx:o.x+o.width/2,cy:o.y+o.height/2,w:o.width,h:o.height,angle:0},score:r.similarity,detectorScore:s.score,accepted:r.cardId!==null,displayId:r.cardId??r.topId}}),d=i.flatMap((s,r)=>s.face.kept?[r]:[]),c=qi({proposals:l,kept:d},t);return ws(c,c.map((s,r)=>`${t}_${r}`),{frameWidth:e.frame.width,frameHeight:e.frame.height,names:u},s=>n[s])}function vs(e,t,n,i){let u=i===void 0||i===e.hover.selection?e.hover.cards:Gd(e,i);return Ud(u,{x:t,y:n},e.frame)}var fe=Math.fround,iT=63/88,bP=128,Tt=90,yP=.2,wP=8,_P=.35,vP=.55,xP=.9,$P=Object.freeze({scales:[.95,1,1.05],maxFacesPerFrame:8,budgetMs:1500}),TP=[1,.8824969025845955,.6065306597126334,.32465246735834974,.1353352832366127,.04393693362340742,.011108996538242306],oT=6,SP=fe(fe(180)/fe(Math.PI)),Hd=[fe(.299),fe(.587),fe(.114)];function IP(e){let t=e-90*Math.ceil((e-45)/90);return t<=-45?45:t}function OP(e,t){let n=e%t;return n!==0&&n<0!=t<0?n+t:n}function EP(e,t){let n=e%t;return n===0?0:n<0?fe(n+t):n}function sT(e){let t=Math.floor(e),n=e-t;return n<.5?t:n>.5?t+1:t%2===0?t:t+1}function AP(e,t){let n=e.length,i=Float32Array.from(e).sort(),u=fe(t),l=fe(fe(fe(n*u)+fe(1+fe(u*-1)))-1),d,c;l>=n-1?d=c=n-1:l<0?d=c=0:(d=Math.floor(l),c=d+1);let s=d===c?0:fe(l-d),r=i[d],o=i[c],a=fe(o-r);return s>=.5?fe(o-fe(a*fe(1-s))):fe(r+fe(a*s))}function Wd(e){let{width:t,height:n}=e,i=e.channels??4,u=Math.max(1,Math.ceil(Math.max(n,t)/bP)),l=u===1?n:Math.floor(n/u),d=u===1?t:Math.floor(t/u);if(Math.min(l,d)c[Math.min(l-1,Math.max(0,C))*d+Math.min(d-1,Math.max(0,ee))],o=l-2,a=d-2,p=o*a,h=new Float32Array(p),m=new Float32Array(p),g=new Uint8Array(p),_=new Float32Array(p),w=0,y=0;for(let C=0;Cy&&(y=_[B]))}if(y<=0)return 0;let T=new Float32Array(w);for(let C=0,ee=0;C=S)||!(ee>0))continue;let v=EP(fe(fe(Math.atan2(m[C],h[C]))*SP),90),R=Math.min(Math.trunc(fe(fe(v/90)*Tt)),Tt-1);O[R]=O[R]+ee}let A=new Float64Array(Tt);for(let C=0;CA[P]&&(P=C);let I=A[(P-1+Tt)%Tt],z=A[(P+1)%Tt],G=I-2*A[P]+z,J=G!==0?.5*(I-z)/G:0,q=OP((P+.5+J)*90/Tt,90);return IP(q)}var aT=1;function Kd(e,t,n){let i=Math.abs(n)*(Math.PI/180),u=Math.cos(i),l=Math.sin(i),d=u*u-l*l;if(d>_P){let s=(e*u-t*l)/d,r=(t*u-e*l)/d;if(s>0&&r>0){let o=Math.min(s,r)/Math.max(s,r);if(o>=vP&&o<=xP)return{w:s,h:r,how:"exact"}}}let c=null;for(let s of[iT,1/iT]){let r=s*u+l,o=s*l+u,a=(e*r+t*o)/(r*r+o*o),p=(e-a*r)**2+(t-a*o)**2;(c===null||pw>=0&&w=0&&yuT(e,c,s,l*r,d*r,u))}}function lT(e,t,n){if(Math.abs(e)!["scales","maxFacesPerFrame","budgetMs"].includes(l));if(n.length>0)return`tiltedRetry has unknown key(s) ${n.sort().join(", ")}`;let i=t.scales;if(!Array.isArray(i)||i.length<1||i.length>5||!i.every(l=>typeof l=="number"&&Number.isFinite(l)&&l>=.5&&l<=1.5))return"tiltedRetry.scales must list 1 to 5 numbers from 0.5 to 1.5";let u=l=>typeof l=="number"&&Number.isInteger(l)&&l>=1;return u(t.maxFacesPerFrame)?u(t.budgetMs)?null:"tiltedRetry.budgetMs must be a whole number above 0":"tiltedRetry.maxFacesPerFrame must be a whole number above 0"}var kP=.3;function hT(e,t){let n=Math.max(0,Math.floor(t.x)),i=Math.max(0,Math.floor(t.y)),u=Math.min(e.width,Math.floor(t.x+t.width)),l=Math.min(e.height,Math.floor(t.y+t.height)),d=Math.max(0,u-n),c=Math.max(0,l-i),s=new Uint8ClampedArray(d*c*4);for(let r=0;r=t.tau&&e.margin>=t.delta}function fT(e,t,n){if(lr(e,n)||!n.rotationRetry)return{orientation:0,match:e,retried:!1};let i=[e,...t()],u=-1;for(let l=0;li[u].similarity)&&(u=l);if(u<0){u=0;for(let l=1;li[u].similarity&&(u=l)}return{orientation:u,match:i[u],retried:!0}}function cT(e){let t=[],n=[];return e.forEach((i,u)=>{let l=i.tilted!==void 0&&i.tilted.scale!==null;i.tauPassed&&(i.orientation===0&&!l?t:n).push(u)}),[...t,...n]}function pT(e,t){let n=(t??e.map((i,u)=>u)).filter(i=>e[i].tauPassed);return Ad(n,i=>e[i].aabb,i=>e[i].score,kP)}async function Yd(e,t,n,i,u=Hn,l=null,d=null,c=!1){let s=n.preprocessing,r=n.rule,o=s.size,a=n.dim,p=[],h=[],m=[];for(let N of i){let X=hT(e,N.aabb),{rgba:W,width:re,height:le}=X;ren.matchScored(w,X*a)),T=[];if(r.rotationRetry)for(let N=0;N[N,X])),O=null;if(T.length>0){let N=new Float32Array(T.length*3*g);for(let X=0;X{let W=S.get(N);if(W===void 0||O===null)throw new Error(`the turned looks of proposal ${N} were not embedded`);return(W*3+X-1)*a},P=h.map((N,X)=>fT(y[X],()=>[1,2,3].map(W=>n.matchScored(O,A(X,W))),r)),I=N=>P[N].orientation===0?{embs:w,off:N*a}:{embs:O,off:A(N,P[N].orientation)},z=new Map,G,J,q=!1;if(l)try{let N=performance.now(),X=[],W=[],re=[];for(let le=0;le0){let le=await l.verifyBatch(re,n.bankIds);X.forEach((ce,xe)=>{let qe=le[xe],Ve=W[xe],it=P[ce].match,Ze=F$(Ve,qe.candidates,zr=>n.columnsOf(zr)),$e=l.reorder?n.lookOf(Ze):n.lookWithin(Ze,n.lookOf(Ve).row),{row:ht,...It}=$e;z.set(ce,{match:It,geometric:L$({topId:it.topId,similarity:it.similarity,margin:it.margin,accepted:lr(it,r)},qe)})})}G=performance.now()-N}catch(N){q=!0,J=N,z.clear(),G=void 0}let C=new Map,ee,v,R=!1,H=0;if(d)try{let N=performance.now(),{scales:X,maxFacesPerFrame:W}=d.settings,re=ce=>z.get(ce)?.match??P[ce].match,le=mT(h.map((ce,xe)=>({aabb:ce.aabb,similarity:P[xe].match.similarity,accepted:lr(re(xe),r)})),d.focus??null).slice(0,W);if(le.length>0){let ce=[],xe=new Float32Array(le.length*X.length*g);le.forEach((Ve,it)=>{let Ze=m[Ve],{tilt:$e,rects:ht}=Xd(e,h[Ve].aabb,{data:Ze.rgba,width:Ze.width,height:Ze.height},X);ce.push($e),ht.forEach((It,zr)=>{let Gt=fs(It.rgba,It.width,It.height,s);xe.set(ms(Gt,P[Ve].orientation,o),(it*X.length+zr)*g)})}),H=le.length*X.length;let qe=await t.embedBatch(xe,H);le.forEach((Ve,it)=>{let Ze=re(Ve),$e=null;for(let ht=0;ht$e.match.similarity)&&($e={q:ht,match:It})}C.set(Ve,{match:$e?$e.match:null,evidence:{tilt:ce[it],scale:$e?X[$e.q]:null,before:{topId:Ze.topId,similarity:Ze.similarity,margin:Ze.margin}}})})}ee=performance.now()-N}catch(N){R=!0,v=N,C.clear(),H=0,ee=void 0}let L=new Map,V=N=>{let X=L.get(N);if(X===void 0){let{aabb:W}=h[N],re=m[N],{tilt:le,w:ce,h:xe}=Zd({data:re.rgba,width:re.width,height:re.height},W.width,W.height);X={cx:W.x+W.width/2,cy:W.y+W.height/2,w:ce,h:xe,angle:le},L.set(N,X)}return X},K=N=>{let X=[];for(let W=0;Wt!==null&&t.x>=d.x&&t.x<=d.x+d.width&&t.y>=d.y&&t.y<=d.y+d.height,i=e.map((d,c)=>c).filter(d=>!e[d].accepted),u=i.filter(d=>n(e[d].aabb)).sort((d,c)=>e[d].aabb.width*e[d].aabb.height-e[c].aabb.width*e[c].aabb.height),l=i.filter(d=>!n(e[d].aabb)).sort((d,c)=>e[c].similarity-e[d].similarity);return[...u,...l]}var $s={tau:.62,delta:.05,rotationRetry:!0},xs=-2,Gi=class{constructor(t,n=$s,i=new Tn){this.bank=t;this.rule=n;this.contract=er[t.preprocessing],this.rowShown=t.ids.map(l=>i.shown(l));let u=new Map;this.rowIdent=new Int32Array(t.ids.length);for(let l=0;lc&&(c=p,s=a)}let r=xs,o=s>=0?this.rowIdent[s]:-1;for(let a=0;ar&&(r=d[a]);return{bestRow:s,best:c,other:r}}matchScored(t,n){let{bestRow:i,best:u,other:l}=this.topAndOther(t,n),d=this.bank.ids[i];return{cardId:u>=this.rule.tau?d:null,similarity:u,topId:d,identity:this.identRep[this.rowIdent[i]],displayId:this.rowShown[i],margin:u-l}}scoreRow(t,n){let{matrix:i,dim:u,ids:l}=this.bank,d=new Float64Array(l.length);for(let c=0;cd);n.sort((l,d)=>t[d]-t[l]);let i=new Set,u=[];for(let l of n){let d=this.bank.ids[l];i.has(d)||(i.add(d),u.push({cardId:d,cosine:t[l]}))}return u}columns=null;columnsOf(t){return this.columns===null&&(this.columns=new Map,this.bank.ids.forEach((n,i)=>{let u=this.columns.get(n);u?u.push(i):this.columns.set(n,[i])})),this.columns.get(t)??[]}bankIdSet=null;get bankIds(){return this.columnsOf(""),this.bankIdSet??=new Set(this.columns.keys()),this.bankIdSet}scored(t,n,i){let u=this.bank.ids[t];return{cardId:n>=this.rule.tau?u:null,similarity:n,topId:u,identity:this.identRep[this.rowIdent[t]],displayId:this.rowShown[t],margin:n-i,row:t}}lookOf(t){let n=0;for(let d=1;dt[n]&&(n=d);let i=this.rowIdent[n],u=xs,l=!1;for(let d=0;du)&&(u=t[d]),l=!0);return this.scored(n,t[n],u)}lookWithin(t,n){let i=this.rowIdent[n],u=-1,l=xs,d=!1;for(let c=0;ct[u])&&(u=c):((!d||t[c]>l)&&(l=t[c]),d=!0);return this.scored(u,t[u],l)}matchPooled(t,n=this.rule.delta){let{bestRow:i,best:u,other:l}=this.topAndOther(t,0),d=u-l;return{cardId:u>=this.rule.tau&&d>=n?this.rowShown[i]:null,similarity:u,margin:d}}};var Hi=class{constructor(t=3){this.k=t;if(!Number.isInteger(t)||t<1)throw new RangeError(`k must be a positive integer, got ${t}`)}k;run=0;misses=0;showing=!1;reset(){this.run=0,this.misses=0,this.showing=!1}observe(t){return t?(this.run+=1,this.misses=0,this.run>=this.k&&(this.showing=!0)):(this.run=0,this.misses+=1,this.misses>=this.k&&(this.showing=!1)),{confirmed:this.showing,consecutive:this.run}}};var PP=.4,CP=2,RP=5,DP=2,MP="track_";function gT(e){let t=e[0].length,n=new Float32Array(t);for(let l of e)for(let d=0;d0))return null;for(let l=0;lu));for(let i of this.tracks){let u=-1,l=PP;for(let d of n){let c=Gn(i.detection.aabb,t[d].aabb);c>l&&(l=c,u=d)}if(u>=0){let d=t[u];i.detection=d,i.misses=0,i.age+=1,i.embeddings.push(d.embedding),i.embeddings.length>RP&&i.embeddings.shift(),n.delete(u)}else i.misses+=1}this.tracks=this.tracks.filter(i=>i.misses<=CP);for(let i of n){let u=t[i];this.tracks.push({instanceId:`${MP}${String(this.nextId++).padStart(4,"0")}`,detection:u,embeddings:[u.embedding],misses:0,age:1})}return this.tracks.filter(i=>i.misses===0).map(i=>({instanceId:i.instanceId,detection:i.detection,identity:i.age>=DP?this.identityOf(i):null}))}};var NP=.25,zP=5;function BP(e,t){if(e===null||t===void 0)return!1;let n=t-e;return n<-NP||n>zP}function FP(e){return[e.x,e.y,e.width,e.height]}var Ki=class{hoverSelection;detector;embedder;recognizer;names;classNames;faceClass;minCropPx;now;tracker;gate=new Hi(3);hoverIds=new ys;heldCards=[];lastVideoTimeSec=null;geometric;geometricFailure=null;tiltedRetry;tiltedFailure=null;constructor(t){this.detector=t.detector,this.embedder=t.embedder,this.names=t.names,this.classNames=t.classNames??["face","back"],this.faceClass=t.faceClass??Rr,this.minCropPx=t.minCropPx??Hn,this.hoverSelection=t.hoverSelection??jd,this.now=t.now??(()=>performance.now()),this.geometric=t.geometric??null,this.tiltedRetry=t.tiltedRetry??null;let n=new Tn(t.identityGroups??null,i=>this.names.has(i),t.identityDisplay??"best-printing");this.recognizer=new Gi(t.bank,t.accept??$s,n),this.tracker=new Wi(i=>this.recognizer.matchPooled(i).cardId)}get size(){return this.recognizer.size}takeGeometricFailure(){let t=this.geometricFailure;return this.geometricFailure=null,t}takeTiltedFailure(){let t=this.tiltedFailure;return this.tiltedFailure=null,t}get tiltedSettings(){return this.tiltedRetry}setTiltedRetry(t){this.tiltedRetry=t,this.tiltedFailure=null}get geometricStage(){return this.geometric}setGeometric(t){this.geometric=t,this.geometricFailure=null}reset(){this.tracker.reset(),this.gate.reset(),this.heldCards=[],this.hoverIds.reset(),this.lastVideoTimeSec=null}async analyze(t,n,i={}){let u=this.now(),l=BP(this.lastVideoTimeSec,n);l&&this.reset(),n!==void 0&&(this.lastVideoTimeSec=n);let d=await this.detector.propose(t),c=this.now()-u,s=d.filter(I=>ls(I.aabb,t.width,t.height,this.minCropPx)).map(I=>D$(I,t)),{faces:r}=M$(s,this.faceClass),o=this.now(),a=this.tiltedRetry&&i.tilted!==!1?{settings:this.tiltedRetry,focus:i.focus??null}:null,p=await Yd(t,this.embedder,this.recognizer,r,this.minCropPx,this.geometric,a,i.rotatedOutlines===!0),h=this.now()-o;if(p.tiltedError!==void 0&&this.tiltedRetry&&(this.tiltedFailure={error:p.tiltedError},this.tiltedRetry=null),p.geometricError!==void 0&&this.geometric&&(this.geometricFailure={stage:this.geometric,error:p.geometricError},this.geometric=null),p.proposals.length!==r.length)throw new Error("pipeline: a valid face box was not recognized");let m={frameWidth:t.width,frameHeight:t.height,names:this.names},g=qi(p,this.hoverSelection),_=r.map(I=>s.indexOf(I)),w=ws(g,this.hoverIds.assign(g),m,I=>_[I]),y=p.base??p,T=y.kept.map(I=>{let z=y.proposals[I];return{aabb:z.aabb,rect:z.rect,cardId:z.topId,embedding:z.embedding,...z.outline?{outline:z.outline}:{}}}),S=this.tracker.update(T),O=T.length>0,A=this.gate.observe(O),P;return A.confirmed?O?(P=bs(S.map(I=>({instanceId:I.instanceId,aabb:I.detection.aabb,rect:I.detection.rect,...I.detection.outline?{outline:I.detection.outline}:{},identity:I.identity})),m),this.heldCards=P):P=this.heldCards:(this.heldCards=[],P=[]),{frame:{width:t.width,height:t.height},boxes:this.boxResults(s,r,p),hover:{selection:this.hoverSelection,cards:w},tracks:{shown:A.confirmed,cards:P},discontinuity:l,retried:p.retried,embeddings:p.embeddings,timings:{detectorMs:c,recognizeMs:h,analyzeMs:this.now()-u,...p.geometricMs!==void 0?{geometricMs:p.geometricMs}:{},...p.tiltedMs!==void 0?{tiltedMs:p.tiltedMs}:{}}}}boxResults(t,n,i){let u=new Map(n.map((d,c)=>[d,c])),l=new Set(i.kept);return t.map(d=>{let c=u.get(d),s=null;if(c!==void 0){let r=i.proposals[c],o=r.accepted&&this.names.has(r.displayId)?r.displayId:null;s={topId:r.topId,topName:this.names.get(r.topId)??null,similarity:r.score,margin:r.margin,look:r.orientation,retried:r.retried,tauPassed:r.tauPassed,accepted:r.accepted,cardId:o,name:o===null?null:this.names.get(o)??null,kept:l.has(c),...r.geometric?{geometric:r.geometric}:{},...r.tilted?{tilted:r.tilted}:{}}}return{box:FP(d.aabb),score:d.score,cls:d.cls,className:this.classNames[d.cls]??String(d.cls),face:s}})}};var bT=1,yT="vision-release",LP=[8,16,32];function wT(e,t){return LP.reduce((n,i)=>n+Math.floor(e/i)*Math.floor(t/i),0)}var jP=/^[0-9a-f]{16}$/,UP=/^[0-9a-f]{64}$/,VP=/^\d+\.\d+\.\d+$/,qP=["schemaVersion","kind","id","game","locale","detector","recognizer","bank","identity","catalog","accept","hover","runtime","tiltedRetry"],_T=["tau","delta","rotationRetry"],Ue=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ft=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,Ji=e=>typeof e=="number"&&Number.isFinite(e),tt=e=>typeof e=="string"&&e.trim()!=="";function GP(e){return!tt(e)||e.includes("\\")||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e)||/[\x00-\x1f\x7f]/.test(e)||/^ | $/.test(e)||e.startsWith("/")?!1:!e.split("/").some(t=>{let n=t.replace(/%2e/gi,".");return n==="."||n===".."})}function Zi(e){return!Ue(e)||!GP(e.path)||typeof e.sha256!="string"||!UP.test(e.sha256)||!ft(e.bytes)?null:{path:e.path,sha256:e.sha256,bytes:e.bytes}}function HP(e){let t=e.input,n=e.decode;if(!Ue(t)||!ft(t.width)||!ft(t.height))return"detector.input must give a width and a height";if(!Ue(n))return"detector.decode must be an object";if(!tt(n.inputName)||!tt(n.outputName))return"detector.decode must name the model's input and output";let i=[["layout","NCHW"],["channels","BGR"],["scale","0-255"],["score","obj * max(cls)"],["class","argmax(cls)"]];for(let[o,a]of i)if(n[o]!==a)return`detector.decode.${o} is not ${JSON.stringify(a)}, the contract this runtime implements`;let u=n.letterbox;if(!Ue(u)||u.width!==t.width||u.height!==t.height)return"detector.decode.letterbox differs from detector.input";if(typeof u.pad!="number"||!Number.isInteger(u.pad)||u.pad<0||u.pad>255)return"detector.decode.letterbox.pad must be a whole number from 0 to 255";let l=[["anchor","top-left"],["resize","pillow-bilinear"],["ratio","min(height / frameHeight, width / frameWidth)"],["size","round(frame * ratio)"]];for(let[o,a]of l)if(u[o]!==a)return`detector.decode.letterbox.${o} is not ${JSON.stringify(a)}`;let d=n.classes;if(!Array.isArray(d)||d.length===0||!d.every(tt)||new Set(d).size!==d.length)return"detector.decode.classes must be a list of distinct class names";if(e.faceClass!==Rr||d[Rr]!=="face")return`detector.faceClass must be ${Rr} and that class must be named "face"`;let c=n.output,s=["cx","cy","w","h","obj",...d.map(o=>`cls_${o}`)];if(!Ue(c)||!Array.isArray(c.columns)||c.columns.length!==s.length||!c.columns.every((o,a)=>o===s[a]))return"detector.decode.output.columns must be cx, cy, w, h, obj and one cls_ per class";if(c.anchors!==wT(t.width,t.height))return`detector.decode.output.anchors must be ${wT(t.width,t.height)} for a ${t.width} x ${t.height} input`;if(!Ji(n.threshold)||!(n.threshold>0&&n.threshold<1))return"detector.decode.threshold must be a number between 0 and 1";if(n.threshold<.01)return`detector.decode.threshold ${n.threshold} is below 0.01, the lowest score at which the detector export checks box parity`;let r=n.nms;return!Ue(r)||!Ji(r.iou)||!(r.iou>0&&r.iou<=1)||r.classAgnostic!==!0||r.greedy!==!0?"detector.decode.nms must give an iou above 0 and at most 1, with classAgnostic and greedy both true":ft(n.maxProposals)?ft(e.minCropPx)?{inputName:n.inputName,outputName:n.outputName,letterbox:{width:t.width,height:t.height,pad:u.pad},anchors:c.anchors,classes:d,decode:{threshold:n.threshold,nmsIou:r.iou,maxProposals:n.maxProposals},faceClass:Rr,minCropPx:e.minCropPx}:"detector.minCropPx must be a whole number above 0":"detector.decode.maxProposals must be a whole number above 0"}function xT(e){let t=A=>({error:A});if(!Ue(e)||e.schemaVersion!==bT||e.kind!==yT)return t(`not a "${yT}" document of schema version ${bT}`);let n=Object.keys(e).filter(A=>!qP.includes(A));if(n.length>0)return t(`unknown key(s) ${n.sort().join(", ")}`);if(typeof e.id!="string"||!jP.test(e.id))return t("id must be 16 lowercase hex digits");if(!tt(e.game)||!tt(e.locale))return t("game and locale must be non-empty strings");let i=e.detector;if(!Ue(i))return t("incomplete release: detector missing (a release is all-or-nothing)");let u=Zi(i);if(!u||!tt(i.version)||!tt(i.weights))return t("detector must pin a file and carry a version and a weights label");if(i.arm!=="yolox")return t(`detector.arm ${JSON.stringify(i.arm)} is not one this runtime implements`);let l=HP(i);if(typeof l=="string")return t(l);let d=e.recognizer;if(!Ue(d))return t("incomplete release: recognizer missing (a release is all-or-nothing)");let c=Zi(d);if(!c||!tt(d.version)||!tt(d.weights)||!ft(d.dim))return t("recognizer must pin a file and carry a version, a weights label and a dim");if(!tt(d.inputName)||!tt(d.outputName))return t("recognizer must name the model's input and output");let s=hs(d.preprocessing);if(s===null)return t(`recognizer.preprocessing is not a contract this runtime implements (known: ${Object.keys(er).join(", ")})`);let r=e.bank;if(!Ue(r))return t("incomplete release: bank missing (a release is all-or-nothing)");let o=Zi(r);if(!o||!ft(r.version)||!ft(r.cardCount)||!ft(r.entryCount))return t("bank must pin a file and carry a version, a cardCount and an entryCount");if(r.aggregation!=="mean")return t('bank.aggregation must be "mean"');let a=e.identity;if(!Ue(a)||!qd(a.level))return t('identity.level must be "name" or "printing"');let p=a.groups,h=Zi(p);if(!h||!Ue(p)||!ft(p.version))return t("incomplete release: identity.groups must pin a file and carry a version");if(a.display!=="best-printing"&&a.display!=="representative")return t(`identity.display ${JSON.stringify(a.display)} is not one of best-printing, representative`);let m=e.catalog,g=Zi(m);if(!g||!Ue(m)||!ft(m.cardCount))return t("incomplete release: catalog must pin a file and carry a cardCount");let _=e.accept;if(!Ue(_))return t("incomplete release: accept missing (a release is all-or-nothing)");if(Object.keys(_).some(A=>!_T.includes(A)))return t(`accept has unknown key(s) (expected ${_T.join(", ")})`);if(!Ji(_.tau)||!(_.tau>0&&_.tau<=1))return t("accept.tau must be a number above 0 and at most 1");if(!Ji(_.delta)||!(_.delta>=0&&_.delta<1))return t("accept.delta must be a number from 0 to below 1");if(typeof _.rotationRetry!="boolean")return t("accept.rotationRetry must be true or false");let w=e.hover;if(!Ue(w)||!Q$(w.selection))return t("hover.selection is not one of accepted-nms, best-score, detector-score");if(!ft(w.maxAgeMs))return t("hover.maxAgeMs must be a whole number above 0");let y=e.runtime;if(!Ue(y)||typeof y.ortWeb!="string"||!VP.test(y.ortWeb))return t("runtime.ortWeb must be an exact version of the form 1.2.3");if(y.wasmThreads!==1)return t("runtime.wasmThreads must be 1");let T=y.executionProviders;if(!Array.isArray(T)||T.length===0||new Set(T).size!==T.length||!T.every(A=>_s.includes(A)))return t(`runtime.executionProviders must list one or more of ${_s.join(", ")}, each once`);let S=y.analysisWidth;if(!Ue(S)||!ft(S.min)||!ft(S.max)||S.min>S.max)return t("runtime.analysisWidth must give whole numbers min <= max above 0");let O=null;if("tiltedRetry"in e){let A=dT(e.tiltedRetry);if(A!==null)return t(A);let P=e.tiltedRetry;O={scales:[...P.scales],maxFacesPerFrame:P.maxFacesPerFrame,budgetMs:P.budgetMs}}return{release:{id:e.id,game:e.game,locale:e.locale,detector:{...u,arm:"yolox",version:i.version,weights:i.weights,settings:l},recognizer:{...c,version:d.version,weights:d.weights,dim:d.dim,inputName:d.inputName,outputName:d.outputName,preprocessing:s},bank:{...o,version:r.version,cardCount:r.cardCount,entryCount:r.entryCount},identity:{level:a.level,groups:{...h,version:p.version},display:a.display},catalog:{...g,cardCount:m.cardCount},accept:{tau:_.tau,delta:_.delta,rotationRetry:_.rotationRetry},hover:{selection:w.selection,maxAgeMs:w.maxAgeMs},runtime:{ortWeb:y.ortWeb,executionProviders:T,wasmThreads:1,analysisWidth:{min:S.min,max:S.max}},tiltedRetry:O}}}function WP(e){let t=0,n=()=>{throw new Error("not JSON")},i=()=>{for(;t{let c=t;for(e[t]!=='"'&&n(),t++;t=e.length&&n(),t++,JSON.parse(e.slice(c,t))},l=c=>{i();let s=e[t];if(s==="{"){t++;let o=[];if(i(),e[t]==="}")t++;else for(;;){i();let a=u();i(),e[t]!==":"&&n(),t++;let p=l(!1);if(c&&a==="id"||o.push([a,p]),i(),e[t]===",")t++;else if(e[t]==="}"){t++;break}else n()}return o.sort((a,p)=>a[0]p[0]?1:0),`{${o.map(([a,p])=>`${JSON.stringify(a)}:${p}`).join(",")}}`}if(s==="["){t++;let o=[];if(i(),e[t]==="]")t++;else for(;;)if(o.push(l(!1)),i(),e[t]===",")t++;else if(e[t]==="]"){t++;break}else n();return`[${o.join(",")}]`}if(s==='"')return JSON.stringify(u());let r=/^(?:true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(e.slice(t,t+64));return r?(t+=r[0].length,r[0]):n()};i(),e[t]!=="{"&&n();let d=l(!0);return i(),t!==e.length&&n(),d}async function KP(e,t){let n=new TextEncoder().encode(WP(e));return(await t(n.buffer)).slice(0,16)}async function XP(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}var Jd={fetchFn:e=>fetch(e),digestSha256Hex:XP};function ZP(e,t){let n=l=>/^(\d+)\.(\d+)\.\d+/.exec(l),i=n(e),u=n(t);return i!==null&&u!==null&&i[1]===u[1]&&i[2]===u[2]}var We=class extends Error{};async function $T(e,t,n){let i;try{i=await e.fetchFn(t)}catch(u){throw new We(`${n}: fetch failed (${String(u)})`)}if(!i.ok)throw new We(`${n}: HTTP ${i.status}`);return i.arrayBuffer()}async function Yi(e,t,n,i){let u=await $T(e,new URL(n.path,t).href,i);if(u.byteLength!==n.bytes)throw new We(`${i}: ${n.path} is ${u.byteLength} bytes, the release says ${n.bytes}`);if(await e.digestSha256Hex(u)!==n.sha256)throw new We(`${i}: sha256 of ${n.path} does not match the release`);return u}function Ts(e,t){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new We(`${t}: the file is not JSON`)}}var YP=/^[a-z][a-zA-Z0-9]*$/,JP=["key","label","values","type"],vT=e=>typeof e=="string"?"text":"number",dr=e=>JSON.stringify(e)??String(e);function TT(e,t,n){for(let i=0;i!JP.includes(r));if(l.length>0)return`${u}: unknown key(s) ${l.join(", ")}`;if(typeof i.key!="string"||!YP.test(i.key))return`${u}: "key" ${dr(i.key)} must be a lowercase letter, then letters and digits only`;let d=i.key;if(d==="kind")return`${u}: "key" "kind" is reserved: the card's kind is always the first filter`;if(t.some(r=>r.key===d))return`${u}: duplicate key ${dr(d)}`;if(!tt(i.label))return`${u} (${d}): "label" must be a non-empty string`;let c=null;if("type"in i){if(i.type!=="text"&&i.type!=="number")return`${u} (${d}): "type" must be "text" or "number", not ${dr(i.type)}`;c=i.type}let s=null;if("values"in i){if(!Array.isArray(i.values)||i.values.length===0)return`${u} (${d}): "values" must be a non-empty list`;let r=TT(i.values,c,`${u} (${d}) values`);if(r!=="text"&&r!=="number")return r;c=r,s=i.values}t.push({key:d,label:i.label,type:c,values:s})}return t}function eC(e,t,n,i){let u=`card ${n}`;if(!Ue(e))return`${u}: "facets" must be an object of facet key to a value or a list of values`;for(let[l,d]of Object.entries(e)){let c=t.find(o=>o.key===l);if(c===void 0)return`${u}: facets.${l}: the catalog declares no facet ${dr(l)}`;let s=Array.isArray(d)?d:[d];if(s.length===0)return`${u}: facets.${l} is an empty list (leave the key out instead)`;let r=TT(s,c.type,`${u}: facets.${l}`);if(r!=="text"&&r!=="number")return r;c.type=r;for(let o of s){if(c.values!==null&&!c.values.includes(o))return`${u}: facets.${l}: ${dr(o)} is not one of the declared values`;let a=i.get(l)??[];a.includes(o)||a.push(o),i.set(l,a)}}return null}function tC(e){if(!Ue(e)||!tt(e.game)||!tt(e.locale)||!Array.isArray(e.cards)||e.cards.length===0)return"the file is not a catalog (game, locale and a list of cards)";let t=e.identity===void 0?"name":e.identity;if(!qd(t))return`"identity" must be "name" or "printing", not ${JSON.stringify(e.identity)}`;let n=e.facets===void 0?[]:QP(e.facets);if(typeof n=="string")return n;let i=new Map,u=new Map,l=[];for(let c of e.cards){if(!Ue(c)||!tt(c.id)||!tt(c.name))return"every card needs an id, a name and an art path";if(!("art"in c)||c.art!==null&&!tt(c.art))return`card ${c.id}: "art" must be an art path (a file path or an http(s) URL), or null for a card without art`;if(u.has(c.id))return`card id ${c.id} appears twice`;let s=c.printingOf??null;if(s!==null&&!tt(s))return`card ${c.id}: "printingOf" must be a card id or null`;let r=c.facets===void 0?null:eC(c.facets,n,c.id,i);if(r!==null)return r;if(c.extra!==void 0&&!Ue(c.extra))return`card ${c.id}: "extra" must be an object (any keys and values), not ${dr(c.extra)}`;let o={id:c.id,name:c.name,art:c.art,printingOf:s};c.extra!==void 0&&(o.extra=c.extra),u.set(o.id,o),l.push(o)}if(t==="printing")for(let c of l){if(c.printingOf===null)continue;let s=u.get(c.printingOf);if(s===void 0||s===c)return`card ${c.id}: "printingOf" names ${c.printingOf}, which is not another card`;if(s.printingOf!==null)return`card ${c.id}: "printingOf" names ${c.printingOf}, which is itself a printing of ${s.printingOf}`}let d=n.map(c=>{let s=c.values??[...i.get(c.key)??[]];return c.values===null&&c.type==="number"&&s.sort((r,o)=>r-o),{key:c.key,label:c.label,type:c.type??"text",values:[...s]}});return{game:e.game,locale:e.locale,identity:t,cards:l,facets:d}}async function Qd(e,t=Jd,n={}){try{let i=await $T(t,e,"release"),u=xT(Ts(i,"release"));if("error"in u)throw new We(`release: ${u.error}`);let l=u.release,d=await KP(new TextDecoder().decode(i),t.digestSha256Hex);if(d!==l.id)throw new We(`release: id ${l.id} is not the hash of the document (which is ${d})`);if(n.ortWeb!==void 0&&!ZP(l.runtime.ortWeb,n.ortWeb))throw new We(`release: measured on onnxruntime-web ${l.runtime.ortWeb}, this build runs ${n.ortWeb} (major and minor version must match)`);try{n.onDocument?.([l.detector,l.recognizer,l.bank,l.identity.groups,l.catalog].reduce((G,J)=>G+J.bytes,0))}catch{}let[c,s,r,o,a]=await Promise.all([Yi(t,e,l.detector,"detector"),Yi(t,e,l.recognizer,"recognizer"),Yi(t,e,l.bank,"bank"),Yi(t,e,l.identity.groups,"identity.groups"),Yi(t,e,l.catalog,"catalog")]);try{n.onFetched?.()}catch{}let p=new Uint8Array(r),h=Bd(p);if(h!==null&&h!==gs)throw new We(`bank: the binary bank is of format version ${h}, and this runtime reads version ${gs} only`);let m=zd(p)?X$(p):Nd(Ts(r,"bank"));if(!m)throw new We("bank: the file is not a bank this runtime can read");let g=[[m.version===l.bank.version,"bank.version differs from the bank file's"],[m.model===l.recognizer.version,`bank: the file's model ${JSON.stringify(m.model)} is not recognizer.version ${JSON.stringify(l.recognizer.version)}`],[m.dim===l.recognizer.dim,"bank: the vector size differs from recognizer.dim"],[m.preprocessing===l.recognizer.preprocessing,"bank: the file's preprocessing differs from recognizer.preprocessing"],[m.ids.length===l.bank.entryCount,"bank.entryCount is not the number of entries in the bank file"],[new Set(m.ids).size===l.bank.cardCount,"bank.cardCount is not the number of distinct card ids in the bank file"],[m.tau===null||m.tau===l.accept.tau,`bank: the file records tau ${m.tau}, accept.tau is ${l.accept.tau}`]];for(let[G,J]of g)if(!G)throw new We(J);let _=tC(Ts(a,"catalog"));if(typeof _=="string")throw new We(`catalog: ${_}`);if(_.game!==l.game||_.locale!==l.locale)throw new We("catalog: the file is for another game or locale");if(_.cards.length!==l.catalog.cardCount)throw new We(`catalog.cardCount ${l.catalog.cardCount} is not the file's ${_.cards.length} cards`);let w=new Map(_.cards.map(G=>[G.id,G.name])),y=m.ids.filter(G=>!w.has(G));if(y.length>0)throw new We(`${new Set(y).size} bank id(s) are not in the catalog (e.g. ${y[0]})`);let T=Ts(o,"identity.groups"),S=Vd(T);if(!S)throw new We("identity.groups: the file is not an identity-groups document");if(S.version!==l.identity.groups.version)throw new We("identity.groups.version differs from the file's");if((Ue(T)&&Ue(T.bank)?T.bank.sha256:void 0)!==l.bank.sha256)throw new We("identity.groups: the file was not made for this release's bank (its bank sha256 differs)");let A=_.identity;if(l.identity.level!==A)throw new We(`identity.level is "${l.identity.level}", and the catalog states the identity rule "${A}": a release is used with the rule its catalog states`);if((Ue(T)&&Ue(T.rule)?T.rule.level:void 0)!==A)throw new We(`identity.groups: the file's groups are not by ${A}`);let I=new Map(_.cards.map(G=>[G.id,rT(G,A)])),z=G=>JSON.stringify(G.map(J=>[...J].sort()).sort((J,q)=>J[0]q[0]?1:0));if(z(S.groups)!==z(nT(m.ids,I)))throw new We(`identity.groups: the groups are not the ones the catalog's ${A==="name"?"names give":"identity rule gives"} for the bank's ids`);return{ok:!0,data:{release:l,detectorBytes:new Uint8Array(c),recognizerBytes:new Uint8Array(s),bank:m,identityGroups:S,cards:_.cards,names:w}}}catch(i){return{ok:!1,reason:i instanceof We?i.message:`unexpected: ${String(i)}`}}}async function rC(e){for(let t of e)try{await t?.release?.()}catch{}}async function ST(e,t,n=e.release.runtime.executionProviders){let{release:i}=e,u=null,l=null,d=async c=>(await rC([u,l]),{error:c});try{if(n.length===0)return await d("no execution provider to try");let c=i.recognizer;return u=await t.embedder(e.recognizerBytes,{inputName:c.inputName,outputName:c.outputName,inputSize:er[c.preprocessing].size,dim:c.dim},n),u?(l=await t.detector(e.detectorBytes,i.detector.settings,n),l?{pipeline:new Ki({detector:l,embedder:u,bank:e.bank,accept:i.accept,identityGroups:e.identityGroups,identityDisplay:i.identity.display,names:e.names,hoverSelection:i.hover.selection,classNames:i.detector.settings.classes,faceClass:i.detector.settings.faceClass,minCropPx:i.detector.settings.minCropPx,tiltedRetry:i.tiltedRetry}),embedder:u,detector:l,providers:[...n]}:await d("detector: the model did not initialize on any execution provider, or is not the model the release describes")):await d("recognizer: the model did not initialize on any execution provider, or is not the model the release describes")}catch(c){return await d(`unexpected while building: ${String(c)}`)}}var Qi=class extends Error{constructor(n){super(`the release could not be loaded: ${n}`);this.reason=n;this.name="ReleaseError"}reason};function nC(e){return async t=>{if(!t.startsWith(Wn))throw new Error(`${t} is not one of the release's files`);let n=U$(t.slice(Wn.length)),i=Object.hasOwn(e,n)?e[n]:void 0;if(i===void 0)throw new Error(`no file ${n} among the release's files`);return{ok:!0,status:200,arrayBuffer:()=>i.arrayBuffer()}}}var Dr=e=>Math.round(e);function iC(e){let t=(n,i)=>{let u=performance.now()-i;return{createMs:Dr(n.createMs),firstRunMs:Dr(n.firstRunMs),failedProvidersMs:Dr(Math.max(0,u-n.createMs-n.firstRunMs)),totalMs:Dr(u)}};return{embedder:async(n,i,u)=>{let l=performance.now(),d=await ji.create(n,i,u);return d&&(e.recognizer=t(d.setup,l)),d},detector:async(n,i,u)=>{let l=performance.now(),d=await Li.create(n,i,u);return d&&(e.detector=t(d.setup,l)),d}}}async function oC(e,t={}){let n=t.files?Wn:typeof location<"u"?location.href:void 0,i=new URL(e,n).href,u=g=>{try{t.onProgress?.(g)}catch{}},l=performance.now();u({phase:"downloading",bytes:null});let d={...Jd,...t.deps,...t.files?{fetchFn:nC(t.files)}:{}},c=null,s=await Qd(i,d,{ortWeb:k$(),onFetched:()=>{c=performance.now()},...t.onProgress?{onDocument:g=>u({phase:"downloading",bytes:g})}:{}});if(!s.ok)throw new Qi(s.reason);let r=performance.now(),o=(c??r)-l,a=r-(c??r);u({phase:"preparing"});let{data:p}=s;P$({wasmThreads:p.release.runtime.wasmThreads,...t.wasmPaths!==void 0?{wasmPaths:t.wasmPaths}:{}}),Od();let h={},m=await ST(p,iC(h),t.providers??p.release.runtime.executionProviders);if("error"in m){let g=Od();throw new Qi(g.length>0?`${m.error} (${g.join("; ")})`:m.error)}return{release:p.release,pipeline:m.pipeline,backend:{detector:m.detector.ep,recognizer:m.embedder.ep},cards:p.cards,names:p.names,stageInputs:{bankSha256:p.release.bank.sha256,bankIds:[...new Set(p.bank.ids)],identities:j$(p.cards,p.release.identity.level,p.identityGroups)},...h.recognizer&&h.detector?{timings:{startedAtMs:Dr(l),filesMs:Dr(o),readMs:Dr(a),recognizer:h.recognizer,detector:h.detector,totalMs:Dr(performance.now()-l)}}:{},dispose:async()=>{await m.embedder.release?.(),await m.detector.release?.()}}}function sC(e,t,n){return e.pipeline.analyze(t,n)}function Ss(e){return e==="wasm"?2e3:1e3}function aC(e){return e==="wasm"?1e3:500}function Is(e,t){return t==="always-on"?Ss(e):aC(e)}var uC=1920,lC=720;function As(e,t,n={min:720,max:1920}){let i=Math.max(n.min,Math.min(n.max,e));return{width:i,height:Math.max(1,Math.round(i*t/e))}}function ET(e,t,n){if(!(e.width>0&&e.height>0))return null;let i=(t-e.left)/e.width,u=(n-e.top)/e.height;return i>=0&&i<=1&&u>=0&&u<=1?{x:i,y:u}:null}function Zn(e){return e instanceof HTMLVideoElement?{width:e.videoWidth,height:e.videoHeight}:{width:e.naturalWidth,height:e.naturalHeight}}function dC(e){return e instanceof HTMLVideoElement?e.currentTime:0}async function ec(e,t,n,i){let u=Zn(e),l=As(u.width,u.height,i);t.width=l.width,t.height=l.height;let d=performance.now(),c=dC(e);return n.drawImage(e,0,0,t.width,t.height),{bitmap:await createImageBitmap(t),videoTimeSec:c,tapMs:performance.now()-d}}var IT=128,OT=.06,cC=.5,AT=60,Es=class{ref=null;seeded=!1;seed(t){this.ref=t,this.seeded=!0}reset(){this.ref=null,this.seeded=!1}get hasReference(){return this.ref!==null}observe(t,n){let i=this.ref;if(i===null||i.width!==t.width||i.height!==t.height)return this.ref=t,this.seeded=!1,{distance:null,cut:!1};let u=fC(i,t,n);return u===null?{distance:u,cut:!1}:u>OT?{distance:u,cut:!0}:((this.seeded||u<=OT*cC)&&(this.ref=t),this.seeded=!1,{distance:u,cut:!1})}};function pC(e,t){return{width:IT,height:Math.max(1,Math.round(IT*t/Math.max(1,e)))}}function hC(e,t,n){let i=new Uint8Array(t*n);for(let u=0,l=0;u>8;return i}function fC(e,t,n){if(e.width!==t.width||e.height!==t.height||!(n.width>0)||!(n.height>0))return null;let{width:i,height:u}=e,l=Os(Math.floor(n.x*i),0,i-1),d=Os(Math.ceil((n.x+n.width)*i),l+1,i),c=Os(Math.floor(n.y*u),0,u-1),s=Os(Math.ceil((n.y+n.height)*u),c+1,u),r=0;for(let o=c;o{s=!1});function o(p){return d.find(h=>h.ticket===p)}function a(p){p.fence&&t.deleteSync(p.fence),p.fence=null,p.ticket=null}return{get usable(){return s&&!t.isContextLost()},sample(p){let h=Zn(p);if(!this.usable||h.width===0||h.height===0)return null;let m=d.find(y=>y.ticket===null);if(!m){if(d.length>=mC)return null;let y=t.createBuffer();if(!y)return null;m={pbo:y,fence:null,width:0,height:0,ticket:null},d.push(m)}let{width:g,height:_}=pC(h.width,h.height);try{(e.width!==g||e.height!==_)&&(e.width=g,e.height=_),t.viewport(0,0,g,_),t.bindTexture(t.TEXTURE_2D,l),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,p),t.generateMipmap(t.TEXTURE_2D),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindBuffer(t.PIXEL_PACK_BUFFER,m.pbo),(m.width!==g||m.height!==_)&&(t.bufferData(t.PIXEL_PACK_BUFFER,g*_*4,t.STREAM_READ),m.width=g,m.height=_),t.readPixels(0,0,g,_,t.RGBA,t.UNSIGNED_BYTE,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),m.fence=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0),t.flush()}catch{return s=!1,null}if(!m.fence)return null;let w={id:c++};return m.ticket=w,w},read(p){let h=o(p);if(!h||!h.fence||!this.usable||t.getSyncParameter(h.fence,t.SYNC_STATUS)!==t.SIGNALED)return null;let m=h.width*h.height*4;r.length!==m&&(r=new Uint8Array(m)),t.bindBuffer(t.PIXEL_PACK_BUFFER,h.pbo),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,r),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);let g={width:h.width,height:h.height,luma:hC(r,h.width,h.height)};return a(h),g},release(p){if(!p)return;let h=o(p);h&&a(h)},dispose(){if(s=!1,!t.isContextLost()){for(let p of d)a(p),t.deleteBuffer(p.pbo);d.length=0,t.getExtension("WEBGL_lose_context")?.loseContext()}}}}function tc(e,t,n){let i={left:e.left,top:e.top,width:e.width,height:e.height};if(t.width<=0||t.height<=0||n==="fill")return i;let u=e.width/t.width,l=e.height/t.height,d;n==="cover"?d=Math.max(u,l):n==="none"?d=1:n==="scale-down"?d=Math.min(1,u,l):d=Math.min(u,l);let c=t.width*d,s=t.height*d;return{left:e.left+(e.width-c)/2,top:e.top+(e.height-s)/2,width:c,height:s}}var wC=250,CT=250,_C=1e4,vC=5e3,xC=400,rc=2e3;function RT(e,t,n){return Math.abs(t-e)*1e3<=n}var $C=250,DT=5e3,MT=15e3,PT=[250,500,1e3,2e3];function nc(e,t){return e===void 0?"stale-request":e.requestId<=t.lastAcceptedRequestId?"superseded":e.requestId!==t.inFlightRequestId?"stale-request":e.videoKey!==t.videoKey?"video-key":e.generation!==t.generation?"generation":null}function NT(e){return e==="video-key"||e==="generation"}var eo=class{constructor(t,n=3,i="always-on",u=t,l=null){this.intervalMs=t;this.confirmFrames=n;this.mode=i;this.readingIntervalMs=u;this.probeIntervalMs=l;this.checkProbe(i)}intervalMs;confirmFrames;mode;readingIntervalMs;probeIntervalMs;pending=!1;repeatsLeft=0;lastStartedAt=-1/0;pointerInside=!1;lastPointerAt=-1/0;tooltipShowing=!1;lastTooltipAt=-1/0;lastHoverTriggerAt=-1/0;lastVideoTimeSec=null;discontinuitySinceLast=!1;lastTriggerKind=null;lookRequested=!1;unanswered=0;retryAt=null;retryPrompt=!1;lastUnansweredCapture=!1;refused=!1;pointerAnalysis=!1;checkProbe(t){if(t==="layout"&&!(this.probeIntervalMs!==null&&this.probeIntervalMs>0))throw new Error("layout mode needs a positive probe interval")}setProbeIntervalMs(t){this.probeIntervalMs=t,this.checkProbe(this.mode)}setPointerAnalysis(t){this.pointerAnalysis=t}setIntervalMs(t){this.intervalMs=t}setReadingIntervalMs(t){this.readingIntervalMs=t}setTooltipShowing(t,n){this.tooltipShowing=t,t&&this.pointerInside&&(this.lastTooltipAt=n)}setMode(t){this.checkProbe(t),this.mode=t}get analysisMode(){return this.mode}framePresented(){this.pending=!0,this.repeatsLeft=0}discontinuity(){this.discontinuitySinceLast=!0,this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}requestLook(){this.discontinuitySinceLast=!0,this.pending=!0,this.repeatsLeft=0,this.lookRequested=!0}lookUnanswered(t,n={}){this.repeatsLeft=0,this.retryAt=t+PT[Math.min(this.unanswered,PT.length-1)],this.retryPrompt=n.prompt===!0,this.lastUnansweredCapture=n.prompt===!0,this.unanswered+=1}lookAnswered(){this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}lookRefused(){this.refused=!0}pictureReceived(){this.refused=!1,this.lastUnansweredCapture&&(this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1)}retryReady(t){return this.retryAt!==null&&t>=this.retryAt}get lookPending(){return this.lookRequested}pointerMoved(t){this.pointerInside=!0,this.lastPointerAt=t,(this.unanswered>0||this.refused)&&this.retryAt===null&&(this.retryAt=t,this.retryPrompt=!1)}pointerLeft(t){this.pointerInside&&(this.lastPointerAt=t),this.pointerInside=!1,this.lastTooltipAt=-1/0}tapped(t){this.lastPointerAt=t}pointerActive(t){return t-this.lastPointerAt<_C}analysisState(t){if(this.mode==="always-on")return"always-on";if(this.mode==="layout"){let n=this.pointerAnalysis?this.pointerState(t):"idle";return n==="idle"?"probe":n}return this.pointerState(t)}pointerState(t){return this.pointerActive(t)?"fast":this.pointerInside&&(this.tooltipShowing||t-this.lastTooltipAt=this.intervalInEffectMs(t):this.analysisState(t)==="probe"?!1:this.repeatsLeft>0&&n>=wC}staleFrameMs(t){return Math.max(xC,this.intervalInEffectMs(t))}frameStale(t,n){return this.lastVideoTimeSec===null||this.discontinuitySinceLast?!0:Math.abs(t-this.lastVideoTimeSec)*1e3>this.staleFrameMs(n)}hoverTriggerDue(t,n,i){let u=this.analysisState(t);return i||u==="idle"||u==="probe"||t-this.lastHoverTriggerAt<$C?!1:this.frameStale(n,t)}started(t,n={}){this.retryReady(t)&&(this.retryAt=null,this.retryPrompt=!1,this.pending=!0,this.repeatsLeft=0),this.lastStartedAt=t;let i=n.trigger==="hover",u=n.trigger==="cut"||this.lookRequested;this.lastTriggerKind=i?"hover":u?"cut":this.pending?"cadence":"repeat",i&&(this.lastHoverTriggerAt=t),n.videoTimeSec!==void 0&&(this.lastVideoTimeSec=n.videoTimeSec),this.discontinuitySinceLast=!1,this.lookRequested=!1,this.pending||i||u?(this.pending=!1,this.repeatsLeft=this.analysisState(t)==="probe"?0:this.confirmFrames-1):this.repeatsLeft>0&&(this.repeatsLeft-=1)}get lastTrigger(){return this.lastTriggerKind}msSinceLastAnalysis(t){return this.lastStartedAt===-1/0?null:t-this.lastStartedAt}get idle(){return!this.pending&&this.repeatsLeft===0&&this.retryAt===null}};var ks="no picture",SC="no picture (the paused video draws nothing)",ic="no 2d context",IC="the video may not be read",OC="the picture is too large",EC=16,AC=9,zT=()=>document.createElement("canvas"),kC=e=>createImageBitmap(e);function oc(){return{canvas:null,readable:!1}}function BT(e){return e.paused&&e.readyState<2&&e.videoWidth>0}function sc(e,t){let n=t?.lastPlayingTime??null;return BT(e)&&n!==null?n:e.currentTime}function PC(e,t=zT){let n=EC,i=t();i.width=n,i.height=n;let u=i.getContext("2d");if(!u)return!1;u.drawImage(e,0,0,n,n);let l=u.getImageData(0,0,n,n).data,d=0,c=0;for(let r=0;r({kind:"failed",reason:h,retry:m}),u=e?.video;if(!e||!u||(n.requireConnected??!0)&&!u.isConnected||u.videoWidth===0)return i(ks,!0);let l=BT(u);if(u.readyState<2&&!l)return i(ks,!0);let d=n.createCanvas??zT,c=As(u.videoWidth,u.videoHeight,t),s=n.maxSide??4096;if(c.width>s||c.height>s)return i(OC);let r=e.source;r.canvas||(r.canvas=d(),r.readable=!1);let o=r.canvas;o.width=c.width,o.height=c.height;let a=o.getContext("2d");if(!a)return i(ic);let p=sc(u,e);try{return a.drawImage(u,0,0,c.width,c.height),l&&PC(o,d)?(r.readable=!0,i(SC,!0)):(r.readable||(a.getImageData(0,0,1,1),r.readable=!0),{kind:"frame",bitmap:await(n.createImageBitmap??kC)(o),mediaTime:p})}catch(h){return i(CC(h)?IC:String(h))}}function LT(e,t){let n=null,i=oc(),u={video:e,get lastPlayingTime(){return n},get source(){return i},mediaTime:()=>sc(e,u),detach:a},l=()=>t.discontinuity(!1),d=()=>{i=oc(),n=null,t.discontinuity(!0)},c=()=>{!e.paused&&e.readyState>=2&&(n=e.currentTime),t.presented(u.mediaTime())},s=()=>t.presented(u.mediaTime()),r=[["seeking",l],["emptied",d],["loadeddata",d],["timeupdate",c],["seeked",c],["canplay",s],["playing",s]];for(let[p,h]of r)e.addEventListener(p,h);let o=!0;function a(){if(o){o=!1;for(let[p,h]of r)e.removeEventListener(p,h)}}return u}var OM=1440*60*1e3;var RC=[/^the worker did not start/,/^unexpected error while loading/];function jT(e,t){return t||e.startsWith("unexpected:")?!1:!RC.some(n=>n.test(e))}var MM=Object.freeze({misses:2,maxMs:5e3,sameBoxIou:.5});function DC(e,t){return e==="loading"?{phase:t.phase,bytes:t.bytes}:void 0}function MC(e,t,n=40){return(e.hover?.cards??[]).map(i=>i.bounds).filter(i=>i&&!(Math.abs(i.x-t.x)<1e-6&&Math.abs(i.y-t.y)<1e-6&&Math.abs(i.width-t.width)<1e-6)).slice(0,n).map(i=>({x:i.x,y:i.y,width:i.width,height:i.height}))}var Ps=class{constructor(t,n={}){this.deps=t;this.mode=n.mode??"pointer",this.hold=n.hold??null,this.maxOtherBoxes=n.maxOtherBoxes??40,this.rotatedOutlines=n.rotatedOutlines===!0,this.hitTest=t.hoverAt??vs,this.scheduler=new eo(Is(null,this.mode),3,this.mode,Ss(null)),this.st={state:"loading",error:null,release:null,backend:null,schedule:"idle",frames:0,lastWorkerMs:null,lastRoundTripMs:null,lastFrameError:null,geometric:n.geometric?{state:"loading",reason:null,bytes:null}:null,loading:null,tilted:null},this.lastStatusKey=this.statusKey()}deps;scheduler;mode;hold;maxOtherBoxes;rotatedOutlines;hitTest;st;cardList=[];analysisWidth={min:720,max:1920};maxAgeMs=rc;nextRequestId=1;inFlight=null;lastAcceptedRequestId=0;analyzedSinceLoad=!1;generation=0;sourceCount=0;result=null;pointerAt=null;mediaTime=0;lastShownKey="null";lastStatusKey="";held=null;get videoKey(){return`source-${this.sourceCount}`}pointer(t,n,i,u=!1){if(this.st.state==="stopped")return;let l=this.deps.now();this.pointerAt={x:t,y:n},this.mediaTime=i,u?this.scheduler.tapped(l):this.scheduler.pointerMoved(l),this.st.state==="ready"&&this.scheduler.hoverTriggerDue(l,this.videoTime(),this.inFlight!==null)&&this.requestCapture("hover"),this.publish()}pointerLeft(){this.st.state!=="stopped"&&(this.pointerAt=null,this.scheduler.pointerLeft(this.deps.now()),this.publish())}presented(t){this.st.state!=="stopped"&&(this.mediaTime=t,this.scheduler.framePresented(),this.publish())}discontinuity(t){this.st.state!=="stopped"&&(this.generation+=1,t&&(this.sourceCount+=1),this.scheduler.discontinuity(),this.result=null,this.held=null,t&&this.scheduler.framePresented(),this.publish())}cut(){this.st.state!=="stopped"&&(this.generation+=1,this.result=null,this.held=null,this.scheduler.requestLook(),this.publish())}frame(t,n,i){let u=this.inFlight;if(this.st.state==="stopped"||!u||u.requestId!==t||u.analyzing){n.close();return}if(this.scheduler.pictureReceived(),u.generation!==this.generation||u.videoKey!==this.videoKey){this.inFlight=null,n.close(),this.publish();return}u.analyzing=!0;let l={requestId:u.requestId,mediaTimeSec:i,generation:u.generation,videoKey:u.videoKey};try{this.deps.toWorker({kind:"frame",bitmap:n,videoTimeSec:i,envelope:l,...this.rotatedOutlines?{rotatedOutlines:!0}:{}},[n])}catch(d){n.close(),this.inFlight=null,this.st.lastFrameError=`analysis-failed: ${String(d)}`,this.scheduler.lookUnanswered(this.deps.now())}this.publish()}captureFailed(t,n,i=!1){let u=this.inFlight;this.st.state==="stopped"||!u||u.requestId!==t||u.analyzing||(this.inFlight=null,this.st.lastFrameError=`capture-failed: ${n}`,i?this.scheduler.lookUnanswered(this.deps.now(),{prompt:!0}):this.scheduler.lookRefused(),this.publish())}fromWorker(t){if(this.st.state!=="stopped")switch(t.kind){case"geometric-status":this.st.geometric={state:t.state,reason:t.reason,bytes:t.bytes},this.deps.onGeometricStatus?.(t),this.publishStatus();return;case"tilted-status":this.st.tilted={state:"off",reason:t.reason},this.deps.onTiltedStatus?.(t),this.publishStatus();return;case"release-progress":{let n=DC(this.st.state,t);n!==void 0&&(this.st.loading=n),this.publishStatus();return}case"release-status":this.st.state=t.ok?"ready":"failed",this.analyzedSinceLoad=!1,this.st.error=t.error,this.st.release=t.release,this.st.loading=null,this.st.tilted=t.release?.tiltedRetry?{state:"on",reason:null}:null,this.cardList=t.cards,t.release&&(this.st.backend=t.release.recognizer.ep,this.maxAgeMs=t.release.hoverMaxAgeMs,this.analysisWidth={...t.release.analysisWidth},this.scheduler.setIntervalMs(Is(this.st.backend,this.mode)),this.scheduler.setReadingIntervalMs(Ss(this.st.backend)),this.scheduler.framePresented()),this.publish();return;case"frame-result":this.onFrameResult(t);return;default:return}}onFrameResult(t){let n=this.deps.now(),i=nc(t.envelope,{inFlightRequestId:this.inFlight?.requestId??null,lastAcceptedRequestId:this.lastAcceptedRequestId,generation:this.generation,videoKey:this.videoKey});if(i!==null&&!NT(i))return;let u=this.inFlight;if(this.inFlight=null,i!==null){this.publish();return}this.lastAcceptedRequestId=t.envelope.requestId,this.st.lastFrameError=t.error??null,this.st.lastWorkerMs=t.workerMs,this.st.lastRoundTripMs=+(n-u.sentAt).toFixed(2),t.analysis?(this.analyzedSinceLoad=!0,this.scheduler.lookAnswered(),this.st.frames+=1,this.result={analysis:t.analysis,videoTimeSec:t.videoTimeSec},this.deps.onAnalysis?.(t.analysis)):(this.result=null,t.error===V$&&this.scheduler.lookUnanswered(n)),this.held&&this.pointerAt&&this.current()&&!this.fresh()&&(this.held.misses+=1),this.scheduler.setTooltipShowing(this.shown()!==null,n),this.publish()}tick(){if(this.st.state==="stopped")return;let t=this.deps.now(),n=this.analyzedSinceLoad?DT:MT;this.inFlight&&t-this.inFlight.sentAt>=n&&(this.inFlight=null,this.st.lastFrameError="no reply",this.scheduler.lookUnanswered(t)),this.scheduler.setTooltipShowing(this.shown()!==null,t),this.st.state==="ready"&&!this.inFlight&&this.scheduler.due(t)&&this.requestCapture(this.scheduler.lookPending?"cut":void 0),this.publish()}stop(){this.st.state!=="stopped"&&(this.st.state="stopped",this.st.loading=null,this.inFlight=null,this.result=null,this.held=null,this.pointerAt=null,this.publishShown(),this.publishStatus())}workerStopped(t){if(!(this.st.state==="stopped"||this.st.state==="failed")){if(this.inFlight=null,this.result=null,this.held=null,this.st.loading=null,this.publishShown(),"restart"in t){let n={kind:"geometric-status",state:"off",reason:"worker-restarted",bytes:null};this.st.geometric&&(this.st.geometric={state:n.state,reason:n.reason,bytes:n.bytes}),this.deps.onGeometricStatus?.(n),this.st.state="loading",this.analyzedSinceLoad=!1,this.st.error=null}else this.st.state="failed",this.st.error=t.error;this.publishStatus()}}reloading(t){this.st.state==="loading"&&(this.st.geometric=t.geometric?{state:"loading",reason:null,bytes:null}:null,this.st.loading=null,this.publishStatus())}requestCapture(t){if(this.st.state!=="ready"||this.inFlight)return;let n=this.deps.now(),i=this.nextRequestId++;this.inFlight={requestId:i,sentAt:n,generation:this.generation,videoKey:this.videoKey,analyzing:!1},this.scheduler.started(n,{videoTimeSec:this.videoTime(),...t?{trigger:t}:{}}),this.deps.capture(i,{...this.analysisWidth})}status(){return{...this.st,schedule:this.scheduler.analysisState(this.deps.now())}}analysis(){return this.current()?.analysis??null}cards(){return this.cardList}hitAt(t,n){let i=this.current();if(!i)return null;let{width:u,height:l}=i.analysis.frame;if(!(u>0&&l>0))return null;let d=t*u,c=n*l;if(!Number.isFinite(d)||!Number.isFinite(c))return null;let s=this.hitTest(i.analysis,d,c);if(!s.box||s.cardId===null||s.name===null)return null;let r={x:s.box.x/u,y:s.box.y/l,width:s.box.width/u,height:s.box.height/l},o={x:s.box.x,y:s.box.y,width:s.box.width,height:s.box.height};return{cardId:s.cardId,name:s.name,box:r,frameBox:o,others:MC(i.analysis,r,this.maxOtherBoxes)}}fresh(){return this.pointerAt?this.hitAt(this.pointerAt.x,this.pointerAt.y):null}shown(){let t=this.fresh(),n=this.hold;if(!n)return t;let i=this.deps.now();if(t)return this.held={card:t,misses:0,seenAt:i},t;let u=this.held;return!u||!this.pointerAt||!zC(u.card.box,this.pointerAt)?(this.held=null,null):this.boxAtPointer(u.card.box,n.sameBoxIou)==="other"||u.misses>=n.misses||i-u.seenAt>=n.maxMs?(this.held=null,null):u.card}current(){let t=this.result;return t&&RT(t.videoTimeSec,this.videoTime(),this.maxAgeMs)?t:null}videoTime(){return this.deps.mediaTimeNow?this.deps.mediaTimeNow():this.mediaTime}boxAtPointer(t,n){let i=this.current();if(!i||!this.pointerAt)return"unknown";let{width:u,height:l}=i.analysis.frame;if(!(u>0&&l>0))return"unknown";let d=this.pointerAt.x*u,c=this.pointerAt.y*l,s={x:t.x*u,y:t.y*l,width:t.width*u,height:t.height*l},r=0,o=!1;for(let a of i.analysis.boxes??[]){let[p,h,m,g]=a.box;dp+m||ch+g||(o=!0,r=Math.max(r,NC(s,{x:p,y:h,width:m,height:g})))}return o?r>=n?"same":"other":"none"}publish(){this.publishShown(),this.publishStatus()}publishShown(){let t=this.shown(),n=t?`${t.cardId}|${t.box.x}|${t.box.y}|${t.box.width}|${t.box.height}`:"null";n!==this.lastShownKey&&(this.lastShownKey=n,this.deps.onShown?.(t))}statusKey(){let t=this.status();return JSON.stringify({...t,release:t.release?t.release.id:null})}publishStatus(){let t=this.statusKey();t!==this.lastStatusKey&&(this.lastStatusKey=t,this.deps.onStatus?.(this.status()))}};function NC(e,t){let n=Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x),i=Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y);if(n<=0||i<=0)return 0;let u=n*i;return u/(e.width*e.height+t.width*t.height-u)}function zC(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}var VT=1;function BC(e){let{geometricUrl:t,geometricManifestSha256:n,geometricWatchdog:i,...u}=e;return u}function qT(e){let t=null,n=null,i=0,u=!1,l=null,d=!1,c=null,s={source:e.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},r=y=>{e.onDecision?.({reused:0,downloaded:0,ms:0,...y})},o=y=>new Ps({now:e.now,toWorker:(T,S)=>t?.postMessage(T,S??[]),capture:e.capture,...e.onShown?{onShown:e.onShown}:{},...e.onStatus?{onStatus:e.onStatus}:{},...e.onAnalysis?{onAnalysis:e.onAnalysis}:{},...e.onGeometricStatus?{onGeometricStatus:e.onGeometricStatus}:{},...e.hoverAt?{hoverAt:e.hoverAt}:{},...e.mediaTimeNow?{mediaTimeNow:e.mediaTimeNow}:{}},{...e.mode?{mode:e.mode}:{},...e.hold?{hold:e.hold}:{},...e.rotatedOutlines?{rotatedOutlines:!0}:{},geometric:y.geometricUrl!==void 0}),a=y=>{u||!n||(l&&y.kind==="release-progress"&&y.phase==="preparing"&&(d=!0),!(y.kind==="release-status"&&(n.status().state!=="loading"||l&&!h(y)))&&(y.kind==="release-status"&&!y.ok&&p(),n.fromWorker(y)))},p=()=>{u=!0,l=null,t?.terminate(),t=null},h=y=>{let T=l;if(y.ok&&y.release?.id===T.pointer.id)return l=null,c=T.pointer.id,s.source="remote",s.id=T.pointer.id,s.reason="ok",s.table=T.facts,r({source:"remote",reason:"ok",pointer:T.pointer.id,reused:T.reused,downloaded:T.downloaded,ms:T.ms}),!0;if(y.ok)return e.recordSkip?.(T.pointer,"id-mismatch"),m("id-mismatch"),!1;let S=y.error??"no reason given";return jT(S,d)&&e.recordSkip?.(T.pointer,`runtime:${S.slice(0,120)}`),m(`runtime:${S}`),!1},m=y=>{let T=l;l=null,t?.terminate(),s.source="bundled",s.id=null,s.reason=y,s.table=null,r({source:"bundled",reason:y,pointer:T.pointer.id,reused:T.reused,downloaded:T.downloaded,ms:T.ms});let S=T.fallback??e.loadRequest;n?.reloading({geometric:S.geometricUrl!==void 0}),w(S)},g=y=>{if(u||!n)return;let T=n.status().state;if(T==="failed"||T==="stopped")return;let S=y.message||"see the console";if(l){h({kind:"release-status",ok:!1,error:`the worker did not start (${S})`,release:null,cards:[]});return}if(t?.terminate(),T==="loading"&&i===0){p(),n.workerStopped({error:`the worker did not start (${S})`});return}if(i{let T=e.createWorker();T.onmessage=S=>{T===t&&a(S.data)},T.onerror=S=>{T===t&&g(S)},t=T,T.postMessage(y)},w=y=>{n??=o(y);try{_(y)}catch(T){t=null,l=null,u=!0,n.workerStopped({error:`the recognition worker could not start (${String(T)})`})}};return e.chooseRelease?e.chooseRelease({onDownloading:()=>e.onDownloading?.()}).catch(y=>({source:"bundled",reason:`unexpected:${String(y)}`,pointer:null,downloaded:0,ms:0})).then(y=>{if(!u){if(y.source==="remote"){l=y,d=!1,w(y.request);return}s.source="bundled",s.reason=y.reason,r({source:"bundled",reason:y.reason,pointer:y.pointer?.id??null,downloaded:y.downloaded,ms:y.ms}),w(y.request??e.loadRequest)}}):w(e.loadRequest),{get core(){return n},get stopped(){return u},get restarts(){return i},get release(){return{...s}},tick(){u||n?.tick()},stop(){u=!0,l=null,t?.terminate(),t=null,n?.stop()}}}var FC={requireConnected:!1,maxSide:1/0};function LC(e,t){let n=e instanceof HTMLVideoElement?e:null,i=e,u=t.workerUrl??new URL("./worker.js",import.meta.url),l=()=>performance.now(),d=!1,c=0,s=!1,r=()=>{c>0?s=!0:d&&t.onUpdate?.()},o=(N,X=!1)=>{c+=1;try{N()}finally{c-=1}X&&(s=!0),c===0&&s&&(s=!1,d&&t.onUpdate?.())},a=null,p=new Es,h=null,m=null,g=-1/0,_=()=>{let N=h&&a?a.read(h):null;N?p.seed(N):(a?.release(h),p.reset()),h=null},w=n?null:document.createElement("canvas"),y=w?.getContext("2d")??null,T=async N=>{if(!w||!y)return{kind:"failed",reason:ic,retry:!1};let X=Zn(e);if(X.width===0||X.height===0)return{kind:"failed",reason:ks,retry:!0};try{let W=await ec(e,w,y,N);return{kind:"frame",bitmap:W.bitmap,mediaTime:W.videoTimeSec}}catch(W){return{kind:"failed",reason:String(W),retry:!1}}},S=(N,X)=>{a?.release(h),h=a?.usable?a.sample(e):null,(z?FT(z,X,FC):T(X)).then(W=>o(()=>{W.kind==="frame"?q.frame(N,W.bitmap,W.mediaTime):q.captureFailed(N,W.reason,W.retry)},W.kind==="failed"))},O=0,A=null,P=()=>{O+=1;let N;try{N=new Worker(u,{type:"module"})}catch(W){throw O===1&&(A={error:W}),W}let X={postMessage:(W,ne)=>N.postMessage(W,ne??[]),terminate:()=>N.terminate(),onmessage:null,onerror:null};return N.onmessage=W=>o(()=>X.onmessage?.(W)),N.onerror=W=>o(()=>X.onerror?.(W)),X},I={kind:"load",releaseUrl:t.releaseFiles?String(t.releaseUrl):new URL(t.releaseUrl,location.href).href,...t.releaseFiles?{files:t.releaseFiles}:{},...t.wasmPaths!==void 0?{wasmPaths:t.wasmPaths}:{},...t.providers?{providers:t.providers}:{},...t.geometricUrl!==void 0?{geometricUrl:new URL(t.geometricUrl,location.href).href}:{},...t.geometricManifestSha256!==void 0?{geometricManifestSha256:t.geometricManifestSha256}:{},...t.geometricWatchdog===!1?{geometricWatchdog:!1}:{}},z=n?LT(n,{presented:N=>o(()=>q.presented(N)),discontinuity:N=>o(()=>{p.reset(),q.discontinuity(N)},!0)}):null,G=()=>z?.mediaTime()??0,J=qT({createWorker:P,loadRequest:I,now:l,...t.mode?{mode:t.mode}:{},...t.rotatedOutlines?{rotatedOutlines:!0}:{},capture:S,mediaTimeNow:()=>G(),onShown:r,onStatus:r,onAnalysis:_});if(A)throw z?.detach(),J.stop(),A.error;let q=J.core,C=(N,X)=>{let W=tc(e.getBoundingClientRect(),Zn(e),getComputedStyle(e).objectFit);if(W.width<=0||W.height<=0)return null;let ne=q.hitAt((N-W.left)/W.width,(X-W.top)/W.height);return ne?{hit:ne,picture:W}:null},ee=(N,X)=>{let W=C(N,X);if(!W)return null;let{hit:ne,picture:le}=W;return{name:ne.name,cardId:ne.cardId,box:{left:le.left+ne.box.x*le.width,top:le.top+ne.box.y*le.height,width:ne.box.width*le.width,height:ne.box.height*le.height},frameBox:ne.frameBox}},v=null,R=()=>v?ee(v.x,v.y):null,H=N=>{let X=v?C(v.x,v.y)?.hit.box??null:null;if(!X){a?.release(m),m=null;return}if(a||(a=kT()),!!a?.usable){if(m){let W=a.read(m);if(W&&(m=null,p.observe(W,X).cut)){p.reset(),q.cut(),s=!0;return}}!m&&N-g>=AT&&(g=N,m=a.sample(e))}},L=null,V=()=>{!d||!n||(o(()=>{q.presented(G()),H(l())}),L=n.requestVideoFrameCallback(V))},K=()=>o(()=>{p.reset(),q.discontinuity(!0)},!0),B=N=>o(()=>{v={x:N.clientX,y:N.clientY};let X=tc(e.getBoundingClientRect(),Zn(e),getComputedStyle(e).objectFit),W=ET(X,N.clientX,N.clientY)??{x:(N.clientX-X.left)/X.width,y:(N.clientY-X.top)/X.height};q.pointer(W.x,W.y,G(),N.pointerType==="touch")},!0),te=()=>o(()=>{v=null,q.pointerLeft()},!0);n&&"requestVideoFrameCallback"in n&&(L=n.requestVideoFrameCallback(V)),n||e.addEventListener("load",K),i.addEventListener("pointermove",B),i.addEventListener("pointerdown",B),i.addEventListener("pointerleave",te);let Y=setInterval(()=>o(()=>J.tick()),CT);return d=!0,{status:()=>q.status(),at:ee,atPointer:R,analysis:()=>q.analysis(),cards:()=>q.cards(),stop:()=>{d&&(d=!1,clearInterval(Y),L!==null&&n&&"cancelVideoFrameCallback"in n&&n.cancelVideoFrameCallback(L),L=null,z?.detach(),e.removeEventListener("load",K),i.removeEventListener("pointermove",B),i.removeEventListener("pointerdown",B),i.removeEventListener("pointerleave",te),a?.release(h),a?.release(m),a?.dispose(),p.reset(),J.stop())}}}var Mr={maxCorrespondences:40,fitMinInliers:3,inlierShare:[2,3],ambiguityMin:2,compatTol:.01,scaleRatioTol:.03},ac=1e-9,Cs=5;function cr(e,t){let n=Math.max(0,Math.min(e.x+e.w,t.x+t.w)-Math.max(e.x,t.x)),i=Math.max(0,Math.min(e.y+e.h,t.y+t.h)-Math.max(e.y,t.y)),u=n*i,l=e.w*e.h+t.w*t.h-u;return l>0?u/l:0}function Sn(e,t){return{x:e.sx*t.x+e.tx,y:e.sy*t.y+e.ty,w:e.sx*t.w,h:e.sy*t.h}}function to(e,t){return{x:e.sx*t.x+e.tx,y:e.sy*t.y+e.ty}}function uc(e){return{x:e.tx,y:e.ty,width:e.sx,height:e.sy}}function Rs(e){if(e.cards.length===0)return null;let t=1/0,n=1/0,i=-1/0,u=-1/0;for(let{bounds:l}of e.cards)t=Math.min(t,l.x),n=Math.min(n,l.y),i=Math.max(i,l.x+l.w),u=Math.max(u,l.y+l.h);return{x:t,y:n,w:i-t,h:u-n}}function lc(e){let t=[];for(let n=0;n=e.x&&t.x<=e.x+e.w&&t.y>=e.y&&t.y<=e.y+e.h}function GT(e,t){return et?1:0}function jC(e,t){return t.identity===void 0?!1:e.blocking===void 0||!In(e.blocking,XT(t.bounds))}function Ds(e,t,n=Mr.maxCorrespondences){let i=new Map;for(let d of e)i.set(d.identity,i.has(d.identity)?null:d);let u=new Map;for(let d of t.cards){if(!jC(t,d))continue;let c=d.identity;u.set(c,u.has(c)?null:d)}let l=[];for(let[d,c]of i){let s=u.get(d);!c||!s||l.push({identity:d,v:c.bounds,r:s.bounds,instance:s.instance})}return l.length>n&&(l.sort((d,c)=>c.v.w*c.v.h-d.v.w*d.v.h||GT(d.identity,c.identity)),l=l.slice(0,n)),l.sort((d,c)=>GT(d.identity,c.identity))}function UC(e){if(!(e.r.w>0)||!(e.r.h>0))return null;let t=e.v.w/e.r.w,n=e.v.h/e.r.h,i={sx:t,sy:n,tx:e.v.x-t*e.r.x,ty:e.v.y-n*e.r.y};return![i.sx,i.sy,i.tx,i.ty].every(Number.isFinite)||!(t>0)||!(n>0)?null:i}function HT(e){let t=e.length;if(t===0)return null;let n=0,i=0;for(let[s,r]of e)n+=s,i+=r;n/=t,i/=t;let u=0,l=0;for(let[s,r]of e)u+=(s-n)*(r-i),l+=(s-n)*(s-n);if(!(l>0))return null;let d=u/l;if(!(d>0)||!Number.isFinite(d))return null;let c=i-d*n;return Number.isFinite(c)?{s:d,t:c}:null}function WT(e){let t=[],n=[];for(let{r:l,v:d}of e)t.push([l.x,d.x],[l.x+l.w,d.x+d.w]),n.push([l.y,d.y],[l.y+l.h,d.y+d.h]);let i=HT(t),u=HT(n);return!i||!u?null:{sx:i.s,sy:u.s,tx:i.t,ty:u.t}}function dc(e,t,n){if(e.length===0||!(t>0)||!(n>0))return null;let i=[],u=[];for(let{r:y,v:T}of e)i.push([y.x,T.x],[y.x+y.w,T.x+T.w]),u.push([y.y,T.y],[y.y+y.h,T.y+T.h]);let l=(y,T)=>y.reduce((S,O)=>S+O[T],0)/y.length,d=l(i,0),c=l(i,1),s=l(u,0),r=l(u,1),o=0,a=0,p=0,h=0;for(let[y,T]of i)o+=(y-d)*(y-d),a+=(y-d)*(T-c);for(let[y,T]of u)p+=(y-s)*(y-s),h+=(y-s)*(T-r);let m=n*n,g=m*o+t*t*p;if(!(g>0))return null;let _=(m*a+t*h)/g;if(!(_>0)||!Number.isFinite(_))return null;let w={sx:_,sy:t*_,tx:c-_*d,ty:r-t*_*s};return[w.sy,w.tx,w.ty].every(Number.isFinite)?w:null}function VC(e,t){if(e.aspect===void 0||t===void 0)return null;let n=i=>Number.isFinite(i)&&i>0;return!n(e.aspect)||!n(t)?NaN:t/e.aspect}function qC(e,t,n,i,u=1){return Ms(e,t,n,i,u).outcome}function Ms(e,t,n,i,u=1){if(t===null)return{outcome:{kind:"no-layout"},correspondences:[],support:[],winner:-1,aspectRejected:[]};let l=Ds(e,t,n.maxCorrespondences),d=l.length,c=[],s=(L,V,K=[],B=-1)=>({outcome:{kind:"insufficient",reason:L,n:d,inliers:V},correspondences:l,support:K,winner:B,aspectRejected:c}),r=VC(t,i);if(r!==null&&(Number.isNaN(r)||!(Number.isFinite(u)&&u>0)))return s("degenerate",0);let o=L=>r!==null&&Math.abs(L.sy/L.sx/r-1)>n.scaleRatioTol,a=L=>{let V=[];for(let K=0;K=n.fitMinIoU&&V.push(K);return V},p=l.map(UC),h=p.map((L,V)=>L&&o(L)?(c.push(V),null):L),m=()=>c.some(L=>a(p[L]).length>=2),g=[],_=[];for(let L=0;L=n.fitMinIoU&&(K.push(te),B+=Y)}g.push(K),_.push(B)}let w=-1;for(let L=0;LK||V===K&&_[L]>_[w]+ac)&&(w=L)}if(w<0){let L=d=n.fitMinInliers)return s(m()?"aspect":"zero-inliers",0,g,w);let y=g[w].map(L=>l[L]),T=r===null?WT(y):dc(y,r*u,i);if(!T)return s("degenerate",0,g,w);let S=[],O=1/0;for(let L of g[w]){let V=cr(Sn(T,l[L].r),l[L].v);V>=n.fitMinIoU&&(S.push(L),O=Math.min(O,V))}let A=S.map(L=>l[L].identity),P=Rs(t),I=new Set(S),z=[];for(let L=0;L!I.has(B));K.length>z.length&&(z=K)}if(z.length>=n.ambiguityMin)return{outcome:{kind:"ambiguous",transform:T,inliers:A,runnerUp:z.map(L=>l[L].identity),n:d},correspondences:l,support:g,winner:w,aspectRejected:c};if(A.lengthl[V]));if(!L||o(L))return s("aspect",A.length,g,w);H=L.sy/L.sx/r}return{outcome:{kind:"verified",transform:T,inliers:A,n:d,minIoU:O,span:R,...H!==void 0?{boardRatio:H}:{}},correspondences:l,support:g,winner:w,aspectRejected:c}}var GC=8,HC=20,WC=.3;function KC(e,t,n,i,u){let l=0;for(let d of lc(n)){let c=to(e,d),s=to(t,d);l=Math.max(l,Math.abs(c.x-s.x)*i,Math.abs(c.y-s.y)*u)}return l}function XC(e,t){return t?e<=GC?"correct":e<=HC?"loose":"false":"none"}function ZT(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}function ZC(e,t,n,i=[]){let u=ZT(e.box);if(!In(n,u)||i.some(c=>In(c,u)))return"blocked";let l=null,d=-1;for(let c of t){let s=cr(e.box,c.box);s>=WC&&s>d&&(l=c,d=s)}return l?!l.faceUp||l.identity===void 0?"back-hidden":l.identity===e.identity?"correct":"wrong-identity":"empty"}function YC(e,t,n,i=[]){let u=0,l=0;for(let d of e){if(!d.faceUp||d.identity===void 0)continue;let c=ZT(d.box);!In(n,c)||i.some(s=>In(s,c))||(u+=1,t.some(s=>s.identity===d.identity&&In(s.box,c))&&(l+=1))}return u===0?null:l/u}function JC(e,t){return t.map(n=>QC(e,n))}function QC(e,t){let n=null;for(let i of e){if(i.atMs>t)break;n=i.display}if(n!=="fitted")return 0;for(let i of e)if(i.atMs>=t&&i.display!=="fitted")return i.atMs-t;return null}var Ns={window:10,minIdentities:3,trip:.4,recover:.7},ro=class{params;exclude;window=[];stateValue="unknown";recoverRun=0;constructor(t={}){this.params=t.params??Ns,this.exclude=t.exclude??(()=>!1)}get state(){return this.stateValue}get tripped(){return this.stateValue==="tripped"}get share(){return this.summary().share}observe(t){if(t.windowIdentities.size===0)return{state:this.stateValue,event:null,...this.summary(),counted:!1};let n=new Map;for(let c of t.accepted)this.exclude(c)||n.set(c,(n.get(c)??!1)||t.windowIdentities.has(c));this.window.push(n),this.window.length>this.params.window&&this.window.shift();let{identities:i,share:u}=this.summary(),l=i>=this.params.minIdentities&&u!==null,d=null;return this.stateValue==="tripped"?(this.recoverRun=l&&u>=this.params.recover?this.recoverRun+1:0,this.recoverRun>=this.params.window&&(this.stateValue="in",this.recoverRun=0,d="recover")):l&&(u0&&t.scaleRatioTol<=.25))return"scaleRatioTol must be above 0 and at most 0.25";let n=t;return n.fitMinIoU<.5||n.fitMinIoU>1?"fitMinIoU must be between 0.5 and 1":n.minSpan<0||n.minSpan>1?"minSpan must be between 0 and 1":!Number.isInteger(n.confirmFits)||n.confirmFits<1||n.confirmFits>3?"confirmFits must be 1, 2 or 3":n.suppressionIoU<=0||n.suppressionIoU>1?"suppressionIoU must be above 0 and at most 1":n.intervalMs<=0?"intervalMs must be positive":n.confirmWindowMs<3*n.intervalMs?"confirmWindowMs must be at least 3 \xD7 intervalMs":n.freshnessMs<2*n.intervalMs?"freshnessMs must be at least 2 \xD7 intervalMs":n.holdMs=u){d.add(c.instance);break}}return e.cards.map(c=>c.instance).filter(c=>d.has(c))}var eS=15;function eR(e){let t=[...e].sort((i,u)=>i-u),n=t.length>>1;return t.length%2===1?t[n]:(t[n-1]+t[n])/2}var no=class{config;fitParams;monitor;generationValue=null;stateValue="off";contradicted=!1;verifiedThisGen=!1;run=null;confirmed=null;confirmedBasis=null;ratioPool=[];appliedScale=1;holdStart=null;lastAnalysisAt=null;zeroStreak=0;lastFrame={kind:"no-layout"};suppressed=[];current;constructor(t,n={}){let i=JT(t);if(i)throw new Error(i);this.config=Object.freeze({...t}),this.fitParams={...Mr,fitMinIoU:t.fitMinIoU,minSpan:t.minSpan,ambiguityMin:t.ambiguityMin??Mr.ambiguityMin,scaleRatioTol:t.scaleRatioTol??Mr.scaleRatioTol},this.monitor=new ro({exclude:n.exclude,params:Ns}),this.current=this.build(0,0)}get generation(){return this.generationValue}get state(){return this.stateValue}get verdict(){return this.current}eligibilityLost(t){return this.clear(),this.generationValue=null,this.stateValue="off",this.current=this.build(1,t)}reset(t,n){return this.clear(),this.generationValue=t,this.stateValue="unverified",this.current=this.build(2,n)}tick(t){return this.expired(t)?(this.expire(),this.current=this.build(11,t)):this.current=this.build(0,t)}analyze(t,n){if(this.generationValue===null||t.generation!==this.generationValue)return null;let i=this.expired(n);i&&this.expire();let u=this.stateValue,l=this.ratioScale(),d=Ms(t.observations,t.layout,this.fitParams,t.frameAspect,l),c=d.outcome;this.lastFrame=c;let s=null;c.kind==="verified"&&c.boardRatio!==void 0&&(s={correspondences:d.support[d.winner].map(_=>d.correspondences[_]),ratio:t.frameAspect/t.layout.aspect,frameAspect:t.frameAspect});let r=this.monitor.observe({windowIdentities:t.windowIdentities,accepted:t.observations.map(_=>_.identity)});this.lastAnalysisAt=n,this.zeroStreak=c.kind==="insufficient"&&c.reason==="zero-inliers"?this.zeroStreak+1:0;let o=t.layout?Rs(t.layout):null,a=c.kind==="verified"&&o!==null?c:null,p=this.fitParams.compatTol,h=a!==null&&this.confirmed!==null&&!Yn(a.transform,this.confirmed,o,p),m=this.run;if(a){let _=this.run!==null&&Yn(a.transform,this.run.latest,o,p)&&t.capturedAtMs-this.run.capturedAtMs<=this.config.confirmWindowMs;m={latest:a.transform,capturedAtMs:t.capturedAtMs,length:_?this.run.length+1:1,basis:s}}let g;return r.event==="trip"?(g=3,this.run=m,this.stateValue="mismatch",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0):u==="mismatch"&&r.event==="recover"?(g=4,this.run=m,this.stateValue="unverified"):h?(g=5,this.run={latest:a.transform,capturedAtMs:t.capturedAtMs,length:1,basis:s},this.stateValue="contradicted",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0,this.verifiedThisGen=!0):this.zeroStreak>=2&&(u==="verified"||u==="held")?(g=6,this.stateValue="contradicted",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0,this.verifiedThisGen=!0):t.faces===0&&t.layout!==null&&t.layout.cards.length>=3&&this.verifiedThisGen&&u!=="mismatch"?(g=7,this.run=m,this.stateValue="no-faces"):a&&m.length>=this.config.confirmFits?(g=9,this.run=m,this.stateValue="verified",this.confirmed=a.transform,this.confirmedBasis=s,this.contradicted=!1,this.holdStart=n,this.verifiedThisGen=!0,this.monitor.clearTrip()):(this.run=m,(u==="verified"||u==="held"||u==="no-faces"&&a!==null)&&this.confirmed!==null&&this.holdStart!==null&&n-this.holdStarteS&&this.ratioPool.shift()),this.applyScale(this.ratioScale()),(this.stateValue==="verified"||this.stateValue==="held")&&this.confirmed&&t.layout?this.suppressed=QT(t.layout,t.observations,this.confirmed,this.fitParams.fitMinIoU,this.config.suppressionIoU,this.fitParams.maxCorrespondences):this.suppressed=[],this.current=this.build(g,n)}expired(t){let n=this.stateValue;if(n!=="verified"&&n!=="held"&&n!=="no-faces")return!1;let i=this.holdStart!==null&&t-this.holdStart>=this.config.holdMs,u=this.lastAnalysisAt!==null&&t-this.lastAnalysisAt>=this.config.freshnessMs;return i||u}applyScale(t){if(t===this.appliedScale)return;let n=i=>i?dc(i.correspondences,i.ratio*t,i.frameAspect):null;this.confirmed&&(this.confirmed=n(this.confirmedBasis)??this.confirmed),this.run&&(this.run.latest=n(this.run.basis)??this.run.latest),this.appliedScale=t}ratioScale(){if(this.ratioPool.length<2)return 1;let t=this.fitParams.scaleRatioTol;return Math.min(1+t,Math.max(1-t,eR(this.ratioPool)))}expire(){this.stateValue=this.monitor.tripped?"mismatch":"unverified",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.suppressed=[]}clear(){this.contradicted=!1,this.verifiedThisGen=!1,this.run=null,this.confirmed=null,this.confirmedBasis=null,this.ratioPool=[],this.appliedScale=1,this.holdStart=null,this.lastAnalysisAt=null,this.zeroStreak=0,this.lastFrame={kind:"no-layout"},this.suppressed=[],this.monitor.reset()}display(){switch(this.stateValue){case"off":return"today";case"verified":case"held":return"fitted";case"no-faces":return"hidden";case"mismatch":case"contradicted":return"vision";case"unverified":return this.contradicted?"vision":"today"}}build(t,n){let i=this.display(),u={display:i,suppressed:i==="fitted"?[...this.suppressed]:[],state:this.stateValue,contradicted:this.contradicted,frame:this.lastFrame,diagnostics:{elapsedSinceLastAnalysisMs:this.lastAnalysisAt===null?0:n-this.lastAnalysisAt,runLength:this.run?.length??0,monitorShare:this.monitor.share,row:t,ratioScale:this.ratioScale()}};return i==="fitted"&&(u.region=uc(this.confirmed)),u}};var cc="layout-recording/1",zs=2,rS=[{x:.05,y:.05},{x:.95,y:.05},{x:.5,y:.5},{x:.05,y:.95},{x:.95,y:.95}],tR=["supported-game","two-region","negative-no-faces","negative-gallery","negative-other-layout","transition"],Bs=class extends Error{};function St(e,t){throw new Bs(`${e}: ${t}`)}function mt(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&St(t,"must be an object"),e}function Nr(e,t){return Array.isArray(e)||St(t,"must be an array"),e}function Xe(e,t,n={}){return(typeof e!="number"||!Number.isFinite(e))&&St(t,"must be a finite number"),n.integer&&!Number.isInteger(e)&&St(t,"must be an integer"),n.min!==void 0&&e{let c=`${t}.cards[${d}]`,s=mt(l,c),r={instance:pr(s.instance,`${c}.instance`),bounds:io(s.bounds,`${c}.bounds`)};return s.identity!==void 0&&(r.identity=pr(s.identity,`${c}.identity`)),s.rotated!==void 0&&(typeof s.rotated!="boolean"&&St(`${c}.rotated`,"must be a boolean"),r.rotated=s.rotated),r}),u={key:pr(n.key,`${t}.key`),cards:i};return n.blocking!==void 0&&(u.blocking=io(n.blocking,`${t}.blocking`)),n.aspect!==void 0&&(u.aspect=Xe(n.aspect,`${t}.aspect`),u.aspect>0||St(`${t}.aspect`,"must be positive")),u}function nR(e,t){try{let n=mt(e,t),i=n.region!==null;return{region:i?tS(n.region,`${t}.region`):null,residualPx:i?Xe(n.residualPx,`${t}.residualPx`,{min:0}):typeof n.residualPx=="number"?n.residualPx:0,mask:io(n.mask,`${t}.mask`),blockers:n.blockers===void 0?[]:Nr(n.blockers,`${t}.blockers`).map((u,l)=>io(u,`${t}.blockers[${l}]`)),solves:n.solves===void 0?[]:Nr(n.solves,`${t}.solves`).map((u,l)=>{let d=mt(u,`${t}.solves[${l}]`);return{atMs:Xe(d.atMs,`${t}.solves[${l}].atMs`),residualPx:Xe(d.residualPx,`${t}.solves[${l}].residualPx`,{min:0}),region:i?tS(d.region,`${t}.solves[${l}].region`):null}})}}catch(n){if(n instanceof Bs)return n.message;throw n}}function iR(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))return n.push(`${t}: no clock`),{status:"missing"};let i=e;return i.status!=="ok"&&i.status!=="undecodable"&&i.status!=="missing"?(n.push(`${t}.status: unknown status ${JSON.stringify(i.status)}`),{status:"missing"}):i.status!=="ok"?{status:i.status}:typeof i.streamTimeMs!="number"||!Number.isFinite(i.streamTimeMs)?(n.push(`${t}.streamTimeMs: an ok clock without a finite time`),{status:"missing"}):{status:"ok",streamTimeMs:i.streamTimeMs}}function oR(e){let t=[],n=mt(e,"recording");n.schema!==cc&&St("recording.schema",`must be "${cc}"`);let i=mt(n.frame,"recording.frame"),u={width:Xe(i.width,"recording.frame.width",{min:1}),height:Xe(i.height,"recording.frame.height",{min:1})},l=Nr(n.cadenceProfiles,"recording.cadenceProfiles").map((o,a)=>{let p=mt(o,`recording.cadenceProfiles[${a}]`),h=Xe(p.intervalMs,`recording.cadenceProfiles[${a}].intervalMs`);return h>0||St(`recording.cadenceProfiles[${a}].intervalMs`,"must be positive"),{name:pr(p.name,`recording.cadenceProfiles[${a}].name`),intervalMs:h}}),d=Nr(n.scenes,"recording.scenes").map((o,a)=>{let p=`recording.scenes[${a}]`,h=mt(o,p),m=pr(h.class,`${p}.class`);tR.includes(m)||St(`${p}.class`,`unknown scene class "${m}"`);let g={id:pr(h.id,`${p}.id`),class:m,startMs:Xe(h.startMs,`${p}.startMs`),endMs:Xe(h.endMs,`${p}.endMs`)};if(g.endMs{let p=`recording.frames[${a}]`,h=mt(o,p),m=Xe(h.capturedAtMs,`${p}.capturedAtMs`);m{let T=`${p}.analysis.observations[${y}]`,S=mt(w,T);return{identity:pr(S.identity,`${T}.identity`),bounds:io(S.bounds,`${T}.bounds`)}})}}}),r=Nr(n.candidates,"recording.candidates").map((o,a)=>{let p=`recording.candidates[${a}]`,h=mt(o,p);return{key:pr(h.key,`${p}.key`),producedAtMs:Xe(h.producedAtMs,`${p}.producedAtMs`),arrivedAtMs:Xe(h.arrivedAtMs,`${p}.arrivedAtMs`),layout:rR(h.layout,`${p}.layout`)}});return{schema:cc,frame:u,cadenceProfiles:l,scenes:d,frames:s,candidates:r,problems:t}}function nS(e,t){return e.candidates.map((n,i)=>({c:n,i})).filter(({c:n})=>n.arrivedAtMs<=t).sort((n,i)=>n.c.arrivedAtMs-i.c.arrivedAtMs||n.i-i.i).map(({c:n})=>n)}function pc(e,t){let n=nS(e,t);return n.length>0?n[n.length-1]:null}function sR(e,t){if(!hc(t.clock))return null;let n=t.clock.streamTimeMs,i=null;for(let u of e.candidates)u.producedAtMs<=n&&(i===null||u.producedAtMs>i.producedAtMs)&&(i=u);return i}function hc(e){return e?.status==="ok"&&typeof e.streamTimeMs=="number"&&Number.isFinite(e.streamTimeMs)}function aR(e){let t=e.frames.filter(n=>hc(n.clock));return{frames:t,excluded:e.frames.length-t.length}}function uR(e,t){return e.scenes.find(n=>t>=n.startMs&&tu.residualPx<=zs))return!1;let i=[n.region];for(let u of n.solves){if(!u.region)return!1;i.push(u.region)}for(let u=0;uzs||l>zs)return!1}return!0}function iS(e){return{layoutAt:t=>pc(e,t)?.layout??null,windowIdentitiesAt:t=>cR(pc(e,t)?.layout??null)}}function cR(e){let t=new Set;for(let n of e?.cards??[])n.identity!==void 0&&t.add(n.identity);return t}function pR(e,t){let n=e.cadenceProfiles.find(p=>p.name===t.profile);if(!n)throw new Error(`no cadence profile "${t.profile}" in the recording`);let i={...t.config,intervalMs:n.intervalMs},u=new no(i,{exclude:t.exclude}),l=t.scheduler(n.intervalMs),d=t.source??iS(e),c=[],s=[],r=null,o=1;e.frames.length>0&&u.reset(o,e.frames[0].capturedAtMs);let a=()=>{let p=r;r=null;let h=p.frame,m={generation:o,capturedAtMs:h.capturedAtMs,faces:h.analysis.faces,observations:h.analysis.observations,layout:d.layoutAt(h.capturedAtMs),windowIdentities:d.windowIdentitiesAt(h.capturedAtMs),frameAspect:e.frame.width/e.frame.height};u.analyze(m,p.endedAtMs),s.push({frameIndex:h.index,startedAtMs:p.startedAtMs,endedAtMs:p.endedAtMs,late:p.endedAtMs>p.startedAtMs+n.intervalMs})};for(let p of e.frames){let h=p.capturedAtMs;r&&r.endedAtMs<=h&&a(),l.framePresented(),!r&&l.due(h)&&(l.started(h),r={frame:p,startedAtMs:h,endedAtMs:h+p.analysis.durationMs},p.analysis.durationMs===0&&a()),c.push({frameIndex:p.index,atMs:h,result:u.tick(h)})}return r&&a(),{steps:c,analyses:s}}export{$s as DEFAULT_ACCEPT,kd as DEFAULT_DECODE,ps as DEFAULT_LETTERBOX,$P as DEFAULT_TILTED_RETRY,Li as Detector,_s as EXECUTION_PROVIDERS,ji as Embedder,Gi as EmbeddingRecognizer,rS as FIDUCIAL_POINTS,eo as FrameScheduler,rc as HOVER_MAX_AGE_MS,J$ as HOVER_SELECTIONS,Tn as IdentityMap,Mr as LAYOUT_FIT_DEFAULTS,no as LayoutRegistration,uC as MAX_ANALYSIS_WIDTH,lC as MIN_ANALYSIS_WIDTH,Ns as MONITOR_DEFAULTS,ro as MismatchMonitor,aT as OUTLINE_MIN_TILT,er as PREPROCESSING,Ki as Pipeline,eS as RATIO_POOL_SIZE,Qi as ReleaseError,Hi as TemporalGate,Wi as Tracker,As as analysisSize,sC as analyzeFrame,G$ as boxAverageRgb,Is as cadenceMs,ec as captureFrame,fT as chooseLook,XC as classifyAccept,ZC as classifyHitbox,hc as clockUsable,Yn as compatible,Fd as computeCardQuad,Ds as correspondences,YC as coverage,LC as createSession,hT as cropRgba,C$ as decodeDetections,Wd as estimateTilt,JC as exitLatency,KC as fitError,qC as fitFrame,Ms as fitFrameDetail,vs as hoverAt,Gd as hoverCardsOf,eT as hoverOrder,Gn as iou,pc as latestOffered,JT as layoutConfigError,Rs as layoutExtent,cr as layoutIoU,Jk as letterboxBgr,Rd as letterboxGeometry,oC as loadRelease,Qd as loadReleaseData,lr as lookAccepted,Ad as nonMaxSuppression,nS as offeredCandidates,lT as outlineFromTilt,Zd as outlineRect,Nd as parseBank,Vd as parseIdentityGroups,xT as parseRelease,KT as placementDistance,Z$ as pointInConvexQuad,gT as poolEmbeddings,Sn as project,oR as readLayoutRecording,Yd as recognizeFrame,iS as recordingSource,Kd as rectFromAabb,pR as replayRecording,nc as replyRejection,cs as resizeBilinearRgb,Ud as resolveHover,Ld as resolveHoveredCard,ms as rotateTensor90,uT as sampleRect,uR as sceneAt,qi as selectHoverLayer,QT as suppressedInstances,mT as tiltedOrder,Xd as tiltedRects,aR as timedFrames,fs as toContractTensor,Dd as toDetectorTensor,uc as toRegion,sR as truthCandidate,lR as truthUsable,ls as validBox}; +}`;function kT(){try{return yC()}catch{return null}}function yC(){let e=document.createElement("canvas"),t=e.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"low-power"});if(!t)return null;let n=t.createProgram();for(let[p,h]of[[t.VERTEX_SHADER,gC],[t.FRAGMENT_SHADER,bC]]){let m=t.createShader(p);if(!m)return null;t.shaderSource(m,h),t.compileShader(m),t.attachShader(n,m)}if(t.linkProgram(n),!t.getProgramParameter(n,t.LINK_STATUS))return null;t.useProgram(n);let i=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),t.STATIC_DRAW);let u=t.getAttribLocation(n,"p");t.enableVertexAttribArray(u),t.vertexAttribPointer(u,2,t.FLOAT,!1,0,0);let l=t.createTexture();t.bindTexture(t.TEXTURE_2D,l),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR_MIPMAP_LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);let d=[],c=1,s=!0,r=new Uint8Array(0);e.addEventListener("webglcontextlost",()=>{s=!1});function o(p){return d.find(h=>h.ticket===p)}function a(p){p.fence&&t.deleteSync(p.fence),p.fence=null,p.ticket=null}return{get usable(){return s&&!t.isContextLost()},sample(p){let h=Zn(p);if(!this.usable||h.width===0||h.height===0)return null;let m=d.find(y=>y.ticket===null);if(!m){if(d.length>=mC)return null;let y=t.createBuffer();if(!y)return null;m={pbo:y,fence:null,width:0,height:0,ticket:null},d.push(m)}let{width:g,height:_}=pC(h.width,h.height);try{(e.width!==g||e.height!==_)&&(e.width=g,e.height=_),t.viewport(0,0,g,_),t.bindTexture(t.TEXTURE_2D,l),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,p),t.generateMipmap(t.TEXTURE_2D),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindBuffer(t.PIXEL_PACK_BUFFER,m.pbo),(m.width!==g||m.height!==_)&&(t.bufferData(t.PIXEL_PACK_BUFFER,g*_*4,t.STREAM_READ),m.width=g,m.height=_),t.readPixels(0,0,g,_,t.RGBA,t.UNSIGNED_BYTE,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),m.fence=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0),t.flush()}catch{return s=!1,null}if(!m.fence)return null;let w={id:c++};return m.ticket=w,w},read(p){let h=o(p);if(!h||!h.fence||!this.usable||t.getSyncParameter(h.fence,t.SYNC_STATUS)!==t.SIGNALED)return null;let m=h.width*h.height*4;r.length!==m&&(r=new Uint8Array(m)),t.bindBuffer(t.PIXEL_PACK_BUFFER,h.pbo),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,r),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);let g={width:h.width,height:h.height,luma:hC(r,h.width,h.height)};return a(h),g},release(p){if(!p)return;let h=o(p);h&&a(h)},dispose(){if(s=!1,!t.isContextLost()){for(let p of d)a(p),t.deleteBuffer(p.pbo);d.length=0,t.getExtension("WEBGL_lose_context")?.loseContext()}}}}function tc(e,t,n){let i={left:e.left,top:e.top,width:e.width,height:e.height};if(t.width<=0||t.height<=0||n==="fill")return i;let u=e.width/t.width,l=e.height/t.height,d;n==="cover"?d=Math.max(u,l):n==="none"?d=1:n==="scale-down"?d=Math.min(1,u,l):d=Math.min(u,l);let c=t.width*d,s=t.height*d;return{left:e.left+(e.width-c)/2,top:e.top+(e.height-s)/2,width:c,height:s}}var wC=250,CT=250,_C=1e4,vC=5e3,xC=400,rc=2e3;function RT(e,t,n){return Math.abs(t-e)*1e3<=n}var $C=250,DT=5e3,MT=15e3,PT=[250,500,1e3,2e3];function nc(e,t){return e===void 0?"stale-request":e.requestId<=t.lastAcceptedRequestId?"superseded":e.requestId!==t.inFlightRequestId?"stale-request":e.videoKey!==t.videoKey?"video-key":e.generation!==t.generation?"generation":null}function NT(e){return e==="video-key"||e==="generation"}var eo=class{constructor(t,n=3,i="always-on",u=t,l=null){this.intervalMs=t;this.confirmFrames=n;this.mode=i;this.readingIntervalMs=u;this.probeIntervalMs=l;this.checkProbe(i)}intervalMs;confirmFrames;mode;readingIntervalMs;probeIntervalMs;pending=!1;repeatsLeft=0;lastStartedAt=-1/0;pointerInside=!1;lastPointerAt=-1/0;tooltipShowing=!1;lastTooltipAt=-1/0;lastHoverTriggerAt=-1/0;lastVideoTimeSec=null;discontinuitySinceLast=!1;lastTriggerKind=null;lookRequested=!1;unanswered=0;retryAt=null;retryPrompt=!1;lastUnansweredCapture=!1;refused=!1;pointerAnalysis=!1;checkProbe(t){if(t==="layout"&&!(this.probeIntervalMs!==null&&this.probeIntervalMs>0))throw new Error("layout mode needs a positive probe interval")}setProbeIntervalMs(t){this.probeIntervalMs=t,this.checkProbe(this.mode)}setPointerAnalysis(t){this.pointerAnalysis=t}setIntervalMs(t){this.intervalMs=t}setReadingIntervalMs(t){this.readingIntervalMs=t}setTooltipShowing(t,n){this.tooltipShowing=t,t&&this.pointerInside&&(this.lastTooltipAt=n)}setMode(t){this.checkProbe(t),this.mode=t}get analysisMode(){return this.mode}framePresented(){this.pending=!0,this.repeatsLeft=0}discontinuity(){this.discontinuitySinceLast=!0,this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}requestLook(){this.discontinuitySinceLast=!0,this.pending=!0,this.repeatsLeft=0,this.lookRequested=!0}lookUnanswered(t,n={}){this.repeatsLeft=0,this.retryAt=t+PT[Math.min(this.unanswered,PT.length-1)],this.retryPrompt=n.prompt===!0,this.lastUnansweredCapture=n.prompt===!0,this.unanswered+=1}lookAnswered(){this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}lookRefused(){this.refused=!0}pictureReceived(){this.refused=!1,this.lastUnansweredCapture&&(this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1)}retryReady(t){return this.retryAt!==null&&t>=this.retryAt}get lookPending(){return this.lookRequested}pointerMoved(t){this.pointerInside=!0,this.lastPointerAt=t,(this.unanswered>0||this.refused)&&this.retryAt===null&&(this.retryAt=t,this.retryPrompt=!1)}pointerLeft(t){this.pointerInside&&(this.lastPointerAt=t),this.pointerInside=!1,this.lastTooltipAt=-1/0}tapped(t){this.lastPointerAt=t}pointerActive(t){return t-this.lastPointerAt<_C}analysisState(t){if(this.mode==="always-on")return"always-on";if(this.mode==="layout"){let n=this.pointerAnalysis?this.pointerState(t):"idle";return n==="idle"?"probe":n}return this.pointerState(t)}pointerState(t){return this.pointerActive(t)?"fast":this.pointerInside&&(this.tooltipShowing||t-this.lastTooltipAt=this.intervalInEffectMs(t):this.analysisState(t)==="probe"?!1:this.repeatsLeft>0&&n>=wC}staleFrameMs(t){return Math.max(xC,this.intervalInEffectMs(t))}frameStale(t,n){return this.lastVideoTimeSec===null||this.discontinuitySinceLast?!0:Math.abs(t-this.lastVideoTimeSec)*1e3>this.staleFrameMs(n)}hoverTriggerDue(t,n,i){let u=this.analysisState(t);return i||u==="idle"||u==="probe"||t-this.lastHoverTriggerAt<$C?!1:this.frameStale(n,t)}started(t,n={}){this.retryReady(t)&&(this.retryAt=null,this.retryPrompt=!1,this.pending=!0,this.repeatsLeft=0),this.lastStartedAt=t;let i=n.trigger==="hover",u=n.trigger==="cut"||this.lookRequested;this.lastTriggerKind=i?"hover":u?"cut":this.pending?"cadence":"repeat",i&&(this.lastHoverTriggerAt=t),n.videoTimeSec!==void 0&&(this.lastVideoTimeSec=n.videoTimeSec),this.discontinuitySinceLast=!1,this.lookRequested=!1,this.pending||i||u?(this.pending=!1,this.repeatsLeft=this.analysisState(t)==="probe"?0:this.confirmFrames-1):this.repeatsLeft>0&&(this.repeatsLeft-=1)}get lastTrigger(){return this.lastTriggerKind}msSinceLastAnalysis(t){return this.lastStartedAt===-1/0?null:t-this.lastStartedAt}get idle(){return!this.pending&&this.repeatsLeft===0&&this.retryAt===null}};var ks="no picture",SC="no picture (the paused video draws nothing)",ic="no 2d context",IC="the video may not be read",OC="the picture is too large",EC=16,AC=9,zT=()=>document.createElement("canvas"),kC=e=>createImageBitmap(e);function oc(){return{canvas:null,readable:!1}}function BT(e){return e.paused&&e.readyState<2&&e.videoWidth>0}function sc(e,t){let n=t?.lastPlayingTime??null;return BT(e)&&n!==null?n:e.currentTime}function PC(e,t=zT){let n=EC,i=t();i.width=n,i.height=n;let u=i.getContext("2d");if(!u)return!1;u.drawImage(e,0,0,n,n);let l=u.getImageData(0,0,n,n).data,d=0,c=0;for(let r=0;r({kind:"failed",reason:h,retry:m}),u=e?.video;if(!e||!u||(n.requireConnected??!0)&&!u.isConnected||u.videoWidth===0)return i(ks,!0);let l=BT(u);if(u.readyState<2&&!l)return i(ks,!0);let d=n.createCanvas??zT,c=As(u.videoWidth,u.videoHeight,t),s=n.maxSide??4096;if(c.width>s||c.height>s)return i(OC);let r=e.source;r.canvas||(r.canvas=d(),r.readable=!1);let o=r.canvas;o.width=c.width,o.height=c.height;let a=o.getContext("2d");if(!a)return i(ic);let p=sc(u,e);try{return a.drawImage(u,0,0,c.width,c.height),l&&PC(o,d)?(r.readable=!0,i(SC,!0)):(r.readable||(a.getImageData(0,0,1,1),r.readable=!0),{kind:"frame",bitmap:await(n.createImageBitmap??kC)(o),mediaTime:p})}catch(h){return i(CC(h)?IC:String(h))}}function LT(e,t){let n=null,i=oc(),u={video:e,get lastPlayingTime(){return n},get source(){return i},mediaTime:()=>sc(e,u),detach:a},l=()=>t.discontinuity(!1),d=()=>{i=oc(),n=null,t.discontinuity(!0)},c=()=>{!e.paused&&e.readyState>=2&&(n=e.currentTime),t.presented(u.mediaTime())},s=()=>t.presented(u.mediaTime()),r=[["seeking",l],["emptied",d],["loadeddata",d],["timeupdate",c],["seeked",c],["canplay",s],["playing",s]];for(let[p,h]of r)e.addEventListener(p,h);let o=!0;function a(){if(o){o=!1;for(let[p,h]of r)e.removeEventListener(p,h)}}return u}var EM=1440*60*1e3;var RC=[/^the worker did not start/,/^unexpected error while loading/];function jT(e,t){return t||e.startsWith("unexpected:")?!1:!RC.some(n=>n.test(e))}var NM=Object.freeze({misses:2,maxMs:5e3,sameBoxIou:.5});function DC(e,t){return e==="loading"?{phase:t.phase,bytes:t.bytes}:void 0}function MC(e){if(!e||!Number.isFinite(e.rotation)||e.rotation===0)return{};let{rotation:t,localWidth:n,localHeight:i}=e;return t>-45&&t<=45&&n>0&&n<=1&&i>0&&i<=1?{rotation:t,localWidth:n,localHeight:i}:{}}function NC(e,t,n=40){return(e.hover?.cards??[]).map(i=>i.bounds).filter(i=>i&&!(Math.abs(i.x-t.x)<1e-6&&Math.abs(i.y-t.y)<1e-6&&Math.abs(i.width-t.width)<1e-6)).slice(0,n).map(i=>({x:i.x,y:i.y,width:i.width,height:i.height}))}var Ps=class{constructor(t,n={}){this.deps=t;this.mode=n.mode??"pointer",this.hold=n.hold??null,this.maxOtherBoxes=n.maxOtherBoxes??40,this.rotatedOutlines=n.rotatedOutlines===!0,this.hitTest=t.hoverAt??vs,this.scheduler=new eo(Is(null,this.mode),3,this.mode,Ss(null)),this.st={state:"loading",error:null,release:null,backend:null,schedule:"idle",frames:0,lastWorkerMs:null,lastRoundTripMs:null,lastFrameError:null,geometric:n.geometric?{state:"loading",reason:null,bytes:null}:null,loading:null,tilted:null},this.lastStatusKey=this.statusKey()}deps;scheduler;mode;hold;maxOtherBoxes;rotatedOutlines;hitTest;st;cardList=[];analysisWidth={min:720,max:1920};maxAgeMs=rc;nextRequestId=1;inFlight=null;lastAcceptedRequestId=0;analyzedSinceLoad=!1;generation=0;sourceCount=0;result=null;pointerAt=null;mediaTime=0;lastShownKey="null";lastStatusKey="";held=null;get videoKey(){return`source-${this.sourceCount}`}pointer(t,n,i,u=!1){if(this.st.state==="stopped")return;let l=this.deps.now();this.pointerAt={x:t,y:n},this.mediaTime=i,u?this.scheduler.tapped(l):this.scheduler.pointerMoved(l),this.st.state==="ready"&&this.scheduler.hoverTriggerDue(l,this.videoTime(),this.inFlight!==null)&&this.requestCapture("hover"),this.publish()}pointerLeft(){this.st.state!=="stopped"&&(this.pointerAt=null,this.scheduler.pointerLeft(this.deps.now()),this.publish())}presented(t){this.st.state!=="stopped"&&(this.mediaTime=t,this.scheduler.framePresented(),this.publish())}discontinuity(t){this.st.state!=="stopped"&&(this.generation+=1,t&&(this.sourceCount+=1),this.scheduler.discontinuity(),this.result=null,this.held=null,t&&this.scheduler.framePresented(),this.publish())}cut(){this.st.state!=="stopped"&&(this.generation+=1,this.result=null,this.held=null,this.scheduler.requestLook(),this.publish())}frame(t,n,i){let u=this.inFlight;if(this.st.state==="stopped"||!u||u.requestId!==t||u.analyzing){n.close();return}if(this.scheduler.pictureReceived(),u.generation!==this.generation||u.videoKey!==this.videoKey){this.inFlight=null,n.close(),this.publish();return}u.analyzing=!0;let l={requestId:u.requestId,mediaTimeSec:i,generation:u.generation,videoKey:u.videoKey};try{this.deps.toWorker({kind:"frame",bitmap:n,videoTimeSec:i,envelope:l,...this.rotatedOutlines?{rotatedOutlines:!0}:{}},[n])}catch(d){n.close(),this.inFlight=null,this.st.lastFrameError=`analysis-failed: ${String(d)}`,this.scheduler.lookUnanswered(this.deps.now())}this.publish()}captureFailed(t,n,i=!1){let u=this.inFlight;this.st.state==="stopped"||!u||u.requestId!==t||u.analyzing||(this.inFlight=null,this.st.lastFrameError=`capture-failed: ${n}`,i?this.scheduler.lookUnanswered(this.deps.now(),{prompt:!0}):this.scheduler.lookRefused(),this.publish())}fromWorker(t){if(this.st.state!=="stopped")switch(t.kind){case"geometric-status":this.st.geometric={state:t.state,reason:t.reason,bytes:t.bytes},this.deps.onGeometricStatus?.(t),this.publishStatus();return;case"tilted-status":this.st.tilted={state:"off",reason:t.reason},this.deps.onTiltedStatus?.(t),this.publishStatus();return;case"release-progress":{let n=DC(this.st.state,t);n!==void 0&&(this.st.loading=n),this.publishStatus();return}case"release-status":this.st.state=t.ok?"ready":"failed",this.analyzedSinceLoad=!1,this.st.error=t.error,this.st.release=t.release,this.st.loading=null,this.st.tilted=t.release?.tiltedRetry?{state:"on",reason:null}:null,this.cardList=t.cards,t.release&&(this.st.backend=t.release.recognizer.ep,this.maxAgeMs=t.release.hoverMaxAgeMs,this.analysisWidth={...t.release.analysisWidth},this.scheduler.setIntervalMs(Is(this.st.backend,this.mode)),this.scheduler.setReadingIntervalMs(Ss(this.st.backend)),this.scheduler.framePresented()),this.publish();return;case"frame-result":this.onFrameResult(t);return;default:return}}onFrameResult(t){let n=this.deps.now(),i=nc(t.envelope,{inFlightRequestId:this.inFlight?.requestId??null,lastAcceptedRequestId:this.lastAcceptedRequestId,generation:this.generation,videoKey:this.videoKey});if(i!==null&&!NT(i))return;let u=this.inFlight;if(this.inFlight=null,i!==null){this.publish();return}this.lastAcceptedRequestId=t.envelope.requestId,this.st.lastFrameError=t.error??null,this.st.lastWorkerMs=t.workerMs,this.st.lastRoundTripMs=+(n-u.sentAt).toFixed(2),t.analysis?(this.analyzedSinceLoad=!0,this.scheduler.lookAnswered(),this.st.frames+=1,this.result={analysis:t.analysis,videoTimeSec:t.videoTimeSec},this.deps.onAnalysis?.(t.analysis)):(this.result=null,t.error===V$&&this.scheduler.lookUnanswered(n)),this.held&&this.pointerAt&&this.current()&&!this.fresh()&&(this.held.misses+=1),this.scheduler.setTooltipShowing(this.shown()!==null,n),this.publish()}tick(){if(this.st.state==="stopped")return;let t=this.deps.now(),n=this.analyzedSinceLoad?DT:MT;this.inFlight&&t-this.inFlight.sentAt>=n&&(this.inFlight=null,this.st.lastFrameError="no reply",this.scheduler.lookUnanswered(t)),this.scheduler.setTooltipShowing(this.shown()!==null,t),this.st.state==="ready"&&!this.inFlight&&this.scheduler.due(t)&&this.requestCapture(this.scheduler.lookPending?"cut":void 0),this.publish()}stop(){this.st.state!=="stopped"&&(this.st.state="stopped",this.st.loading=null,this.inFlight=null,this.result=null,this.held=null,this.pointerAt=null,this.publishShown(),this.publishStatus())}workerStopped(t){if(!(this.st.state==="stopped"||this.st.state==="failed")){if(this.inFlight=null,this.result=null,this.held=null,this.st.loading=null,this.publishShown(),"restart"in t){let n={kind:"geometric-status",state:"off",reason:"worker-restarted",bytes:null};this.st.geometric&&(this.st.geometric={state:n.state,reason:n.reason,bytes:n.bytes}),this.deps.onGeometricStatus?.(n),this.st.state="loading",this.analyzedSinceLoad=!1,this.st.error=null}else this.st.state="failed",this.st.error=t.error;this.publishStatus()}}reloading(t){this.st.state==="loading"&&(this.st.geometric=t.geometric?{state:"loading",reason:null,bytes:null}:null,this.st.loading=null,this.publishStatus())}requestCapture(t){if(this.st.state!=="ready"||this.inFlight)return;let n=this.deps.now(),i=this.nextRequestId++;this.inFlight={requestId:i,sentAt:n,generation:this.generation,videoKey:this.videoKey,analyzing:!1},this.scheduler.started(n,{videoTimeSec:this.videoTime(),...t?{trigger:t}:{}}),this.deps.capture(i,{...this.analysisWidth})}status(){return{...this.st,schedule:this.scheduler.analysisState(this.deps.now())}}analysis(){return this.current()?.analysis??null}cards(){return this.cardList}hitAt(t,n){let i=this.current();if(!i)return null;let{width:u,height:l}=i.analysis.frame;if(!(u>0&&l>0))return null;let d=t*u,c=n*l;if(!Number.isFinite(d)||!Number.isFinite(c))return null;let s=this.hitTest(i.analysis,d,c);if(!s.box||s.cardId===null||s.name===null)return null;let r={x:s.box.x/u,y:s.box.y/l,width:s.box.width/u,height:s.box.height/l},o={x:s.box.x,y:s.box.y,width:s.box.width,height:s.box.height};return{cardId:s.cardId,name:s.name,box:r,frameBox:o,others:NC(i.analysis,r,this.maxOtherBoxes),...MC(s.card)}}fresh(){return this.pointerAt?this.hitAt(this.pointerAt.x,this.pointerAt.y):null}shown(){let t=this.fresh(),n=this.hold;if(!n)return t;let i=this.deps.now();if(t)return this.held={card:t,misses:0,seenAt:i},t;let u=this.held;return!u||!this.pointerAt||!BC(u.card.box,this.pointerAt)?(this.held=null,null):this.boxAtPointer(u.card.box,n.sameBoxIou)==="other"||u.misses>=n.misses||i-u.seenAt>=n.maxMs?(this.held=null,null):u.card}current(){let t=this.result;return t&&RT(t.videoTimeSec,this.videoTime(),this.maxAgeMs)?t:null}videoTime(){return this.deps.mediaTimeNow?this.deps.mediaTimeNow():this.mediaTime}boxAtPointer(t,n){let i=this.current();if(!i||!this.pointerAt)return"unknown";let{width:u,height:l}=i.analysis.frame;if(!(u>0&&l>0))return"unknown";let d=this.pointerAt.x*u,c=this.pointerAt.y*l,s={x:t.x*u,y:t.y*l,width:t.width*u,height:t.height*l},r=0,o=!1;for(let a of i.analysis.boxes??[]){let[p,h,m,g]=a.box;dp+m||ch+g||(o=!0,r=Math.max(r,zC(s,{x:p,y:h,width:m,height:g})))}return o?r>=n?"same":"other":"none"}publish(){this.publishShown(),this.publishStatus()}publishShown(){let t=this.shown(),n=t?`${t.cardId}|${t.box.x}|${t.box.y}|${t.box.width}|${t.box.height}|${t.rotation??""}|${t.localWidth??""}|${t.localHeight??""}`:"null";n!==this.lastShownKey&&(this.lastShownKey=n,this.deps.onShown?.(t))}statusKey(){let t=this.status();return JSON.stringify({...t,release:t.release?t.release.id:null})}publishStatus(){let t=this.statusKey();t!==this.lastStatusKey&&(this.lastStatusKey=t,this.deps.onStatus?.(this.status()))}};function zC(e,t){let n=Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x),i=Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y);if(n<=0||i<=0)return 0;let u=n*i;return u/(e.width*e.height+t.width*t.height-u)}function BC(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}var VT=1;function FC(e){let{geometricUrl:t,geometricManifestSha256:n,geometricWatchdog:i,...u}=e;return u}function qT(e){let t=null,n=null,i=0,u=!1,l=null,d=!1,c=null,s={source:e.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},r=y=>{e.onDecision?.({reused:0,downloaded:0,ms:0,...y})},o=y=>new Ps({now:e.now,toWorker:(T,S)=>t?.postMessage(T,S??[]),capture:e.capture,...e.onShown?{onShown:e.onShown}:{},...e.onStatus?{onStatus:e.onStatus}:{},...e.onAnalysis?{onAnalysis:e.onAnalysis}:{},...e.onGeometricStatus?{onGeometricStatus:e.onGeometricStatus}:{},...e.hoverAt?{hoverAt:e.hoverAt}:{},...e.mediaTimeNow?{mediaTimeNow:e.mediaTimeNow}:{}},{...e.mode?{mode:e.mode}:{},...e.hold?{hold:e.hold}:{},...e.rotatedOutlines?{rotatedOutlines:!0}:{},geometric:y.geometricUrl!==void 0}),a=y=>{u||!n||(l&&y.kind==="release-progress"&&y.phase==="preparing"&&(d=!0),!(y.kind==="release-status"&&(n.status().state!=="loading"||l&&!h(y)))&&(y.kind==="release-status"&&!y.ok&&p(),n.fromWorker(y)))},p=()=>{u=!0,l=null,t?.terminate(),t=null},h=y=>{let T=l;if(y.ok&&y.release?.id===T.pointer.id)return l=null,c=T.pointer.id,s.source="remote",s.id=T.pointer.id,s.reason="ok",s.table=T.facts,r({source:"remote",reason:"ok",pointer:T.pointer.id,reused:T.reused,downloaded:T.downloaded,ms:T.ms}),!0;if(y.ok)return e.recordSkip?.(T.pointer,"id-mismatch"),m("id-mismatch"),!1;let S=y.error??"no reason given";return jT(S,d)&&e.recordSkip?.(T.pointer,`runtime:${S.slice(0,120)}`),m(`runtime:${S}`),!1},m=y=>{let T=l;l=null,t?.terminate(),s.source="bundled",s.id=null,s.reason=y,s.table=null,r({source:"bundled",reason:y,pointer:T.pointer.id,reused:T.reused,downloaded:T.downloaded,ms:T.ms});let S=T.fallback??e.loadRequest;n?.reloading({geometric:S.geometricUrl!==void 0}),w(S)},g=y=>{if(u||!n)return;let T=n.status().state;if(T==="failed"||T==="stopped")return;let S=y.message||"see the console";if(l){h({kind:"release-status",ok:!1,error:`the worker did not start (${S})`,release:null,cards:[]});return}if(t?.terminate(),T==="loading"&&i===0){p(),n.workerStopped({error:`the worker did not start (${S})`});return}if(i{let T=e.createWorker();T.onmessage=S=>{T===t&&a(S.data)},T.onerror=S=>{T===t&&g(S)},t=T,T.postMessage(y)},w=y=>{n??=o(y);try{_(y)}catch(T){t=null,l=null,u=!0,n.workerStopped({error:`the recognition worker could not start (${String(T)})`})}};return e.chooseRelease?e.chooseRelease({onDownloading:()=>e.onDownloading?.()}).catch(y=>({source:"bundled",reason:`unexpected:${String(y)}`,pointer:null,downloaded:0,ms:0})).then(y=>{if(!u){if(y.source==="remote"){l=y,d=!1,w(y.request);return}s.source="bundled",s.reason=y.reason,r({source:"bundled",reason:y.reason,pointer:y.pointer?.id??null,downloaded:y.downloaded,ms:y.ms}),w(y.request??e.loadRequest)}}):w(e.loadRequest),{get core(){return n},get stopped(){return u},get restarts(){return i},get release(){return{...s}},tick(){u||n?.tick()},stop(){u=!0,l=null,t?.terminate(),t=null,n?.stop()}}}var LC={requireConnected:!1,maxSide:1/0};function jC(e,t){let n=e instanceof HTMLVideoElement?e:null,i=e,u=t.workerUrl??new URL("./worker.js",import.meta.url),l=()=>performance.now(),d=!1,c=0,s=!1,r=()=>{c>0?s=!0:d&&t.onUpdate?.()},o=(N,X=!1)=>{c+=1;try{N()}finally{c-=1}X&&(s=!0),c===0&&s&&(s=!1,d&&t.onUpdate?.())},a=null,p=new Es,h=null,m=null,g=-1/0,_=()=>{let N=h&&a?a.read(h):null;N?p.seed(N):(a?.release(h),p.reset()),h=null},w=n?null:document.createElement("canvas"),y=w?.getContext("2d")??null,T=async N=>{if(!w||!y)return{kind:"failed",reason:ic,retry:!1};let X=Zn(e);if(X.width===0||X.height===0)return{kind:"failed",reason:ks,retry:!0};try{let W=await ec(e,w,y,N);return{kind:"frame",bitmap:W.bitmap,mediaTime:W.videoTimeSec}}catch(W){return{kind:"failed",reason:String(W),retry:!1}}},S=(N,X)=>{a?.release(h),h=a?.usable?a.sample(e):null,(z?FT(z,X,LC):T(X)).then(W=>o(()=>{W.kind==="frame"?q.frame(N,W.bitmap,W.mediaTime):q.captureFailed(N,W.reason,W.retry)},W.kind==="failed"))},O=0,A=null,P=()=>{O+=1;let N;try{N=new Worker(u,{type:"module"})}catch(W){throw O===1&&(A={error:W}),W}let X={postMessage:(W,re)=>N.postMessage(W,re??[]),terminate:()=>N.terminate(),onmessage:null,onerror:null};return N.onmessage=W=>o(()=>X.onmessage?.(W)),N.onerror=W=>o(()=>X.onerror?.(W)),X},I={kind:"load",releaseUrl:t.releaseFiles?String(t.releaseUrl):new URL(t.releaseUrl,location.href).href,...t.releaseFiles?{files:t.releaseFiles}:{},...t.wasmPaths!==void 0?{wasmPaths:t.wasmPaths}:{},...t.providers?{providers:t.providers}:{},...t.geometricUrl!==void 0?{geometricUrl:new URL(t.geometricUrl,location.href).href}:{},...t.geometricManifestSha256!==void 0?{geometricManifestSha256:t.geometricManifestSha256}:{},...t.geometricWatchdog===!1?{geometricWatchdog:!1}:{}},z=n?LT(n,{presented:N=>o(()=>q.presented(N)),discontinuity:N=>o(()=>{p.reset(),q.discontinuity(N)},!0)}):null,G=()=>z?.mediaTime()??0,J=qT({createWorker:P,loadRequest:I,now:l,...t.mode?{mode:t.mode}:{},...t.rotatedOutlines?{rotatedOutlines:!0}:{},capture:S,mediaTimeNow:()=>G(),onShown:r,onStatus:r,onAnalysis:_});if(A)throw z?.detach(),J.stop(),A.error;let q=J.core,C=(N,X)=>{let W=tc(e.getBoundingClientRect(),Zn(e),getComputedStyle(e).objectFit);if(W.width<=0||W.height<=0)return null;let re=q.hitAt((N-W.left)/W.width,(X-W.top)/W.height);return re?{hit:re,picture:W}:null},ee=(N,X)=>{let W=C(N,X);if(!W)return null;let{hit:re,picture:le}=W;return{name:re.name,cardId:re.cardId,box:{left:le.left+re.box.x*le.width,top:le.top+re.box.y*le.height,width:re.box.width*le.width,height:re.box.height*le.height},frameBox:re.frameBox,...re.rotation!==void 0&&re.localWidth!==void 0&&re.localHeight!==void 0?{rotation:re.rotation,localWidth:re.localWidth,localHeight:re.localHeight}:{}}},v=null,R=()=>v?ee(v.x,v.y):null,H=N=>{let X=v?C(v.x,v.y)?.hit.box??null:null;if(!X){a?.release(m),m=null;return}if(a||(a=kT()),!!a?.usable){if(m){let W=a.read(m);if(W&&(m=null,p.observe(W,X).cut)){p.reset(),q.cut(),s=!0;return}}!m&&N-g>=AT&&(g=N,m=a.sample(e))}},L=null,V=()=>{!d||!n||(o(()=>{q.presented(G()),H(l())}),L=n.requestVideoFrameCallback(V))},K=()=>o(()=>{p.reset(),q.discontinuity(!0)},!0),B=N=>o(()=>{v={x:N.clientX,y:N.clientY};let X=tc(e.getBoundingClientRect(),Zn(e),getComputedStyle(e).objectFit),W=ET(X,N.clientX,N.clientY)??{x:(N.clientX-X.left)/X.width,y:(N.clientY-X.top)/X.height};q.pointer(W.x,W.y,G(),N.pointerType==="touch")},!0),te=()=>o(()=>{v=null,q.pointerLeft()},!0);n&&"requestVideoFrameCallback"in n&&(L=n.requestVideoFrameCallback(V)),n||e.addEventListener("load",K),i.addEventListener("pointermove",B),i.addEventListener("pointerdown",B),i.addEventListener("pointerleave",te);let Y=setInterval(()=>o(()=>J.tick()),CT);return d=!0,{status:()=>q.status(),at:ee,atPointer:R,analysis:()=>q.analysis(),cards:()=>q.cards(),stop:()=>{d&&(d=!1,clearInterval(Y),L!==null&&n&&"cancelVideoFrameCallback"in n&&n.cancelVideoFrameCallback(L),L=null,z?.detach(),e.removeEventListener("load",K),i.removeEventListener("pointermove",B),i.removeEventListener("pointerdown",B),i.removeEventListener("pointerleave",te),a?.release(h),a?.release(m),a?.dispose(),p.reset(),J.stop())}}}var Mr={maxCorrespondences:40,fitMinInliers:3,inlierShare:[2,3],ambiguityMin:2,compatTol:.01,scaleRatioTol:.03},ac=1e-9,Cs=5;function cr(e,t){let n=Math.max(0,Math.min(e.x+e.w,t.x+t.w)-Math.max(e.x,t.x)),i=Math.max(0,Math.min(e.y+e.h,t.y+t.h)-Math.max(e.y,t.y)),u=n*i,l=e.w*e.h+t.w*t.h-u;return l>0?u/l:0}function Sn(e,t){return{x:e.sx*t.x+e.tx,y:e.sy*t.y+e.ty,w:e.sx*t.w,h:e.sy*t.h}}function to(e,t){return{x:e.sx*t.x+e.tx,y:e.sy*t.y+e.ty}}function uc(e){return{x:e.tx,y:e.ty,width:e.sx,height:e.sy}}function Rs(e){if(e.cards.length===0)return null;let t=1/0,n=1/0,i=-1/0,u=-1/0;for(let{bounds:l}of e.cards)t=Math.min(t,l.x),n=Math.min(n,l.y),i=Math.max(i,l.x+l.w),u=Math.max(u,l.y+l.h);return{x:t,y:n,w:i-t,h:u-n}}function lc(e){let t=[];for(let n=0;n=e.x&&t.x<=e.x+e.w&&t.y>=e.y&&t.y<=e.y+e.h}function GT(e,t){return et?1:0}function UC(e,t){return t.identity===void 0?!1:e.blocking===void 0||!In(e.blocking,XT(t.bounds))}function Ds(e,t,n=Mr.maxCorrespondences){let i=new Map;for(let d of e)i.set(d.identity,i.has(d.identity)?null:d);let u=new Map;for(let d of t.cards){if(!UC(t,d))continue;let c=d.identity;u.set(c,u.has(c)?null:d)}let l=[];for(let[d,c]of i){let s=u.get(d);!c||!s||l.push({identity:d,v:c.bounds,r:s.bounds,instance:s.instance})}return l.length>n&&(l.sort((d,c)=>c.v.w*c.v.h-d.v.w*d.v.h||GT(d.identity,c.identity)),l=l.slice(0,n)),l.sort((d,c)=>GT(d.identity,c.identity))}function VC(e){if(!(e.r.w>0)||!(e.r.h>0))return null;let t=e.v.w/e.r.w,n=e.v.h/e.r.h,i={sx:t,sy:n,tx:e.v.x-t*e.r.x,ty:e.v.y-n*e.r.y};return![i.sx,i.sy,i.tx,i.ty].every(Number.isFinite)||!(t>0)||!(n>0)?null:i}function HT(e){let t=e.length;if(t===0)return null;let n=0,i=0;for(let[s,r]of e)n+=s,i+=r;n/=t,i/=t;let u=0,l=0;for(let[s,r]of e)u+=(s-n)*(r-i),l+=(s-n)*(s-n);if(!(l>0))return null;let d=u/l;if(!(d>0)||!Number.isFinite(d))return null;let c=i-d*n;return Number.isFinite(c)?{s:d,t:c}:null}function WT(e){let t=[],n=[];for(let{r:l,v:d}of e)t.push([l.x,d.x],[l.x+l.w,d.x+d.w]),n.push([l.y,d.y],[l.y+l.h,d.y+d.h]);let i=HT(t),u=HT(n);return!i||!u?null:{sx:i.s,sy:u.s,tx:i.t,ty:u.t}}function dc(e,t,n){if(e.length===0||!(t>0)||!(n>0))return null;let i=[],u=[];for(let{r:y,v:T}of e)i.push([y.x,T.x],[y.x+y.w,T.x+T.w]),u.push([y.y,T.y],[y.y+y.h,T.y+T.h]);let l=(y,T)=>y.reduce((S,O)=>S+O[T],0)/y.length,d=l(i,0),c=l(i,1),s=l(u,0),r=l(u,1),o=0,a=0,p=0,h=0;for(let[y,T]of i)o+=(y-d)*(y-d),a+=(y-d)*(T-c);for(let[y,T]of u)p+=(y-s)*(y-s),h+=(y-s)*(T-r);let m=n*n,g=m*o+t*t*p;if(!(g>0))return null;let _=(m*a+t*h)/g;if(!(_>0)||!Number.isFinite(_))return null;let w={sx:_,sy:t*_,tx:c-_*d,ty:r-t*_*s};return[w.sy,w.tx,w.ty].every(Number.isFinite)?w:null}function qC(e,t){if(e.aspect===void 0||t===void 0)return null;let n=i=>Number.isFinite(i)&&i>0;return!n(e.aspect)||!n(t)?NaN:t/e.aspect}function GC(e,t,n,i,u=1){return Ms(e,t,n,i,u).outcome}function Ms(e,t,n,i,u=1){if(t===null)return{outcome:{kind:"no-layout"},correspondences:[],support:[],winner:-1,aspectRejected:[]};let l=Ds(e,t,n.maxCorrespondences),d=l.length,c=[],s=(L,V,K=[],B=-1)=>({outcome:{kind:"insufficient",reason:L,n:d,inliers:V},correspondences:l,support:K,winner:B,aspectRejected:c}),r=qC(t,i);if(r!==null&&(Number.isNaN(r)||!(Number.isFinite(u)&&u>0)))return s("degenerate",0);let o=L=>r!==null&&Math.abs(L.sy/L.sx/r-1)>n.scaleRatioTol,a=L=>{let V=[];for(let K=0;K=n.fitMinIoU&&V.push(K);return V},p=l.map(VC),h=p.map((L,V)=>L&&o(L)?(c.push(V),null):L),m=()=>c.some(L=>a(p[L]).length>=2),g=[],_=[];for(let L=0;L=n.fitMinIoU&&(K.push(te),B+=Y)}g.push(K),_.push(B)}let w=-1;for(let L=0;LK||V===K&&_[L]>_[w]+ac)&&(w=L)}if(w<0){let L=d=n.fitMinInliers)return s(m()?"aspect":"zero-inliers",0,g,w);let y=g[w].map(L=>l[L]),T=r===null?WT(y):dc(y,r*u,i);if(!T)return s("degenerate",0,g,w);let S=[],O=1/0;for(let L of g[w]){let V=cr(Sn(T,l[L].r),l[L].v);V>=n.fitMinIoU&&(S.push(L),O=Math.min(O,V))}let A=S.map(L=>l[L].identity),P=Rs(t),I=new Set(S),z=[];for(let L=0;L!I.has(B));K.length>z.length&&(z=K)}if(z.length>=n.ambiguityMin)return{outcome:{kind:"ambiguous",transform:T,inliers:A,runnerUp:z.map(L=>l[L].identity),n:d},correspondences:l,support:g,winner:w,aspectRejected:c};if(A.lengthl[V]));if(!L||o(L))return s("aspect",A.length,g,w);H=L.sy/L.sx/r}return{outcome:{kind:"verified",transform:T,inliers:A,n:d,minIoU:O,span:R,...H!==void 0?{boardRatio:H}:{}},correspondences:l,support:g,winner:w,aspectRejected:c}}var HC=8,WC=20,KC=.3;function XC(e,t,n,i,u){let l=0;for(let d of lc(n)){let c=to(e,d),s=to(t,d);l=Math.max(l,Math.abs(c.x-s.x)*i,Math.abs(c.y-s.y)*u)}return l}function ZC(e,t){return t?e<=HC?"correct":e<=WC?"loose":"false":"none"}function ZT(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}function YC(e,t,n,i=[]){let u=ZT(e.box);if(!In(n,u)||i.some(c=>In(c,u)))return"blocked";let l=null,d=-1;for(let c of t){let s=cr(e.box,c.box);s>=KC&&s>d&&(l=c,d=s)}return l?!l.faceUp||l.identity===void 0?"back-hidden":l.identity===e.identity?"correct":"wrong-identity":"empty"}function JC(e,t,n,i=[]){let u=0,l=0;for(let d of e){if(!d.faceUp||d.identity===void 0)continue;let c=ZT(d.box);!In(n,c)||i.some(s=>In(s,c))||(u+=1,t.some(s=>s.identity===d.identity&&In(s.box,c))&&(l+=1))}return u===0?null:l/u}function QC(e,t){return t.map(n=>eR(e,n))}function eR(e,t){let n=null;for(let i of e){if(i.atMs>t)break;n=i.display}if(n!=="fitted")return 0;for(let i of e)if(i.atMs>=t&&i.display!=="fitted")return i.atMs-t;return null}var Ns={window:10,minIdentities:3,trip:.4,recover:.7},ro=class{params;exclude;window=[];stateValue="unknown";recoverRun=0;constructor(t={}){this.params=t.params??Ns,this.exclude=t.exclude??(()=>!1)}get state(){return this.stateValue}get tripped(){return this.stateValue==="tripped"}get share(){return this.summary().share}observe(t){if(t.windowIdentities.size===0)return{state:this.stateValue,event:null,...this.summary(),counted:!1};let n=new Map;for(let c of t.accepted)this.exclude(c)||n.set(c,(n.get(c)??!1)||t.windowIdentities.has(c));this.window.push(n),this.window.length>this.params.window&&this.window.shift();let{identities:i,share:u}=this.summary(),l=i>=this.params.minIdentities&&u!==null,d=null;return this.stateValue==="tripped"?(this.recoverRun=l&&u>=this.params.recover?this.recoverRun+1:0,this.recoverRun>=this.params.window&&(this.stateValue="in",this.recoverRun=0,d="recover")):l&&(u0&&t.scaleRatioTol<=.25))return"scaleRatioTol must be above 0 and at most 0.25";let n=t;return n.fitMinIoU<.5||n.fitMinIoU>1?"fitMinIoU must be between 0.5 and 1":n.minSpan<0||n.minSpan>1?"minSpan must be between 0 and 1":!Number.isInteger(n.confirmFits)||n.confirmFits<1||n.confirmFits>3?"confirmFits must be 1, 2 or 3":n.suppressionIoU<=0||n.suppressionIoU>1?"suppressionIoU must be above 0 and at most 1":n.intervalMs<=0?"intervalMs must be positive":n.confirmWindowMs<3*n.intervalMs?"confirmWindowMs must be at least 3 \xD7 intervalMs":n.freshnessMs<2*n.intervalMs?"freshnessMs must be at least 2 \xD7 intervalMs":n.holdMs=u){d.add(c.instance);break}}return e.cards.map(c=>c.instance).filter(c=>d.has(c))}var eS=15;function tR(e){let t=[...e].sort((i,u)=>i-u),n=t.length>>1;return t.length%2===1?t[n]:(t[n-1]+t[n])/2}var no=class{config;fitParams;monitor;generationValue=null;stateValue="off";contradicted=!1;verifiedThisGen=!1;run=null;confirmed=null;confirmedBasis=null;ratioPool=[];appliedScale=1;holdStart=null;lastAnalysisAt=null;zeroStreak=0;lastFrame={kind:"no-layout"};suppressed=[];current;constructor(t,n={}){let i=JT(t);if(i)throw new Error(i);this.config=Object.freeze({...t}),this.fitParams={...Mr,fitMinIoU:t.fitMinIoU,minSpan:t.minSpan,ambiguityMin:t.ambiguityMin??Mr.ambiguityMin,scaleRatioTol:t.scaleRatioTol??Mr.scaleRatioTol},this.monitor=new ro({exclude:n.exclude,params:Ns}),this.current=this.build(0,0)}get generation(){return this.generationValue}get state(){return this.stateValue}get verdict(){return this.current}eligibilityLost(t){return this.clear(),this.generationValue=null,this.stateValue="off",this.current=this.build(1,t)}reset(t,n){return this.clear(),this.generationValue=t,this.stateValue="unverified",this.current=this.build(2,n)}tick(t){return this.expired(t)?(this.expire(),this.current=this.build(11,t)):this.current=this.build(0,t)}analyze(t,n){if(this.generationValue===null||t.generation!==this.generationValue)return null;let i=this.expired(n);i&&this.expire();let u=this.stateValue,l=this.ratioScale(),d=Ms(t.observations,t.layout,this.fitParams,t.frameAspect,l),c=d.outcome;this.lastFrame=c;let s=null;c.kind==="verified"&&c.boardRatio!==void 0&&(s={correspondences:d.support[d.winner].map(_=>d.correspondences[_]),ratio:t.frameAspect/t.layout.aspect,frameAspect:t.frameAspect});let r=this.monitor.observe({windowIdentities:t.windowIdentities,accepted:t.observations.map(_=>_.identity)});this.lastAnalysisAt=n,this.zeroStreak=c.kind==="insufficient"&&c.reason==="zero-inliers"?this.zeroStreak+1:0;let o=t.layout?Rs(t.layout):null,a=c.kind==="verified"&&o!==null?c:null,p=this.fitParams.compatTol,h=a!==null&&this.confirmed!==null&&!Yn(a.transform,this.confirmed,o,p),m=this.run;if(a){let _=this.run!==null&&Yn(a.transform,this.run.latest,o,p)&&t.capturedAtMs-this.run.capturedAtMs<=this.config.confirmWindowMs;m={latest:a.transform,capturedAtMs:t.capturedAtMs,length:_?this.run.length+1:1,basis:s}}let g;return r.event==="trip"?(g=3,this.run=m,this.stateValue="mismatch",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0):u==="mismatch"&&r.event==="recover"?(g=4,this.run=m,this.stateValue="unverified"):h?(g=5,this.run={latest:a.transform,capturedAtMs:t.capturedAtMs,length:1,basis:s},this.stateValue="contradicted",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0,this.verifiedThisGen=!0):this.zeroStreak>=2&&(u==="verified"||u==="held")?(g=6,this.stateValue="contradicted",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0,this.verifiedThisGen=!0):t.faces===0&&t.layout!==null&&t.layout.cards.length>=3&&this.verifiedThisGen&&u!=="mismatch"?(g=7,this.run=m,this.stateValue="no-faces"):a&&m.length>=this.config.confirmFits?(g=9,this.run=m,this.stateValue="verified",this.confirmed=a.transform,this.confirmedBasis=s,this.contradicted=!1,this.holdStart=n,this.verifiedThisGen=!0,this.monitor.clearTrip()):(this.run=m,(u==="verified"||u==="held"||u==="no-faces"&&a!==null)&&this.confirmed!==null&&this.holdStart!==null&&n-this.holdStarteS&&this.ratioPool.shift()),this.applyScale(this.ratioScale()),(this.stateValue==="verified"||this.stateValue==="held")&&this.confirmed&&t.layout?this.suppressed=QT(t.layout,t.observations,this.confirmed,this.fitParams.fitMinIoU,this.config.suppressionIoU,this.fitParams.maxCorrespondences):this.suppressed=[],this.current=this.build(g,n)}expired(t){let n=this.stateValue;if(n!=="verified"&&n!=="held"&&n!=="no-faces")return!1;let i=this.holdStart!==null&&t-this.holdStart>=this.config.holdMs,u=this.lastAnalysisAt!==null&&t-this.lastAnalysisAt>=this.config.freshnessMs;return i||u}applyScale(t){if(t===this.appliedScale)return;let n=i=>i?dc(i.correspondences,i.ratio*t,i.frameAspect):null;this.confirmed&&(this.confirmed=n(this.confirmedBasis)??this.confirmed),this.run&&(this.run.latest=n(this.run.basis)??this.run.latest),this.appliedScale=t}ratioScale(){if(this.ratioPool.length<2)return 1;let t=this.fitParams.scaleRatioTol;return Math.min(1+t,Math.max(1-t,tR(this.ratioPool)))}expire(){this.stateValue=this.monitor.tripped?"mismatch":"unverified",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.suppressed=[]}clear(){this.contradicted=!1,this.verifiedThisGen=!1,this.run=null,this.confirmed=null,this.confirmedBasis=null,this.ratioPool=[],this.appliedScale=1,this.holdStart=null,this.lastAnalysisAt=null,this.zeroStreak=0,this.lastFrame={kind:"no-layout"},this.suppressed=[],this.monitor.reset()}display(){switch(this.stateValue){case"off":return"today";case"verified":case"held":return"fitted";case"no-faces":return"hidden";case"mismatch":case"contradicted":return"vision";case"unverified":return this.contradicted?"vision":"today"}}build(t,n){let i=this.display(),u={display:i,suppressed:i==="fitted"?[...this.suppressed]:[],state:this.stateValue,contradicted:this.contradicted,frame:this.lastFrame,diagnostics:{elapsedSinceLastAnalysisMs:this.lastAnalysisAt===null?0:n-this.lastAnalysisAt,runLength:this.run?.length??0,monitorShare:this.monitor.share,row:t,ratioScale:this.ratioScale()}};return i==="fitted"&&(u.region=uc(this.confirmed)),u}};var cc="layout-recording/1",zs=2,rS=[{x:.05,y:.05},{x:.95,y:.05},{x:.5,y:.5},{x:.05,y:.95},{x:.95,y:.95}],rR=["supported-game","two-region","negative-no-faces","negative-gallery","negative-other-layout","transition"],Bs=class extends Error{};function St(e,t){throw new Bs(`${e}: ${t}`)}function mt(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&St(t,"must be an object"),e}function Nr(e,t){return Array.isArray(e)||St(t,"must be an array"),e}function Xe(e,t,n={}){return(typeof e!="number"||!Number.isFinite(e))&&St(t,"must be a finite number"),n.integer&&!Number.isInteger(e)&&St(t,"must be an integer"),n.min!==void 0&&e{let c=`${t}.cards[${d}]`,s=mt(l,c),r={instance:pr(s.instance,`${c}.instance`),bounds:io(s.bounds,`${c}.bounds`)};return s.identity!==void 0&&(r.identity=pr(s.identity,`${c}.identity`)),s.rotated!==void 0&&(typeof s.rotated!="boolean"&&St(`${c}.rotated`,"must be a boolean"),r.rotated=s.rotated),r}),u={key:pr(n.key,`${t}.key`),cards:i};return n.blocking!==void 0&&(u.blocking=io(n.blocking,`${t}.blocking`)),n.aspect!==void 0&&(u.aspect=Xe(n.aspect,`${t}.aspect`),u.aspect>0||St(`${t}.aspect`,"must be positive")),u}function iR(e,t){try{let n=mt(e,t),i=n.region!==null;return{region:i?tS(n.region,`${t}.region`):null,residualPx:i?Xe(n.residualPx,`${t}.residualPx`,{min:0}):typeof n.residualPx=="number"?n.residualPx:0,mask:io(n.mask,`${t}.mask`),blockers:n.blockers===void 0?[]:Nr(n.blockers,`${t}.blockers`).map((u,l)=>io(u,`${t}.blockers[${l}]`)),solves:n.solves===void 0?[]:Nr(n.solves,`${t}.solves`).map((u,l)=>{let d=mt(u,`${t}.solves[${l}]`);return{atMs:Xe(d.atMs,`${t}.solves[${l}].atMs`),residualPx:Xe(d.residualPx,`${t}.solves[${l}].residualPx`,{min:0}),region:i?tS(d.region,`${t}.solves[${l}].region`):null}})}}catch(n){if(n instanceof Bs)return n.message;throw n}}function oR(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))return n.push(`${t}: no clock`),{status:"missing"};let i=e;return i.status!=="ok"&&i.status!=="undecodable"&&i.status!=="missing"?(n.push(`${t}.status: unknown status ${JSON.stringify(i.status)}`),{status:"missing"}):i.status!=="ok"?{status:i.status}:typeof i.streamTimeMs!="number"||!Number.isFinite(i.streamTimeMs)?(n.push(`${t}.streamTimeMs: an ok clock without a finite time`),{status:"missing"}):{status:"ok",streamTimeMs:i.streamTimeMs}}function sR(e){let t=[],n=mt(e,"recording");n.schema!==cc&&St("recording.schema",`must be "${cc}"`);let i=mt(n.frame,"recording.frame"),u={width:Xe(i.width,"recording.frame.width",{min:1}),height:Xe(i.height,"recording.frame.height",{min:1})},l=Nr(n.cadenceProfiles,"recording.cadenceProfiles").map((o,a)=>{let p=mt(o,`recording.cadenceProfiles[${a}]`),h=Xe(p.intervalMs,`recording.cadenceProfiles[${a}].intervalMs`);return h>0||St(`recording.cadenceProfiles[${a}].intervalMs`,"must be positive"),{name:pr(p.name,`recording.cadenceProfiles[${a}].name`),intervalMs:h}}),d=Nr(n.scenes,"recording.scenes").map((o,a)=>{let p=`recording.scenes[${a}]`,h=mt(o,p),m=pr(h.class,`${p}.class`);rR.includes(m)||St(`${p}.class`,`unknown scene class "${m}"`);let g={id:pr(h.id,`${p}.id`),class:m,startMs:Xe(h.startMs,`${p}.startMs`),endMs:Xe(h.endMs,`${p}.endMs`)};if(g.endMs{let p=`recording.frames[${a}]`,h=mt(o,p),m=Xe(h.capturedAtMs,`${p}.capturedAtMs`);m{let T=`${p}.analysis.observations[${y}]`,S=mt(w,T);return{identity:pr(S.identity,`${T}.identity`),bounds:io(S.bounds,`${T}.bounds`)}})}}}),r=Nr(n.candidates,"recording.candidates").map((o,a)=>{let p=`recording.candidates[${a}]`,h=mt(o,p);return{key:pr(h.key,`${p}.key`),producedAtMs:Xe(h.producedAtMs,`${p}.producedAtMs`),arrivedAtMs:Xe(h.arrivedAtMs,`${p}.arrivedAtMs`),layout:nR(h.layout,`${p}.layout`)}});return{schema:cc,frame:u,cadenceProfiles:l,scenes:d,frames:s,candidates:r,problems:t}}function nS(e,t){return e.candidates.map((n,i)=>({c:n,i})).filter(({c:n})=>n.arrivedAtMs<=t).sort((n,i)=>n.c.arrivedAtMs-i.c.arrivedAtMs||n.i-i.i).map(({c:n})=>n)}function pc(e,t){let n=nS(e,t);return n.length>0?n[n.length-1]:null}function aR(e,t){if(!hc(t.clock))return null;let n=t.clock.streamTimeMs,i=null;for(let u of e.candidates)u.producedAtMs<=n&&(i===null||u.producedAtMs>i.producedAtMs)&&(i=u);return i}function hc(e){return e?.status==="ok"&&typeof e.streamTimeMs=="number"&&Number.isFinite(e.streamTimeMs)}function uR(e){let t=e.frames.filter(n=>hc(n.clock));return{frames:t,excluded:e.frames.length-t.length}}function lR(e,t){return e.scenes.find(n=>t>=n.startMs&&tu.residualPx<=zs))return!1;let i=[n.region];for(let u of n.solves){if(!u.region)return!1;i.push(u.region)}for(let u=0;uzs||l>zs)return!1}return!0}function iS(e){return{layoutAt:t=>pc(e,t)?.layout??null,windowIdentitiesAt:t=>pR(pc(e,t)?.layout??null)}}function pR(e){let t=new Set;for(let n of e?.cards??[])n.identity!==void 0&&t.add(n.identity);return t}function hR(e,t){let n=e.cadenceProfiles.find(p=>p.name===t.profile);if(!n)throw new Error(`no cadence profile "${t.profile}" in the recording`);let i={...t.config,intervalMs:n.intervalMs},u=new no(i,{exclude:t.exclude}),l=t.scheduler(n.intervalMs),d=t.source??iS(e),c=[],s=[],r=null,o=1;e.frames.length>0&&u.reset(o,e.frames[0].capturedAtMs);let a=()=>{let p=r;r=null;let h=p.frame,m={generation:o,capturedAtMs:h.capturedAtMs,faces:h.analysis.faces,observations:h.analysis.observations,layout:d.layoutAt(h.capturedAtMs),windowIdentities:d.windowIdentitiesAt(h.capturedAtMs),frameAspect:e.frame.width/e.frame.height};u.analyze(m,p.endedAtMs),s.push({frameIndex:h.index,startedAtMs:p.startedAtMs,endedAtMs:p.endedAtMs,late:p.endedAtMs>p.startedAtMs+n.intervalMs})};for(let p of e.frames){let h=p.capturedAtMs;r&&r.endedAtMs<=h&&a(),l.framePresented(),!r&&l.due(h)&&(l.started(h),r={frame:p,startedAtMs:h,endedAtMs:h+p.analysis.durationMs},p.analysis.durationMs===0&&a()),c.push({frameIndex:p.index,atMs:h,result:u.tick(h)})}return r&&a(),{steps:c,analyses:s}}export{$s as DEFAULT_ACCEPT,kd as DEFAULT_DECODE,ps as DEFAULT_LETTERBOX,$P as DEFAULT_TILTED_RETRY,Li as Detector,_s as EXECUTION_PROVIDERS,ji as Embedder,Gi as EmbeddingRecognizer,rS as FIDUCIAL_POINTS,eo as FrameScheduler,rc as HOVER_MAX_AGE_MS,J$ as HOVER_SELECTIONS,Tn as IdentityMap,Mr as LAYOUT_FIT_DEFAULTS,no as LayoutRegistration,uC as MAX_ANALYSIS_WIDTH,lC as MIN_ANALYSIS_WIDTH,Ns as MONITOR_DEFAULTS,ro as MismatchMonitor,aT as OUTLINE_MIN_TILT,er as PREPROCESSING,Ki as Pipeline,eS as RATIO_POOL_SIZE,Qi as ReleaseError,Hi as TemporalGate,Wi as Tracker,As as analysisSize,sC as analyzeFrame,G$ as boxAverageRgb,Is as cadenceMs,ec as captureFrame,fT as chooseLook,ZC as classifyAccept,YC as classifyHitbox,hc as clockUsable,Yn as compatible,Fd as computeCardQuad,Ds as correspondences,JC as coverage,jC as createSession,hT as cropRgba,C$ as decodeDetections,Wd as estimateTilt,QC as exitLatency,XC as fitError,GC as fitFrame,Ms as fitFrameDetail,vs as hoverAt,Gd as hoverCardsOf,eT as hoverOrder,Gn as iou,pc as latestOffered,JT as layoutConfigError,Rs as layoutExtent,cr as layoutIoU,Jk as letterboxBgr,Rd as letterboxGeometry,oC as loadRelease,Qd as loadReleaseData,lr as lookAccepted,Ad as nonMaxSuppression,nS as offeredCandidates,lT as outlineFromTilt,Zd as outlineRect,Nd as parseBank,Vd as parseIdentityGroups,xT as parseRelease,KT as placementDistance,Z$ as pointInConvexQuad,gT as poolEmbeddings,Sn as project,sR as readLayoutRecording,Yd as recognizeFrame,iS as recordingSource,Kd as rectFromAabb,hR as replayRecording,nc as replyRejection,cs as resizeBilinearRgb,Ud as resolveHover,Ld as resolveHoveredCard,ms as rotateTensor90,uT as sampleRect,lR as sceneAt,qi as selectHoverLayer,QT as suppressedInstances,mT as tiltedOrder,Xd as tiltedRects,uR as timedFrames,fs as toContractTensor,Dd as toDetectorTensor,uc as toRegion,aR as truthCandidate,dR as truthUsable,ls as validBox}; /*! For license information please see cardvision.js.LEGAL.txt */ diff --git a/vendor/cardvision-browser/compute-session.js b/vendor/cardvision-browser/compute-session.js index 10810a8..a28e66a 100644 --- a/vendor/cardvision-browser/compute-session.js +++ b/vendor/cardvision-browser/compute-session.js @@ -1 +1 @@ -function C(t){return t==="wasm"?2e3:1e3}function ye(t){return t==="wasm"?1e3:500}function F(t,e){return e==="always-on"?C(t):ye(t)}var ge=250,be=250,Se=1e4,xe=5e3,ve=400,W=2e3;function z(t,e,r){return Math.abs(e-t)*1e3<=r}var we=250,K=5e3,X=15e3,G=[250,500,1e3,2e3];function H(t,e){return t===void 0?"stale-request":t.requestId<=e.lastAcceptedRequestId?"superseded":t.requestId!==e.inFlightRequestId?"stale-request":t.videoKey!==e.videoKey?"video-key":t.generation!==e.generation?"generation":null}function $(t){return t==="video-key"||t==="generation"}var T=class{constructor(e,r=3,i="always-on",n=e,s=null){this.intervalMs=e;this.confirmFrames=r;this.mode=i;this.readingIntervalMs=n;this.probeIntervalMs=s;this.checkProbe(i)}intervalMs;confirmFrames;mode;readingIntervalMs;probeIntervalMs;pending=!1;repeatsLeft=0;lastStartedAt=-1/0;pointerInside=!1;lastPointerAt=-1/0;tooltipShowing=!1;lastTooltipAt=-1/0;lastHoverTriggerAt=-1/0;lastVideoTimeSec=null;discontinuitySinceLast=!1;lastTriggerKind=null;lookRequested=!1;unanswered=0;retryAt=null;retryPrompt=!1;lastUnansweredCapture=!1;refused=!1;pointerAnalysis=!1;checkProbe(e){if(e==="layout"&&!(this.probeIntervalMs!==null&&this.probeIntervalMs>0))throw new Error("layout mode needs a positive probe interval")}setProbeIntervalMs(e){this.probeIntervalMs=e,this.checkProbe(this.mode)}setPointerAnalysis(e){this.pointerAnalysis=e}setIntervalMs(e){this.intervalMs=e}setReadingIntervalMs(e){this.readingIntervalMs=e}setTooltipShowing(e,r){this.tooltipShowing=e,e&&this.pointerInside&&(this.lastTooltipAt=r)}setMode(e){this.checkProbe(e),this.mode=e}get analysisMode(){return this.mode}framePresented(){this.pending=!0,this.repeatsLeft=0}discontinuity(){this.discontinuitySinceLast=!0,this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}requestLook(){this.discontinuitySinceLast=!0,this.pending=!0,this.repeatsLeft=0,this.lookRequested=!0}lookUnanswered(e,r={}){this.repeatsLeft=0,this.retryAt=e+G[Math.min(this.unanswered,G.length-1)],this.retryPrompt=r.prompt===!0,this.lastUnansweredCapture=r.prompt===!0,this.unanswered+=1}lookAnswered(){this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}lookRefused(){this.refused=!0}pictureReceived(){this.refused=!1,this.lastUnansweredCapture&&(this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1)}retryReady(e){return this.retryAt!==null&&e>=this.retryAt}get lookPending(){return this.lookRequested}pointerMoved(e){this.pointerInside=!0,this.lastPointerAt=e,(this.unanswered>0||this.refused)&&this.retryAt===null&&(this.retryAt=e,this.retryPrompt=!1)}pointerLeft(e){this.pointerInside&&(this.lastPointerAt=e),this.pointerInside=!1,this.lastTooltipAt=-1/0}tapped(e){this.lastPointerAt=e}pointerActive(e){return e-this.lastPointerAt=this.intervalInEffectMs(e):this.analysisState(e)==="probe"?!1:this.repeatsLeft>0&&r>=ge}staleFrameMs(e){return Math.max(ve,this.intervalInEffectMs(e))}frameStale(e,r){return this.lastVideoTimeSec===null||this.discontinuitySinceLast?!0:Math.abs(e-this.lastVideoTimeSec)*1e3>this.staleFrameMs(r)}hoverTriggerDue(e,r,i){let n=this.analysisState(e);return i||n==="idle"||n==="probe"||e-this.lastHoverTriggerAt0&&(this.repeatsLeft-=1)}get lastTrigger(){return this.lastTriggerKind}msSinceLastAnalysis(e){return this.lastStartedAt===-1/0?null:e-this.lastStartedAt}get idle(){return!this.pending&&this.repeatsLeft===0&&this.retryAt===null}};function Ae(t){let e=t.localWidth??t.bounds.width,r=t.localHeight??t.bounds.height,i=t.bounds.x+t.bounds.width/2,n=t.bounds.y+t.bounds.height/2;return{left:i-e/2,top:n-r/2,width:e,height:r}}function U(t,e){let r=Ae(t),i=(r.left+r.width/2)*e.width,n=(r.top+r.height/2)*e.height,s=r.width/2*e.width,o=r.height/2*e.height,l=t.rotation*Math.PI/180,a=Math.cos(l),u=Math.sin(l);return{points:[{x:-s,y:-o},{x:s,y:-o},{x:s,y:o},{x:-s,y:o}].map(({x:g,y:b})=>({x:i+g*a-b*u,y:n+g*u+b*a}))}}function ke(t,e){let{points:r}=e,i=0;for(let n=0;n0?1:-1;if(i===0)i=g;else if(g!==i)return!1}return!0}function Y(t,e){let r=null;for(let i of e)ke(t,i.quad)&&(!r||i.zIndex>=r.zIndex)&&(r=i);return r?r.card:null}function E(t){return t<0?0:t>1?1:t}function Z(t,e){let{frameWidth:r,frameHeight:i,names:n}=e;return t.map(s=>{let{aabb:o}=s,l=s.identity?n.get(s.identity):void 0,a=l!==void 0&&s.outline?s.outline:s.rect,u={instanceId:s.instanceId,bounds:{x:E(o.x/r),y:E(o.y/i),width:E(o.width/r),height:E(o.height/i)},rotation:(a.angle+45)%90-45,localWidth:E(a.w/r),localHeight:E(a.h/i),landscape:a.w>a.h,cardId:null,name:null};return s.identity&&l!==void 0&&(u.cardId=s.identity,u.name=l),u})}var Ie="accepted-nms";function Q(t){return t.width*t.height}function Re(t,e){let r=e==="accepted-nms"?t.kept:t.proposals.map((n,s)=>s),i=(n,s)=>{let o=t.proposals[n],l=t.proposals[s];if(e==="detector-score")return o.detectorScore!==l.detectorScore?o.detectorScore{let n=t.proposals[r];return{proposal:r,aabb:n.aabb,rect:n.rect,...n.outline?{outline:n.outline}:{},identity:n.accepted?n.displayId:null,score:n.score,zIndex:i+1}})}function ee(t,e,r,i=n=>n){return Z(t.map((s,o)=>({instanceId:e[o],aabb:s.aabb,rect:s.rect,...s.outline?{outline:s.outline}:{},identity:s.identity})),r).map((s,o)=>({...s,zIndex:t[o].zIndex,boxIndex:i(t[o].proposal)}))}var Ee={card:null,boxIndex:null,box:null,cardId:null,name:null};function te(t,e,r){let i=t.map(s=>({card:s,quad:U(s,r),zIndex:s.zIndex??0})),n=Y(e,i);return n?{card:n,boxIndex:n.boxIndex??null,box:{x:n.bounds.x*r.width,y:n.bounds.y*r.height,width:n.bounds.width*r.width,height:n.bounds.height*r.height},cardId:n.cardId,name:n.name}:Ee}function Te(t,e=t.hover.selection){let r=t.boxes.flatMap((a,u)=>a.face!==null?[u]:[]),i=r.map(a=>t.boxes[a]),n=new Map,s=i.map(a=>{let u=a.face;u.cardId!==null&&u.name!==null&&n.set(u.cardId,u.name);let p={x:a.box[0],y:a.box[1],width:a.box[2],height:a.box[3]};return{aabb:p,rect:{cx:p.x+p.width/2,cy:p.y+p.height/2,w:p.width,h:p.height,angle:0},score:u.similarity,detectorScore:a.score,accepted:u.cardId!==null,displayId:u.cardId??u.topId}}),o=i.flatMap((a,u)=>a.face.kept?[u]:[]),l=J({proposals:s,kept:o},e);return ee(l,l.map((a,u)=>`${e}_${u}`),{frameWidth:t.frame.width,frameHeight:t.frame.height,names:n},a=>r[a])}function B(t,e,r,i){let n=i===void 0||i===t.hover.selection?t.hover.cards:Te(t,i);return te(n,{x:e,y:r},t.frame)}var N=1,q=4096,P=40,Me=200,j=200,_e=/^[0-9a-f]{16}$/,Ce=/^[0-9a-f]{16}$/,A=t=>typeof t=="number"&&Number.isFinite(t),re=t=>A(t)&&t>=0&&t<=1,L=t=>Number.isSafeInteger(t)&&t>0,ne=(t,e=200)=>typeof t=="string"&&t.length>0&&t.length<=e,se=L,ie=t=>Number.isInteger(t)&&t>=1&&t<=4096,oe=t=>t===null?null:typeof t=="string"?t.slice(0,200):void 0;function Fe(t){return typeof ImageBitmap<"u"&&t instanceof ImageBitmap}function Le(t){let{width:e,height:r}=t;return Number.isInteger(e)&&Number.isInteger(r)&&e>0&&r>0&&e<=4096&&r<=4096}function ae(t){if(typeof t!="object"||t===null)return null;let e=t;return A(e.x)&&A(e.y)&&A(e.width)&&A(e.height)&&e.width>0&&e.height>0?{x:e.x,y:e.y,width:e.width,height:e.height}:null}var Pe=new Set(["kind","x","y","mediaTime","touch","newSource","requestId","bitmap","reason","retry","state","error","backend","analysisWidth","card","version","instance"]),Oe=/^[a-z][a-z0-9-]*$/;function We(t="cardvision"){if(typeof t!="string"||!Oe.test(t)||Pe.has(t))throw new TypeError(`computeProtocol: not a usable tag: ${String(t)}`);function e(s){if(typeof s!="object"||s===null)return null;let o=s;return o[t]===1&&typeof o.kind=="string"?o:null}function r(s){return Fe(s.bitmap)?L(s.requestId)&&A(s.mediaTime)&&Le(s.bitmap)?{kind:"frame",requestId:s.requestId,bitmap:s.bitmap,mediaTime:s.mediaTime}:(s.bitmap.close(),null):null}function i(s){let o=e(s);if(!o)return null;switch(o.kind){case"hello":return se(o.version)?{kind:"hello",version:o.version}:null;case"pointer":return re(o.x)&&re(o.y)&&A(o.mediaTime)&&typeof o.touch=="boolean"?{kind:"pointer",x:o.x,y:o.y,mediaTime:o.mediaTime,touch:o.touch}:null;case"leave":return{kind:"leave"};case"presented":return A(o.mediaTime)?{kind:"presented",mediaTime:o.mediaTime}:null;case"discontinuity":return typeof o.newSource=="boolean"?{kind:"discontinuity",newSource:o.newSource}:null;case"cut":return{kind:"cut"};case"frame":return r(o);case"capture-failed":return L(o.requestId)&&typeof o.reason=="string"?{kind:"capture-failed",requestId:o.requestId,reason:o.reason.slice(0,200),retry:o.retry===!0}:null;default:return null}}function n(s){let o=e(s);if(!o)return null;switch(o.kind){case"ready":return se(o.version)&&typeof o.instance=="string"&&Ce.test(o.instance)?{kind:"ready",version:o.version,instance:o.instance}:null;case"status":{let l=oe(o.error),a=oe(o.backend);return(o.state==="loading"||o.state==="ready"||o.state==="failed")&&l!==void 0&&a!==void 0?{kind:"status",state:o.state,error:l,backend:a}:null}case"capture":{let l=o.analysisWidth;return L(o.requestId)&&typeof l=="object"&&l!==null&&ie(l.min)&&ie(l.max)&&l.max>=l.min?{kind:"capture",requestId:o.requestId,analysisWidth:{min:l.min,max:l.max}}:null}case"shown":{if(o.card===null)return{kind:"shown",card:null};let l=o.card,a=typeof l=="object"&&l!==null?ae(l.box):null;if(!(l&&ne(l.cardId)&&ne(l.name)&&a))return null;let u=Array.isArray(l.others)?l.others.slice(0,40).map(ae).filter(y=>y!==null):[],p=typeof l.releaseId=="string"&&_e.test(l.releaseId)?l.releaseId:void 0;return{kind:"shown",card:{cardId:l.cardId,name:l.name,...p?{releaseId:p}:{},box:a,others:u}}}default:return null}}return{name:t,tag:s=>({...s,[t]:1}),parseComputeIn:i,parseComputeOut:n}}var le="busy";var He=Object.freeze({misses:2,maxMs:5e3,sameBoxIou:.5});function Be(t,e){return t==="loading"?{phase:e.phase,bytes:e.bytes}:void 0}function ue(t,e,r=40){return(t.hover?.cards??[]).map(i=>i.bounds).filter(i=>i&&!(Math.abs(i.x-e.x)<1e-6&&Math.abs(i.y-e.y)<1e-6&&Math.abs(i.width-e.width)<1e-6)).slice(0,r).map(i=>({x:i.x,y:i.y,width:i.width,height:i.height}))}var M=class{constructor(e,r={}){this.deps=e;this.mode=r.mode??"pointer",this.hold=r.hold??null,this.maxOtherBoxes=r.maxOtherBoxes??40,this.rotatedOutlines=r.rotatedOutlines===!0,this.hitTest=e.hoverAt??B,this.scheduler=new T(F(null,this.mode),3,this.mode,C(null)),this.st={state:"loading",error:null,release:null,backend:null,schedule:"idle",frames:0,lastWorkerMs:null,lastRoundTripMs:null,lastFrameError:null,geometric:r.geometric?{state:"loading",reason:null,bytes:null}:null,loading:null,tilted:null},this.lastStatusKey=this.statusKey()}deps;scheduler;mode;hold;maxOtherBoxes;rotatedOutlines;hitTest;st;cardList=[];analysisWidth={min:720,max:1920};maxAgeMs=W;nextRequestId=1;inFlight=null;lastAcceptedRequestId=0;analyzedSinceLoad=!1;generation=0;sourceCount=0;result=null;pointerAt=null;mediaTime=0;lastShownKey="null";lastStatusKey="";held=null;get videoKey(){return`source-${this.sourceCount}`}pointer(e,r,i,n=!1){if(this.st.state==="stopped")return;let s=this.deps.now();this.pointerAt={x:e,y:r},this.mediaTime=i,n?this.scheduler.tapped(s):this.scheduler.pointerMoved(s),this.st.state==="ready"&&this.scheduler.hoverTriggerDue(s,this.videoTime(),this.inFlight!==null)&&this.requestCapture("hover"),this.publish()}pointerLeft(){this.st.state!=="stopped"&&(this.pointerAt=null,this.scheduler.pointerLeft(this.deps.now()),this.publish())}presented(e){this.st.state!=="stopped"&&(this.mediaTime=e,this.scheduler.framePresented(),this.publish())}discontinuity(e){this.st.state!=="stopped"&&(this.generation+=1,e&&(this.sourceCount+=1),this.scheduler.discontinuity(),this.result=null,this.held=null,e&&this.scheduler.framePresented(),this.publish())}cut(){this.st.state!=="stopped"&&(this.generation+=1,this.result=null,this.held=null,this.scheduler.requestLook(),this.publish())}frame(e,r,i){let n=this.inFlight;if(this.st.state==="stopped"||!n||n.requestId!==e||n.analyzing){r.close();return}if(this.scheduler.pictureReceived(),n.generation!==this.generation||n.videoKey!==this.videoKey){this.inFlight=null,r.close(),this.publish();return}n.analyzing=!0;let s={requestId:n.requestId,mediaTimeSec:i,generation:n.generation,videoKey:n.videoKey};try{this.deps.toWorker({kind:"frame",bitmap:r,videoTimeSec:i,envelope:s,...this.rotatedOutlines?{rotatedOutlines:!0}:{}},[r])}catch(o){r.close(),this.inFlight=null,this.st.lastFrameError=`analysis-failed: ${String(o)}`,this.scheduler.lookUnanswered(this.deps.now())}this.publish()}captureFailed(e,r,i=!1){let n=this.inFlight;this.st.state==="stopped"||!n||n.requestId!==e||n.analyzing||(this.inFlight=null,this.st.lastFrameError=`capture-failed: ${r}`,i?this.scheduler.lookUnanswered(this.deps.now(),{prompt:!0}):this.scheduler.lookRefused(),this.publish())}fromWorker(e){if(this.st.state!=="stopped")switch(e.kind){case"geometric-status":this.st.geometric={state:e.state,reason:e.reason,bytes:e.bytes},this.deps.onGeometricStatus?.(e),this.publishStatus();return;case"tilted-status":this.st.tilted={state:"off",reason:e.reason},this.deps.onTiltedStatus?.(e),this.publishStatus();return;case"release-progress":{let r=Be(this.st.state,e);r!==void 0&&(this.st.loading=r),this.publishStatus();return}case"release-status":this.st.state=e.ok?"ready":"failed",this.analyzedSinceLoad=!1,this.st.error=e.error,this.st.release=e.release,this.st.loading=null,this.st.tilted=e.release?.tiltedRetry?{state:"on",reason:null}:null,this.cardList=e.cards,e.release&&(this.st.backend=e.release.recognizer.ep,this.maxAgeMs=e.release.hoverMaxAgeMs,this.analysisWidth={...e.release.analysisWidth},this.scheduler.setIntervalMs(F(this.st.backend,this.mode)),this.scheduler.setReadingIntervalMs(C(this.st.backend)),this.scheduler.framePresented()),this.publish();return;case"frame-result":this.onFrameResult(e);return;default:return}}onFrameResult(e){let r=this.deps.now(),i=H(e.envelope,{inFlightRequestId:this.inFlight?.requestId??null,lastAcceptedRequestId:this.lastAcceptedRequestId,generation:this.generation,videoKey:this.videoKey});if(i!==null&&!$(i))return;let n=this.inFlight;if(this.inFlight=null,i!==null){this.publish();return}this.lastAcceptedRequestId=e.envelope.requestId,this.st.lastFrameError=e.error??null,this.st.lastWorkerMs=e.workerMs,this.st.lastRoundTripMs=+(r-n.sentAt).toFixed(2),e.analysis?(this.analyzedSinceLoad=!0,this.scheduler.lookAnswered(),this.st.frames+=1,this.result={analysis:e.analysis,videoTimeSec:e.videoTimeSec},this.deps.onAnalysis?.(e.analysis)):(this.result=null,e.error===le&&this.scheduler.lookUnanswered(r)),this.held&&this.pointerAt&&this.current()&&!this.fresh()&&(this.held.misses+=1),this.scheduler.setTooltipShowing(this.shown()!==null,r),this.publish()}tick(){if(this.st.state==="stopped")return;let e=this.deps.now(),r=this.analyzedSinceLoad?K:X;this.inFlight&&e-this.inFlight.sentAt>=r&&(this.inFlight=null,this.st.lastFrameError="no reply",this.scheduler.lookUnanswered(e)),this.scheduler.setTooltipShowing(this.shown()!==null,e),this.st.state==="ready"&&!this.inFlight&&this.scheduler.due(e)&&this.requestCapture(this.scheduler.lookPending?"cut":void 0),this.publish()}stop(){this.st.state!=="stopped"&&(this.st.state="stopped",this.st.loading=null,this.inFlight=null,this.result=null,this.held=null,this.pointerAt=null,this.publishShown(),this.publishStatus())}workerStopped(e){if(!(this.st.state==="stopped"||this.st.state==="failed")){if(this.inFlight=null,this.result=null,this.held=null,this.st.loading=null,this.publishShown(),"restart"in e){let r={kind:"geometric-status",state:"off",reason:"worker-restarted",bytes:null};this.st.geometric&&(this.st.geometric={state:r.state,reason:r.reason,bytes:r.bytes}),this.deps.onGeometricStatus?.(r),this.st.state="loading",this.analyzedSinceLoad=!1,this.st.error=null}else this.st.state="failed",this.st.error=e.error;this.publishStatus()}}reloading(e){this.st.state==="loading"&&(this.st.geometric=e.geometric?{state:"loading",reason:null,bytes:null}:null,this.st.loading=null,this.publishStatus())}requestCapture(e){if(this.st.state!=="ready"||this.inFlight)return;let r=this.deps.now(),i=this.nextRequestId++;this.inFlight={requestId:i,sentAt:r,generation:this.generation,videoKey:this.videoKey,analyzing:!1},this.scheduler.started(r,{videoTimeSec:this.videoTime(),...e?{trigger:e}:{}}),this.deps.capture(i,{...this.analysisWidth})}status(){return{...this.st,schedule:this.scheduler.analysisState(this.deps.now())}}analysis(){return this.current()?.analysis??null}cards(){return this.cardList}hitAt(e,r){let i=this.current();if(!i)return null;let{width:n,height:s}=i.analysis.frame;if(!(n>0&&s>0))return null;let o=e*n,l=r*s;if(!Number.isFinite(o)||!Number.isFinite(l))return null;let a=this.hitTest(i.analysis,o,l);if(!a.box||a.cardId===null||a.name===null)return null;let u={x:a.box.x/n,y:a.box.y/s,width:a.box.width/n,height:a.box.height/s},p={x:a.box.x,y:a.box.y,width:a.box.width,height:a.box.height};return{cardId:a.cardId,name:a.name,box:u,frameBox:p,others:ue(i.analysis,u,this.maxOtherBoxes)}}fresh(){return this.pointerAt?this.hitAt(this.pointerAt.x,this.pointerAt.y):null}shown(){let e=this.fresh(),r=this.hold;if(!r)return e;let i=this.deps.now();if(e)return this.held={card:e,misses:0,seenAt:i},e;let n=this.held;return!n||!this.pointerAt||!qe(n.card.box,this.pointerAt)?(this.held=null,null):this.boxAtPointer(n.card.box,r.sameBoxIou)==="other"||n.misses>=r.misses||i-n.seenAt>=r.maxMs?(this.held=null,null):n.card}current(){let e=this.result;return e&&z(e.videoTimeSec,this.videoTime(),this.maxAgeMs)?e:null}videoTime(){return this.deps.mediaTimeNow?this.deps.mediaTimeNow():this.mediaTime}boxAtPointer(e,r){let i=this.current();if(!i||!this.pointerAt)return"unknown";let{width:n,height:s}=i.analysis.frame;if(!(n>0&&s>0))return"unknown";let o=this.pointerAt.x*n,l=this.pointerAt.y*s,a={x:e.x*n,y:e.y*s,width:e.width*n,height:e.height*s},u=0,p=!1;for(let y of i.analysis.boxes??[]){let[g,b,v,k]=y.box;og+v||lb+k||(p=!0,u=Math.max(u,Ne(a,{x:g,y:b,width:v,height:k})))}return p?u>=r?"same":"other":"none"}publish(){this.publishShown(),this.publishStatus()}publishShown(){let e=this.shown(),r=e?`${e.cardId}|${e.box.x}|${e.box.y}|${e.box.width}|${e.box.height}`:"null";r!==this.lastShownKey&&(this.lastShownKey=r,this.deps.onShown?.(e))}statusKey(){let e=this.status();return JSON.stringify({...e,release:e.release?e.release.id:null})}publishStatus(){let e=this.statusKey();e!==this.lastStatusKey&&(this.lastStatusKey=e,this.deps.onStatus?.(this.status()))}};function Ne(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),i=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);if(r<=0||i<=0)return 0;let n=r*i;return n/(t.width*t.height+e.width*e.height-n)}function qe(t,e){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}var St=1440*60*1e3;var je=[/^the worker did not start/,/^unexpected error while loading/];function de(t,e){return e||t.startsWith("unexpected:")?!1:!je.some(r=>r.test(t))}var ce=1;function he(t){let{geometricUrl:e,geometricManifestSha256:r,geometricWatchdog:i,...n}=t;return n}function D(t){let e=null,r=null,i=0,n=!1,s=null,o=!1,l=null,a={source:t.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},u=d=>{t.onDecision?.({reused:0,downloaded:0,ms:0,...d})},p=d=>new M({now:t.now,toWorker:(h,f)=>e?.postMessage(h,f??[]),capture:t.capture,...t.onShown?{onShown:t.onShown}:{},...t.onStatus?{onStatus:t.onStatus}:{},...t.onAnalysis?{onAnalysis:t.onAnalysis}:{},...t.onGeometricStatus?{onGeometricStatus:t.onGeometricStatus}:{},...t.hoverAt?{hoverAt:t.hoverAt}:{},...t.mediaTimeNow?{mediaTimeNow:t.mediaTimeNow}:{}},{...t.mode?{mode:t.mode}:{},...t.hold?{hold:t.hold}:{},...t.rotatedOutlines?{rotatedOutlines:!0}:{},geometric:d.geometricUrl!==void 0}),y=d=>{n||!r||(s&&d.kind==="release-progress"&&d.phase==="preparing"&&(o=!0),!(d.kind==="release-status"&&(r.status().state!=="loading"||s&&!b(d)))&&(d.kind==="release-status"&&!d.ok&&g(),r.fromWorker(d)))},g=()=>{n=!0,s=null,e?.terminate(),e=null},b=d=>{let h=s;if(d.ok&&d.release?.id===h.pointer.id)return s=null,l=h.pointer.id,a.source="remote",a.id=h.pointer.id,a.reason="ok",a.table=h.facts,u({source:"remote",reason:"ok",pointer:h.pointer.id,reused:h.reused,downloaded:h.downloaded,ms:h.ms}),!0;if(d.ok)return t.recordSkip?.(h.pointer,"id-mismatch"),v("id-mismatch"),!1;let f=d.error??"no reason given";return de(f,o)&&t.recordSkip?.(h.pointer,`runtime:${f.slice(0,120)}`),v(`runtime:${f}`),!1},v=d=>{let h=s;s=null,e?.terminate(),a.source="bundled",a.id=null,a.reason=d,a.table=null,u({source:"bundled",reason:d,pointer:h.pointer.id,reused:h.reused,downloaded:h.downloaded,ms:h.ms});let f=h.fallback??t.loadRequest;r?.reloading({geometric:f.geometricUrl!==void 0}),I(f)},k=d=>{if(n||!r)return;let h=r.status().state;if(h==="failed"||h==="stopped")return;let f=d.message||"see the console";if(s){b({kind:"release-status",ok:!1,error:`the worker did not start (${f})`,release:null,cards:[]});return}if(e?.terminate(),h==="loading"&&i===0){g(),r.workerStopped({error:`the worker did not start (${f})`});return}if(i{let h=t.createWorker();h.onmessage=f=>{h===e&&y(f.data)},h.onerror=f=>{h===e&&k(f)},e=h,h.postMessage(d)},I=d=>{r??=p(d);try{_(d)}catch(h){e=null,s=null,n=!0,r.workerStopped({error:`the recognition worker could not start (${String(h)})`})}};return t.chooseRelease?t.chooseRelease({onDownloading:()=>t.onDownloading?.()}).catch(d=>({source:"bundled",reason:`unexpected:${String(d)}`,pointer:null,downloaded:0,ms:0})).then(d=>{if(!n){if(d.source==="remote"){s=d,o=!1,I(d.request);return}a.source="bundled",a.reason=d.reason,u({source:"bundled",reason:d.reason,pointer:d.pointer?.id??null,downloaded:d.downloaded,ms:d.ms}),I(d.request??t.loadRequest)}}):I(t.loadRequest),{get core(){return r},get stopped(){return n},get restarts(){return i},get release(){return{...a}},tick(){n||r?.tick()},stop(){n=!0,s=null,e?.terminate(),e=null,r?.stop()}}}var De=/^[0-9a-f]{16}$/;function Ve(){let t=crypto.getRandomValues(new Uint8Array(8));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Ge(t){let e=t.parentOrigin;if(!t.framed||e===null||!t.allowedParentOrigin(e))return null;let{win:r,protocol:i}=t,n=(t.instanceId??Ve)();if(typeof n!="string"||!De.test(n))throw new TypeError(`startComputeFrame: not an instance id: ${String(n)}`);let s=c=>r.parent.postMessage(i.tag(c),e),o=()=>s({kind:"ready",version:1,instance:n}),l=!1,a=()=>{l||(l=!0,o())},u={state:"loading",error:null,backend:null},p=c=>c===null?null:c.slice(0,200),y=(c,m,S,R=!1)=>{let w={state:c,error:p(m),backend:p(S)};!R&&w.state===u.state&&w.error===u.error&&w.backend===u.backend||(u=w,s({kind:"status",...w}))},g=c=>{c.state!=="stopped"&&y(c.state,c.error,c.state==="ready"?c.backend:null)},b=null,v=()=>b?.release??{source:t.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},k=null,_=c=>{k=c,t.onShown?.(c,v()),s({kind:"shown",card:c})},I=c=>{let m=v(),S=c?{cardId:c.cardId,name:c.name,...m.source==="remote"&&m.id!==null?{releaseId:m.id}:{},box:{...c.box},others:c.others.map(R=>({...R}))}:null;_(S)},{win:d,framed:h,parentOrigin:f,allowedParentOrigin:Ke,protocol:Xe,onShown:$e,instanceId:Ue,...pe}=t,x=D({...pe,createWorker:()=>(a(),t.createWorker()),capture:(c,m)=>{let S=Math.min(m.max,4096);s({kind:"capture",requestId:c,analysisWidth:{min:Math.min(m.min,S),max:S}})},onShown:I,onStatus:g,onDownloading:()=>{y("loading",null,null,!0),t.onDownloading?.()}});b=x,x.core&&a();let me=()=>{o(),y(u.state,u.error,u.backend,!0),_(k)},fe=(c,m)=>{switch(m.kind){case"pointer":c.pointer(m.x,m.y,m.mediaTime,m.touch);return;case"leave":c.pointerLeft();return;case"presented":c.presented(m.mediaTime);return;case"discontinuity":c.discontinuity(m.newSource);return;case"cut":c.cut();return;case"frame":c.frame(m.requestId,m.bitmap,m.mediaTime);return;case"capture-failed":c.captureFailed(m.requestId,m.reason,m.retry===!0);return}},V=c=>{let S=c.source===r.parent&&c.origin===e?i.parseComputeIn(c.data):null,R=x.core,w=null;try{S?.kind==="hello"?R&&me():S&&R&&!x.stopped&&(S.kind==="frame"&&(w=S.bitmap),fe(R,S))}finally{ze(c.data,w)}};return r.addEventListener("message",V),{get core(){return x.core},get stopped(){return x.stopped},get restarts(){return x.restarts},get release(){return x.release},instance:n,tick(){x.tick()},stop(){r.removeEventListener("message",V),x.stop()}}}function ze(t,e){if(!(typeof ImageBitmap>"u"||typeof t!="object"||t===null))for(let r of Object.values(t))r!==e&&r instanceof ImageBitmap&&r.close()}export{be as DRIVER_TICK_MS,T as FrameScheduler,W as HOVER_MAX_AGE_MS,q as MAX_FRAME_SIDE,P as MAX_OTHER_BOXES,Me as MAX_REASON_LENGTH,j as MAX_TEXT_LENGTH,N as PROTOCOL_VERSION,He as SHOWN_HOLD,M as SessionCore,ce as WORKER_RESTARTS,F as cadenceMs,We as computeProtocol,D as createWorkerSession,B as hoverAt,ue as neighborBoxes,he as plainLoad,H as replyRejection,Ge as startComputeFrame}; +function _(t){return t==="wasm"?2e3:1e3}function ye(t){return t==="wasm"?1e3:500}function F(t,e){return e==="always-on"?_(t):ye(t)}var ge=250,be=250,Se=1e4,xe=5e3,ve=400,W=2e3;function z(t,e,r){return Math.abs(e-t)*1e3<=r}var we=250,K=5e3,X=15e3,G=[250,500,1e3,2e3];function H(t,e){return t===void 0?"stale-request":t.requestId<=e.lastAcceptedRequestId?"superseded":t.requestId!==e.inFlightRequestId?"stale-request":t.videoKey!==e.videoKey?"video-key":t.generation!==e.generation?"generation":null}function $(t){return t==="video-key"||t==="generation"}var T=class{constructor(e,r=3,i="always-on",n=e,o=null){this.intervalMs=e;this.confirmFrames=r;this.mode=i;this.readingIntervalMs=n;this.probeIntervalMs=o;this.checkProbe(i)}intervalMs;confirmFrames;mode;readingIntervalMs;probeIntervalMs;pending=!1;repeatsLeft=0;lastStartedAt=-1/0;pointerInside=!1;lastPointerAt=-1/0;tooltipShowing=!1;lastTooltipAt=-1/0;lastHoverTriggerAt=-1/0;lastVideoTimeSec=null;discontinuitySinceLast=!1;lastTriggerKind=null;lookRequested=!1;unanswered=0;retryAt=null;retryPrompt=!1;lastUnansweredCapture=!1;refused=!1;pointerAnalysis=!1;checkProbe(e){if(e==="layout"&&!(this.probeIntervalMs!==null&&this.probeIntervalMs>0))throw new Error("layout mode needs a positive probe interval")}setProbeIntervalMs(e){this.probeIntervalMs=e,this.checkProbe(this.mode)}setPointerAnalysis(e){this.pointerAnalysis=e}setIntervalMs(e){this.intervalMs=e}setReadingIntervalMs(e){this.readingIntervalMs=e}setTooltipShowing(e,r){this.tooltipShowing=e,e&&this.pointerInside&&(this.lastTooltipAt=r)}setMode(e){this.checkProbe(e),this.mode=e}get analysisMode(){return this.mode}framePresented(){this.pending=!0,this.repeatsLeft=0}discontinuity(){this.discontinuitySinceLast=!0,this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}requestLook(){this.discontinuitySinceLast=!0,this.pending=!0,this.repeatsLeft=0,this.lookRequested=!0}lookUnanswered(e,r={}){this.repeatsLeft=0,this.retryAt=e+G[Math.min(this.unanswered,G.length-1)],this.retryPrompt=r.prompt===!0,this.lastUnansweredCapture=r.prompt===!0,this.unanswered+=1}lookAnswered(){this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}lookRefused(){this.refused=!0}pictureReceived(){this.refused=!1,this.lastUnansweredCapture&&(this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1)}retryReady(e){return this.retryAt!==null&&e>=this.retryAt}get lookPending(){return this.lookRequested}pointerMoved(e){this.pointerInside=!0,this.lastPointerAt=e,(this.unanswered>0||this.refused)&&this.retryAt===null&&(this.retryAt=e,this.retryPrompt=!1)}pointerLeft(e){this.pointerInside&&(this.lastPointerAt=e),this.pointerInside=!1,this.lastTooltipAt=-1/0}tapped(e){this.lastPointerAt=e}pointerActive(e){return e-this.lastPointerAt=this.intervalInEffectMs(e):this.analysisState(e)==="probe"?!1:this.repeatsLeft>0&&r>=ge}staleFrameMs(e){return Math.max(ve,this.intervalInEffectMs(e))}frameStale(e,r){return this.lastVideoTimeSec===null||this.discontinuitySinceLast?!0:Math.abs(e-this.lastVideoTimeSec)*1e3>this.staleFrameMs(r)}hoverTriggerDue(e,r,i){let n=this.analysisState(e);return i||n==="idle"||n==="probe"||e-this.lastHoverTriggerAt0&&(this.repeatsLeft-=1)}get lastTrigger(){return this.lastTriggerKind}msSinceLastAnalysis(e){return this.lastStartedAt===-1/0?null:e-this.lastStartedAt}get idle(){return!this.pending&&this.repeatsLeft===0&&this.retryAt===null}};function Ae(t){let e=t.localWidth??t.bounds.width,r=t.localHeight??t.bounds.height,i=t.bounds.x+t.bounds.width/2,n=t.bounds.y+t.bounds.height/2;return{left:i-e/2,top:n-r/2,width:e,height:r}}function U(t,e){let r=Ae(t),i=(r.left+r.width/2)*e.width,n=(r.top+r.height/2)*e.height,o=r.width/2*e.width,s=r.height/2*e.height,l=t.rotation*Math.PI/180,a=Math.cos(l),u=Math.sin(l);return{points:[{x:-o,y:-s},{x:o,y:-s},{x:o,y:s},{x:-o,y:s}].map(({x:g,y:b})=>({x:i+g*a-b*u,y:n+g*u+b*a}))}}function ke(t,e){let{points:r}=e,i=0;for(let n=0;n0?1:-1;if(i===0)i=g;else if(g!==i)return!1}return!0}function Y(t,e){let r=null;for(let i of e)ke(t,i.quad)&&(!r||i.zIndex>=r.zIndex)&&(r=i);return r?r.card:null}function E(t){return t<0?0:t>1?1:t}function Z(t,e){let{frameWidth:r,frameHeight:i,names:n}=e;return t.map(o=>{let{aabb:s}=o,l=o.identity?n.get(o.identity):void 0,a=l!==void 0&&o.outline?o.outline:o.rect,u={instanceId:o.instanceId,bounds:{x:E(s.x/r),y:E(s.y/i),width:E(s.width/r),height:E(s.height/i)},rotation:(a.angle+45)%90-45,localWidth:E(a.w/r),localHeight:E(a.h/i),landscape:a.w>a.h,cardId:null,name:null};return o.identity&&l!==void 0&&(u.cardId=o.identity,u.name=l),u})}var Ie="accepted-nms";function Q(t){return t.width*t.height}function Re(t,e){let r=e==="accepted-nms"?t.kept:t.proposals.map((n,o)=>o),i=(n,o)=>{let s=t.proposals[n],l=t.proposals[o];if(e==="detector-score")return s.detectorScore!==l.detectorScore?s.detectorScore{let n=t.proposals[r];return{proposal:r,aabb:n.aabb,rect:n.rect,...n.outline?{outline:n.outline}:{},identity:n.accepted?n.displayId:null,score:n.score,zIndex:i+1}})}function ee(t,e,r,i=n=>n){return Z(t.map((o,s)=>({instanceId:e[s],aabb:o.aabb,rect:o.rect,...o.outline?{outline:o.outline}:{},identity:o.identity})),r).map((o,s)=>({...o,zIndex:t[s].zIndex,boxIndex:i(t[s].proposal)}))}var Ee={card:null,boxIndex:null,box:null,cardId:null,name:null};function te(t,e,r){let i=t.map(o=>({card:o,quad:U(o,r),zIndex:o.zIndex??0})),n=Y(e,i);return n?{card:n,boxIndex:n.boxIndex??null,box:{x:n.bounds.x*r.width,y:n.bounds.y*r.height,width:n.bounds.width*r.width,height:n.bounds.height*r.height},cardId:n.cardId,name:n.name}:Ee}function Te(t,e=t.hover.selection){let r=t.boxes.flatMap((a,u)=>a.face!==null?[u]:[]),i=r.map(a=>t.boxes[a]),n=new Map,o=i.map(a=>{let u=a.face;u.cardId!==null&&u.name!==null&&n.set(u.cardId,u.name);let p={x:a.box[0],y:a.box[1],width:a.box[2],height:a.box[3]};return{aabb:p,rect:{cx:p.x+p.width/2,cy:p.y+p.height/2,w:p.width,h:p.height,angle:0},score:u.similarity,detectorScore:a.score,accepted:u.cardId!==null,displayId:u.cardId??u.topId}}),s=i.flatMap((a,u)=>a.face.kept?[u]:[]),l=J({proposals:o,kept:s},e);return ee(l,l.map((a,u)=>`${e}_${u}`),{frameWidth:t.frame.width,frameHeight:t.frame.height,names:n},a=>r[a])}function B(t,e,r,i){let n=i===void 0||i===t.hover.selection?t.hover.cards:Te(t,i);return te(n,{x:e,y:r},t.frame)}var N=1,q=4096,P=40,Me=200,j=200,Ce=/^[0-9a-f]{16}$/,_e=/^[0-9a-f]{16}$/,v=t=>typeof t=="number"&&Number.isFinite(t),re=t=>v(t)&&t>=0&&t<=1,L=t=>Number.isSafeInteger(t)&&t>0,ne=(t,e=200)=>typeof t=="string"&&t.length>0&&t.length<=e,ie=L,oe=t=>Number.isInteger(t)&&t>=1&&t<=4096,se=t=>t===null?null:typeof t=="string"?t.slice(0,200):void 0;function Fe(t){return typeof ImageBitmap<"u"&&t instanceof ImageBitmap}function Le(t){let{width:e,height:r}=t;return Number.isInteger(e)&&Number.isInteger(r)&&e>0&&r>0&&e<=4096&&r<=4096}function ae(t){if(typeof t!="object"||t===null)return null;let e=t;return v(e.x)&&v(e.y)&&v(e.width)&&v(e.height)&&e.width>0&&e.height>0?{x:e.x,y:e.y,width:e.width,height:e.height}:null}function Pe(t){let{rotation:e,localWidth:r,localHeight:i}=t,n=o=>v(o)&&o>0&&o<=1;return v(e)&&e>-45&&e<=45&&n(r)&&n(i)?{rotation:e,localWidth:r,localHeight:i}:{}}var Oe=new Set(["kind","x","y","mediaTime","touch","newSource","requestId","bitmap","reason","retry","state","error","backend","analysisWidth","card","version","instance"]),We=/^[a-z][a-z0-9-]*$/;function He(t="cardvision"){if(typeof t!="string"||!We.test(t)||Oe.has(t))throw new TypeError(`computeProtocol: not a usable tag: ${String(t)}`);function e(o){if(typeof o!="object"||o===null)return null;let s=o;return s[t]===1&&typeof s.kind=="string"?s:null}function r(o){return Fe(o.bitmap)?L(o.requestId)&&v(o.mediaTime)&&Le(o.bitmap)?{kind:"frame",requestId:o.requestId,bitmap:o.bitmap,mediaTime:o.mediaTime}:(o.bitmap.close(),null):null}function i(o){let s=e(o);if(!s)return null;switch(s.kind){case"hello":return ie(s.version)?{kind:"hello",version:s.version}:null;case"pointer":return re(s.x)&&re(s.y)&&v(s.mediaTime)&&typeof s.touch=="boolean"?{kind:"pointer",x:s.x,y:s.y,mediaTime:s.mediaTime,touch:s.touch}:null;case"leave":return{kind:"leave"};case"presented":return v(s.mediaTime)?{kind:"presented",mediaTime:s.mediaTime}:null;case"discontinuity":return typeof s.newSource=="boolean"?{kind:"discontinuity",newSource:s.newSource}:null;case"cut":return{kind:"cut"};case"frame":return r(s);case"capture-failed":return L(s.requestId)&&typeof s.reason=="string"?{kind:"capture-failed",requestId:s.requestId,reason:s.reason.slice(0,200),retry:s.retry===!0}:null;default:return null}}function n(o){let s=e(o);if(!s)return null;switch(s.kind){case"ready":return ie(s.version)&&typeof s.instance=="string"&&_e.test(s.instance)?{kind:"ready",version:s.version,instance:s.instance}:null;case"status":{let l=se(s.error),a=se(s.backend);return(s.state==="loading"||s.state==="ready"||s.state==="failed")&&l!==void 0&&a!==void 0?{kind:"status",state:s.state,error:l,backend:a}:null}case"capture":{let l=s.analysisWidth;return L(s.requestId)&&typeof l=="object"&&l!==null&&oe(l.min)&&oe(l.max)&&l.max>=l.min?{kind:"capture",requestId:s.requestId,analysisWidth:{min:l.min,max:l.max}}:null}case"shown":{if(s.card===null)return{kind:"shown",card:null};let l=s.card,a=typeof l=="object"&&l!==null?ae(l.box):null;if(!(l&&ne(l.cardId)&&ne(l.name)&&a))return null;let u=Array.isArray(l.others)?l.others.slice(0,40).map(ae).filter(y=>y!==null):[],p=typeof l.releaseId=="string"&&Ce.test(l.releaseId)?l.releaseId:void 0;return{kind:"shown",card:{cardId:l.cardId,name:l.name,...p?{releaseId:p}:{},box:a,others:u,...Pe(l)}}}default:return null}}return{name:t,tag:o=>({...o,[t]:1}),parseComputeIn:i,parseComputeOut:n}}var le="busy";var Be=Object.freeze({misses:2,maxMs:5e3,sameBoxIou:.5});function Ne(t,e){return t==="loading"?{phase:e.phase,bytes:e.bytes}:void 0}function qe(t){if(!t||!Number.isFinite(t.rotation)||t.rotation===0)return{};let{rotation:e,localWidth:r,localHeight:i}=t;return e>-45&&e<=45&&r>0&&r<=1&&i>0&&i<=1?{rotation:e,localWidth:r,localHeight:i}:{}}function ue(t,e,r=40){return(t.hover?.cards??[]).map(i=>i.bounds).filter(i=>i&&!(Math.abs(i.x-e.x)<1e-6&&Math.abs(i.y-e.y)<1e-6&&Math.abs(i.width-e.width)<1e-6)).slice(0,r).map(i=>({x:i.x,y:i.y,width:i.width,height:i.height}))}var M=class{constructor(e,r={}){this.deps=e;this.mode=r.mode??"pointer",this.hold=r.hold??null,this.maxOtherBoxes=r.maxOtherBoxes??40,this.rotatedOutlines=r.rotatedOutlines===!0,this.hitTest=e.hoverAt??B,this.scheduler=new T(F(null,this.mode),3,this.mode,_(null)),this.st={state:"loading",error:null,release:null,backend:null,schedule:"idle",frames:0,lastWorkerMs:null,lastRoundTripMs:null,lastFrameError:null,geometric:r.geometric?{state:"loading",reason:null,bytes:null}:null,loading:null,tilted:null},this.lastStatusKey=this.statusKey()}deps;scheduler;mode;hold;maxOtherBoxes;rotatedOutlines;hitTest;st;cardList=[];analysisWidth={min:720,max:1920};maxAgeMs=W;nextRequestId=1;inFlight=null;lastAcceptedRequestId=0;analyzedSinceLoad=!1;generation=0;sourceCount=0;result=null;pointerAt=null;mediaTime=0;lastShownKey="null";lastStatusKey="";held=null;get videoKey(){return`source-${this.sourceCount}`}pointer(e,r,i,n=!1){if(this.st.state==="stopped")return;let o=this.deps.now();this.pointerAt={x:e,y:r},this.mediaTime=i,n?this.scheduler.tapped(o):this.scheduler.pointerMoved(o),this.st.state==="ready"&&this.scheduler.hoverTriggerDue(o,this.videoTime(),this.inFlight!==null)&&this.requestCapture("hover"),this.publish()}pointerLeft(){this.st.state!=="stopped"&&(this.pointerAt=null,this.scheduler.pointerLeft(this.deps.now()),this.publish())}presented(e){this.st.state!=="stopped"&&(this.mediaTime=e,this.scheduler.framePresented(),this.publish())}discontinuity(e){this.st.state!=="stopped"&&(this.generation+=1,e&&(this.sourceCount+=1),this.scheduler.discontinuity(),this.result=null,this.held=null,e&&this.scheduler.framePresented(),this.publish())}cut(){this.st.state!=="stopped"&&(this.generation+=1,this.result=null,this.held=null,this.scheduler.requestLook(),this.publish())}frame(e,r,i){let n=this.inFlight;if(this.st.state==="stopped"||!n||n.requestId!==e||n.analyzing){r.close();return}if(this.scheduler.pictureReceived(),n.generation!==this.generation||n.videoKey!==this.videoKey){this.inFlight=null,r.close(),this.publish();return}n.analyzing=!0;let o={requestId:n.requestId,mediaTimeSec:i,generation:n.generation,videoKey:n.videoKey};try{this.deps.toWorker({kind:"frame",bitmap:r,videoTimeSec:i,envelope:o,...this.rotatedOutlines?{rotatedOutlines:!0}:{}},[r])}catch(s){r.close(),this.inFlight=null,this.st.lastFrameError=`analysis-failed: ${String(s)}`,this.scheduler.lookUnanswered(this.deps.now())}this.publish()}captureFailed(e,r,i=!1){let n=this.inFlight;this.st.state==="stopped"||!n||n.requestId!==e||n.analyzing||(this.inFlight=null,this.st.lastFrameError=`capture-failed: ${r}`,i?this.scheduler.lookUnanswered(this.deps.now(),{prompt:!0}):this.scheduler.lookRefused(),this.publish())}fromWorker(e){if(this.st.state!=="stopped")switch(e.kind){case"geometric-status":this.st.geometric={state:e.state,reason:e.reason,bytes:e.bytes},this.deps.onGeometricStatus?.(e),this.publishStatus();return;case"tilted-status":this.st.tilted={state:"off",reason:e.reason},this.deps.onTiltedStatus?.(e),this.publishStatus();return;case"release-progress":{let r=Ne(this.st.state,e);r!==void 0&&(this.st.loading=r),this.publishStatus();return}case"release-status":this.st.state=e.ok?"ready":"failed",this.analyzedSinceLoad=!1,this.st.error=e.error,this.st.release=e.release,this.st.loading=null,this.st.tilted=e.release?.tiltedRetry?{state:"on",reason:null}:null,this.cardList=e.cards,e.release&&(this.st.backend=e.release.recognizer.ep,this.maxAgeMs=e.release.hoverMaxAgeMs,this.analysisWidth={...e.release.analysisWidth},this.scheduler.setIntervalMs(F(this.st.backend,this.mode)),this.scheduler.setReadingIntervalMs(_(this.st.backend)),this.scheduler.framePresented()),this.publish();return;case"frame-result":this.onFrameResult(e);return;default:return}}onFrameResult(e){let r=this.deps.now(),i=H(e.envelope,{inFlightRequestId:this.inFlight?.requestId??null,lastAcceptedRequestId:this.lastAcceptedRequestId,generation:this.generation,videoKey:this.videoKey});if(i!==null&&!$(i))return;let n=this.inFlight;if(this.inFlight=null,i!==null){this.publish();return}this.lastAcceptedRequestId=e.envelope.requestId,this.st.lastFrameError=e.error??null,this.st.lastWorkerMs=e.workerMs,this.st.lastRoundTripMs=+(r-n.sentAt).toFixed(2),e.analysis?(this.analyzedSinceLoad=!0,this.scheduler.lookAnswered(),this.st.frames+=1,this.result={analysis:e.analysis,videoTimeSec:e.videoTimeSec},this.deps.onAnalysis?.(e.analysis)):(this.result=null,e.error===le&&this.scheduler.lookUnanswered(r)),this.held&&this.pointerAt&&this.current()&&!this.fresh()&&(this.held.misses+=1),this.scheduler.setTooltipShowing(this.shown()!==null,r),this.publish()}tick(){if(this.st.state==="stopped")return;let e=this.deps.now(),r=this.analyzedSinceLoad?K:X;this.inFlight&&e-this.inFlight.sentAt>=r&&(this.inFlight=null,this.st.lastFrameError="no reply",this.scheduler.lookUnanswered(e)),this.scheduler.setTooltipShowing(this.shown()!==null,e),this.st.state==="ready"&&!this.inFlight&&this.scheduler.due(e)&&this.requestCapture(this.scheduler.lookPending?"cut":void 0),this.publish()}stop(){this.st.state!=="stopped"&&(this.st.state="stopped",this.st.loading=null,this.inFlight=null,this.result=null,this.held=null,this.pointerAt=null,this.publishShown(),this.publishStatus())}workerStopped(e){if(!(this.st.state==="stopped"||this.st.state==="failed")){if(this.inFlight=null,this.result=null,this.held=null,this.st.loading=null,this.publishShown(),"restart"in e){let r={kind:"geometric-status",state:"off",reason:"worker-restarted",bytes:null};this.st.geometric&&(this.st.geometric={state:r.state,reason:r.reason,bytes:r.bytes}),this.deps.onGeometricStatus?.(r),this.st.state="loading",this.analyzedSinceLoad=!1,this.st.error=null}else this.st.state="failed",this.st.error=e.error;this.publishStatus()}}reloading(e){this.st.state==="loading"&&(this.st.geometric=e.geometric?{state:"loading",reason:null,bytes:null}:null,this.st.loading=null,this.publishStatus())}requestCapture(e){if(this.st.state!=="ready"||this.inFlight)return;let r=this.deps.now(),i=this.nextRequestId++;this.inFlight={requestId:i,sentAt:r,generation:this.generation,videoKey:this.videoKey,analyzing:!1},this.scheduler.started(r,{videoTimeSec:this.videoTime(),...e?{trigger:e}:{}}),this.deps.capture(i,{...this.analysisWidth})}status(){return{...this.st,schedule:this.scheduler.analysisState(this.deps.now())}}analysis(){return this.current()?.analysis??null}cards(){return this.cardList}hitAt(e,r){let i=this.current();if(!i)return null;let{width:n,height:o}=i.analysis.frame;if(!(n>0&&o>0))return null;let s=e*n,l=r*o;if(!Number.isFinite(s)||!Number.isFinite(l))return null;let a=this.hitTest(i.analysis,s,l);if(!a.box||a.cardId===null||a.name===null)return null;let u={x:a.box.x/n,y:a.box.y/o,width:a.box.width/n,height:a.box.height/o},p={x:a.box.x,y:a.box.y,width:a.box.width,height:a.box.height};return{cardId:a.cardId,name:a.name,box:u,frameBox:p,others:ue(i.analysis,u,this.maxOtherBoxes),...qe(a.card)}}fresh(){return this.pointerAt?this.hitAt(this.pointerAt.x,this.pointerAt.y):null}shown(){let e=this.fresh(),r=this.hold;if(!r)return e;let i=this.deps.now();if(e)return this.held={card:e,misses:0,seenAt:i},e;let n=this.held;return!n||!this.pointerAt||!De(n.card.box,this.pointerAt)?(this.held=null,null):this.boxAtPointer(n.card.box,r.sameBoxIou)==="other"||n.misses>=r.misses||i-n.seenAt>=r.maxMs?(this.held=null,null):n.card}current(){let e=this.result;return e&&z(e.videoTimeSec,this.videoTime(),this.maxAgeMs)?e:null}videoTime(){return this.deps.mediaTimeNow?this.deps.mediaTimeNow():this.mediaTime}boxAtPointer(e,r){let i=this.current();if(!i||!this.pointerAt)return"unknown";let{width:n,height:o}=i.analysis.frame;if(!(n>0&&o>0))return"unknown";let s=this.pointerAt.x*n,l=this.pointerAt.y*o,a={x:e.x*n,y:e.y*o,width:e.width*n,height:e.height*o},u=0,p=!1;for(let y of i.analysis.boxes??[]){let[g,b,w,k]=y.box;sg+w||lb+k||(p=!0,u=Math.max(u,je(a,{x:g,y:b,width:w,height:k})))}return p?u>=r?"same":"other":"none"}publish(){this.publishShown(),this.publishStatus()}publishShown(){let e=this.shown(),r=e?`${e.cardId}|${e.box.x}|${e.box.y}|${e.box.width}|${e.box.height}|${e.rotation??""}|${e.localWidth??""}|${e.localHeight??""}`:"null";r!==this.lastShownKey&&(this.lastShownKey=r,this.deps.onShown?.(e))}statusKey(){let e=this.status();return JSON.stringify({...e,release:e.release?e.release.id:null})}publishStatus(){let e=this.statusKey();e!==this.lastStatusKey&&(this.lastStatusKey=e,this.deps.onStatus?.(this.status()))}};function je(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),i=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);if(r<=0||i<=0)return 0;let n=r*i;return n/(t.width*t.height+e.width*e.height-n)}function De(t,e){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}var vt=1440*60*1e3;var Ve=[/^the worker did not start/,/^unexpected error while loading/];function de(t,e){return e||t.startsWith("unexpected:")?!1:!Ve.some(r=>r.test(t))}var ce=1;function he(t){let{geometricUrl:e,geometricManifestSha256:r,geometricWatchdog:i,...n}=t;return n}function D(t){let e=null,r=null,i=0,n=!1,o=null,s=!1,l=null,a={source:t.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},u=c=>{t.onDecision?.({reused:0,downloaded:0,ms:0,...c})},p=c=>new M({now:t.now,toWorker:(h,f)=>e?.postMessage(h,f??[]),capture:t.capture,...t.onShown?{onShown:t.onShown}:{},...t.onStatus?{onStatus:t.onStatus}:{},...t.onAnalysis?{onAnalysis:t.onAnalysis}:{},...t.onGeometricStatus?{onGeometricStatus:t.onGeometricStatus}:{},...t.hoverAt?{hoverAt:t.hoverAt}:{},...t.mediaTimeNow?{mediaTimeNow:t.mediaTimeNow}:{}},{...t.mode?{mode:t.mode}:{},...t.hold?{hold:t.hold}:{},...t.rotatedOutlines?{rotatedOutlines:!0}:{},geometric:c.geometricUrl!==void 0}),y=c=>{n||!r||(o&&c.kind==="release-progress"&&c.phase==="preparing"&&(s=!0),!(c.kind==="release-status"&&(r.status().state!=="loading"||o&&!b(c)))&&(c.kind==="release-status"&&!c.ok&&g(),r.fromWorker(c)))},g=()=>{n=!0,o=null,e?.terminate(),e=null},b=c=>{let h=o;if(c.ok&&c.release?.id===h.pointer.id)return o=null,l=h.pointer.id,a.source="remote",a.id=h.pointer.id,a.reason="ok",a.table=h.facts,u({source:"remote",reason:"ok",pointer:h.pointer.id,reused:h.reused,downloaded:h.downloaded,ms:h.ms}),!0;if(c.ok)return t.recordSkip?.(h.pointer,"id-mismatch"),w("id-mismatch"),!1;let f=c.error??"no reason given";return de(f,s)&&t.recordSkip?.(h.pointer,`runtime:${f.slice(0,120)}`),w(`runtime:${f}`),!1},w=c=>{let h=o;o=null,e?.terminate(),a.source="bundled",a.id=null,a.reason=c,a.table=null,u({source:"bundled",reason:c,pointer:h.pointer.id,reused:h.reused,downloaded:h.downloaded,ms:h.ms});let f=h.fallback??t.loadRequest;r?.reloading({geometric:f.geometricUrl!==void 0}),I(f)},k=c=>{if(n||!r)return;let h=r.status().state;if(h==="failed"||h==="stopped")return;let f=c.message||"see the console";if(o){b({kind:"release-status",ok:!1,error:`the worker did not start (${f})`,release:null,cards:[]});return}if(e?.terminate(),h==="loading"&&i===0){g(),r.workerStopped({error:`the worker did not start (${f})`});return}if(i{let h=t.createWorker();h.onmessage=f=>{h===e&&y(f.data)},h.onerror=f=>{h===e&&k(f)},e=h,h.postMessage(c)},I=c=>{r??=p(c);try{C(c)}catch(h){e=null,o=null,n=!0,r.workerStopped({error:`the recognition worker could not start (${String(h)})`})}};return t.chooseRelease?t.chooseRelease({onDownloading:()=>t.onDownloading?.()}).catch(c=>({source:"bundled",reason:`unexpected:${String(c)}`,pointer:null,downloaded:0,ms:0})).then(c=>{if(!n){if(c.source==="remote"){o=c,s=!1,I(c.request);return}a.source="bundled",a.reason=c.reason,u({source:"bundled",reason:c.reason,pointer:c.pointer?.id??null,downloaded:c.downloaded,ms:c.ms}),I(c.request??t.loadRequest)}}):I(t.loadRequest),{get core(){return r},get stopped(){return n},get restarts(){return i},get release(){return{...a}},tick(){n||r?.tick()},stop(){n=!0,o=null,e?.terminate(),e=null,r?.stop()}}}var Ge=/^[0-9a-f]{16}$/;function ze(){let t=crypto.getRandomValues(new Uint8Array(8));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Ke(t){let e=t.parentOrigin;if(!t.framed||e===null||!t.allowedParentOrigin(e))return null;let{win:r,protocol:i}=t,n=(t.instanceId??ze)();if(typeof n!="string"||!Ge.test(n))throw new TypeError(`startComputeFrame: not an instance id: ${String(n)}`);let o=d=>r.parent.postMessage(i.tag(d),e),s=()=>o({kind:"ready",version:1,instance:n}),l=!1,a=()=>{l||(l=!0,s())},u={state:"loading",error:null,backend:null},p=d=>d===null?null:d.slice(0,200),y=(d,m,S,R=!1)=>{let A={state:d,error:p(m),backend:p(S)};!R&&A.state===u.state&&A.error===u.error&&A.backend===u.backend||(u=A,o({kind:"status",...A}))},g=d=>{d.state!=="stopped"&&y(d.state,d.error,d.state==="ready"?d.backend:null)},b=null,w=()=>b?.release??{source:t.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},k=null,C=d=>{k=d,t.onShown?.(d,w()),o({kind:"shown",card:d})},I=d=>{let m=w(),S=d?{cardId:d.cardId,name:d.name,...m.source==="remote"&&m.id!==null?{releaseId:m.id}:{},box:{...d.box},others:d.others.map(R=>({...R})),...d.rotation!==void 0&&d.localWidth!==void 0&&d.localHeight!==void 0?{rotation:d.rotation,localWidth:d.localWidth,localHeight:d.localHeight}:{}}:null;C(S)},{win:c,framed:h,parentOrigin:f,allowedParentOrigin:$e,protocol:Ue,onShown:Ye,instanceId:Ze,...pe}=t,x=D({...pe,createWorker:()=>(a(),t.createWorker()),capture:(d,m)=>{let S=Math.min(m.max,4096);o({kind:"capture",requestId:d,analysisWidth:{min:Math.min(m.min,S),max:S}})},onShown:I,onStatus:g,onDownloading:()=>{y("loading",null,null,!0),t.onDownloading?.()}});b=x,x.core&&a();let me=()=>{s(),y(u.state,u.error,u.backend,!0),C(k)},fe=(d,m)=>{switch(m.kind){case"pointer":d.pointer(m.x,m.y,m.mediaTime,m.touch);return;case"leave":d.pointerLeft();return;case"presented":d.presented(m.mediaTime);return;case"discontinuity":d.discontinuity(m.newSource);return;case"cut":d.cut();return;case"frame":d.frame(m.requestId,m.bitmap,m.mediaTime);return;case"capture-failed":d.captureFailed(m.requestId,m.reason,m.retry===!0);return}},V=d=>{let S=d.source===r.parent&&d.origin===e?i.parseComputeIn(d.data):null,R=x.core,A=null;try{S?.kind==="hello"?R&&me():S&&R&&!x.stopped&&(S.kind==="frame"&&(A=S.bitmap),fe(R,S))}finally{Xe(d.data,A)}};return r.addEventListener("message",V),{get core(){return x.core},get stopped(){return x.stopped},get restarts(){return x.restarts},get release(){return x.release},instance:n,tick(){x.tick()},stop(){r.removeEventListener("message",V),x.stop()}}}function Xe(t,e){if(!(typeof ImageBitmap>"u"||typeof t!="object"||t===null))for(let r of Object.values(t))r!==e&&r instanceof ImageBitmap&&r.close()}export{be as DRIVER_TICK_MS,T as FrameScheduler,W as HOVER_MAX_AGE_MS,q as MAX_FRAME_SIDE,P as MAX_OTHER_BOXES,Me as MAX_REASON_LENGTH,j as MAX_TEXT_LENGTH,N as PROTOCOL_VERSION,Be as SHOWN_HOLD,M as SessionCore,ce as WORKER_RESTARTS,F as cadenceMs,He as computeProtocol,D as createWorkerSession,B as hoverAt,ue as neighborBoxes,he as plainLoad,H as replyRejection,Ke as startComputeFrame}; diff --git a/vendor/cardvision-browser/page-capture.js b/vendor/cardvision-browser/page-capture.js index 483d50d..8158f13 100644 --- a/vendor/cardvision-browser/page-capture.js +++ b/vendor/cardvision-browser/page-capture.js @@ -1 +1 @@ -function K(e,n,r={min:720,max:1920}){let s=Math.max(r.min,Math.min(r.max,e));return{width:s,height:Math.max(1,Math.round(s*n/e))}}function z(e,n,r){if(!(e.width>0&&e.height>0))return null;let s=(n-e.left)/e.width,c=(r-e.top)/e.height;return s>=0&&s<=1&&c>=0&&c<=1?{x:s,y:c}:null}function j(e,n,r){let s={left:e.left,top:e.top,width:e.width,height:e.height};if(n.width<=0||n.height<=0||r==="fill")return s;let c=e.width/n.width,l=e.height/n.height,t;r==="cover"?t=Math.max(c,l):r==="none"?t=1:r==="scale-down"?t=Math.min(1,c,l):t=Math.min(c,l);let a=n.width*t,u=n.height*t;return{left:e.left+(e.width-a)/2,top:e.top+(e.height-u)/2,width:a,height:u}}var M=1,$=4096,Ne=40,Fe=200,Oe=200,De=/^[0-9a-f]{16}$/,Ge=/^[0-9a-f]{16}$/,I=e=>typeof e=="number"&&Number.isFinite(e),oe=e=>I(e)&&e>=0&&e<=1,O=e=>Number.isSafeInteger(e)&&e>0,ae=(e,n=200)=>typeof e=="string"&&e.length>0&&e.length<=n,se=O,ue=e=>Number.isInteger(e)&&e>=1&&e<=4096,le=e=>e===null?null:typeof e=="string"?e.slice(0,200):void 0;function Be(e){return typeof ImageBitmap<"u"&&e instanceof ImageBitmap}function Xe(e){let{width:n,height:r}=e;return Number.isInteger(n)&&Number.isInteger(r)&&n>0&&r>0&&n<=4096&&r<=4096}function ce(e){if(typeof e!="object"||e===null)return null;let n=e;return I(n.x)&&I(n.y)&&I(n.width)&&I(n.height)&&n.width>0&&n.height>0?{x:n.x,y:n.y,width:n.width,height:n.height}:null}var He=new Set(["kind","x","y","mediaTime","touch","newSource","requestId","bitmap","reason","retry","state","error","backend","analysisWidth","card","version","instance"]),Ue=/^[a-z][a-z0-9-]*$/;function We(e="cardvision"){if(typeof e!="string"||!Ue.test(e)||He.has(e))throw new TypeError(`computeProtocol: not a usable tag: ${String(e)}`);function n(l){if(typeof l!="object"||l===null)return null;let t=l;return t[e]===1&&typeof t.kind=="string"?t:null}function r(l){return Be(l.bitmap)?O(l.requestId)&&I(l.mediaTime)&&Xe(l.bitmap)?{kind:"frame",requestId:l.requestId,bitmap:l.bitmap,mediaTime:l.mediaTime}:(l.bitmap.close(),null):null}function s(l){let t=n(l);if(!t)return null;switch(t.kind){case"hello":return se(t.version)?{kind:"hello",version:t.version}:null;case"pointer":return oe(t.x)&&oe(t.y)&&I(t.mediaTime)&&typeof t.touch=="boolean"?{kind:"pointer",x:t.x,y:t.y,mediaTime:t.mediaTime,touch:t.touch}:null;case"leave":return{kind:"leave"};case"presented":return I(t.mediaTime)?{kind:"presented",mediaTime:t.mediaTime}:null;case"discontinuity":return typeof t.newSource=="boolean"?{kind:"discontinuity",newSource:t.newSource}:null;case"cut":return{kind:"cut"};case"frame":return r(t);case"capture-failed":return O(t.requestId)&&typeof t.reason=="string"?{kind:"capture-failed",requestId:t.requestId,reason:t.reason.slice(0,200),retry:t.retry===!0}:null;default:return null}}function c(l){let t=n(l);if(!t)return null;switch(t.kind){case"ready":return se(t.version)&&typeof t.instance=="string"&&Ge.test(t.instance)?{kind:"ready",version:t.version,instance:t.instance}:null;case"status":{let a=le(t.error),u=le(t.backend);return(t.state==="loading"||t.state==="ready"||t.state==="failed")&&a!==void 0&&u!==void 0?{kind:"status",state:t.state,error:a,backend:u}:null}case"capture":{let a=t.analysisWidth;return O(t.requestId)&&typeof a=="object"&&a!==null&&ue(a.min)&&ue(a.max)&&a.max>=a.min?{kind:"capture",requestId:t.requestId,analysisWidth:{min:a.min,max:a.max}}:null}case"shown":{if(t.card===null)return{kind:"shown",card:null};let a=t.card,u=typeof a=="object"&&a!==null?ce(a.box):null;if(!(a&&ae(a.cardId)&&ae(a.name)&&u))return null;let o=Array.isArray(a.others)?a.others.slice(0,40).map(ce).filter(g=>g!==null):[],p=typeof a.releaseId=="string"&&De.test(a.releaseId)?a.releaseId:void 0;return{kind:"shown",card:{cardId:a.cardId,name:a.name,...p?{releaseId:p}:{},box:u,others:o}}}default:return null}}return{name:e,tag:l=>({...l,[e]:1}),parseComputeIn:s,parseComputeOut:c}}var J="no picture",de="no picture (the paused video draws nothing)",me="no 2d context",pe="the video may not be read",fe="the picture is too large",Ve=16,qe=9,he=()=>document.createElement("canvas"),Ye=e=>createImageBitmap(e);function D(){return{canvas:null,readable:!1}}function Q(e){return e.paused&&e.readyState<2&&e.videoWidth>0}function G(e,n){let r=n?.lastPlayingTime??null;return Q(e)&&r!==null?r:e.currentTime}function ge(e,n=he){let r=Ve,s=n();s.width=r,s.height=r;let c=s.getContext("2d");if(!c)return!1;c.drawImage(e,0,0,r,r);let l=c.getImageData(0,0,r,r).data,t=0,a=0;for(let o=0;o({kind:"failed",reason:f,retry:A}),c=e?.video;if(!e||!c||(r.requireConnected??!0)&&!c.isConnected||c.videoWidth===0)return s(J,!0);let l=Q(c);if(c.readyState<2&&!l)return s(J,!0);let t=r.createCanvas??he,a=K(c.videoWidth,c.videoHeight,n),u=r.maxSide??4096;if(a.width>u||a.height>u)return s(fe);let o=e.source;o.canvas||(o.canvas=t(),o.readable=!1);let p=o.canvas;p.width=a.width,p.height=a.height;let g=p.getContext("2d");if(!g)return s(me);let E=G(c,e);try{return g.drawImage(c,0,0,a.width,a.height),l&&ge(p,t)?(o.readable=!0,s(de,!0)):(o.readable||(g.getImageData(0,0,1,1),o.readable=!0),{kind:"frame",bitmap:await(r.createImageBitmap??Ye)(p),mediaTime:E})}catch(f){return s(Ke(f)?pe:String(f))}}function ee(e,n){let r=null,s=D(),c={video:e,get lastPlayingTime(){return r},get source(){return s},mediaTime:()=>G(e,c),detach:g},l=()=>n.discontinuity(!1),t=()=>{s=D(),r=null,n.discontinuity(!0)},a=()=>{!e.paused&&e.readyState>=2&&(r=e.currentTime),n.presented(c.mediaTime())},u=()=>n.presented(c.mediaTime()),o=[["seeking",l],["emptied",t],["loadeddata",t],["timeupdate",a],["seeked",a],["canplay",u],["playing",u]];for(let[E,f]of o)e.addEventListener(E,f);let p=!0;function g(){if(p){p=!1;for(let[E,f]of o)e.removeEventListener(E,f)}}return c}var te=1e4,ne=5e3;var be=6e4;function B(e,n,{graceMs:r=te,lingerMs:s=ne,restMs:c=be}={}){return!e.inside||!Number.isFinite(e.lastTrustedPointerAt)||n-e.lastTrustedPointerAt>=c?!1:n-e.lastTrustedPointerAtsetTimeout(e,n),clear:e=>clearTimeout(e)};function Qe(e,n,r){let s=r.ownerDocument?.defaultView,c=s?s.getComputedStyle(r).objectFit:"contain";return z(j(r.getBoundingClientRect(),{width:r.videoWidth,height:r.videoHeight},c),e,n)}var Ze=e=>Math.min(2e3,250*2**e);function et(e){let{protocol:n,frameOrigin:r}=e,s=e.now??(()=>performance.now()),c=e.eligible??Qe,l=e.timers??Je,t=e.helloRetries??10,a=e.helloDelayMs??Ze,u=null,o=null,p=!1,g=-1/0,E=0,f=null,A=null,k=0,X=null,H=!1,b=!1,U=new Set;function R(){let i=e.frame();return f&&i===f.window?i:null}function re(i){try{return i.location.origin===r}catch{return!0}}function w(i,m=R()){if(!(b||!m||!re(m)))try{m.postMessage(n.tag(i),r)}catch{}}function P(i,m){return u?c(i,m,u.video):null}function y(){let i=o!==null;o=null,p=!1,g=-1/0,E++,i&&w({kind:"leave"})}function W(){return o?o.kind==="tap"?{inside:!0,lastTrustedPointerAt:o.at,tooltipShowing:!1,lastTooltipAt:-1/0}:{inside:!0,lastTrustedPointerAt:o.at,tooltipShowing:p,lastTooltipAt:g}:{inside:!1,lastTrustedPointerAt:-1/0,tooltipShowing:p,lastTooltipAt:g}}function ie(){return!o||!u?!1:P(o.clientX,o.clientY)?B(W(),s(),e.limits):(y(),!1)}function L(i){if(!o||!u)return;let m=i??P(o.clientX,o.clientY);m&&w({kind:"pointer",x:m.x,y:m.y,mediaTime:u.mediaTime(),touch:o.kind==="tap"})}function we(i){if(b||i.isTrusted!==!0||!u)return;let m=i.pointerType==="touch"?"tap":"hover",d=i.pointerId,h=P(i.clientX,i.clientY);if(m==="hover"){h?(o={kind:m,pointerId:d,clientX:i.clientX,clientY:i.clientY,at:s()},L(h)):o?.kind==="hover"&&y();return}let T=o?.kind==="tap"&&o.pointerId===d;if(i.type==="pointerdown")h?(o={kind:m,pointerId:d,clientX:i.clientX,clientY:i.clientY,at:s()},L(h)):o?.kind==="tap"&&y();else if(i.type==="pointermove"&&T&&o){if(!h)return y();o.clientX=i.clientX,o.clientY=i.clientY,L(h)}}function xe(i){b||i.isTrusted!==!0||o&&o.pointerId===i.pointerId&&y()}function Ie(i){i.visibilityState==="hidden"&&y()}function _e(i){b||(u?.video??null)===i||(y(),u?.detach(),u=null,i&&(u=ee(i,{presented:d=>w({kind:"presented",mediaTime:d}),discontinuity:d=>{d&&y(),w({kind:"discontinuity",newSource:d})}})),w({kind:"discontinuity",newSource:!0}))}function N(){A!==null&&l.clear(A),A=null}function V(){if(A=null,b||R())return;let i=e.frame();if(i&&!re(i)){let m=s();X??=m,m-X=t){e.onProblem?.({kind:"no-answer"});return}w({kind:"hello",version:1},i),A=l.set(V,a(k)),k++}function Re(){b||(N(),k=0,X=null,V())}function Ce(i,m){let{version:d,instance:h}=i;if(d!==1){f=null,N(),y(),e.onProblem?.({kind:"version",expected:1,received:d});return}if(typeof h!="string"||!ze.test(h)||(N(),f&&f.window===m&&f.instance===h))return;f={window:m,instance:h};let T=o;p=!1,g=-1/0,E++,T&&!(P(T.clientX,T.clientY)&&B(W(),s(),e.limits))&&(o=null),u&&w({kind:"presented",mediaTime:u.mediaTime()}),L()}async function Me(i,m){let d=(x,C=!1)=>w({kind:"capture-failed",requestId:i,reason:x,retry:C});if(H)return d(Te);let h;try{h=ie()}catch(x){return d(String(x))}if(!h)return d(ye);let T={watch:u,source:u?.source,handshake:f,resets:E};H=!0;let S;try{S=await Z(u,m,e.grab)}catch(x){S={kind:"failed",reason:String(x),retry:!1}}finally{H=!1}let q=!b&&f===T.handshake&&R()!==null,F=u===T.watch&&u?.source===T.source&&E===T.resets;if(!q||!F){S.kind==="frame"&&S.bitmap.close(),q&&d(Se);return}if(S.kind==="failed")return d(S.reason,S.retry);Ae(R(),n.tag({kind:"frame",requestId:i,bitmap:S.bitmap,mediaTime:S.mediaTime}),r,S.bitmap)}function ke(i){if(b)return!1;let m=e.frame(),d=ve(i,{frame:m,origin:r,protocol:n});if(!d||!m)return!1;if(d.kind==="ready")return Ce(d,m),!0;if(!R())return!0;switch(d.kind){case"status":e.onStatus?.(d);break;case"shown":{o&&((p||d.card)&&(g=s()),p=d.card!==null),e.onShown?.(d.card);break}case"capture":Me(d.requestId,d.analysisWidth);break}return!0}function Pe(i,m){let d={capture:!0,passive:!0},h=v=>we(v),F=[[i,"pointermove",h],[i,"pointerdown",h],[i,"pointerup",h],[i,"pointercancel",v=>xe(v)],[i,"pointerleave",v=>{let _=v;b||_.isTrusted!==!0||_.target!==m.documentElement||_.pointerType==="touch"||y()}],[i,"visibilitychange",()=>Ie(m)]];for(let[v,_,Y]of F)v.addEventListener(_,Y,d);let x=!0,C=()=>{if(x){x=!1,U.delete(C);for(let[v,_,Y]of F)v.removeEventListener(_,Y,d)}};return U.add(C),C}function Le(){if(!b){y(),b=!0,N();for(let i of[...U])i();u?.detach(),u=null,f=null}}return{attach:_e,listen:Pe,connect:Re,onMessage:ke,get watch(){return u},get connected(){return R()!==null},gateState:W,captureAllowedNow:ie,stop:Le}}export{de as BLANK_PICTURE,Te as CAPTURE_PENDING,$ as MAX_FRAME_SIDE,Ne as MAX_OTHER_BOXES,Fe as MAX_REASON_LENGTH,be as MAX_REST_MS,Oe as MAX_TEXT_LENGTH,ye as NOT_POINTING,me as NO_CONTEXT,J as NO_PICTURE,Se as PICTURE_CHANGED,te as POINTER_GRACE_MS,M as PROTOCOL_VERSION,ne as READING_LINGER_MS,fe as TOO_LARGE,pe as UNREADABLE,ve as acceptComputeOut,K as analysisSize,ge as blankFrame,B as captureAllowed,We as computeProtocol,et as createCaptureControl,D as createSourceCanvas,z as fractionIn,Ee as fromExtensionFrame,Z as grabFrame,Q as isFrozen,G as mediaTimeOf,j as pictureBox,Ae as postWithTransfer,ee as watchVideo}; +function K(e,t,r={min:720,max:1920}){let a=Math.max(r.min,Math.min(r.max,e));return{width:a,height:Math.max(1,Math.round(a*t/e))}}function z(e,t,r){if(!(e.width>0&&e.height>0))return null;let a=(t-e.left)/e.width,c=(r-e.top)/e.height;return a>=0&&a<=1&&c>=0&&c<=1?{x:a,y:c}:null}function j(e,t,r){let a={left:e.left,top:e.top,width:e.width,height:e.height};if(t.width<=0||t.height<=0||r==="fill")return a;let c=e.width/t.width,u=e.height/t.height,n;r==="cover"?n=Math.max(c,u):r==="none"?n=1:r==="scale-down"?n=Math.min(1,c,u):n=Math.min(c,u);let s=t.width*n,l=t.height*n;return{left:e.left+(e.width-s)/2,top:e.top+(e.height-l)/2,width:s,height:l}}var M=1,$=4096,Ne=40,Fe=200,Oe=200,De=/^[0-9a-f]{16}$/,Ge=/^[0-9a-f]{16}$/,v=e=>typeof e=="number"&&Number.isFinite(e),oe=e=>v(e)&&e>=0&&e<=1,O=e=>Number.isSafeInteger(e)&&e>0,ae=(e,t=200)=>typeof e=="string"&&e.length>0&&e.length<=t,se=O,ue=e=>Number.isInteger(e)&&e>=1&&e<=4096,le=e=>e===null?null:typeof e=="string"?e.slice(0,200):void 0;function Be(e){return typeof ImageBitmap<"u"&&e instanceof ImageBitmap}function He(e){let{width:t,height:r}=e;return Number.isInteger(t)&&Number.isInteger(r)&&t>0&&r>0&&t<=4096&&r<=4096}function ce(e){if(typeof e!="object"||e===null)return null;let t=e;return v(t.x)&&v(t.y)&&v(t.width)&&v(t.height)&&t.width>0&&t.height>0?{x:t.x,y:t.y,width:t.width,height:t.height}:null}function Xe(e){let{rotation:t,localWidth:r,localHeight:a}=e,c=u=>v(u)&&u>0&&u<=1;return v(t)&&t>-45&&t<=45&&c(r)&&c(a)?{rotation:t,localWidth:r,localHeight:a}:{}}var Ue=new Set(["kind","x","y","mediaTime","touch","newSource","requestId","bitmap","reason","retry","state","error","backend","analysisWidth","card","version","instance"]),We=/^[a-z][a-z0-9-]*$/;function Ve(e="cardvision"){if(typeof e!="string"||!We.test(e)||Ue.has(e))throw new TypeError(`computeProtocol: not a usable tag: ${String(e)}`);function t(u){if(typeof u!="object"||u===null)return null;let n=u;return n[e]===1&&typeof n.kind=="string"?n:null}function r(u){return Be(u.bitmap)?O(u.requestId)&&v(u.mediaTime)&&He(u.bitmap)?{kind:"frame",requestId:u.requestId,bitmap:u.bitmap,mediaTime:u.mediaTime}:(u.bitmap.close(),null):null}function a(u){let n=t(u);if(!n)return null;switch(n.kind){case"hello":return se(n.version)?{kind:"hello",version:n.version}:null;case"pointer":return oe(n.x)&&oe(n.y)&&v(n.mediaTime)&&typeof n.touch=="boolean"?{kind:"pointer",x:n.x,y:n.y,mediaTime:n.mediaTime,touch:n.touch}:null;case"leave":return{kind:"leave"};case"presented":return v(n.mediaTime)?{kind:"presented",mediaTime:n.mediaTime}:null;case"discontinuity":return typeof n.newSource=="boolean"?{kind:"discontinuity",newSource:n.newSource}:null;case"cut":return{kind:"cut"};case"frame":return r(n);case"capture-failed":return O(n.requestId)&&typeof n.reason=="string"?{kind:"capture-failed",requestId:n.requestId,reason:n.reason.slice(0,200),retry:n.retry===!0}:null;default:return null}}function c(u){let n=t(u);if(!n)return null;switch(n.kind){case"ready":return se(n.version)&&typeof n.instance=="string"&&Ge.test(n.instance)?{kind:"ready",version:n.version,instance:n.instance}:null;case"status":{let s=le(n.error),l=le(n.backend);return(n.state==="loading"||n.state==="ready"||n.state==="failed")&&s!==void 0&&l!==void 0?{kind:"status",state:n.state,error:s,backend:l}:null}case"capture":{let s=n.analysisWidth;return O(n.requestId)&&typeof s=="object"&&s!==null&&ue(s.min)&&ue(s.max)&&s.max>=s.min?{kind:"capture",requestId:n.requestId,analysisWidth:{min:s.min,max:s.max}}:null}case"shown":{if(n.card===null)return{kind:"shown",card:null};let s=n.card,l=typeof s=="object"&&s!==null?ce(s.box):null;if(!(s&&ae(s.cardId)&&ae(s.name)&&l))return null;let o=Array.isArray(s.others)?s.others.slice(0,40).map(ce).filter(g=>g!==null):[],p=typeof s.releaseId=="string"&&De.test(s.releaseId)?s.releaseId:void 0;return{kind:"shown",card:{cardId:s.cardId,name:s.name,...p?{releaseId:p}:{},box:l,others:o,...Xe(s)}}}default:return null}}return{name:e,tag:u=>({...u,[e]:1}),parseComputeIn:a,parseComputeOut:c}}var J="no picture",de="no picture (the paused video draws nothing)",me="no 2d context",pe="the video may not be read",fe="the picture is too large",qe=16,Ye=9,he=()=>document.createElement("canvas"),Ke=e=>createImageBitmap(e);function D(){return{canvas:null,readable:!1}}function Q(e){return e.paused&&e.readyState<2&&e.videoWidth>0}function G(e,t){let r=t?.lastPlayingTime??null;return Q(e)&&r!==null?r:e.currentTime}function ge(e,t=he){let r=qe,a=t();a.width=r,a.height=r;let c=a.getContext("2d");if(!c)return!1;c.drawImage(e,0,0,r,r);let u=c.getImageData(0,0,r,r).data,n=0,s=0;for(let o=0;o({kind:"failed",reason:f,retry:w}),c=e?.video;if(!e||!c||(r.requireConnected??!0)&&!c.isConnected||c.videoWidth===0)return a(J,!0);let u=Q(c);if(c.readyState<2&&!u)return a(J,!0);let n=r.createCanvas??he,s=K(c.videoWidth,c.videoHeight,t),l=r.maxSide??4096;if(s.width>l||s.height>l)return a(fe);let o=e.source;o.canvas||(o.canvas=n(),o.readable=!1);let p=o.canvas;p.width=s.width,p.height=s.height;let g=p.getContext("2d");if(!g)return a(me);let E=G(c,e);try{return g.drawImage(c,0,0,s.width,s.height),u&&ge(p,n)?(o.readable=!0,a(de,!0)):(o.readable||(g.getImageData(0,0,1,1),o.readable=!0),{kind:"frame",bitmap:await(r.createImageBitmap??Ke)(p),mediaTime:E})}catch(f){return a(ze(f)?pe:String(f))}}function ee(e,t){let r=null,a=D(),c={video:e,get lastPlayingTime(){return r},get source(){return a},mediaTime:()=>G(e,c),detach:g},u=()=>t.discontinuity(!1),n=()=>{a=D(),r=null,t.discontinuity(!0)},s=()=>{!e.paused&&e.readyState>=2&&(r=e.currentTime),t.presented(c.mediaTime())},l=()=>t.presented(c.mediaTime()),o=[["seeking",u],["emptied",n],["loadeddata",n],["timeupdate",s],["seeked",s],["canplay",l],["playing",l]];for(let[E,f]of o)e.addEventListener(E,f);let p=!0;function g(){if(p){p=!1;for(let[E,f]of o)e.removeEventListener(E,f)}}return c}var te=1e4,ne=5e3;var be=6e4;function B(e,t,{graceMs:r=te,lingerMs:a=ne,restMs:c=be}={}){return!e.inside||!Number.isFinite(e.lastTrustedPointerAt)||t-e.lastTrustedPointerAt>=c?!1:t-e.lastTrustedPointerAtsetTimeout(e,t),clear:e=>clearTimeout(e)};function Ze(e,t,r){let a=r.ownerDocument?.defaultView,c=a?a.getComputedStyle(r).objectFit:"contain";return z(j(r.getBoundingClientRect(),{width:r.videoWidth,height:r.videoHeight},c),e,t)}var et=e=>Math.min(2e3,250*2**e);function tt(e){let{protocol:t,frameOrigin:r}=e,a=e.now??(()=>performance.now()),c=e.eligible??Ze,u=e.timers??Qe,n=e.helloRetries??10,s=e.helloDelayMs??et,l=null,o=null,p=!1,g=-1/0,E=0,f=null,w=null,k=0,H=null,X=!1,b=!1,U=new Set;function R(){let i=e.frame();return f&&i===f.window?i:null}function re(i){try{return i.location.origin===r}catch{return!0}}function x(i,m=R()){if(!(b||!m||!re(m)))try{m.postMessage(t.tag(i),r)}catch{}}function P(i,m){return l?c(i,m,l.video):null}function y(){let i=o!==null;o=null,p=!1,g=-1/0,E++,i&&x({kind:"leave"})}function W(){return o?o.kind==="tap"?{inside:!0,lastTrustedPointerAt:o.at,tooltipShowing:!1,lastTooltipAt:-1/0}:{inside:!0,lastTrustedPointerAt:o.at,tooltipShowing:p,lastTooltipAt:g}:{inside:!1,lastTrustedPointerAt:-1/0,tooltipShowing:p,lastTooltipAt:g}}function ie(){return!o||!l?!1:P(o.clientX,o.clientY)?B(W(),a(),e.limits):(y(),!1)}function L(i){if(!o||!l)return;let m=i??P(o.clientX,o.clientY);m&&x({kind:"pointer",x:m.x,y:m.y,mediaTime:l.mediaTime(),touch:o.kind==="tap"})}function we(i){if(b||i.isTrusted!==!0||!l)return;let m=i.pointerType==="touch"?"tap":"hover",d=i.pointerId,h=P(i.clientX,i.clientY);if(m==="hover"){h?(o={kind:m,pointerId:d,clientX:i.clientX,clientY:i.clientY,at:a()},L(h)):o?.kind==="hover"&&y();return}let T=o?.kind==="tap"&&o.pointerId===d;if(i.type==="pointerdown")h?(o={kind:m,pointerId:d,clientX:i.clientX,clientY:i.clientY,at:a()},L(h)):o?.kind==="tap"&&y();else if(i.type==="pointermove"&&T&&o){if(!h)return y();o.clientX=i.clientX,o.clientY=i.clientY,L(h)}}function xe(i){b||i.isTrusted!==!0||o&&o.pointerId===i.pointerId&&y()}function Ie(i){i.visibilityState==="hidden"&&y()}function _e(i){b||(l?.video??null)===i||(y(),l?.detach(),l=null,i&&(l=ee(i,{presented:d=>x({kind:"presented",mediaTime:d}),discontinuity:d=>{d&&y(),x({kind:"discontinuity",newSource:d})}})),x({kind:"discontinuity",newSource:!0}))}function N(){w!==null&&u.clear(w),w=null}function V(){if(w=null,b||R())return;let i=e.frame();if(i&&!re(i)){let m=a();H??=m,m-H<$e?w=u.set(V,Je):e.onProblem?.({kind:"no-answer"});return}if(k>=n){e.onProblem?.({kind:"no-answer"});return}x({kind:"hello",version:1},i),w=u.set(V,s(k)),k++}function Re(){b||(N(),k=0,H=null,V())}function Ce(i,m){let{version:d,instance:h}=i;if(d!==1){f=null,N(),y(),e.onProblem?.({kind:"version",expected:1,received:d});return}if(typeof h!="string"||!je.test(h)||(N(),f&&f.window===m&&f.instance===h))return;f={window:m,instance:h};let T=o;p=!1,g=-1/0,E++,T&&!(P(T.clientX,T.clientY)&&B(W(),a(),e.limits))&&(o=null),l&&x({kind:"presented",mediaTime:l.mediaTime()}),L()}async function Me(i,m){let d=(I,C=!1)=>x({kind:"capture-failed",requestId:i,reason:I,retry:C});if(X)return d(Te);let h;try{h=ie()}catch(I){return d(String(I))}if(!h)return d(ye);let T={watch:l,source:l?.source,handshake:f,resets:E};X=!0;let S;try{S=await Z(l,m,e.grab)}catch(I){S={kind:"failed",reason:String(I),retry:!1}}finally{X=!1}let q=!b&&f===T.handshake&&R()!==null,F=l===T.watch&&l?.source===T.source&&E===T.resets;if(!q||!F){S.kind==="frame"&&S.bitmap.close(),q&&d(Se);return}if(S.kind==="failed")return d(S.reason,S.retry);Ae(R(),t.tag({kind:"frame",requestId:i,bitmap:S.bitmap,mediaTime:S.mediaTime}),r,S.bitmap)}function ke(i){if(b)return!1;let m=e.frame(),d=ve(i,{frame:m,origin:r,protocol:t});if(!d||!m)return!1;if(d.kind==="ready")return Ce(d,m),!0;if(!R())return!0;switch(d.kind){case"status":e.onStatus?.(d);break;case"shown":{o&&((p||d.card)&&(g=a()),p=d.card!==null),e.onShown?.(d.card);break}case"capture":Me(d.requestId,d.analysisWidth);break}return!0}function Pe(i,m){let d={capture:!0,passive:!0},h=A=>we(A),F=[[i,"pointermove",h],[i,"pointerdown",h],[i,"pointerup",h],[i,"pointercancel",A=>xe(A)],[i,"pointerleave",A=>{let _=A;b||_.isTrusted!==!0||_.target!==m.documentElement||_.pointerType==="touch"||y()}],[i,"visibilitychange",()=>Ie(m)]];for(let[A,_,Y]of F)A.addEventListener(_,Y,d);let I=!0,C=()=>{if(I){I=!1,U.delete(C);for(let[A,_,Y]of F)A.removeEventListener(_,Y,d)}};return U.add(C),C}function Le(){if(!b){y(),b=!0,N();for(let i of[...U])i();l?.detach(),l=null,f=null}}return{attach:_e,listen:Pe,connect:Re,onMessage:ke,get watch(){return l},get connected(){return R()!==null},gateState:W,captureAllowedNow:ie,stop:Le}}export{de as BLANK_PICTURE,Te as CAPTURE_PENDING,$ as MAX_FRAME_SIDE,Ne as MAX_OTHER_BOXES,Fe as MAX_REASON_LENGTH,be as MAX_REST_MS,Oe as MAX_TEXT_LENGTH,ye as NOT_POINTING,me as NO_CONTEXT,J as NO_PICTURE,Se as PICTURE_CHANGED,te as POINTER_GRACE_MS,M as PROTOCOL_VERSION,ne as READING_LINGER_MS,fe as TOO_LARGE,pe as UNREADABLE,ve as acceptComputeOut,K as analysisSize,ge as blankFrame,B as captureAllowed,Ve as computeProtocol,tt as createCaptureControl,D as createSourceCanvas,z as fractionIn,Ee as fromExtensionFrame,Z as grabFrame,Q as isFrozen,G as mediaTimeOf,j as pictureBox,Ae as postWithTransfer,ee as watchVideo}; diff --git a/vendor/cardvision-browser/types/compute-messages.d.ts b/vendor/cardvision-browser/types/compute-messages.d.ts index c7921eb..45291d5 100644 --- a/vendor/cardvision-browser/types/compute-messages.d.ts +++ b/vendor/cardvision-browser/types/compute-messages.d.ts @@ -15,6 +15,13 @@ export interface ShownCard { /** The other cards of the same analysis (at most `MAX_OTHER_BOXES`), so that a tooltip can be * placed off them. */ others?: FractionBox[]; + /** The card's outline when it is turned (session option `rotatedOutlines`): its tilt in + * degrees in (-45, 45], positive clockwise like CSS `rotate()`, and its own sides in fractions + * of the picture, about the center of `box` (the same fields as a hover card, so + * `computeCardQuad` takes them). All three or none; absent for an upright card. */ + rotation?: number; + localWidth?: number; + localHeight?: number; } /** The two-frame contract's version. A content script and a compute frame work together only * when they speak the same one: `hello` and `ready` carry it, and each side compares. */ diff --git a/vendor/cardvision-browser/types/session-core.d.ts b/vendor/cardvision-browser/types/session-core.d.ts index f35fb50..e9dcb70 100644 --- a/vendor/cardvision-browser/types/session-core.d.ts +++ b/vendor/cardvision-browser/types/session-core.d.ts @@ -19,6 +19,12 @@ export interface Shown { /** The boxes of the other cards of the same analysis, in fractions, for placing a tooltip off * them (at most `maxOtherBoxes`). */ others: FractionBox[]; + /** The card's outline when it is turned (session option `rotatedOutlines`): its tilt in + * degrees in (-45, 45], positive clockwise like CSS `rotate()`, and its own sides in fractions + * of the picture, about the center of `box`. All three or none; absent for an upright card. */ + rotation?: number; + localWidth?: number; + localHeight?: number; } /** The shown card's hold: how long it survives analyses that do not see it at the pointer. */ export interface ShownHold { @@ -181,7 +187,7 @@ export declare class SessionCore { * one, none, or "unknown" when no analysis is recent enough to judge by. */ private boxAtPointer; private publish; - /** Report what is shown when it changed (the card, or its box). */ + /** Report what is shown when it changed (the card, its box, or its outline). */ private publishShown; private statusKey; private publishStatus; diff --git a/vendor/cardvision-browser/types/session.d.ts b/vendor/cardvision-browser/types/session.d.ts index 0b5c248..184ca0f 100644 --- a/vendor/cardvision-browser/types/session.d.ts +++ b/vendor/cardvision-browser/types/session.d.ts @@ -50,6 +50,12 @@ export interface Shown { box: ClientBox; /** The card's box in pixels of the analyzed frame. */ frameBox: AABB; + /** With `rotatedOutlines`, for a turned card: its tilt in degrees in (-45, 45], positive + * clockwise like CSS `rotate()`, and its own sides in fractions of the picture, about the + * center of `box`. All three or none; absent for an upright card. */ + rotation?: number; + localWidth?: number; + localHeight?: number; } export interface SessionStatus { /** "loading" until the release has loaded; "failed" when it did not, or when the worker