@dudko.dev/agent-web 0.0.50 → 0.0.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -4
- package/dist/agent-web.js +159 -151
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-3V27UZT6.js → chunk-DOWC4CFZ.js} +257 -3
- package/dist/chunk-DOWC4CFZ.js.map +1 -0
- package/dist/{chunk-6XHCPSZE.js → chunk-EUJWS42C.js} +56 -5
- package/dist/{chunk-6XHCPSZE.js.map → chunk-EUJWS42C.js.map} +1 -1
- package/dist/{chunk-IT77BVAD.js → chunk-HXUR2SG5.js} +2 -2
- package/dist/{chunk-JTZEUPIG.js → chunk-NUL6QEAX.js} +49 -49
- package/dist/chunk-NUL6QEAX.js.map +1 -0
- package/dist/chunk-R5VCITT3.js +192 -0
- package/dist/chunk-R5VCITT3.js.map +1 -0
- package/dist/{chunk-7Y5UC6L7.js → chunk-SVGIGIRR.js} +3 -3
- package/dist/fit-reference-worker.cjs +158 -0
- package/dist/fit-reference-worker.cjs.map +1 -0
- package/dist/fit-reference-worker.d.cts +1 -0
- package/dist/fit-reference-worker.d.ts +1 -0
- package/dist/fit-reference-worker.js +16 -0
- package/dist/fit-reference-worker.js.map +1 -0
- package/dist/index.cjs +1140 -360
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +82 -72
- package/dist/index.d.ts +82 -72
- package/dist/index.js +365 -84
- package/dist/index.js.map +1 -1
- package/dist/mcp.js +2 -2
- package/dist/media-fit-worker-CFK2z8LF.d.cts +149 -0
- package/dist/media-fit-worker-CFK2z8LF.d.ts +149 -0
- package/dist/{sandbox-IGTCMOOX.js → sandbox-X6T4ZOEQ.js} +3 -3
- package/dist/secrets.js +3 -3
- package/dist/{webllm-BEL5A4OF.js → webllm-EZSJGU6P.js} +2 -2
- package/package.json +14 -2
- package/dist/chunk-3V27UZT6.js.map +0 -1
- package/dist/chunk-JTZEUPIG.js.map +0 -1
- /package/dist/{chunk-IT77BVAD.js.map → chunk-HXUR2SG5.js.map} +0 -0
- /package/dist/{chunk-7Y5UC6L7.js.map → chunk-SVGIGIRR.js.map} +0 -0
- /package/dist/{sandbox-IGTCMOOX.js.map → sandbox-X6T4ZOEQ.js.map} +0 -0
- /package/dist/{webllm-BEL5A4OF.js.map → webllm-EZSJGU6P.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage/db.ts","../src/sync/tab.ts","../src/sync/notices.ts"],"sourcesContent":["import { openDB, type IDBPDatabase } from 'idb'\n\nexport interface AgentWebDBOptions {\n /** Database name (default 'agent-web'). Use a distinct name to isolate apps. */\n dbName?: string\n}\n\nexport const KEYS_STORE = 'keys'\nexport const SECRETS_STORE = 'secrets'\nexport const SESSIONS_STORE = 'sessions'\nexport const FILES_STORE = 'files'\nexport const RUNS_STORE = 'runs'\n\n// v1: keys, secrets, sessions. v2: + files (the virtual file system). v3: + runs (checkpoints).\nconst DB_VERSION = 3\n\nlet cache = new Map<string, Promise<IDBPDatabase>>()\n\n/**\n * The single owner of the IndexedDB database. Every persistent store — the\n * non-extractable crypto key, encrypted secrets, and session transcripts —\n * lives under ONE database name + version. Centralising `openDB` here prevents\n * the classic bug where two modules open the same DB name with different store\n * sets and the second call throws a VersionError.\n *\n * One connection per name, shared by every store of the page - and never in another tab's way:\n * when another connection asks to delete or upgrade the database (`versionchange`: another tab's\n * `indexedDB.deleteDatabase`, or a newer copy of this package), this one is closed at once, so\n * that request goes ahead instead of waiting (blocked) for this tab to close. The browser lets the\n * transactions already under way finish first. A connection the browser closed by itself (site\n * data cleared, storage gone) is let go too. Either way the next use opens the database again:\n * after a deletion that is a NEW, EMPTY database at this version (every store of this package\n * starts from nothing - no key, no secret, no session, no file); after an upgrade by a newer copy,\n * the open fails with a `VersionError` until the page is reloaded with that copy.\n */\nexport const openAgentWebDB = (opts: AgentWebDBOptions = {}): Promise<IDBPDatabase> => {\n const name = opts.dbName ?? 'agent-web'\n let p = cache.get(name)\n if (!p) {\n const opened: Promise<IDBPDatabase> = openDB(name, DB_VERSION, {\n upgrade(db) {\n // Idempotent by store: an existing v1 database gains only what it lacks.\n if (!db.objectStoreNames.contains(KEYS_STORE)) db.createObjectStore(KEYS_STORE)\n if (!db.objectStoreNames.contains(SECRETS_STORE)) db.createObjectStore(SECRETS_STORE)\n if (!db.objectStoreNames.contains(SESSIONS_STORE)) db.createObjectStore(SESSIONS_STORE)\n if (!db.objectStoreNames.contains(FILES_STORE)) db.createObjectStore(FILES_STORE)\n if (!db.objectStoreNames.contains(RUNS_STORE)) db.createObjectStore(RUNS_STORE)\n },\n // Another connection (another tab, or this one) deletes or upgrades the database: let it.\n blocking(_current, _next, event) {\n forget(name, opened)\n ;(event.target as IDBDatabase).close()\n },\n // Closed by the browser, not by us: a dead connection must not stay cached.\n terminated() {\n forget(name, opened)\n },\n })\n p = opened\n cache.set(name, p)\n // A failed open (private mode, storage denied) must not stay cached, or\n // every later call would replay the same rejection forever.\n p.catch(() => forget(name, opened))\n }\n return p\n}\n\n/** Drop `name`'s cached connection - only if it is still `p` (a newer one stays). */\nconst forget = (name: string, p: Promise<IDBPDatabase>): void => {\n if (cache.get(name) === p) cache.delete(name)\n}\n\n/** Test hook: drop cached connections so a fresh (e.g. fake-indexeddb) DB is opened. */\nexport const _resetDBCache = (): void => {\n cache = new Map()\n}\n","/**\n * Several tabs of one origin.\n *\n * Everything this package keeps lives in IndexedDB, and every tab (and installed PWA window) of\n * the origin shares it - but nothing told one tab what another did. This module is the plumbing\n * the rest of `sync/` stands on:\n *\n * - which TAB this is (one per JS realm): a random id, the Web Locks it holds, and\n * - one `BroadcastChannel` per name per tab (a hub), shared by everything in the tab that posts\n * or listens under that name. A channel never delivers a message to itself, so a tab never\n * hears its own messages - only the other tabs'.\n *\n * Browser APIs only, no dependency; every part is a no-op where the browser lacks the API\n * (`BroadcastChannel`, `navigator.locks`).\n *\n * Two test seams, NOT API (not exported from the package, never documented as options): a\n * function under `Symbol.for('@dudko.dev/agent-web:tab-test')` on `globalThis` names the tab a\n * caller is in (tests run two \"tabs\" in one Node process - Node's BroadcastChannel delivers\n * between instances of one process), and a LockManager-like object under\n * `Symbol.for('@dudko.dev/agent-web:locks-test')` stands in for `navigator.locks` (Node 22 has none;\n * Node 24+ has a real one, shared by the whole process). The seam wins over a native manager; set\n * to `null` it means \"this runtime has no Web Locks\", whatever the runtime has. The real API path\n * is tested in a real browser (the React package's e2e) and on Node's own Web Locks where present\n * (`tests/native-locks.test.ts`).\n */\n\nconst TAB_TEST = Symbol.for('@dudko.dev/agent-web:tab-test')\nconst LOCKS_TEST = Symbol.for('@dudko.dev/agent-web:locks-test')\n\n/** What every message on a channel of this package carries: the shape's version. */\nexport const SYNC_VERSION = 1\n\n/** Ids that cross a channel: a tab's, a watcher's, a request's. */\nexport const SYNC_ID_RE = /^[A-Za-z0-9_-]{1,64}$/\n\nexport interface Hub {\n /** Post to the OTHER tabs listening under this name (never to this tab). */\n post(message: unknown): void\n /** Hear the other tabs. Returns the unsubscribe; the channel closes with its last listener. */\n listen(listener: (data: unknown) => void): () => void\n}\n\nexport interface Tab {\n readonly id: string\n /** The session locks this tab holds right now (their names). */\n readonly held: Set<string>\n readonly hubs: Map<string, Hub>\n}\n\nconst randomId = (): string => {\n const c = globalThis.crypto\n if (c?.randomUUID) return c.randomUUID().replace(/-/g, '')\n return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`\n}\n\n// One registry per REALM, not per copy of this library: two copies in one page (an ESM and a CJS\n// build, two bundles) share the tab - its id, its held locks and its channels - so they never hear\n// each other as two tabs. The shape (`id`, `held`, `hubs` with `post` / `listen`) is the\n// contract between copies; keep it.\nconst TABS = Symbol.for('@dudko.dev/agent-web:tabs')\nconst tabs: Map<string, Tab> = ((globalThis as Record<symbol, unknown>)[TABS] ??= new Map<\n string,\n Tab\n>()) as Map<string, Tab>\n\n/** The tab the caller is in. In a browser: one per realm. */\nexport const currentTab = (): Tab => {\n const seam = (globalThis as Record<symbol, unknown>)[TAB_TEST]\n const named = typeof seam === 'function' ? (seam as () => unknown)() : undefined\n const key = typeof named === 'string' ? named : ''\n let tab = tabs.get(key)\n if (!tab) {\n tab = { id: randomId(), held: new Set(), hubs: new Map() }\n tabs.set(key, tab)\n }\n return tab\n}\n\ntype BroadcastChannelLike = {\n postMessage(message: unknown): void\n close(): void\n onmessage: ((event: { data: unknown }) => void) | null\n unref?: () => void\n}\n\n/** The tab's hub for `name`; undefined where there is no BroadcastChannel. */\nexport const hubOf = (tab: Tab, name: string): Hub | undefined => {\n const Channel = (globalThis as { BroadcastChannel?: new (name: string) => BroadcastChannelLike })\n .BroadcastChannel\n if (typeof Channel !== 'function') return undefined\n const known = tab.hubs.get(name)\n if (known) return known\n let channel: BroadcastChannelLike | undefined\n const listeners = new Set<(data: unknown) => void>()\n const open = (): BroadcastChannelLike => {\n if (channel) return channel\n const opened = new Channel(name)\n // Node: an open channel would keep the process alive. Browsers have no such method.\n opened.unref?.()\n opened.onmessage = (event) => {\n for (const listener of [...listeners]) {\n try {\n listener(event.data)\n } catch {\n /* one bad listener must not silence the others */\n }\n }\n }\n channel = opened\n return opened\n }\n const hub: Hub = {\n post(message) {\n try {\n open().postMessage(message)\n } catch {\n /* a notice is best-effort: it must never break the write it reports */\n }\n },\n listen(listener) {\n try {\n open()\n } catch {\n return () => undefined\n }\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n if (listeners.size === 0 && channel) {\n channel.onmessage = null\n channel.close()\n channel = undefined\n }\n }\n },\n }\n tab.hubs.set(name, hub)\n return hub\n}\n\n/** The subset of the Web Locks API used here. */\nexport interface LockManagerLike {\n request(\n name: string,\n options: { mode?: 'exclusive' | 'shared'; ifAvailable?: boolean; signal?: AbortSignal },\n callback: (lock: unknown) => unknown,\n ): Promise<unknown>\n /** Who holds what (`navigator.locks.query()`); a watcher reads it, it never takes the lock. */\n query?(): Promise<{ held?: { name?: string; mode?: string }[] }>\n}\n\n/** True while someone holds `name` EXCLUSIVELY (a run); undefined when it cannot be asked. */\nexport const heldExclusively = async (\n locks: LockManagerLike,\n name: string,\n): Promise<boolean | undefined> => {\n if (typeof locks.query !== 'function') return undefined\n try {\n const state = await locks.query()\n return (state?.held ?? []).some((l) => l?.name === name && l?.mode !== 'shared')\n } catch {\n return undefined\n }\n}\n\n/** `navigator.locks`, or the test seam; undefined where the browser has none. */\nexport const lockManager = (): LockManagerLike | undefined => {\n const seam = (globalThis as Record<symbol, unknown>)[LOCKS_TEST]\n // A test says \"no Web Locks here\" - also on a runtime that has them (Node 24+).\n if (seam === null) return undefined\n if (seam && typeof (seam as LockManagerLike).request === 'function') {\n return seam as LockManagerLike\n }\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks\n return locks && typeof locks.request === 'function' ? locks : undefined\n}\n\n/** A plain object (not an array, not null): what every message must be before it is read. */\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** The name a database's channels and locks are under: one app's never meets another's. */\nexport const scopeOf = (dbName: string): string => encodeURIComponent(dbName)\n\n/** A fresh id for a watcher or a request. */\nexport const newSyncId = (): string => randomId().slice(0, 32)\n","import { currentTab, hubOf, isRecord, scopeOf, SYNC_ID_RE, SYNC_VERSION, type Tab } from './tab.js'\n\n/**\n * Change notices: after a write to IndexedDB COMMITS, the store that made it tells the other tabs\n * of the origin \"this changed\" - never what it changed to. A notice carries the kind of store, the\n * operation and at most a name (a path, a session id); never a value, a file's content, a message,\n * a key. A tab that hears one reads the store again if it shows that data.\n *\n * One channel per database name (`dbName`), so two apps on one origin with different databases\n * never hear each other. A tab does not hear its own notices. Nothing is sent from an in-memory\n * store (nothing is shared), and nothing anywhere without BroadcastChannel.\n */\n\n/**\n * The stores that announce their writes:\n * - `credentials` - `VaultCredentialStore` (an API key stored or removed). No `key`.\n * - `oauth` - `VaultOAuthStorage` (an MCP server's OAuth record). No `key`.\n * - `files` - `VirtualFileSystem`: `key` = the path, `namespace` = the file system's namespace.\n * - `session` - `IndexedDBStore` (the agent's memory): `key` = the session id.\n * - `runs` - `IndexedDBRunStore` (checkpoints): `key` = the run id.\n * - `skills` - `VfsSkillStore` (the agent's lessons): `key` = the lesson's name, `namespace` =\n * the store's folder.\n * - `chats` - the React package's `ChatHistoryStore`: `key` = the chat id.\n * - `host` - a store of the host's own that is none of the above (`postStorageChange`): `key` =\n * which record, `namespace` = which of the host's stores - names the host chose, never a value.\n */\nexport type StorageChangeKind =\n 'credentials' | 'oauth' | 'files' | 'session' | 'runs' | 'skills' | 'chats' | 'host'\n\n/** `put` = written (created or replaced), `delete` = one removed, `clear` = all of them removed. */\nexport type StorageChangeOp = 'put' | 'delete' | 'clear'\n\nexport interface StorageChange {\n kind: StorageChangeKind\n op: StorageChangeOp\n /** Which one (see `StorageChangeKind`); absent for `clear` and for the kinds that carry none. */\n key?: string\n /** `files`: the file system's namespace; `skills`: the store's folder; `host`: which store. */\n namespace?: string\n}\n\nexport const STORAGE_CHANGE_KINDS: readonly StorageChangeKind[] = [\n 'credentials',\n 'oauth',\n 'files',\n 'session',\n 'runs',\n 'skills',\n 'chats',\n 'host',\n]\nconst OPS: readonly StorageChangeOp[] = ['put', 'delete', 'clear']\n// A notice names, it does not describe: a path, an id. Longer is not a name.\nexport const MAX_NOTICE_KEY_CHARS = 1024\nexport const MAX_NOTICE_NAMESPACE_CHARS = 256\n// The kinds whose name is withheld (see docs/security.md): a vault id may be an MCP server's URL\n// with its query string, and a listener re-reads what it shows anyway.\nconst KEYLESS: ReadonlySet<StorageChangeKind> = new Set(['credentials', 'oauth'])\n\n/** The channel a database's notices go out on. */\nexport const storageChannelName = (dbName: string): string =>\n `@dudko.dev/agent-web/storage:${scopeOf(dbName)}`\n\nconst nameOk = (value: unknown, max: number): value is string =>\n typeof value === 'string' && value.length > 0 && value.length <= max\n\n/**\n * What a message on the channel says, or undefined when it is not a notice of this shape. The\n * channel is open to every page of the origin, so a message is checked before anyone reads it:\n * a known kind and op, a name of bounded length or none (none at all for the keyless kinds), and\n * nothing else is passed on.\n */\nexport const storageChangeOf = (data: unknown): StorageChange | undefined => {\n if (!isRecord(data) || data.v !== SYNC_VERSION || data.t !== 'change') return undefined\n if (typeof data.from !== 'string' || !SYNC_ID_RE.test(data.from)) return undefined\n const kind = data.kind as StorageChangeKind\n const op = data.op as StorageChangeOp\n if (!STORAGE_CHANGE_KINDS.includes(kind) || !OPS.includes(op)) return undefined\n if (data.key !== undefined && (KEYLESS.has(kind) || !nameOk(data.key, MAX_NOTICE_KEY_CHARS))) {\n return undefined\n }\n if (data.ns !== undefined && !nameOk(data.ns, MAX_NOTICE_NAMESPACE_CHARS)) return undefined\n return {\n kind,\n op,\n ...(data.key !== undefined ? { key: data.key as string } : {}),\n ...(data.ns !== undefined ? { namespace: data.ns as string } : {}),\n }\n}\n\n/** Post a notice from `tab` (a store passes the tab it was made in). */\nexport const postStorageChangeFrom = (\n tab: Tab,\n dbName: string | undefined,\n change: StorageChange,\n): void => {\n if (!dbName) return\n const message = {\n v: SYNC_VERSION,\n t: 'change',\n from: tab.id,\n kind: change.kind,\n op: change.op,\n ...(change.key !== undefined && !KEYLESS.has(change.kind) ? { key: change.key } : {}),\n ...(change.namespace !== undefined ? { ns: change.namespace } : {}),\n }\n // What a listener would refuse is not sent: a store with a bad name says nothing.\n if (!storageChangeOf(message)) return\n hubOf(tab, storageChannelName(dbName))?.post(message)\n}\n\n/**\n * Tell the other tabs that a store in database `dbName` changed - for a store of your own on\n * IndexedDB (the built-in ones post their own): one of the built-in kinds when it keeps that kind\n * of thing, `host` for anything else (`namespace` names which of your stores, `key` which record).\n * Call it AFTER the write committed. Never put a value in it: a notice says which, not what. A\n * no-op without `dbName` or BroadcastChannel; a notice of the wrong shape is dropped.\n */\nexport const postStorageChange = (dbName: string | undefined, change: StorageChange): void =>\n postStorageChangeFrom(currentTab(), dbName, change)\n\n/**\n * Hear the OTHER tabs' notices for database `dbName` (default database of the built-in stores:\n * `'agent-web'`; the React package's chat history: `'agent-web-react'`). This tab's own writes\n * are not reported - you made them. Returns the unsubscribe. A no-op (and a no-op unsubscribe)\n * without `dbName` or BroadcastChannel.\n */\nexport const onStorageChange = (\n dbName: string | undefined,\n listener: (change: StorageChange) => void,\n): (() => void) => {\n if (!dbName) return () => undefined\n const tab = currentTab()\n const hub = hubOf(tab, storageChannelName(dbName))\n if (!hub) return () => undefined\n // The tab's one channel for the name never delivers to itself: its own posts do not come back.\n return hub.listen((data) => {\n const change = storageChangeOf(data)\n if (change) listener(change)\n })\n}\n"],"mappings":";AAAA,SAAS,cAAiC;AAOnC,IAAM,aAAa;AACnB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,cAAc;AACpB,IAAM,aAAa;AAG1B,IAAM,aAAa;AAEnB,IAAI,QAAQ,oBAAI,IAAmC;AAmB5C,IAAM,iBAAiB,CAAC,OAA0B,CAAC,MAA6B;AACrF,QAAM,OAAO,KAAK,UAAU;AAC5B,MAAI,IAAI,MAAM,IAAI,IAAI;AACtB,MAAI,CAAC,GAAG;AACN,UAAM,SAAgC,OAAO,MAAM,YAAY;AAAA,MAC7D,QAAQ,IAAI;AAEV,YAAI,CAAC,GAAG,iBAAiB,SAAS,UAAU,EAAG,IAAG,kBAAkB,UAAU;AAC9E,YAAI,CAAC,GAAG,iBAAiB,SAAS,aAAa,EAAG,IAAG,kBAAkB,aAAa;AACpF,YAAI,CAAC,GAAG,iBAAiB,SAAS,cAAc,EAAG,IAAG,kBAAkB,cAAc;AACtF,YAAI,CAAC,GAAG,iBAAiB,SAAS,WAAW,EAAG,IAAG,kBAAkB,WAAW;AAChF,YAAI,CAAC,GAAG,iBAAiB,SAAS,UAAU,EAAG,IAAG,kBAAkB,UAAU;AAAA,MAChF;AAAA;AAAA,MAEA,SAAS,UAAU,OAAO,OAAO;AAC/B,eAAO,MAAM,MAAM;AAClB,QAAC,MAAM,OAAuB,MAAM;AAAA,MACvC;AAAA;AAAA,MAEA,aAAa;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
5
|
+
var positive = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
|
|
6
|
+
var scaled = (width, height, scale) => ({
|
|
7
|
+
width: Math.max(1, Math.floor(width * scale)),
|
|
8
|
+
height: Math.max(1, Math.floor(height * scale))
|
|
9
|
+
});
|
|
10
|
+
var isPortrait = (w, h) => w < h;
|
|
11
|
+
var decodeScaled = async (blob, width, height, maxSide) => {
|
|
12
|
+
const scale = Math.min(1, maxSide / Math.max(width, height));
|
|
13
|
+
const target = scaled(width, height, scale);
|
|
14
|
+
const decode = (portrait, w, h) => createImageBitmap(
|
|
15
|
+
blob,
|
|
16
|
+
portrait ? { resizeWidth: w, resizeQuality: "high" } : { resizeHeight: h, resizeQuality: "high" }
|
|
17
|
+
);
|
|
18
|
+
const first = await decode(isPortrait(width, height), target.width, target.height);
|
|
19
|
+
const turned = width !== height && isPortrait(first.width, first.height) !== isPortrait(width, height) && Math.max(first.width, first.height) < Math.max(target.width, target.height);
|
|
20
|
+
if (!turned) return first;
|
|
21
|
+
first.close();
|
|
22
|
+
const again = scaled(height, width, scale);
|
|
23
|
+
return decode(isPortrait(height, width), again.width, again.height);
|
|
24
|
+
};
|
|
25
|
+
var fitSide = (bitmap, maxSide) => scaled(bitmap.width, bitmap.height, Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height)));
|
|
26
|
+
var draw = (bitmap, width, height, opaque) => {
|
|
27
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
28
|
+
const ctx = canvas.getContext("2d");
|
|
29
|
+
if (!ctx) throw new Error("fitReferenceImage: no 2D canvas");
|
|
30
|
+
if (opaque) {
|
|
31
|
+
ctx.fillStyle = "#fff";
|
|
32
|
+
ctx.fillRect(0, 0, width, height);
|
|
33
|
+
}
|
|
34
|
+
ctx.imageSmoothingEnabled = true;
|
|
35
|
+
ctx.imageSmoothingQuality = "high";
|
|
36
|
+
ctx.drawImage(bitmap, 0, 0, width, height);
|
|
37
|
+
return canvas;
|
|
38
|
+
};
|
|
39
|
+
var bytesOf = async (blob) => new Uint8Array(await blob.arrayBuffer());
|
|
40
|
+
var fitReferenceImage = async (picture, bounds, options) => {
|
|
41
|
+
if (typeof createImageBitmap !== "function" || typeof OffscreenCanvas === "undefined") {
|
|
42
|
+
return void 0;
|
|
43
|
+
}
|
|
44
|
+
const { maxSide, maxBytes } = bounds ?? {};
|
|
45
|
+
if (!positive(maxSide) || !positive(maxBytes)) return void 0;
|
|
46
|
+
if (!(picture?.bytes instanceof Uint8Array) || !positive(picture.width) || !positive(picture.height))
|
|
47
|
+
return void 0;
|
|
48
|
+
const signal = options?.signal;
|
|
49
|
+
signal?.throwIfAborted();
|
|
50
|
+
let bitmap;
|
|
51
|
+
try {
|
|
52
|
+
bitmap = await decodeScaled(
|
|
53
|
+
new Blob([picture.bytes], { type: picture.mediaType }),
|
|
54
|
+
picture.width,
|
|
55
|
+
picture.height,
|
|
56
|
+
maxSide
|
|
57
|
+
);
|
|
58
|
+
} catch {
|
|
59
|
+
signal?.throwIfAborted();
|
|
60
|
+
return void 0;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
let size = fitSide(bitmap, maxSide);
|
|
64
|
+
if (picture.mediaType === "image/png") {
|
|
65
|
+
signal?.throwIfAborted();
|
|
66
|
+
const png = await draw(bitmap, size.width, size.height, false).convertToBlob({
|
|
67
|
+
type: "image/png"
|
|
68
|
+
});
|
|
69
|
+
if (png.size <= maxBytes) return { bytes: await bytesOf(png), mediaType: "image/png" };
|
|
70
|
+
}
|
|
71
|
+
for (let step = 0; step < SIZES; step++) {
|
|
72
|
+
const canvas = draw(bitmap, size.width, size.height, true);
|
|
73
|
+
for (const quality of QUALITIES) {
|
|
74
|
+
signal?.throwIfAborted();
|
|
75
|
+
const jpeg = await canvas.convertToBlob({ type: "image/jpeg", quality });
|
|
76
|
+
if (jpeg.size <= maxBytes) return { bytes: await bytesOf(jpeg), mediaType: jpeg.type };
|
|
77
|
+
}
|
|
78
|
+
size = scaled(size.width, size.height, STEP);
|
|
79
|
+
}
|
|
80
|
+
return void 0;
|
|
81
|
+
} finally {
|
|
82
|
+
bitmap.close();
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var ownBytes = (bytes) => bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength && !(typeof SharedArrayBuffer !== "undefined" && bytes.buffer instanceof SharedArrayBuffer) ? bytes : bytes.slice();
|
|
86
|
+
var fitReferenceInWorker = (createWorker) => (picture, bounds, options) => new Promise((resolve, reject) => {
|
|
87
|
+
const signal = options?.signal;
|
|
88
|
+
if (signal?.aborted) {
|
|
89
|
+
reject(signal.reason ?? new Error("aborted"));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
let worker;
|
|
93
|
+
try {
|
|
94
|
+
worker = createWorker();
|
|
95
|
+
} catch (err) {
|
|
96
|
+
reject(err);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
let settled = false;
|
|
100
|
+
const finish = (fn) => {
|
|
101
|
+
if (settled) return;
|
|
102
|
+
settled = true;
|
|
103
|
+
signal?.removeEventListener("abort", onAbort);
|
|
104
|
+
worker.terminate();
|
|
105
|
+
fn();
|
|
106
|
+
};
|
|
107
|
+
const onAbort = () => finish(() => reject(signal?.reason ?? new Error("aborted")));
|
|
108
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
109
|
+
worker.addEventListener("message", (ev) => {
|
|
110
|
+
const a = ev.data;
|
|
111
|
+
if (!a || a.type !== "fit-reference") return;
|
|
112
|
+
if (!a.ok) {
|
|
113
|
+
finish(() => reject(new Error(`fitReferenceInWorker: ${String(a.error).slice(0, 200)}`)));
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
finish(
|
|
117
|
+
() => resolve(
|
|
118
|
+
a.bytes instanceof Uint8Array ? {
|
|
119
|
+
bytes: a.bytes,
|
|
120
|
+
...typeof a.mediaType === "string" ? { mediaType: a.mediaType } : {}
|
|
121
|
+
} : void 0
|
|
122
|
+
)
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
worker.addEventListener(
|
|
126
|
+
"error",
|
|
127
|
+
(ev) => finish(
|
|
128
|
+
() => reject(new Error(`fitReferenceInWorker: the worker failed (${ev?.message ?? "error"})`))
|
|
129
|
+
)
|
|
130
|
+
);
|
|
131
|
+
worker.addEventListener(
|
|
132
|
+
"messageerror",
|
|
133
|
+
() => finish(() => reject(new Error("fitReferenceInWorker: the answer could not be read")))
|
|
134
|
+
);
|
|
135
|
+
const bytes = ownBytes(picture.bytes);
|
|
136
|
+
const request = {
|
|
137
|
+
type: "fit-reference",
|
|
138
|
+
picture: {
|
|
139
|
+
bytes,
|
|
140
|
+
mediaType: picture.mediaType,
|
|
141
|
+
width: picture.width,
|
|
142
|
+
height: picture.height,
|
|
143
|
+
path: picture.path
|
|
144
|
+
},
|
|
145
|
+
bounds: { maxSide: bounds.maxSide, maxBytes: bounds.maxBytes }
|
|
146
|
+
};
|
|
147
|
+
try {
|
|
148
|
+
worker.postMessage(request, [bytes.buffer]);
|
|
149
|
+
} catch (err) {
|
|
150
|
+
finish(() => reject(err));
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
var serveFitReferenceWorker = (opts = {}) => {
|
|
154
|
+
const scope = opts.scope ?? globalThis;
|
|
155
|
+
const fit = opts.fit ?? fitReferenceImage;
|
|
156
|
+
scope.addEventListener("message", (ev) => {
|
|
157
|
+
const req = ev.data;
|
|
158
|
+
if (!req || req.type !== "fit-reference") return;
|
|
159
|
+
const answer = (a, transfer = []) => scope.postMessage(a, transfer);
|
|
160
|
+
const signal = new AbortController().signal;
|
|
161
|
+
Promise.resolve().then(() => fit(req.picture, req.bounds, { signal })).then(
|
|
162
|
+
(out) => {
|
|
163
|
+
if (!out || !(out.bytes instanceof Uint8Array)) {
|
|
164
|
+
answer({ type: "fit-reference", ok: true });
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const bytes = ownBytes(out.bytes);
|
|
168
|
+
answer(
|
|
169
|
+
{
|
|
170
|
+
type: "fit-reference",
|
|
171
|
+
ok: true,
|
|
172
|
+
bytes,
|
|
173
|
+
...typeof out.mediaType === "string" ? { mediaType: out.mediaType } : {}
|
|
174
|
+
},
|
|
175
|
+
[bytes.buffer]
|
|
176
|
+
);
|
|
177
|
+
},
|
|
178
|
+
(err) => answer({
|
|
179
|
+
type: "fit-reference",
|
|
180
|
+
ok: false,
|
|
181
|
+
error: err instanceof Error ? err.message : String(err)
|
|
182
|
+
})
|
|
183
|
+
);
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
export {
|
|
188
|
+
fitReferenceImage,
|
|
189
|
+
fitReferenceInWorker,
|
|
190
|
+
serveFitReferenceWorker
|
|
191
|
+
};
|
|
192
|
+
//# sourceMappingURL=chunk-R5VCITT3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools/media-fit.ts"],"sourcesContent":["// `media.fitReference` for the browser: a reference picture over the bounds made small enough to\n// send, with the browser's own codecs - `createImageBitmap` decodes and scales, an\n// `OffscreenCanvas` encodes. Web APIs only (no DOM, no `node:*`): it works in a page and in a\n// Web Worker. On a page's thread the encode is a long task (about 200 ms for a 4096 px JPEG), so a\n// host runs it in a worker: `fitReferenceInWorker(() => new Worker(...))` with the\n// `@dudko.dev/agent-web/fit-reference-worker` entry, which serves `fitReferenceImage` by itself.\n//\n// Types only from the shared file: the worker entry stays a few kilobytes.\nimport type {\n IFittedReference,\n IFitReferenceOptions,\n IReferenceBounds,\n IReferencePicture,\n MediaFitReference,\n} from './media-shared.js'\n\n/** JPEG qualities tried at each size, best first. */\nconst QUALITIES = [0.85, 0.72, 0.6]\n/** How much smaller each next size is (on each side), and how many sizes are tried. */\nconst STEP = 0.75\nconst SIZES = 6\n\nconst positive = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0\n\n/** Width and height scaled by `scale`, rounded DOWN (never over the bound), at least 1. */\nconst scaled = (width: number, height: number, scale: number) => ({\n width: Math.max(1, Math.floor(width * scale)),\n height: Math.max(1, Math.floor(height * scale)),\n})\n\nconst isPortrait = (w: number, h: number) => w < h\n\n/**\n * The picture decoded and scaled so that its longer side is at most `maxSide`, as the browser\n * shows it (EXIF orientation applied).\n *\n * Only the SHORTER side is asked for (`resizeWidth` or `resizeHeight`): the browser keeps the\n * aspect, so the picture is never stretched. The header's width and height are the stored ones; a\n * phone's portrait photo is stored landscape with an orientation tag, and the browser turns it -\n * then the side asked for was the longer one of the turned picture and the result is smaller than\n * it could be (never larger), so it is decoded once more with the side it really has.\n *\n * A browser that ignores the resize options hands back the picture at its full size: it is then\n * scaled when it is drawn (`drawImage`, smoothing 'high') - the same result, with the full-size\n * bitmap held in memory meanwhile.\n */\nconst decodeScaled = async (\n blob: Blob,\n width: number,\n height: number,\n maxSide: number,\n): Promise<ImageBitmap> => {\n const scale = Math.min(1, maxSide / Math.max(width, height))\n const target = scaled(width, height, scale)\n const decode = (portrait: boolean, w: number, h: number) =>\n createImageBitmap(\n blob,\n portrait\n ? { resizeWidth: w, resizeQuality: 'high' }\n : { resizeHeight: h, resizeQuality: 'high' },\n )\n const first = await decode(isPortrait(width, height), target.width, target.height)\n const turned =\n width !== height &&\n isPortrait(first.width, first.height) !== isPortrait(width, height) &&\n Math.max(first.width, first.height) < Math.max(target.width, target.height)\n if (!turned) return first\n first.close()\n // The browser turned it: the stored height is its width now.\n const again = scaled(height, width, scale)\n return decode(isPortrait(height, width), again.width, again.height)\n}\n\n/** What fits in `maxSide`, from the bitmap as it is (in case the resize options were ignored). */\nconst fitSide = (bitmap: ImageBitmap, maxSide: number) =>\n scaled(bitmap.width, bitmap.height, Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height)))\n\nconst draw = (bitmap: ImageBitmap, width: number, height: number, opaque: boolean) => {\n const canvas = new OffscreenCanvas(width, height)\n const ctx = canvas.getContext('2d')\n if (!ctx) throw new Error('fitReferenceImage: no 2D canvas')\n if (opaque) {\n // JPEG has no transparency: what was transparent becomes white, not black.\n ctx.fillStyle = '#fff'\n ctx.fillRect(0, 0, width, height)\n }\n ctx.imageSmoothingEnabled = true\n ctx.imageSmoothingQuality = 'high'\n ctx.drawImage(bitmap, 0, 0, width, height)\n return canvas\n}\n\nconst bytesOf = async (blob: Blob): Promise<Uint8Array> => new Uint8Array(await blob.arrayBuffer())\n\n/**\n * `media.fitReference` with the browser's codecs. The longer side is brought to at most\n * `maxSide`; a PNG stays a PNG when it then fits in `maxBytes` (a screenshot keeps sharp text),\n * anything else - and a PNG that does not fit - becomes a JPEG (on white where it was\n * transparent), at falling quality and then falling size until it fits. undefined when this\n * browser cannot do it (no `createImageBitmap` / `OffscreenCanvas`), cannot decode the picture, or\n * nothing it tried fits: the agent then refuses the picture. Stops when `options.signal` aborts.\n *\n * Decoding (`createImageBitmap` of a Blob) happens off the calling thread in Chromium and Safari;\n * the encode (`convertToBlob`) does not on a page's thread - run this in a worker\n * (`fitReferenceInWorker`) on a page that must keep answering.\n */\nexport const fitReferenceImage: MediaFitReference = async (\n picture: IReferencePicture,\n bounds: IReferenceBounds,\n options?: IFitReferenceOptions,\n): Promise<IFittedReference | undefined> => {\n if (typeof createImageBitmap !== 'function' || typeof OffscreenCanvas === 'undefined') {\n return undefined\n }\n const { maxSide, maxBytes } = bounds ?? ({} as IReferenceBounds)\n if (!positive(maxSide) || !positive(maxBytes)) return undefined\n if (\n !(picture?.bytes instanceof Uint8Array) ||\n !positive(picture.width) ||\n !positive(picture.height)\n )\n return undefined\n const signal = options?.signal\n signal?.throwIfAborted()\n let bitmap: ImageBitmap\n try {\n bitmap = await decodeScaled(\n new Blob([picture.bytes as Uint8Array<ArrayBuffer>], { type: picture.mediaType }),\n picture.width,\n picture.height,\n maxSide,\n )\n } catch {\n signal?.throwIfAborted()\n return undefined // a picture this browser cannot decode\n }\n try {\n let size = fitSide(bitmap, maxSide)\n if (picture.mediaType === 'image/png') {\n signal?.throwIfAborted()\n const png = await draw(bitmap, size.width, size.height, false).convertToBlob({\n type: 'image/png',\n })\n if (png.size <= maxBytes) return { bytes: await bytesOf(png), mediaType: 'image/png' }\n }\n for (let step = 0; step < SIZES; step++) {\n const canvas = draw(bitmap, size.width, size.height, true)\n for (const quality of QUALITIES) {\n signal?.throwIfAborted()\n const jpeg = await canvas.convertToBlob({ type: 'image/jpeg', quality })\n if (jpeg.size <= maxBytes) return { bytes: await bytesOf(jpeg), mediaType: jpeg.type }\n }\n size = scaled(size.width, size.height, STEP)\n }\n return undefined\n } finally {\n bitmap.close()\n }\n}\n\n// ── in a Web Worker ──────────────────────────────────────────────────────────\n\n/** What the page posts to the worker, and what the worker answers. */\ninterface FitRequest {\n type: 'fit-reference'\n picture: IReferencePicture\n bounds: IReferenceBounds\n}\ntype FitAnswer =\n | { type: 'fit-reference'; ok: true; bytes?: Uint8Array; mediaType?: string }\n | { type: 'fit-reference'; ok: false; error: string }\n\n/** The slice of a Worker this needs (a `Worker`, or anything shaped like one in a test). */\nexport interface FitReferenceWorker {\n postMessage(message: unknown, transfer: Transferable[]): void\n addEventListener(type: 'message' | 'error' | 'messageerror', listener: (ev: any) => void): void\n terminate(): void\n}\n\n/** Bytes that own their whole buffer can be handed over as they are; a view is copied first. */\nconst ownBytes = (bytes: Uint8Array): Uint8Array =>\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength &&\n !(typeof SharedArrayBuffer !== 'undefined' && bytes.buffer instanceof SharedArrayBuffer)\n ? bytes\n : bytes.slice()\n\n/**\n * `media.fitReference` that runs in a Web Worker: one worker per picture, from `createWorker`,\n * terminated when it has answered - or at once when the call's signal aborts (the agent's time\n * bound, a stopped run), so a stuck decode is stopped, not just left behind. The picture's bytes\n * are transferred to the worker, not copied. The worker is the `fit-reference-worker` entry (or a\n * script that calls `serveFitReferenceWorker`):\n *\n * ```ts\n * // Vite\n * import FitWorker from '@dudko.dev/agent-web/fit-reference-worker?worker'\n * media: { imageModel, fitReference: fitReferenceInWorker(() => new FitWorker()) }\n * // bundlers that follow `new URL(..., import.meta.url)`\n * fitReferenceInWorker(\n * () =>\n * new Worker(new URL('@dudko.dev/agent-web/fit-reference-worker', import.meta.url), {\n * type: 'module',\n * }),\n * )\n * ```\n */\nexport const fitReferenceInWorker =\n (createWorker: () => FitReferenceWorker): MediaFitReference =>\n (picture, bounds, options) =>\n new Promise<IFittedReference | undefined>((resolve, reject) => {\n const signal = options?.signal\n if (signal?.aborted) {\n reject(signal.reason ?? new Error('aborted'))\n return\n }\n let worker: FitReferenceWorker\n try {\n worker = createWorker()\n } catch (err) {\n reject(err)\n return\n }\n let settled = false\n const finish = (fn: () => void) => {\n if (settled) return\n settled = true\n signal?.removeEventListener('abort', onAbort)\n worker.terminate()\n fn()\n }\n const onAbort = () => finish(() => reject(signal?.reason ?? new Error('aborted')))\n signal?.addEventListener('abort', onAbort, { once: true })\n worker.addEventListener('message', (ev: MessageEvent) => {\n const a = ev.data as FitAnswer | undefined\n if (!a || a.type !== 'fit-reference') return\n if (!a.ok) {\n finish(() => reject(new Error(`fitReferenceInWorker: ${String(a.error).slice(0, 200)}`)))\n return\n }\n finish(() =>\n resolve(\n a.bytes instanceof Uint8Array\n ? {\n bytes: a.bytes,\n ...(typeof a.mediaType === 'string' ? { mediaType: a.mediaType } : {}),\n }\n : undefined,\n ),\n )\n })\n worker.addEventListener('error', (ev: ErrorEvent) =>\n finish(() =>\n reject(new Error(`fitReferenceInWorker: the worker failed (${ev?.message ?? 'error'})`)),\n ),\n )\n worker.addEventListener('messageerror', () =>\n finish(() => reject(new Error('fitReferenceInWorker: the answer could not be read'))),\n )\n const bytes = ownBytes(picture.bytes)\n const request: FitRequest = {\n type: 'fit-reference',\n picture: {\n bytes,\n mediaType: picture.mediaType,\n width: picture.width,\n height: picture.height,\n path: picture.path,\n },\n bounds: { maxSide: bounds.maxSide, maxBytes: bounds.maxBytes },\n }\n try {\n worker.postMessage(request, [bytes.buffer])\n } catch (err) {\n finish(() => reject(err))\n }\n })\n\n/** The slice of a worker scope this needs. */\nexport interface FitReferenceWorkerScope {\n postMessage(message: unknown, transfer?: Transferable[]): void\n addEventListener(type: 'message', listener: (ev: MessageEvent) => void): void\n}\n\nexport interface ServeFitReferenceOptions {\n /** The message endpoint (default: the worker global scope). */\n scope?: FitReferenceWorkerScope\n /** What fits a picture (default: `fitReferenceImage`). */\n fit?: MediaFitReference\n}\n\n/**\n * The worker side of `fitReferenceInWorker`: answers each request with `fit` (default\n * `fitReferenceImage`), the result's bytes transferred back. The `fit-reference-worker` entry\n * calls it when it is loaded.\n */\nexport const serveFitReferenceWorker = (opts: ServeFitReferenceOptions = {}): void => {\n const scope = opts.scope ?? (globalThis as unknown as FitReferenceWorkerScope)\n const fit = opts.fit ?? fitReferenceImage\n scope.addEventListener('message', (ev: MessageEvent) => {\n const req = ev.data as FitRequest | undefined\n if (!req || req.type !== 'fit-reference') return\n const answer = (a: FitAnswer, transfer: Transferable[] = []) => scope.postMessage(a, transfer)\n // The page terminates the worker at its time bound: this signal never fires on its own.\n const signal = new AbortController().signal\n Promise.resolve()\n .then(() => fit(req.picture, req.bounds, { signal }))\n .then(\n (out) => {\n if (!out || !(out.bytes instanceof Uint8Array)) {\n answer({ type: 'fit-reference', ok: true })\n return\n }\n const bytes = ownBytes(out.bytes)\n answer(\n {\n type: 'fit-reference',\n ok: true,\n bytes,\n ...(typeof out.mediaType === 'string' ? { mediaType: out.mediaType } : {}),\n },\n [bytes.buffer],\n )\n },\n (err) =>\n answer({\n type: 'fit-reference',\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n })\n}\n"],"mappings":";AAiBA,IAAM,YAAY,CAAC,MAAM,MAAM,GAAG;AAElC,IAAM,OAAO;AACb,IAAM,QAAQ;AAEd,IAAM,WAAW,CAAC,MAA4B,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,IAAI;AAGjG,IAAM,SAAS,CAAC,OAAe,QAAgB,WAAmB;AAAA,EAChE,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,KAA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AS,gBAAiB;AAC1C,UAAM,SAAS,CAAC,GAAc,WAA2B,CAAC,MAAM,MAAM,YAAY,GAAG,QAAQ;AAE7F,UAAM,SAAS,IAAI,gBAAgB,EAAE;AACrC,YAAQ,QAAQ,EACb,KAAK,MAAM,IAAI,IAAI,SAAS,IAAI,QAAQ,EAAE,OAAO,CAAC,CAAC,EACnD;AAAA,MACC,CAAC,QAAQ;AACP,YAAI,CAAC,OAAO,EAAE,IAAI,iBAAiB,aAAa;AAC9C,iBAAO,EAAE,MAAM,iBAAiB,IAAI,KAAK,CAAC;AAC1C;AAAA,QACF;AACA,cAAM,QAAQ,SAAS,IAAI,KAAK;AAChC;AAAA,UACE;AAAA,YACE,MAAM;AAAA,YACN,IAAI;AAAA,YACJ;AAAA,YACA,GAAI,OAAO,IAAI,cAAc,WAAW,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;AAAA,UAC1E;AAAA,UACA,CAAC,MAAM,MAAM;AAAA,QACf;AAAA,MACF;AAAA,MACA,CAAC,QACC,OAAO;AAAA,QACL,MAAM;AAAA,QACN,IAAI;AAAA,QACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACxD,CAAC;AAAA,IACL;AAAA,EACJ,CAAC;AACH;","names":[]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
IndexedDBVault
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-HXUR2SG5.js";
|
|
4
4
|
import {
|
|
5
5
|
currentTab,
|
|
6
6
|
postStorageChangeFrom
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-NUL6QEAX.js";
|
|
8
8
|
|
|
9
9
|
// src/secrets/store.ts
|
|
10
10
|
var VaultCredentialStore = class {
|
|
@@ -49,4 +49,4 @@ export {
|
|
|
49
49
|
VaultCredentialStore,
|
|
50
50
|
MemoryCredentialStore
|
|
51
51
|
};
|
|
52
|
-
//# sourceMappingURL=chunk-
|
|
52
|
+
//# sourceMappingURL=chunk-SVGIGIRR.js.map
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/tools/media-fit-worker.ts
|
|
21
|
+
var media_fit_worker_exports = {};
|
|
22
|
+
__export(media_fit_worker_exports, {
|
|
23
|
+
fitReferenceImage: () => fitReferenceImage,
|
|
24
|
+
serveFitReferenceWorker: () => serveFitReferenceWorker
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(media_fit_worker_exports);
|
|
27
|
+
|
|
28
|
+
// src/tools/media-fit.ts
|
|
29
|
+
var QUALITIES = [0.85, 0.72, 0.6];
|
|
30
|
+
var STEP = 0.75;
|
|
31
|
+
var SIZES = 6;
|
|
32
|
+
var positive = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
|
|
33
|
+
var scaled = (width, height, scale) => ({
|
|
34
|
+
width: Math.max(1, Math.floor(width * scale)),
|
|
35
|
+
height: Math.max(1, Math.floor(height * scale))
|
|
36
|
+
});
|
|
37
|
+
var isPortrait = (w, h) => w < h;
|
|
38
|
+
var decodeScaled = async (blob, width, height, maxSide) => {
|
|
39
|
+
const scale = Math.min(1, maxSide / Math.max(width, height));
|
|
40
|
+
const target = scaled(width, height, scale);
|
|
41
|
+
const decode = (portrait, w, h) => createImageBitmap(
|
|
42
|
+
blob,
|
|
43
|
+
portrait ? { resizeWidth: w, resizeQuality: "high" } : { resizeHeight: h, resizeQuality: "high" }
|
|
44
|
+
);
|
|
45
|
+
const first = await decode(isPortrait(width, height), target.width, target.height);
|
|
46
|
+
const turned = width !== height && isPortrait(first.width, first.height) !== isPortrait(width, height) && Math.max(first.width, first.height) < Math.max(target.width, target.height);
|
|
47
|
+
if (!turned) return first;
|
|
48
|
+
first.close();
|
|
49
|
+
const again = scaled(height, width, scale);
|
|
50
|
+
return decode(isPortrait(height, width), again.width, again.height);
|
|
51
|
+
};
|
|
52
|
+
var fitSide = (bitmap, maxSide) => scaled(bitmap.width, bitmap.height, Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height)));
|
|
53
|
+
var draw = (bitmap, width, height, opaque) => {
|
|
54
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
55
|
+
const ctx = canvas.getContext("2d");
|
|
56
|
+
if (!ctx) throw new Error("fitReferenceImage: no 2D canvas");
|
|
57
|
+
if (opaque) {
|
|
58
|
+
ctx.fillStyle = "#fff";
|
|
59
|
+
ctx.fillRect(0, 0, width, height);
|
|
60
|
+
}
|
|
61
|
+
ctx.imageSmoothingEnabled = true;
|
|
62
|
+
ctx.imageSmoothingQuality = "high";
|
|
63
|
+
ctx.drawImage(bitmap, 0, 0, width, height);
|
|
64
|
+
return canvas;
|
|
65
|
+
};
|
|
66
|
+
var bytesOf = async (blob) => new Uint8Array(await blob.arrayBuffer());
|
|
67
|
+
var fitReferenceImage = async (picture, bounds, options) => {
|
|
68
|
+
if (typeof createImageBitmap !== "function" || typeof OffscreenCanvas === "undefined") {
|
|
69
|
+
return void 0;
|
|
70
|
+
}
|
|
71
|
+
const { maxSide, maxBytes } = bounds ?? {};
|
|
72
|
+
if (!positive(maxSide) || !positive(maxBytes)) return void 0;
|
|
73
|
+
if (!(picture?.bytes instanceof Uint8Array) || !positive(picture.width) || !positive(picture.height))
|
|
74
|
+
return void 0;
|
|
75
|
+
const signal = options?.signal;
|
|
76
|
+
signal?.throwIfAborted();
|
|
77
|
+
let bitmap;
|
|
78
|
+
try {
|
|
79
|
+
bitmap = await decodeScaled(
|
|
80
|
+
new Blob([picture.bytes], { type: picture.mediaType }),
|
|
81
|
+
picture.width,
|
|
82
|
+
picture.height,
|
|
83
|
+
maxSide
|
|
84
|
+
);
|
|
85
|
+
} catch {
|
|
86
|
+
signal?.throwIfAborted();
|
|
87
|
+
return void 0;
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
let size = fitSide(bitmap, maxSide);
|
|
91
|
+
if (picture.mediaType === "image/png") {
|
|
92
|
+
signal?.throwIfAborted();
|
|
93
|
+
const png = await draw(bitmap, size.width, size.height, false).convertToBlob({
|
|
94
|
+
type: "image/png"
|
|
95
|
+
});
|
|
96
|
+
if (png.size <= maxBytes) return { bytes: await bytesOf(png), mediaType: "image/png" };
|
|
97
|
+
}
|
|
98
|
+
for (let step = 0; step < SIZES; step++) {
|
|
99
|
+
const canvas = draw(bitmap, size.width, size.height, true);
|
|
100
|
+
for (const quality of QUALITIES) {
|
|
101
|
+
signal?.throwIfAborted();
|
|
102
|
+
const jpeg = await canvas.convertToBlob({ type: "image/jpeg", quality });
|
|
103
|
+
if (jpeg.size <= maxBytes) return { bytes: await bytesOf(jpeg), mediaType: jpeg.type };
|
|
104
|
+
}
|
|
105
|
+
size = scaled(size.width, size.height, STEP);
|
|
106
|
+
}
|
|
107
|
+
return void 0;
|
|
108
|
+
} finally {
|
|
109
|
+
bitmap.close();
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
var ownBytes = (bytes) => bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength && !(typeof SharedArrayBuffer !== "undefined" && bytes.buffer instanceof SharedArrayBuffer) ? bytes : bytes.slice();
|
|
113
|
+
var serveFitReferenceWorker = (opts = {}) => {
|
|
114
|
+
const scope = opts.scope ?? globalThis;
|
|
115
|
+
const fit = opts.fit ?? fitReferenceImage;
|
|
116
|
+
scope.addEventListener("message", (ev) => {
|
|
117
|
+
const req = ev.data;
|
|
118
|
+
if (!req || req.type !== "fit-reference") return;
|
|
119
|
+
const answer = (a, transfer = []) => scope.postMessage(a, transfer);
|
|
120
|
+
const signal = new AbortController().signal;
|
|
121
|
+
Promise.resolve().then(() => fit(req.picture, req.bounds, { signal })).then(
|
|
122
|
+
(out) => {
|
|
123
|
+
if (!out || !(out.bytes instanceof Uint8Array)) {
|
|
124
|
+
answer({ type: "fit-reference", ok: true });
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const bytes = ownBytes(out.bytes);
|
|
128
|
+
answer(
|
|
129
|
+
{
|
|
130
|
+
type: "fit-reference",
|
|
131
|
+
ok: true,
|
|
132
|
+
bytes,
|
|
133
|
+
...typeof out.mediaType === "string" ? { mediaType: out.mediaType } : {}
|
|
134
|
+
},
|
|
135
|
+
[bytes.buffer]
|
|
136
|
+
);
|
|
137
|
+
},
|
|
138
|
+
(err) => answer({
|
|
139
|
+
type: "fit-reference",
|
|
140
|
+
ok: false,
|
|
141
|
+
error: err instanceof Error ? err.message : String(err)
|
|
142
|
+
})
|
|
143
|
+
);
|
|
144
|
+
});
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
// src/tools/media-fit-worker.ts
|
|
148
|
+
var inWorker = () => {
|
|
149
|
+
const g = globalThis;
|
|
150
|
+
return typeof g.WorkerGlobalScope !== "undefined" && typeof g.document === "undefined";
|
|
151
|
+
};
|
|
152
|
+
if (inWorker()) serveFitReferenceWorker();
|
|
153
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
154
|
+
0 && (module.exports = {
|
|
155
|
+
fitReferenceImage,
|
|
156
|
+
serveFitReferenceWorker
|
|
157
|
+
});
|
|
158
|
+
//# sourceMappingURL=fit-reference-worker.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools/media-fit-worker.ts","../src/tools/media-fit.ts"],"sourcesContent":["import { serveFitReferenceWorker } from './media-fit.js'\n\n/**\n * The Web Worker side of `fitReferenceInWorker`: the entry\n * `@dudko.dev/agent-web/fit-reference-worker`. Loaded as a worker it serves `fitReferenceImage`\n * by itself - a reference picture over the bounds decoded, scaled and encoded off the page's\n * thread:\n *\n * ```ts\n * // Vite\n * import FitWorker from '@dudko.dev/agent-web/fit-reference-worker?worker'\n * createAgent({ media: { imageModel, fitReference: fitReferenceInWorker(() => new FitWorker()) } })\n * ```\n *\n * One worker fits one picture and is terminated by the page when it has answered, or at the\n * agent's time bound. Web APIs only (`createImageBitmap`, `OffscreenCanvas`); nothing else is\n * imported, so the worker's chunk is a few kilobytes.\n */\nexport { serveFitReferenceWorker, fitReferenceImage } from './media-fit.js'\n\n// Served only inside a worker (not when a page, or a test, imports the module).\nconst inWorker = (): boolean => {\n const g = globalThis as { WorkerGlobalScope?: unknown; document?: unknown }\n return typeof g.WorkerGlobalScope !== 'undefined' && typeof g.document === 'undefined'\n}\n\nif (inWorker()) serveFitReferenceWorker()\n","// `media.fitReference` for the browser: a reference picture over the bounds made small enough to\n// send, with the browser's own codecs - `createImageBitmap` decodes and scales, an\n// `OffscreenCanvas` encodes. Web APIs only (no DOM, no `node:*`): it works in a page and in a\n// Web Worker. On a page's thread the encode is a long task (about 200 ms for a 4096 px JPEG), so a\n// host runs it in a worker: `fitReferenceInWorker(() => new Worker(...))` with the\n// `@dudko.dev/agent-web/fit-reference-worker` entry, which serves `fitReferenceImage` by itself.\n//\n// Types only from the shared file: the worker entry stays a few kilobytes.\nimport type {\n IFittedReference,\n IFitReferenceOptions,\n IReferenceBounds,\n IReferencePicture,\n MediaFitReference,\n} from './media-shared.js'\n\n/** JPEG qualities tried at each size, best first. */\nconst QUALITIES = [0.85, 0.72, 0.6]\n/** How much smaller each next size is (on each side), and how many sizes are tried. */\nconst STEP = 0.75\nconst SIZES = 6\n\nconst positive = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n > 0\n\n/** Width and height scaled by `scale`, rounded DOWN (never over the bound), at least 1. */\nconst scaled = (width: number, height: number, scale: number) => ({\n width: Math.max(1, Math.floor(width * scale)),\n height: Math.max(1, Math.floor(height * scale)),\n})\n\nconst isPortrait = (w: number, h: number) => w < h\n\n/**\n * The picture decoded and scaled so that its longer side is at most `maxSide`, as the browser\n * shows it (EXIF orientation applied).\n *\n * Only the SHORTER side is asked for (`resizeWidth` or `resizeHeight`): the browser keeps the\n * aspect, so the picture is never stretched. The header's width and height are the stored ones; a\n * phone's portrait photo is stored landscape with an orientation tag, and the browser turns it -\n * then the side asked for was the longer one of the turned picture and the result is smaller than\n * it could be (never larger), so it is decoded once more with the side it really has.\n *\n * A browser that ignores the resize options hands back the picture at its full size: it is then\n * scaled when it is drawn (`drawImage`, smoothing 'high') - the same result, with the full-size\n * bitmap held in memory meanwhile.\n */\nconst decodeScaled = async (\n blob: Blob,\n width: number,\n height: number,\n maxSide: number,\n): Promise<ImageBitmap> => {\n const scale = Math.min(1, maxSide / Math.max(width, height))\n const target = scaled(width, height, scale)\n const decode = (portrait: boolean, w: number, h: number) =>\n createImageBitmap(\n blob,\n portrait\n ? { resizeWidth: w, resizeQuality: 'high' }\n : { resizeHeight: h, resizeQuality: 'high' },\n )\n const first = await decode(isPortrait(width, height), target.width, target.height)\n const turned =\n width !== height &&\n isPortrait(first.width, first.height) !== isPortrait(width, height) &&\n Math.max(first.width, first.height) < Math.max(target.width, target.height)\n if (!turned) return first\n first.close()\n // The browser turned it: the stored height is its width now.\n const again = scaled(height, width, scale)\n return decode(isPortrait(height, width), again.width, again.height)\n}\n\n/** What fits in `maxSide`, from the bitmap as it is (in case the resize options were ignored). */\nconst fitSide = (bitmap: ImageBitmap, maxSide: number) =>\n scaled(bitmap.width, bitmap.height, Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height)))\n\nconst draw = (bitmap: ImageBitmap, width: number, height: number, opaque: boolean) => {\n const canvas = new OffscreenCanvas(width, height)\n const ctx = canvas.getContext('2d')\n if (!ctx) throw new Error('fitReferenceImage: no 2D canvas')\n if (opaque) {\n // JPEG has no transparency: what was transparent becomes white, not black.\n ctx.fillStyle = '#fff'\n ctx.fillRect(0, 0, width, height)\n }\n ctx.imageSmoothingEnabled = true\n ctx.imageSmoothingQuality = 'high'\n ctx.drawImage(bitmap, 0, 0, width, height)\n return canvas\n}\n\nconst bytesOf = async (blob: Blob): Promise<Uint8Array> => new Uint8Array(await blob.arrayBuffer())\n\n/**\n * `media.fitReference` with the browser's codecs. The longer side is brought to at most\n * `maxSide`; a PNG stays a PNG when it then fits in `maxBytes` (a screenshot keeps sharp text),\n * anything else - and a PNG that does not fit - becomes a JPEG (on white where it was\n * transparent), at falling quality and then falling size until it fits. undefined when this\n * browser cannot do it (no `createImageBitmap` / `OffscreenCanvas`), cannot decode the picture, or\n * nothing it tried fits: the agent then refuses the picture. Stops when `options.signal` aborts.\n *\n * Decoding (`createImageBitmap` of a Blob) happens off the calling thread in Chromium and Safari;\n * the encode (`convertToBlob`) does not on a page's thread - run this in a worker\n * (`fitReferenceInWorker`) on a page that must keep answering.\n */\nexport const fitReferenceImage: MediaFitReference = async (\n picture: IReferencePicture,\n bounds: IReferenceBounds,\n options?: IFitReferenceOptions,\n): Promise<IFittedReference | undefined> => {\n if (typeof createImageBitmap !== 'function' || typeof OffscreenCanvas === 'undefined') {\n return undefined\n }\n const { maxSide, maxBytes } = bounds ?? ({} as IReferenceBounds)\n if (!positive(maxSide) || !positive(maxBytes)) return undefined\n if (\n !(picture?.bytes instanceof Uint8Array) ||\n !positive(picture.width) ||\n !positive(picture.height)\n )\n return undefined\n const signal = options?.signal\n signal?.throwIfAborted()\n let bitmap: ImageBitmap\n try {\n bitmap = await decodeScaled(\n new Blob([picture.bytes as Uint8Array<ArrayBuffer>], { type: picture.mediaType }),\n picture.width,\n picture.height,\n maxSide,\n )\n } catch {\n signal?.throwIfAborted()\n return undefined // a picture this browser cannot decode\n }\n try {\n let size = fitSide(bitmap, maxSide)\n if (picture.mediaType === 'image/png') {\n signal?.throwIfAborted()\n const png = await draw(bitmap, size.width, size.height, false).convertToBlob({\n type: 'image/png',\n })\n if (png.size <= maxBytes) return { bytes: await bytesOf(png), mediaType: 'image/png' }\n }\n for (let step = 0; step < SIZES; step++) {\n const canvas = draw(bitmap, size.width, size.height, true)\n for (const quality of QUALITIES) {\n signal?.throwIfAborted()\n const jpeg = await canvas.convertToBlob({ type: 'image/jpeg', quality })\n if (jpeg.size <= maxBytes) return { bytes: await bytesOf(jpeg), mediaType: jpeg.type }\n }\n size = scaled(size.width, size.height, STEP)\n }\n return undefined\n } finally {\n bitmap.close()\n }\n}\n\n// ── in a Web Worker ──────────────────────────────────────────────────────────\n\n/** What the page posts to the worker, and what the worker answers. */\ninterface FitRequest {\n type: 'fit-reference'\n picture: IReferencePicture\n bounds: IReferenceBounds\n}\ntype FitAnswer =\n | { type: 'fit-reference'; ok: true; bytes?: Uint8Array; mediaType?: string }\n | { type: 'fit-reference'; ok: false; error: string }\n\n/** The slice of a Worker this needs (a `Worker`, or anything shaped like one in a test). */\nexport interface FitReferenceWorker {\n postMessage(message: unknown, transfer: Transferable[]): void\n addEventListener(type: 'message' | 'error' | 'messageerror', listener: (ev: any) => void): void\n terminate(): void\n}\n\n/** Bytes that own their whole buffer can be handed over as they are; a view is copied first. */\nconst ownBytes = (bytes: Uint8Array): Uint8Array =>\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength &&\n !(typeof SharedArrayBuffer !== 'undefined' && bytes.buffer instanceof SharedArrayBuffer)\n ? bytes\n : bytes.slice()\n\n/**\n * `media.fitReference` that runs in a Web Worker: one worker per picture, from `createWorker`,\n * terminated when it has answered - or at once when the call's signal aborts (the agent's time\n * bound, a stopped run), so a stuck decode is stopped, not just left behind. The picture's bytes\n * are transferred to the worker, not copied. The worker is the `fit-reference-worker` entry (or a\n * script that calls `serveFitReferenceWorker`):\n *\n * ```ts\n * // Vite\n * import FitWorker from '@dudko.dev/agent-web/fit-reference-worker?worker'\n * media: { imageModel, fitReference: fitReferenceInWorker(() => new FitWorker()) }\n * // bundlers that follow `new URL(..., import.meta.url)`\n * fitReferenceInWorker(\n * () =>\n * new Worker(new URL('@dudko.dev/agent-web/fit-reference-worker', import.meta.url), {\n * type: 'module',\n * }),\n * )\n * ```\n */\nexport const fitReferenceInWorker =\n (createWorker: () => FitReferenceWorker): MediaFitReference =>\n (picture, bounds, options) =>\n new Promise<IFittedReference | undefined>((resolve, reject) => {\n const signal = options?.signal\n if (signal?.aborted) {\n reject(signal.reason ?? new Error('aborted'))\n return\n }\n let worker: FitReferenceWorker\n try {\n worker = createWorker()\n } catch (err) {\n reject(err)\n return\n }\n let settled = false\n const finish = (fn: () => void) => {\n if (settled) return\n settled = true\n signal?.removeEventListener('abort', onAbort)\n worker.terminate()\n fn()\n }\n const onAbort = () => finish(() => reject(signal?.reason ?? new Error('aborted')))\n signal?.addEventListener('abort', onAbort, { once: true })\n worker.addEventListener('message', (ev: MessageEvent) => {\n const a = ev.data as FitAnswer | undefined\n if (!a || a.type !== 'fit-reference') return\n if (!a.ok) {\n finish(() => reject(new Error(`fitReferenceInWorker: ${String(a.error).slice(0, 200)}`)))\n return\n }\n finish(() =>\n resolve(\n a.bytes instanceof Uint8Array\n ? {\n bytes: a.bytes,\n ...(typeof a.mediaType === 'string' ? { mediaType: a.mediaType } : {}),\n }\n : undefined,\n ),\n )\n })\n worker.addEventListener('error', (ev: ErrorEvent) =>\n finish(() =>\n reject(new Error(`fitReferenceInWorker: the worker failed (${ev?.message ?? 'error'})`)),\n ),\n )\n worker.addEventListener('messageerror', () =>\n finish(() => reject(new Error('fitReferenceInWorker: the answer could not be read'))),\n )\n const bytes = ownBytes(picture.bytes)\n const request: FitRequest = {\n type: 'fit-reference',\n picture: {\n bytes,\n mediaType: picture.mediaType,\n width: picture.width,\n height: picture.height,\n path: picture.path,\n },\n bounds: { maxSide: bounds.maxSide, maxBytes: bounds.maxBytes },\n }\n try {\n worker.postMessage(request, [bytes.buffer])\n } catch (err) {\n finish(() => reject(err))\n }\n })\n\n/** The slice of a worker scope this needs. */\nexport interface FitReferenceWorkerScope {\n postMessage(message: unknown, transfer?: Transferable[]): void\n addEventListener(type: 'message', listener: (ev: MessageEvent) => void): void\n}\n\nexport interface ServeFitReferenceOptions {\n /** The message endpoint (default: the worker global scope). */\n scope?: FitReferenceWorkerScope\n /** What fits a picture (default: `fitReferenceImage`). */\n fit?: MediaFitReference\n}\n\n/**\n * The worker side of `fitReferenceInWorker`: answers each request with `fit` (default\n * `fitReferenceImage`), the result's bytes transferred back. The `fit-reference-worker` entry\n * calls it when it is loaded.\n */\nexport const serveFitReferenceWorker = (opts: ServeFitReferenceOptions = {}): void => {\n const scope = opts.scope ?? (globalThis as unknown as FitReferenceWorkerScope)\n const fit = opts.fit ?? fitReferenceImage\n scope.addEventListener('message', (ev: MessageEvent) => {\n const req = ev.data as FitRequest | undefined\n if (!req || req.type !== 'fit-reference') return\n const answer = (a: FitAnswer, transfer: Transferable[] = []) => scope.postMessage(a, transfer)\n // The page terminates the worker at its time bound: this signal never fires on its own.\n const signal = new AbortController().signal\n Promise.resolve()\n .then(() => fit(req.picture, req.bounds, { signal }))\n .then(\n (out) => {\n if (!out || !(out.bytes instanceof Uint8Array)) {\n answer({ type: 'fit-reference', ok: true })\n return\n }\n const bytes = ownBytes(out.bytes)\n answer(\n {\n type: 'fit-reference',\n ok: true,\n bytes,\n ...(typeof out.mediaType === 'string' ? { mediaType: out.mediaType } : {}),\n },\n [bytes.buffer],\n )\n },\n (err) =>\n answer({\n type: 'fit-reference',\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA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AAC,EACnD;AAAA,MACC,CAAC,QAAQ;AACP,YAAI,CAAC,OAAO,EAAE,IAAI,iBAAiB,aAAa;AAC9C,iBAAO,EAAE,MAAM,iBAAiB,IAAI,KAAK,CAAC;AAC1C;AAAA,QACF;AACA,cAAM,QAAQ,SAAS,IAAI,KAAK;AAChC;AAAA,UACE;AAAA,YACE,MAAM;AAAA,YACN,IAAI;AAAA,YACJ;AAAA,YACA,GAAI,OAAO,IAAI,cAAc,WAAW,EAAE,WAAW,IAAI,UAAU,IAAI,CAAC;AAAA,UAC1E;AAAA,UACA,CAAC,MAAM,MAAM;AAAA,QACf;AAAA,MACF;AAAA,MACA,CAAC,QACC,OAAO;AAAA,QACL,MAAM;AAAA,QACN,IAAI;AAAA,QACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,MACxD,CAAC;AAAA,IACL;AAAA,EACJ,CAAC;AACH;;;ADvTA,IAAM,WAAW,MAAe;AAC9B,QAAM,IAAI;AACV,SAAO,OAAO,EAAE,sBAAsB,eAAe,OAAO,EAAE,aAAa;AAC7E;AAEA,IAAI,SAAS,EAAG,yBAAwB;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { N as fitReferenceImage, R as serveFitReferenceWorker } from './media-fit-worker-CFK2z8LF.cjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { N as fitReferenceImage, R as serveFitReferenceWorker } from './media-fit-worker-CFK2z8LF.js';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {
|
|
2
|
+
fitReferenceImage,
|
|
3
|
+
serveFitReferenceWorker
|
|
4
|
+
} from "./chunk-R5VCITT3.js";
|
|
5
|
+
|
|
6
|
+
// src/tools/media-fit-worker.ts
|
|
7
|
+
var inWorker = () => {
|
|
8
|
+
const g = globalThis;
|
|
9
|
+
return typeof g.WorkerGlobalScope !== "undefined" && typeof g.document === "undefined";
|
|
10
|
+
};
|
|
11
|
+
if (inWorker()) serveFitReferenceWorker();
|
|
12
|
+
export {
|
|
13
|
+
fitReferenceImage,
|
|
14
|
+
serveFitReferenceWorker
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=fit-reference-worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools/media-fit-worker.ts"],"sourcesContent":["import { serveFitReferenceWorker } from './media-fit.js'\n\n/**\n * The Web Worker side of `fitReferenceInWorker`: the entry\n * `@dudko.dev/agent-web/fit-reference-worker`. Loaded as a worker it serves `fitReferenceImage`\n * by itself - a reference picture over the bounds decoded, scaled and encoded off the page's\n * thread:\n *\n * ```ts\n * // Vite\n * import FitWorker from '@dudko.dev/agent-web/fit-reference-worker?worker'\n * createAgent({ media: { imageModel, fitReference: fitReferenceInWorker(() => new FitWorker()) } })\n * ```\n *\n * One worker fits one picture and is terminated by the page when it has answered, or at the\n * agent's time bound. Web APIs only (`createImageBitmap`, `OffscreenCanvas`); nothing else is\n * imported, so the worker's chunk is a few kilobytes.\n */\nexport { serveFitReferenceWorker, fitReferenceImage } from './media-fit.js'\n\n// Served only inside a worker (not when a page, or a test, imports the module).\nconst inWorker = (): boolean => {\n const g = globalThis as { WorkerGlobalScope?: unknown; document?: unknown }\n return typeof g.WorkerGlobalScope !== 'undefined' && typeof g.document === 'undefined'\n}\n\nif (inWorker()) serveFitReferenceWorker()\n"],"mappings":";;;;;;AAqBA,IAAM,WAAW,MAAe;AAC9B,QAAM,IAAI;AACV,SAAO,OAAO,EAAE,sBAAsB,eAAe,OAAO,EAAE,aAAa;AAC7E;AAEA,IAAI,SAAS,EAAG,yBAAwB;","names":[]}
|