@webex/ladon-ts 5.1.0 → 5.4.1

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.
@@ -1,6 +1,7 @@
1
- import * as a from "onnxruntime-web";
2
- import { isResolvedUri as d, toAbsoluteURI as m } from "./util.js";
3
- class c {
1
+ import * as i from "onnxruntime-web";
2
+ import { loadAndCacheFile as h, isResolvedUri as c, toAbsoluteURI as m } from "./util.js";
3
+ const k = "ort-wasm-simd-threaded.wasm";
4
+ class U {
4
5
  constructor() {
5
6
  this.modelSessions = {}, this.resolvedUriCache = /* @__PURE__ */ new Map();
6
7
  }
@@ -13,8 +14,8 @@ class c {
13
14
  async initializeWorker(e) {
14
15
  if (typeof Worker > "u")
15
16
  throw new Error("[ladon-ts] web workers are not supported in this environment");
16
- const r = await this.resolveUri(e, e.mask.workerUri), o = await (await fetch(r, { cache: "force-cache" })).text();
17
- return this.workerUrl = URL.createObjectURL(new Blob([o], { type: "text/javascript" })), new Worker(this.workerUrl, { type: "module" });
17
+ const r = await this.resolveUri(e, e.mask.workerUri), t = await (await fetch(r, { cache: "force-cache" })).text();
18
+ return this.workerUrl = URL.createObjectURL(new Blob([t], { type: "text/javascript" })), new Worker(this.workerUrl, { type: "module" });
18
19
  }
19
20
  /**
20
21
  * Terminate the worker.
@@ -30,13 +31,28 @@ class c {
30
31
  * @returns A promise that resolves when the model is preloaded.
31
32
  */
32
33
  async loadModel(e) {
33
- var i;
34
- const { mask: r, executionProviders: s } = e, o = await this.resolveUri(e, e.wasmUri);
35
- o && (a.env.wasm.wasmPaths = o), a.env.wasm.numThreads = 1;
36
- const t = await this.resolveUri(e, r.modelUri), n = s != null && s.length ? s : ["wasm"];
37
- return (i = this.modelSessions)[t] || (i[t] = await a.InferenceSession.create(t, {
38
- executionProviders: n
39
- })), await this.warmupModel(this.modelSessions[t], r.inputSize, r.modelRank), this.modelSessions[t];
34
+ const { mask: r, executionProviders: s } = e;
35
+ i.env.wasm.numThreads = 1;
36
+ const t = await this.resolveUri(e, e.wasmUri);
37
+ if (t)
38
+ try {
39
+ i.env.wasm.wasmBinary = await h(t + k);
40
+ } catch (w) {
41
+ console.warn("Failed to load or cache WASM file. Using WASM paths.", w), i.env.wasm.wasmPaths = t;
42
+ }
43
+ const a = await this.resolveUri(e, r.modelUri);
44
+ let o = this.modelSessions[a];
45
+ if (!o) {
46
+ const n = { executionProviders: s != null && s.length ? s : ["wasm"] };
47
+ try {
48
+ const l = await h(a);
49
+ o = await i.InferenceSession.create(l, n);
50
+ } catch (l) {
51
+ console.warn("Failed to load or cache model file. Using model URL.", l), o = await i.InferenceSession.create(a, n);
52
+ }
53
+ o = await i.InferenceSession.create(a, n);
54
+ }
55
+ return this.modelSessions[a] = o, await this.warmupModel(o, r.inputSize, r.modelRank), o;
40
56
  }
41
57
  /**
42
58
  * Preload the worker using the provided configuration.
@@ -59,23 +75,23 @@ class c {
59
75
  * @example
60
76
  * await warmupModel(session, inputSize, inputChannels, inputType);
61
77
  */
62
- async warmupModel(e, r = { width: 1280, height: 720 }, s = 3, o = "float32") {
63
- const t = r.height * r.width, n = new Float32Array(s * t).fill(0), i = new a.Tensor(o, n, [
78
+ async warmupModel(e, r = { width: 1280, height: 720 }, s = 3, t = "float32") {
79
+ const a = r.height * r.width, o = new Float32Array(s * a).fill(0), w = new i.Tensor(t, o, [
64
80
  1,
65
81
  s,
66
82
  r.height,
67
83
  r.width
68
- ]), l = { [e.inputNames[0]]: i };
84
+ ]), n = { [e.inputNames[0]]: w };
69
85
  if (s === 3) {
70
- const w = new Float32Array(t).fill(0), h = new a.Tensor(o, w, [
86
+ const l = new Float32Array(a).fill(0), d = new i.Tensor(t, l, [
71
87
  1,
72
88
  1,
73
89
  r.height,
74
90
  r.width
75
91
  ]);
76
- l[e.inputNames[1]] = h;
92
+ n[e.inputNames[1]] = d;
77
93
  }
78
- await e.run(l);
94
+ await e.run(n);
79
95
  }
80
96
  /**
81
97
  * Get the model session for the provided model URL.
@@ -113,7 +129,7 @@ class c {
113
129
  if (this.resolvedUriCache.has(r))
114
130
  return this.resolvedUriCache.get(r);
115
131
  let s;
116
- if (d(r) ? s = r : r.match(/\.[a-z0-9]+$/i) ? typeof e.assetUrlResolver == "function" && (s = await e.assetUrlResolver(r, e)) : s = m(r, e.baseUrl), !s)
132
+ if (c(r) ? s = r : r.match(/\.[a-z0-9]+$/i) ? typeof e.assetUrlResolver == "function" && (s = await e.assetUrlResolver(r, e)) : s = m(r, e.baseUrl), !s)
117
133
  throw new Error(`Failed to resolve asset URI: ${r}`);
118
134
  return this.resolvedUriCache.set(r, s), s;
119
135
  }
@@ -144,8 +160,8 @@ class c {
144
160
  return JSON.parse(JSON.stringify(s));
145
161
  }
146
162
  }
147
- const U = new c();
163
+ const f = new U();
148
164
  export {
149
- U as sharedResourceManager
165
+ f as sharedResourceManager
150
166
  };
151
167
  //# sourceMappingURL=shared-resource-manager.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-resource-manager.js","sources":["../../../src/lib/shared-resource-manager.ts"],"sourcesContent":["import * as ort from 'onnxruntime-web';\n\nimport { PreloadConfig, ResolutionConfig, WorkerConfig } from './config-types';\nimport { isResolvedUri, toAbsoluteURI } from './util';\n\n/**\n * Shared resource manager used to preload and share resources across different pipelines.\n * This is useful when multiple pipelines are using the same model or when the model needs\n * to be preloaded before the pipeline is created.\n */\nclass SharedResourceManager {\n private modelSessions: Record<string, ort.InferenceSession> = {};\n private worker?: Worker;\n private workerUrl?: string;\n\n // In-memory cache for resolved URLs\n private resolvedUriCache: Map<string, string> = new Map();\n\n /**\n * Initialize the worker using the provided configuration.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the worker is initialized.\n */\n public async initializeWorker(config: WorkerConfig): Promise<Worker> {\n if (typeof Worker === 'undefined') {\n throw new Error('[ladon-ts] web workers are not supported in this environment');\n }\n\n const scriptUri = await this.resolveUri(config, config.mask.workerUri);\n const response = await fetch(scriptUri, { cache: 'force-cache' });\n const workerSource = await response.text();\n\n this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: 'text/javascript' }));\n\n return new Worker(this.workerUrl, { type: 'module' });\n }\n\n /**\n * Terminate the worker.\n */\n public terminateWorker() {\n if (this.worker) {\n this.worker.terminate();\n this.worker = undefined;\n }\n }\n\n /**\n * Load the model using the provided configuration. This gets called by the worker when using\n * the worker generator.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the model is preloaded.\n */\n public async loadModel(config: PreloadConfig) {\n const { mask, executionProviders: providers } = config;\n\n const wasmPaths = await this.resolveUri(config, config.wasmUri);\n if (wasmPaths) {\n ort.env.wasm.wasmPaths = wasmPaths;\n }\n\n // Lock to a single thread to avoid performance issues.\n ort.env.wasm.numThreads = 1;\n\n const modelUrl = await this.resolveUri(config, mask.modelUri);\n const executionProviders = providers?.length ? providers : ['wasm'];\n\n // Use the model session cache to avoid creating multiple sessions for the same model.\n this.modelSessions[modelUrl] ||= await ort.InferenceSession.create(modelUrl, {\n executionProviders,\n });\n\n // Warmup the model with a dummy input to avoid latency when running the model for the first time.\n await this.warmupModel(this.modelSessions[modelUrl], mask.inputSize, mask.modelRank);\n\n return this.modelSessions[modelUrl];\n }\n\n /**\n * Preload the worker using the provided configuration.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the worker is preloaded.\n */\n public async preloadWorker(config: PreloadConfig) {\n const workerConfig = await this.prepareWorkerConfig(config);\n\n this.worker = await this.initializeWorker(workerConfig);\n this.worker.postMessage({ type: 'preload', config: workerConfig });\n }\n\n /**\n * Warmup the model session with a dummy input to avoid latency when running the model for the first time.\n *\n * @param {ort.InferenceSession} session The model session.\n * @param {ResolutionConfig} inputSize The input size of the model.\n * @param {number} inputChannels The number of input channels (e.g., RGB is 3).\n * @param {ort.Tensor.Type} inputType The input tensor type.\n * @returns {Promise<void>} A promise that resolves when the model is warmed up.\n * @example\n * await warmupModel(session, inputSize, inputChannels, inputType);\n */\n public async warmupModel(\n session: ort.InferenceSession,\n inputSize: ResolutionConfig = { width: 1280, height: 720 },\n inputChannels = 3,\n inputType: ort.Tensor.Type = 'float32'\n ): Promise<void> {\n const numPixels = inputSize.height * inputSize.width;\n const dummyInputData = new Float32Array(inputChannels * numPixels).fill(0);\n const dummyInput = new ort.Tensor(inputType, dummyInputData, [\n 1,\n inputChannels,\n inputSize.height,\n inputSize.width,\n ]);\n const feed = { [session.inputNames[0]]: dummyInput };\n\n // Use an additional dummy tensor if the model expects a previous mask.\n if (inputChannels === 3) {\n const dummyMaskData = new Float32Array(numPixels).fill(0);\n const prevMaskTensor = new ort.Tensor(inputType, dummyMaskData, [\n 1,\n 1,\n inputSize.height,\n inputSize.width,\n ]);\n feed[session.inputNames[1]] = prevMaskTensor;\n }\n\n // Run the model with the dummy input to warm it up.\n await session.run(feed);\n }\n\n /**\n * Get the model session for the provided model URL.\n *\n * @param {string} modelUrl The model URL.\n * @returns {ort.InferenceSession} The model session.\n * @example\n * const session = getModelSession(modelUrl);\n */\n public getModelSession(modelUrl: string) {\n return this.modelSessions[modelUrl];\n }\n\n /**\n * Resolves the full URL for a given asset. Non-file URIs are treated as paths\n * and resolved using the `toAbsoluteURI` method.\n *\n * @param config - The preload configuration.\n * @param assetUri - The asset URI from the config.\n * @returns The resolved full URL.\n */\n /**\n * Resolves the full URL for a given asset. Non-file URIs are treated as paths and resolved\n * using the `toAbsoluteURI` method. If the assetUri is already resolved, or if it's found in\n * cache, it will be returned directly. If an assetUrlResolver function is provided in the\n * configuration, it will be used to resolve the URL if the assetUri is not fully qualified,\n * a blob URL, or in the cache.\n *\n * @param config - The preload configuration.\n * @param assetUri - The asset URI from the config.\n * @returns The resolved full URL.\n */\n public async resolveUri(config: PreloadConfig, assetUri?: string): Promise<string> {\n if (!assetUri) {\n throw new Error('Asset URI is undefined.');\n }\n\n // Check if the URL is already cached\n if (this.resolvedUriCache.has(assetUri)) {\n return this.resolvedUriCache.get(assetUri) as string;\n }\n\n let resolvedUrl: string | undefined;\n\n if (isResolvedUri(assetUri)) {\n // If the assetUri is fully qualified or a blob URL, return it directly.\n // (Assets uris are resolved before being sent to the worker.)\n resolvedUrl = assetUri;\n } else if (!assetUri.match(/\\.[a-z0-9]+$/i)) {\n // Resolve as an absolute path to a non-file endpoint (e.g., wasmPaths).\n resolvedUrl = toAbsoluteURI(assetUri, config.baseUrl);\n } else if (typeof config.assetUrlResolver === 'function') {\n // Resolve via assetUrlResolver. This delegates the resolution logic to the caller.\n resolvedUrl = await config.assetUrlResolver(assetUri, config);\n }\n\n if (!resolvedUrl) {\n throw new Error(`Failed to resolve asset URI: ${assetUri}`);\n }\n\n // Cache the resolved URL\n this.resolvedUriCache.set(assetUri, resolvedUrl);\n\n return resolvedUrl;\n }\n\n public getWorker() {\n return this.worker;\n }\n\n public getWorkerUrl() {\n return this.workerUrl;\n }\n\n /**\n * Prepare the worker configuration by resolving the final URLs and paths to send to the\n * worker. This is necessary because we can't send functions to the worker. We also need to\n * remove the assetUrlResolver function from the configuration.\n *\n * @param config - The preload configuration.\n * @returns The worker configuration.\n */\n public async prepareWorkerConfig(config: PreloadConfig) {\n // Resolve and cache the URIs before sending the config to the worker. Future calls to the\n // resolveUri method will use the cache.\n const resolvedConfig: PreloadConfig = {\n ...config,\n mask: {\n ...config.mask,\n modelUri: await this.resolveUri(config, config.mask.modelUri),\n workerUri: await this.resolveUri(config, config.mask.workerUri),\n },\n wasmUri: await this.resolveUri(config, config.wasmUri),\n };\n\n // We can't send the assetUrlResolver function to the worker so we remove it from the config.\n const workerConfig = { ...resolvedConfig, assetUrlResolver: undefined };\n\n // This is a workaround to ensure the worker configuration can be sent to the worker.\n return JSON.parse(JSON.stringify(workerConfig));\n }\n}\n\n// Global instance of the shared resource manager.\nexport const sharedResourceManager = new SharedResourceManager();\n"],"names":["SharedResourceManager","config","scriptUri","workerSource","mask","providers","wasmPaths","ort","modelUrl","executionProviders","_a","workerConfig","session","inputSize","inputChannels","inputType","numPixels","dummyInputData","dummyInput","feed","dummyMaskData","prevMaskTensor","assetUri","resolv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+ {"version":3,"file":"shared-resource-manager.js","sources":["../../../src/lib/shared-resource-manager.ts"],"sourcesContent":["import * as ort from 'onnxruntime-web';\n\nimport { PreloadConfig, ResolutionConfig, WorkerConfig } from './config-types';\nimport { isResolvedUri, loadAndCacheFile, toAbsoluteURI } from './util';\n\n// There is only a single WASM file for all WebAssembly binaries now.\nconst ONNX_WASM_FILENAME = 'ort-wasm-simd-threaded.wasm';\n\n/**\n * Shared resource manager used to preload and share resources across different pipelines.\n * This is useful when multiple pipelines are using the same model or when the model needs\n * to be preloaded before the pipeline is created.\n */\nclass SharedResourceManager {\n private modelSessions: Record<string, ort.InferenceSession> = {};\n private worker?: Worker;\n private workerUrl?: string;\n\n // In-memory cache for resolved URLs\n private resolvedUriCache: Map<string, string> = new Map();\n\n /**\n * Initialize the worker using the provided configuration.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the worker is initialized.\n */\n public async initializeWorker(config: WorkerConfig): Promise<Worker> {\n if (typeof Worker === 'undefined') {\n throw new Error('[ladon-ts] web workers are not supported in this environment');\n }\n\n const scriptUri = await this.resolveUri(config, config.mask.workerUri);\n const response = await fetch(scriptUri, { cache: 'force-cache' });\n const workerSource = await response.text();\n\n this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: 'text/javascript' }));\n\n return new Worker(this.workerUrl, { type: 'module' });\n }\n\n /**\n * Terminate the worker.\n */\n public terminateWorker() {\n if (this.worker) {\n this.worker.terminate();\n this.worker = undefined;\n }\n }\n\n /**\n * Load the model using the provided configuration. This gets called by the worker when using\n * the worker generator.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the model is preloaded.\n */\n public async loadModel(config: PreloadConfig) {\n const { mask, executionProviders: providers } = config;\n\n // Lock to a single thread to avoid performance issues.\n ort.env.wasm.numThreads = 1;\n\n // Get the resolved paths for the WASM binary.\n const wasmPaths = await this.resolveUri(config, config.wasmUri);\n\n if (wasmPaths) {\n try {\n ort.env.wasm.wasmBinary = await loadAndCacheFile(wasmPaths + ONNX_WASM_FILENAME);\n } catch (error) {\n console.warn('Failed to load or cache WASM file. Using WASM paths.', error);\n ort.env.wasm.wasmPaths = wasmPaths;\n }\n }\n\n // Resolve the model URL.\n const modelUrl = await this.resolveUri(config, mask.modelUri);\n let modelSession = this.modelSessions[modelUrl];\n\n // If the model session is not already cached, create a new session and cache.\n if (!modelSession) {\n // Allows the user to specify the execution providers to use. The default is the WASM provider.\n // TODO: Add and test support for other execution providers.\n const executionProviders = providers?.length ? providers : ['wasm'];\n const sessionOptions = { executionProviders };\n\n // First try to get the model binary either from cache or by fetching and cacheing it.\n try {\n const modelBinary = await loadAndCacheFile(modelUrl);\n modelSession = await ort.InferenceSession.create(modelBinary, sessionOptions);\n } catch (error) {\n console.warn('Failed to load or cache model file. Using model URL.', error);\n modelSession = await ort.InferenceSession.create(modelUrl, sessionOptions);\n }\n modelSession = await ort.InferenceSession.create(modelUrl, sessionOptions);\n }\n\n // Cache the model session.\n this.modelSessions[modelUrl] = modelSession;\n\n // Warmup the model with a dummy input to avoid latency when running the model for the first time.\n await this.warmupModel(modelSession, mask.inputSize, mask.modelRank);\n\n return modelSession;\n }\n\n /**\n * Preload the worker using the provided configuration.\n *\n * @param config - The configuration object.\n * @returns A promise that resolves when the worker is preloaded.\n */\n public async preloadWorker(config: PreloadConfig) {\n const workerConfig = await this.prepareWorkerConfig(config);\n\n this.worker = await this.initializeWorker(workerConfig);\n this.worker.postMessage({ type: 'preload', config: workerConfig });\n }\n\n /**\n * Warmup the model session with a dummy input to avoid latency when running the model for the first time.\n *\n * @param {ort.InferenceSession} session The model session.\n * @param {ResolutionConfig} inputSize The input size of the model.\n * @param {number} inputChannels The number of input channels (e.g., RGB is 3).\n * @param {ort.Tensor.Type} inputType The input tensor type.\n * @returns {Promise<void>} A promise that resolves when the model is warmed up.\n * @example\n * await warmupModel(session, inputSize, inputChannels, inputType);\n */\n public async warmupModel(\n session: ort.InferenceSession,\n inputSize: ResolutionConfig = { width: 1280, height: 720 },\n inputChannels = 3,\n inputType: ort.Tensor.Type = 'float32'\n ): Promise<void> {\n const numPixels = inputSize.height * inputSize.width;\n const dummyInputData = new Float32Array(inputChannels * numPixels).fill(0);\n const dummyInput = new ort.Tensor(inputType, dummyInputData, [\n 1,\n inputChannels,\n inputSize.height,\n inputSize.width,\n ]);\n const feed = { [session.inputNames[0]]: dummyInput };\n\n // Use an additional dummy tensor if the model expects a previous mask.\n if (inputChannels === 3) {\n const dummyMaskData = new Float32Array(numPixels).fill(0);\n const prevMaskTensor = new ort.Tensor(inputType, dummyMaskData, [\n 1,\n 1,\n inputSize.height,\n inputSize.width,\n ]);\n feed[session.inputNames[1]] = prevMaskTensor;\n }\n\n // Run the model with the dummy input to warm it up.\n await session.run(feed);\n }\n\n /**\n * Get the model session for the provided model URL.\n *\n * @param {string} modelUrl The model URL.\n * @returns {ort.InferenceSession} The model session.\n * @example\n * const session = getModelSession(modelUrl);\n */\n public getModelSession(modelUrl: string) {\n return this.modelSessions[modelUrl];\n }\n\n /**\n * Resolves the full URL for a given asset. Non-file URIs are treated as paths\n * and resolved using the `toAbsoluteURI` method.\n *\n * @param config - The preload configuration.\n * @param assetUri - The asset URI from the config.\n * @returns The resolved full URL.\n */\n /**\n * Resolves the full URL for a given asset. Non-file URIs are treated as paths and resolved\n * using the `toAbsoluteURI` method. If the assetUri is already resolved, or if it's found in\n * cache, it will be returned directly. If an assetUrlResolver function is provided in the\n * configuration, it will be used to resolve the URL if the assetUri is not fully qualified,\n * a blob URL, or in the cache.\n *\n * @param config - The preload configuration.\n * @param assetUri - The asset URI from the config.\n * @returns The resolved full URL.\n */\n public async resolveUri(config: PreloadConfig, assetUri?: string): Promise<string> {\n if (!assetUri) {\n throw new Error('Asset URI is undefined.');\n }\n\n // Check if the URL is already cached\n if (this.resolvedUriCache.has(assetUri)) {\n return this.resolvedUriCache.get(assetUri) as string;\n }\n\n let resolvedUrl: string | undefined;\n\n if (isResolvedUri(assetUri)) {\n // If the assetUri is fully qualified or a blob URL, return it directly.\n // (Assets uris are resolved before being sent to the worker.)\n resolvedUrl = assetUri;\n } else if (!assetUri.match(/\\.[a-z0-9]+$/i)) {\n // Resolve as an absolute path to a non-file endpoint (e.g., wasmPaths).\n resolvedUrl = toAbsoluteURI(assetUri, config.baseUrl);\n } else if (typeof config.assetUrlResolver === 'function') {\n // Resolve via assetUrlResolver. This delegates the resolution logic to the caller.\n resolvedUrl = await config.assetUrlResolver(assetUri, config);\n }\n\n if (!resolvedUrl) {\n throw new Error(`Failed to resolve asset URI: ${assetUri}`);\n }\n\n // Cache the resolved URL\n this.resolvedUriCache.set(assetUri, resolvedUrl);\n\n return resolvedUrl;\n }\n\n public getWorker() {\n return this.worker;\n }\n\n public getWorkerUrl() {\n return this.workerUrl;\n }\n\n /**\n * Prepare the worker configuration by resolving the final URLs and paths to send to the\n * worker. This is necessary because we can't send functions to the worker. We also need to\n * remove the assetUrlResolver function from the configuration.\n *\n * @param config - The preload configuration.\n * @returns The worker configuration.\n */\n public async prepareWorkerConfig(config: PreloadConfig) {\n // Resolve and cache the URIs before sending the config to the worker. Future calls to the\n // resolveUri method will use the cache.\n const resolvedConfig: PreloadConfig = {\n ...config,\n mask: {\n ...config.mask,\n modelUri: await this.resolveUri(config, config.mask.modelUri),\n workerUri: await this.resolveUri(config, config.mask.workerUri),\n },\n wasmUri: await this.resolveUri(config, config.wasmUri),\n };\n\n // We can't send the assetUrlResolver function to the worker so we remove it from the config.\n const workerConfig = { ...resolvedConfig, assetUrlResolver: undefined };\n\n // This is a workaround to ensure the worker configuration can be sent to the worker.\n return JSON.parse(JSON.stringify(workerConfig));\n }\n}\n\n// Global instance of the shared resource manager.\nexport const sharedResourceManager = new SharedResourceManager();\n"],"names":["ONNX_WASM_FILENAME","SharedResourceManager","config","scriptUri","workerSource","mask","providers","ort","wasmPaths","loadAndCacheFile","error","modelUrl","modelSession","sessionOptions","modelBinary","workerConfig","session","inputSize","inputChannels","inputType","numPixels","dummyInputData","dummyInput","feed","dummyMaskData","prevMaskT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B,MAAa,oBAAoBzB,GAAuB;AAcpD,UAAMa,IAAe,EAAE,GAXe;AAAA,MAClC,GAAGb;AAAA,MACH,MAAM;AAAA,QACF,GAAGA,EAAO;AAAA,QACV,UAAU,MAAM,KAAK,WAAWA,GAAQA,EAAO,KAAK,QAAQ;AAAA,QAC5D,WAAW,MAAM,KAAK,WAAWA,GAAQA,EAAO,KAAK,SAAS;AAAA,MAClE;AAAA,MACA,SAAS,MAAM,KAAK,WAAWA,GAAQA,EAAO,OAAO;AAAA,IACzD,GAG0C,kBAAkB,OAAU;AAGtE,WAAO,KAAK,MAAM,KAAK,UAAUa,CAAY,CAAC;AAAA,EAAA;AAEtD;AAGa,MAAAe,IAAwB,IAAI7B,EAAsB;"}
@@ -61,3 +61,4 @@ export declare function linkProgram(gl: WebGL2RenderingContext, vertex_shader: W
61
61
  * @returns Whether the URI is already resolved.
62
62
  */
63
63
  export declare function isResolvedUri(uri: string): boolean;
64
+ export declare function loadAndCacheFile(fileUrl: string): Promise<ArrayBufferLike | Uint8Array>;
@@ -1,76 +1,76 @@
1
- var U = /* @__PURE__ */ ((o) => (o.Nearest = "nearest", o))(U || {});
2
- const A = (o, n, u, r, e) => {
3
- const l = new Uint8ClampedArray(r * e * 4), p = n / r, y = u / e, s = n * 4;
4
- let a = 0;
5
- for (let t = 0; t < e; t++) {
6
- const f = Math.floor(t * y) * s;
7
- for (let c = 0; c < r; c++) {
8
- const m = f + Math.floor(c * p) * 4;
9
- l[a++] = o[m], l[a++] = o[m + 1], l[a++] = o[m + 2], l[a++] = o[m + 3];
1
+ var C = /* @__PURE__ */ ((o) => (o.Nearest = "nearest", o))(C || {});
2
+ const E = (o, r, s, n, t) => {
3
+ const a = new Uint8ClampedArray(n * t * 4), m = r / n, M = s / t, i = r * 4;
4
+ let c = 0;
5
+ for (let e = 0; e < t; e++) {
6
+ const l = Math.floor(e * M) * i;
7
+ for (let f = 0; f < n; f++) {
8
+ const u = l + Math.floor(f * m) * 4;
9
+ a[c++] = o[u], a[c++] = o[u + 1], a[c++] = o[u + 2], a[c++] = o[u + 3];
10
10
  }
11
11
  }
12
- return l;
12
+ return a;
13
13
  };
14
- function d(o, n, u, r, e) {
15
- const l = new Uint8ClampedArray(r * e);
16
- if (n === r && u === e) {
17
- for (let s = 0; s < o.length; s++)
18
- l[s] = Math.min(Math.max(o[s], 0), 255);
19
- return l;
14
+ function I(o, r, s, n, t) {
15
+ const a = new Uint8ClampedArray(n * t);
16
+ if (r === n && s === t) {
17
+ for (let i = 0; i < o.length; i++)
18
+ a[i] = Math.min(Math.max(o[i], 0), 255);
19
+ return a;
20
20
  }
21
- const p = (n - 1) / (r - 1), y = (u - 1) / (e - 1);
22
- for (let s = 0; s < e; s++)
23
- for (let a = 0; a < r; a++) {
24
- const t = p * a, f = y * s, c = Math.floor(t), m = Math.floor(f), S = Math.min(Math.ceil(t), n - 1), x = Math.min(Math.ceil(f), u - 1), w = t - c, i = f - m, M = o[m * n + c], h = o[m * n + S], k = o[x * n + c], P = o[x * n + S], I = M * (1 - w) * (1 - i) + h * w * (1 - i) + k * (1 - w) * i + P * w * i;
25
- l[s * r + a] = Math.min(Math.max(I, 0), 255);
21
+ const m = (r - 1) / (n - 1), M = (s - 1) / (t - 1);
22
+ for (let i = 0; i < t; i++)
23
+ for (let c = 0; c < n; c++) {
24
+ const e = m * c, l = M * i, f = Math.floor(e), u = Math.floor(l), d = Math.min(Math.ceil(e), r - 1), S = Math.min(Math.ceil(l), s - 1), y = e - f, h = l - u, p = o[u * r + f], w = o[u * r + d], P = o[S * r + f], x = o[S * r + d], k = p * (1 - y) * (1 - h) + w * y * (1 - h) + P * (1 - y) * h + x * y * h;
25
+ a[i * n + c] = Math.min(Math.max(k, 0), 255);
26
26
  }
27
- return l;
27
+ return a;
28
28
  }
29
- function E(o, n, u, r, e) {
30
- const l = new Uint8ClampedArray(r * e), p = n / r, y = u / e, s = (t, f) => {
31
- if (t === 0) return 1;
32
- if (t < 0 && (t = -t), t < f) {
33
- const c = Math.PI * t;
34
- return f * Math.sin(c) * Math.sin(c / f) / (c * c);
29
+ function R(o, r, s, n, t) {
30
+ const a = new Uint8ClampedArray(n * t), m = r / n, M = s / t, i = (e, l) => {
31
+ if (e === 0) return 1;
32
+ if (e < 0 && (e = -e), e < l) {
33
+ const f = Math.PI * e;
34
+ return l * Math.sin(f) * Math.sin(f / l) / (f * f);
35
35
  }
36
36
  return 0;
37
- }, a = 3;
38
- for (let t = 0; t < e; t++)
39
- for (let f = 0; f < r; f++) {
40
- const c = f * p, m = t * y, S = Math.floor(c), x = Math.floor(m);
41
- let w = 0, i = 0;
42
- for (let M = x - a + 1; M <= x + a; M++)
43
- for (let h = S - a + 1; h <= S + a; h++)
44
- if (h >= 0 && h < n && M >= 0 && M < u) {
45
- const k = o[M * n + h], P = s(c - h, a) * s(m - M, a);
46
- w += k * P, i += P;
37
+ }, c = 3;
38
+ for (let e = 0; e < t; e++)
39
+ for (let l = 0; l < n; l++) {
40
+ const f = l * m, u = e * M, d = Math.floor(f), S = Math.floor(u);
41
+ let y = 0, h = 0;
42
+ for (let p = S - c + 1; p <= S + c; p++)
43
+ for (let w = d - c + 1; w <= d + c; w++)
44
+ if (w >= 0 && w < r && p >= 0 && p < s) {
45
+ const P = o[p * r + w], x = i(f - w, c) * i(u - p, c);
46
+ y += P * x, h += x;
47
47
  }
48
- l[t * r + f] = i !== 0 ? Math.round(w / i) : 0;
48
+ a[e * n + l] = h !== 0 ? Math.round(y / h) : 0;
49
49
  }
50
- return l;
50
+ return a;
51
51
  }
52
- const L = (o, n) => !n || o.startsWith("http") ? new URL(o).href : o ? n.replace(/\/+$/, "") + "/" + o.replace(/^\/+/, "") : n;
53
- function R(o, n, u) {
54
- const r = o.createShader(n);
55
- if (!r)
52
+ const A = (o, r) => !r || o.startsWith("http") ? new URL(o).href : o ? r.replace(/\/+$/, "") + "/" + o.replace(/^\/+/, "") : r;
53
+ function L(o, r, s) {
54
+ const n = o.createShader(r);
55
+ if (!n)
56
56
  throw new Error("[ladon-ts] - error creating shader");
57
- if (o.shaderSource(r, u), o.compileShader(r), !o.getShaderParameter(r, o.COMPILE_STATUS)) {
58
- const e = o.getShaderInfoLog(r) ?? "unknown error compiling shader.";
59
- throw new Error("[ladon-ts] - " + e);
57
+ if (o.shaderSource(n, s), o.compileShader(n), !o.getShaderParameter(n, o.COMPILE_STATUS)) {
58
+ const t = o.getShaderInfoLog(n) ?? "unknown error compiling shader.";
59
+ throw new Error("[ladon-ts] - " + t);
60
60
  }
61
- return r;
61
+ return n;
62
62
  }
63
- function C(o, n, u) {
64
- const r = o.createProgram();
65
- if (!r)
63
+ function T(o, r, s) {
64
+ const n = o.createProgram();
65
+ if (!n)
66
66
  throw new Error("[ladon-ts] - error creating GPU program");
67
- if (o.attachShader(r, n), o.attachShader(r, u), o.linkProgram(r), !o.getProgramParameter(r, o.LINK_STATUS)) {
68
- const e = o.getProgramInfoLog(r) ?? "unknown error linking program.";
69
- throw new Error("[ladon-ts] - " + e);
67
+ if (o.attachShader(n, r), o.attachShader(n, s), o.linkProgram(n), !o.getProgramParameter(n, o.LINK_STATUS)) {
68
+ const t = o.getProgramInfoLog(n) ?? "unknown error linking program.";
69
+ throw new Error("[ladon-ts] - " + t);
70
70
  }
71
- return r;
71
+ return n;
72
72
  }
73
- function T(o) {
73
+ function b(o) {
74
74
  if (o.startsWith("blob:"))
75
75
  return !0;
76
76
  try {
@@ -79,14 +79,33 @@ function T(o) {
79
79
  return !1;
80
80
  }
81
81
  }
82
+ async function U(o) {
83
+ const r = await caches.open("ladon-cache"), s = await r.match(o);
84
+ if (s)
85
+ return s.arrayBuffer();
86
+ const n = await fetch(o);
87
+ if (!n.ok)
88
+ throw new Error(`Failed to fetch file: ${o}`);
89
+ const t = n.headers.get("Content-Type") || "application/octet-stream";
90
+ if (!t.includes("application/wasm") && !t.includes("binary/octet-stream"))
91
+ throw new Error(`Unexpected MIME type: ${t} for ${o}`);
92
+ const a = await n.arrayBuffer(), m = new Response(a, {
93
+ headers: {
94
+ "Content-Type": t,
95
+ "Content-Length": a.byteLength.toString()
96
+ }
97
+ });
98
+ return await r.put(o, m), a;
99
+ }
82
100
  export {
83
- U as InterpolationMethod,
84
- d as bilinearUpsample,
85
- R as compileShader,
86
- T as isResolvedUri,
87
- E as lanczos3Upsample,
88
- C as linkProgram,
89
- A as resizeImage,
90
- L as toAbsoluteURI
101
+ C as InterpolationMethod,
102
+ I as bilinearUpsample,
103
+ L as compileShader,
104
+ b as isResolvedUri,
105
+ R as lanczos3Upsample,
106
+ T as linkProgram,
107
+ U as loadAndCacheFile,
108
+ E as resizeImage,
109
+ A as toAbsoluteURI
91
110
  };
92
111
  //# sourceMappingURL=util.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"util.js","sources":["../../../src/lib/util.ts"],"sourcesContent":["export enum InterpolationMethod {\n Nearest = 'nearest',\n}\n\n/**\n * Resizes an image from the source dimensions to target dimensions.\n *\n * @param {Uint8ClampedArray} imageData The source image data in Uint8ClampedArray format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The target image data in Uint8ClampedArray format.\n *\n * @example\n * const targetData = resizeImage(sourceData, 800, 600, 400, 300);\n *\n * @note The function uses a \"nearest neighbor\" algorithm for resizing,\n * which is fast but might not provide the best quality for all images.\n */\nexport const resizeImage = (\n imageData: Uint8ClampedArray,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n): Uint8ClampedArray => {\n const targetData = new Uint8ClampedArray(targetWidth * targetHeight * 4);\n const xRatio = srcWidth / targetWidth;\n const yRatio = srcHeight / targetHeight;\n const scaledSrcWidth = srcWidth * 4;\n let offset = 0;\n\n for (let y = 0; y < targetHeight; y++) {\n const srcY = Math.floor(y * yRatio) * scaledSrcWidth;\n for (let x = 0; x < targetWidth; x++) {\n const srcOffset = srcY + Math.floor(x * xRatio) * 4;\n\n targetData[offset++] = imageData[srcOffset];\n targetData[offset++] = imageData[srcOffset + 1];\n targetData[offset++] = imageData[srcOffset + 2];\n targetData[offset++] = imageData[srcOffset + 3];\n }\n }\n\n return targetData;\n};\n\n/**\n * Upsamples an image using the bilinear interpolation method. The input image is expected to be in\n * Float32Array format. The output image is in Uint8ClampedArray format. The input image is expected\n * to be in the [0, 1] range. The output image is in the [0, 255] range.\n *\n * @param {Float32Array} input The input image data in Float32Array format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The upsampled image data in Uint8ClampedArray format.\n *\n */\nexport function bilinearUpsample(\n input: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n) {\n const output = new Uint8ClampedArray(targetWidth * targetHeight);\n\n // If the source and target dimensions are the same, just copy the input to the output.\n // The output is expected to be in the [0, 255] range\n if (srcWidth === targetWidth && srcHeight === targetHeight) {\n for (let i = 0; i < input.length; i++) {\n output[i] = Math.min(Math.max(input[i], 0), 255);\n }\n return output;\n }\n\n const xRatio = (srcWidth - 1) / (targetWidth - 1);\n const yRatio = (srcHeight - 1) / (targetHeight - 1);\n\n for (let i = 0; i < targetHeight; i++) {\n for (let j = 0; j < targetWidth; j++) {\n const x = xRatio * j;\n const y = yRatio * i;\n\n const xL = Math.floor(x);\n const yL = Math.floor(y);\n const xH = Math.min(Math.ceil(x), srcWidth - 1);\n const yH = Math.min(Math.ceil(y), srcHeight - 1);\n\n const xWeight = x - xL;\n const yWeight = y - yL;\n\n const a = input[yL * srcWidth + xL];\n const b = input[yL * srcWidth + xH];\n const c = input[yH * srcWidth + xL];\n const d = input[yH * srcWidth + xH];\n\n const value =\n a * (1 - xWeight) * (1 - yWeight) +\n b * xWeight * (1 - yWeight) +\n c * (1 - xWeight) * yWeight +\n d * xWeight * yWeight;\n\n output[i * targetWidth + j] = Math.min(Math.max(value, 0), 255);\n }\n }\n\n return output;\n}\n\n/**\n * Upsamples an image using the Lanczos3 interpolation method. The input image is expected to be in\n * Float32Array format. The output image is in Uint8ClampedArray format. The input image is expected\n * to be in the [0, 1] range. The output image is in the [0, 255] range.\n *\n * @param {Float32Array} input The input image data in Float32Array format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The upsampled image data in Uint8ClampedArray format.\n */\nexport function lanczos3Upsample(\n input: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n) {\n const output = new Uint8ClampedArray(targetWidth * targetHeight);\n\n const xRatio = srcWidth / targetWidth;\n const yRatio = srcHeight / targetHeight;\n\n const lanczos = (x: number, a: number) => {\n if (x === 0) return 1;\n if (x < 0) x = -x;\n if (x < a) {\n const piX = Math.PI * x;\n return (a * Math.sin(piX) * Math.sin(piX / a)) / (piX * piX);\n }\n return 0;\n };\n\n const a = 3; // Lanczos parameter\n\n for (let i = 0; i < targetHeight; i++) {\n for (let j = 0; j < targetWidth; j++) {\n const x = j * xRatio;\n const y = i * yRatio;\n\n const xL = Math.floor(x);\n const yL = Math.floor(y);\n\n let value = 0;\n let weightSum = 0;\n\n for (let ky = yL - a + 1; ky <= yL + a; ky++) {\n for (let kx = xL - a + 1; kx <= xL + a; kx++) {\n if (kx >= 0 && kx < srcWidth && ky >= 0 && ky < srcHeight) {\n const pixel = input[ky * srcWidth + kx];\n const weight = lanczos(x - kx, a) * lanczos(y - ky, a);\n value += pixel * weight;\n weightSum += weight;\n }\n }\n }\n\n output[i * targetWidth + j] = weightSum !== 0 ? Math.round(value / weightSum) : 0;\n }\n }\n\n return output;\n}\n\nexport const toAbsoluteURI = (relativeURL: string, baseURL?: string) => {\n // adapted from - https://github.com/axios/axios/blob/fe7d09bb08fa1c0e414956b7fc760c80459b0a43/lib/helpers/combineURLs.js\n\n if (!baseURL || relativeURL.startsWith('http')) {\n return new URL(relativeURL).href;\n }\n\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n\nexport function compileShader(\n gl: WebGL2RenderingContext,\n shader_type: number,\n source: string\n): WebGLShader {\n const shader = gl.createShader(shader_type);\n\n if (!shader) {\n throw new Error('[ladon-ts] - error creating shader');\n }\n\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const error = gl.getShaderInfoLog(shader) ?? 'unknown error compiling shader.';\n throw new Error('[ladon-ts] - ' + error);\n }\n\n return shader;\n}\n\nexport function linkProgram(\n gl: WebGL2RenderingContext,\n vertex_shader: WebGLShader,\n fragment_shader: WebGLShader\n): WebGLProgram {\n const program = gl.createProgram();\n\n if (!program) {\n throw new Error('[ladon-ts] - error creating GPU program');\n }\n\n gl.attachShader(program, vertex_shader);\n gl.attachShader(program, fragment_shader);\n\n gl.linkProgram(program);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const error = gl.getProgramInfoLog(program) ?? 'unknown error linking program.';\n throw new Error('[ladon-ts] - ' + error);\n }\n\n return program;\n}\n\n/**\n * Determines if a URI is already resolved.\n * A resolved URI is either:\n * - A blob URL (starts with 'blob:')\n * - A fully qualified URL (e.g., http:// or https://)\n *\n * @param uri - The URI to check.\n * @returns Whether the URI is already resolved.\n */\nexport function isResolvedUri(uri: string): boolean {\n if (uri.startsWith('blob:')) {\n // Blob URIs are resolved\n return true;\n }\n\n try {\n // Throws if the URI is not a valid full URL\n new URL(uri);\n return true;\n } catch {\n // Not a fully qualified URL\n return false;\n }\n}\n"],"names":["InterpolationMethod","resizeImage","imageData","srcWidth","srcHeight","targetWidth","targetHeight","targetData","xRatio","yRatio","scaledSrcWidth","offset","y","srcY","x","srcOffset","bilinearUpsample","input","output","i","j","xL","yL","xH","yH","xWeight","yWeight","a","b","c","d","value","lanczos3Upsample","lanczos","piX","weightSum","ky","kx","pixel","weight","toAbsoluteURI","relativeURL","baseURL","compileShader","gl","shader_type","source","shader","error","linkProgram","vertex_shader","fragment_shader","program","isResolvedUri","uri"],"mappings":"AAAY,IAAAA,sBAAAA,OACRA,EAAA,UAAU,WADFA,IAAAA,KAAA,CAAA,CAAA;AAqBL,MAAMC,IAAc,CACvBC,GACAC,GACAC,GACAC,GACAC,MACoB;AACpB,QAAMC,IAAa,IAAI,kBAAkBF,IAAcC,IAAe,CAAC,GACjEE,IAASL,IAAWE,GACpBI,IAASL,IAAYE,GACrBI,IAAiBP,IAAW;AAClC,MAAIQ,IAAS;AAEb,WAASC,IAAI,GAAGA,IAAIN,GAAcM,KAAK;AACnC,UAAMC,IAAO,KAAK,MAAMD,IAAIH,CAAM,IAAIC;AACtC,aAASI,IAAI,GAAGA,IAAIT,GAAaS,KAAK;AAClC,YAAMC,IAAYF,IAAO,KAAK,MAAMC,IAAIN,CAAM,IAAI;AAEvC,MAAAD,EAAAI,GAAQ,IAAIT,EAAUa,CAAS,GAC1CR,EAAWI,GAAQ,IAAIT,EAAUa,IAAY,CAAC,GAC9CR,EAAWI,GAAQ,IAAIT,EAAUa,IAAY,CAAC,GAC9CR,EAAWI,GAAQ,IAAIT,EAAUa,IAAY,CAAC;AAAA,IAAA;AAAA,EAClD;AAGG,SAAAR;AACX;AAgBO,SAASS,EACZC,GACAd,GACAC,GACAC,GACAC,GACF;AACE,QAAMY,IAAS,IAAI,kBAAkBb,IAAcC,CAAY;AAI3D,MAAAH,MAAaE,KAAeD,MAAcE,GAAc;AACxD,aAASa,IAAI,GAAGA,IAAIF,EAAM,QAAQE;AACvB,MAAAD,EAAAC,CAAC,IAAI,KAAK,IAAI,KAAK,IAAIF,EAAME,CAAC,GAAG,CAAC,GAAG,GAAG;AAE5C,WAAAD;AAAA,EAAA;AAGL,QAAAV,KAAUL,IAAW,MAAME,IAAc,IACzCI,KAAUL,IAAY,MAAME,IAAe;AAEjD,WAASa,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AM,kBAAkBC,CAAK;AAAA,EAAA;AAGpC,SAAAD;AACX;AAEgB,SAAAE,EACZL,GACAM,GACAC,GACY;AACN,QAAAC,IAAUR,EAAG,cAAc;AAEjC,MAAI,CAACQ;AACK,UAAA,IAAI,MAAM,yCAAyC;AAQ7D,MALGR,EAAA,aAAaQ,GAASF,CAAa,GACnCN,EAAA,aAAaQ,GAASD,CAAe,GAExCP,EAAG,YAAYQ,CAAO,GAElB,CAACR,EAAG,oBAAoBQ,GAASR,EAAG,WAAW,GAAG;AAClD,UAAMI,IAAQJ,EAAG,kBAAkBQ,CAAO,KAAK;AACzC,UAAA,IAAI,MAAM,kBAAkBJ,CAAK;AAAA,EAAA;AAGpC,SAAAI;AACX;AAWO,SAASC,EAAcC,GAAsB;AAC5C,MAAAA,EAAI,WAAW,OAAO;AAEf,WAAA;AAGP,MAAA;AAEA,eAAI,IAAIA,CAAG,GACJ;AAAA,EAAA,QACH;AAEG,WAAA;AAAA,EAAA;AAEf;"}
1
+ {"version":3,"file":"util.js","sources":["../../../src/lib/util.ts"],"sourcesContent":["export enum InterpolationMethod {\n Nearest = 'nearest',\n}\n\n/**\n * Resizes an image from the source dimensions to target dimensions.\n *\n * @param {Uint8ClampedArray} imageData The source image data in Uint8ClampedArray format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The target image data in Uint8ClampedArray format.\n *\n * @example\n * const targetData = resizeImage(sourceData, 800, 600, 400, 300);\n *\n * @note The function uses a \"nearest neighbor\" algorithm for resizing,\n * which is fast but might not provide the best quality for all images.\n */\nexport const resizeImage = (\n imageData: Uint8ClampedArray,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n): Uint8ClampedArray => {\n const targetData = new Uint8ClampedArray(targetWidth * targetHeight * 4);\n const xRatio = srcWidth / targetWidth;\n const yRatio = srcHeight / targetHeight;\n const scaledSrcWidth = srcWidth * 4;\n let offset = 0;\n\n for (let y = 0; y < targetHeight; y++) {\n const srcY = Math.floor(y * yRatio) * scaledSrcWidth;\n for (let x = 0; x < targetWidth; x++) {\n const srcOffset = srcY + Math.floor(x * xRatio) * 4;\n\n targetData[offset++] = imageData[srcOffset];\n targetData[offset++] = imageData[srcOffset + 1];\n targetData[offset++] = imageData[srcOffset + 2];\n targetData[offset++] = imageData[srcOffset + 3];\n }\n }\n\n return targetData;\n};\n\n/**\n * Upsamples an image using the bilinear interpolation method. The input image is expected to be in\n * Float32Array format. The output image is in Uint8ClampedArray format. The input image is expected\n * to be in the [0, 1] range. The output image is in the [0, 255] range.\n *\n * @param {Float32Array} input The input image data in Float32Array format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The upsampled image data in Uint8ClampedArray format.\n *\n */\nexport function bilinearUpsample(\n input: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n) {\n const output = new Uint8ClampedArray(targetWidth * targetHeight);\n\n // If the source and target dimensions are the same, just copy the input to the output.\n // The output is expected to be in the [0, 255] range\n if (srcWidth === targetWidth && srcHeight === targetHeight) {\n for (let i = 0; i < input.length; i++) {\n output[i] = Math.min(Math.max(input[i], 0), 255);\n }\n return output;\n }\n\n const xRatio = (srcWidth - 1) / (targetWidth - 1);\n const yRatio = (srcHeight - 1) / (targetHeight - 1);\n\n for (let i = 0; i < targetHeight; i++) {\n for (let j = 0; j < targetWidth; j++) {\n const x = xRatio * j;\n const y = yRatio * i;\n\n const xL = Math.floor(x);\n const yL = Math.floor(y);\n const xH = Math.min(Math.ceil(x), srcWidth - 1);\n const yH = Math.min(Math.ceil(y), srcHeight - 1);\n\n const xWeight = x - xL;\n const yWeight = y - yL;\n\n const a = input[yL * srcWidth + xL];\n const b = input[yL * srcWidth + xH];\n const c = input[yH * srcWidth + xL];\n const d = input[yH * srcWidth + xH];\n\n const value =\n a * (1 - xWeight) * (1 - yWeight) +\n b * xWeight * (1 - yWeight) +\n c * (1 - xWeight) * yWeight +\n d * xWeight * yWeight;\n\n output[i * targetWidth + j] = Math.min(Math.max(value, 0), 255);\n }\n }\n\n return output;\n}\n\n/**\n * Upsamples an image using the Lanczos3 interpolation method. The input image is expected to be in\n * Float32Array format. The output image is in Uint8ClampedArray format. The input image is expected\n * to be in the [0, 1] range. The output image is in the [0, 255] range.\n *\n * @param {Float32Array} input The input image data in Float32Array format.\n * @param {number} srcWidth The width of the source image.\n * @param {number} srcHeight The height of the source image.\n * @param {number} targetWidth The width of the target image.\n * @param {number} targetHeight The height of the target image.\n *\n * @returns {Uint8ClampedArray} The upsampled image data in Uint8ClampedArray format.\n */\nexport function lanczos3Upsample(\n input: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number\n) {\n const output = new Uint8ClampedArray(targetWidth * targetHeight);\n\n const xRatio = srcWidth / targetWidth;\n const yRatio = srcHeight / targetHeight;\n\n const lanczos = (x: number, a: number) => {\n if (x === 0) return 1;\n if (x < 0) x = -x;\n if (x < a) {\n const piX = Math.PI * x;\n return (a * Math.sin(piX) * Math.sin(piX / a)) / (piX * piX);\n }\n return 0;\n };\n\n const a = 3; // Lanczos parameter\n\n for (let i = 0; i < targetHeight; i++) {\n for (let j = 0; j < targetWidth; j++) {\n const x = j * xRatio;\n const y = i * yRatio;\n\n const xL = Math.floor(x);\n const yL = Math.floor(y);\n\n let value = 0;\n let weightSum = 0;\n\n for (let ky = yL - a + 1; ky <= yL + a; ky++) {\n for (let kx = xL - a + 1; kx <= xL + a; kx++) {\n if (kx >= 0 && kx < srcWidth && ky >= 0 && ky < srcHeight) {\n const pixel = input[ky * srcWidth + kx];\n const weight = lanczos(x - kx, a) * lanczos(y - ky, a);\n value += pixel * weight;\n weightSum += weight;\n }\n }\n }\n\n output[i * targetWidth + j] = weightSum !== 0 ? Math.round(value / weightSum) : 0;\n }\n }\n\n return output;\n}\n\nexport const toAbsoluteURI = (relativeURL: string, baseURL?: string) => {\n // adapted from - https://github.com/axios/axios/blob/fe7d09bb08fa1c0e414956b7fc760c80459b0a43/lib/helpers/combineURLs.js\n\n if (!baseURL || relativeURL.startsWith('http')) {\n return new URL(relativeURL).href;\n }\n\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n\nexport function compileShader(\n gl: WebGL2RenderingContext,\n shader_type: number,\n source: string\n): WebGLShader {\n const shader = gl.createShader(shader_type);\n\n if (!shader) {\n throw new Error('[ladon-ts] - error creating shader');\n }\n\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const error = gl.getShaderInfoLog(shader) ?? 'unknown error compiling shader.';\n throw new Error('[ladon-ts] - ' + error);\n }\n\n return shader;\n}\n\nexport function linkProgram(\n gl: WebGL2RenderingContext,\n vertex_shader: WebGLShader,\n fragment_shader: WebGLShader\n): WebGLProgram {\n const program = gl.createProgram();\n\n if (!program) {\n throw new Error('[ladon-ts] - error creating GPU program');\n }\n\n gl.attachShader(program, vertex_shader);\n gl.attachShader(program, fragment_shader);\n\n gl.linkProgram(program);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const error = gl.getProgramInfoLog(program) ?? 'unknown error linking program.';\n throw new Error('[ladon-ts] - ' + error);\n }\n\n return program;\n}\n\n/**\n * Determines if a URI is already resolved.\n * A resolved URI is either:\n * - A blob URL (starts with 'blob:')\n * - A fully qualified URL (e.g., http:// or https://)\n *\n * @param uri - The URI to check.\n * @returns Whether the URI is already resolved.\n */\nexport function isResolvedUri(uri: string): boolean {\n if (uri.startsWith('blob:')) {\n // Blob URIs are resolved\n return true;\n }\n\n try {\n // Throws if the URI is not a valid full URL\n new URL(uri);\n return true;\n } catch {\n // Not a fully qualified URL\n return false;\n }\n}\n\nexport async function loadAndCacheFile(fileUrl: string): Promise<ArrayBufferLike | Uint8Array> {\n const cache = await caches.open('ladon-cache');\n\n // Try to get the file from cache using its full URL\n const cachedResponse = await cache.match(fileUrl);\n if (cachedResponse) {\n return cachedResponse.arrayBuffer();\n }\n\n // If not in cache, fetch and cache the file\n const response = await fetch(fileUrl);\n\n // Ensure the response is valid\n if (!response.ok) {\n throw new Error(`Failed to fetch file: ${fileUrl}`);\n }\n\n const contentType = response.headers.get('Content-Type') || 'application/octet-stream';\n\n // Validate expected MIME types\n if (!contentType.includes('application/wasm') && !contentType.includes('binary/octet-stream')) {\n throw new Error(`Unexpected MIME type: ${contentType} for ${fileUrl}`);\n }\n\n const fileBinary = await response.arrayBuffer();\n\n // Cache the response with proper headers\n const cachedResponseWithHeaders = new Response(fileBinary, {\n headers: {\n 'Content-Type': contentType,\n 'Content-Length': fileBinary.byteLength.toString(),\n },\n });\n\n // Store the response in the cache using the full URL as the key\n await cache.put(fileUrl, cachedResponseWithHeaders);\n\n return fileBinary;\n}\n"],"names":["InterpolationMethod","resizeImage","imageData","srcWidth","srcHeight","targetWidth","targetHeight","targetData","xRatio","yRatio","scaledSrcWidth","offset","y","srcY","x","srcOffset","bilinearUpsample","input","output","j","xL","yL","xH","yH","xWeight","yWeight","a","b","c","d","value","lanczos3Upsample","lanczos","piX","i","weightSum","ky","kx","pixel","weight","toAbsoluteURI","relativeURL","baseURL","compileShader","gl","shader_type","source","shader","error","linkProgram","vertex_shader","fragment_shader","program","isResolvedUri","uri","loadAndCacheFile","fileUrl","cache","cachedResponse","response","contentType","fileBinary","cachedResponseWithHeaders"],"mappings":"AAAY,IAAAA,sBAAAA,OACRA,EAAA,UAAU,WADFA,IAAAA,KAAA,CAAA,CAAA;AAqBL,MAAMC,IAAc,CACvBC,GACAC,GACAC,GACAC,GACAC,MACoB;AACpB,QAAMC,IAAa,IAAI,kBAAkBF,IAAcC,IAAe,CAAC,GACjEE,IAASL,IAAWE,GACpBI,IAASL,I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,EAAG,kBAAkBQ,CAAO,KAAK;AACzC,UAAA,IAAI,MAAM,kBAAkBJ,CAAK;AAAA,EAAA;AAGpC,SAAAI;AACX;AAWO,SAASC,EAAcC,GAAsB;AAC5C,MAAAA,EAAI,WAAW,OAAO;AAEf,WAAA;AAGP,MAAA;AAEA,eAAI,IAAIA,CAAG,GACJ;AAAA,EAAA,QACH;AAEG,WAAA;AAAA,EAAA;AAEf;AAEA,eAAsBC,EAAiBC,GAAwD;AAC3F,QAAMC,IAAQ,MAAM,OAAO,KAAK,aAAa,GAGvCC,IAAiB,MAAMD,EAAM,MAAMD,CAAO;AAChD,MAAIE;AACA,WAAOA,EAAe,YAAY;AAIhC,QAAAC,IAAW,MAAM,MAAMH,CAAO;AAGhC,MAAA,CAACG,EAAS;AACV,UAAM,IAAI,MAAM,yBAAyBH,CAAO,EAAE;AAGtD,QAAMI,IAAcD,EAAS,QAAQ,IAAI,cAAc,KAAK;AAGxD,MAAA,CAACC,EAAY,SAAS,kBAAkB,KAAK,CAACA,EAAY,SAAS,qBAAqB;AACxF,UAAM,IAAI,MAAM,yBAAyBA,CAAW,QAAQJ,CAAO,EAAE;AAGnE,QAAAK,IAAa,MAAMF,EAAS,YAAY,GAGxCG,IAA4B,IAAI,SAASD,GAAY;AAAA,IACvD,SAAS;AAAA,MACL,gBAAgBD;AAAA,MAChB,kBAAkBC,EAAW,WAAW,SAAS;AAAA,IAAA;AAAA,EACrD,CACH;AAGK,eAAAJ,EAAM,IAAID,GAASM,CAAyB,GAE3CD;AACX;"}
@@ -1 +1 @@
1
- export declare const LIB_VERSION = "5.1.0";
1
+ export declare const LIB_VERSION = "5.4.1";
@@ -1,4 +1,4 @@
1
- const o = "5.1.0";
1
+ const o = "5.4.1";
2
2
  export {
3
3
  o as LIB_VERSION
4
4
  };
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sources":["../../../src/lib/version.ts"],"sourcesContent":["export const LIB_VERSION = '5.1.0';\n"],"names":["LIB_VERSION"],"mappings":"AAAO,MAAMA,IAAc;"}
1
+ {"version":3,"file":"version.js","sources":["../../../src/lib/version.ts"],"sourcesContent":["export const LIB_VERSION = '5.4.1';\n"],"names":["LIB_VERSION"],"mappings":"AAAO,MAAMA,IAAc;"}