@takumi-rs/wasm2.22.153.7 kB
import { defaultStore, fetchImages, fetchImagesSettled } from "@takumi-rs/helpers/renderer";
import { fontFromUrl } from "@takumi-rs/helpers";
// pkg/takumi_wasm.js
/**
* The main renderer for Takumi image rendering engine.
*
* Every method takes `&self` and the fonts are copy-on-write, mirroring the
* napi bindings: a panic mid-call can't leave the wasm-bindgen borrow flag or
* the font store held, which would otherwise fail all subsequent calls.
*/
var Renderer$1 = class {
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
RendererFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_renderer_free(ptr, 0);
}
/**
* Reads what every scene of an animation needs fetched before it renders.
* @param {RenderAnimationOptions} options
* @param {ListedFont[] | null} [fonts]
* @returns {RenderNeeds}
*/
animationNeeds(options, fonts) {
const ret = wasm.renderer_animationNeeds(this.__wbg_ptr, options, isLikeNone(fonts) ? 0 : addToExternrefTable0(fonts));
if (ret[2]) throw takeFromExternrefTable0(ret[1]);
return takeFromExternrefTable0(ret[0]);
}
/**
* Loads the `@font-face` file `url` names, as `needs` reported it, leased to `lease` and evicted
* once no lease holds it and the renderer's cache needs the room.
* @param {string} url
* @param {Uint8Array | number[]} data
* @param {number | null} [lease]
*/
cacheFontFile(url, data, lease) {
const val3 = +(isLikeNone(lease) ? Number.MAX_SAFE_INTEGER : lease >>> 0);
let ptr0, len0, ptr1, len1;
try {
ptr0 = passStringToWasm0(url, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
len0 = WASM_VECTOR_LEN;
ptr1 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
len1 = WASM_VECTOR_LEN;
} catch (e) {
if (ptr1) wasm.__wbindgen_free(ptr1, len1 * 1, 1);
if (ptr0) wasm.__wbindgen_free(ptr0, len0 * 1, 1);
throw e;
}
const ret = wasm.renderer_cacheFontFile(this.__wbg_ptr, ptr0, len0, ptr1, len1, val3);
if (ret[1]) throw takeFromExternrefTable0(ret[0]);
}
/**
* Registers a font a render's `fonts` list loaded under `key`, its file leased to `lease` and
* evicted once no lease holds it and the renderer's cache needs the room.
* @param {Font} font
* @param {string} key
* @param {number | null} [lease]
* @returns {RegisteredFamily[]}
*/
cacheFont(font, key, lease) {
const val2 = +(isLikeNone(lease) ? Number.MAX_SAFE_INTEGER : lease >>> 0);
const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.renderer_cacheFont(this.__wbg_ptr, font, ptr0, len0, val2);
if (ret[2]) throw takeFromExternrefTable0(ret[1]);
return takeFromExternrefTable0(ret[0]);
}
/**
* What the renderer's caches hold and how their lookups went since it was created.
* @returns {CacheStats}
*/
cacheStats() {
const ret = wasm.renderer_cacheStats(this.__wbg_ptr);
if (ret[2]) throw takeFromExternrefTable0(ret[1]);
return takeFromExternrefTable0(ret[0]);
}
/**
* Whether the renderer still holds the `@font-face` file `url`, leasing it to `lease` when it
* does.
* @param {string} url
* @param {number} lease
* @returns {boolean}
*/
cachedFontFile(url, lease) {
const val2 = +lease;
const ptr0 = passStringToWasm0(url, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
return wasm.renderer_cachedFontFile(this.__wbg_ptr, ptr0, len0, val2) !== 0;
}
/**
* The families a registration under `key` added, while the renderer holds its file. Leases the
* file to `lease`, or with `pin` keeps it from eviction for good.
* @param {string} key
* @param {boolean} pin
* @param {number | null} [lease]
* @returns {RegisteredFamily[] | undefined}
*/
cachedFonts(key, pin, lease) {
const val2 = +pin;
const val3 = +(isLikeNone(lease) ? Number.MAX_SAFE_INTEGER : lease >>> 0);
const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.renderer_cachedFonts(this.__wbg_ptr, ptr0, len0, val2, val3);
if (ret[2]) throw takeFromExternrefTable0(ret[1]);
return takeFromExternrefTable0(ret[0]);
}
/**
* Removes every registered font, leaving the bundled fallback font.
*/
clearFonts() {
const ret = wasm.renderer_clearFonts(this.__wbg_ptr);
if (ret[1]) throw takeFromExternrefTable0(ret[0]);
}
/**
* Forgets the fonts registered under `keys` whose files no render leases, as a font with
* `cache: "none"` asks once its render settles, returning those keys and the ones nothing is
* registered under.
* @param {string[]} keys
* @returns {string[]}
*/
dropFonts(keys) {
const ptr0 = passArrayJsValueToWasm0(keys, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.renderer_dropFonts(this.__wbg_ptr, ptr0, len0);
var v2 = getArrayJsValueFromWasm0(ret[0], ret[1]);
wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
return v2;
}
/**
* Opens a set of leases that keeps the font files a render uses from eviction until
* `releaseFonts`.
* @returns {number}
*/
leaseFonts() {
return wasm.renderer_leaseFonts(this.__wbg_ptr) >>> 0;
}
/**
* Measures a node tree, or HTML, and returns layout information.
* @param {Node | string | { json: string }} source
* @param {RenderOptions | null} [options]
* @returns {MeasuredNode}
*/
measure(source, options) {
const ret = wasm.renderer_measure(this.__wbg_ptr, source, isLikeNone(options) ? 0 : addToExternrefTable0(options));
if (ret[2]) throw takeFromExternrefTable0(ret[1]);
return takeFromExternrefTable0(ret[0]);
}
/**
* Reads what a node tree, or HTML, needs fetched before it renders.
* @param {Node | string | { json: string }} source
* @param {RenderOptions | null} [options]
* @param {ListedFont[] | null} [fonts]
* @returns {RenderNeeds}
*/
needs(source, options, fonts) {
const ret = wasm.renderer_needs(this.__wbg_ptr, source, isLikeNone(options) ? 0 : addToExternrefTable0(options), isLikeNone(fonts) ? 0 : addToExternrefTable0(fonts));
if (ret[2]) throw takeFromExternrefTable0(ret[1]);
return takeFromExternrefTable0(ret[0]);
}
/**
* Creates a new Renderer instance.
* @param {RendererOptions | null} [options]
*/
constructor(options) {
const ret = wasm.renderer_new(isLikeNone(options) ? 0 : addToExternrefTable0(options));
if (ret[2]) throw takeFromExternrefTable0(ret[1]);
this.__wbg_ptr = ret[0];
RendererFinalization.register(this, this.__wbg_ptr, this);
return this;
}
/**
* Registers fonts into the renderer, returning the families each font produced.
* @param {Font} font
* @param {string | null} [key]
* @returns {RegisteredFamily[]}
*/
registerFont(font, key) {
var ptr0 = isLikeNone(key) ? 0 : passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
const ret = wasm.renderer_registerFont(this.__wbg_ptr, font, ptr0, len0);
if (ret[2]) throw takeFromExternrefTable0(ret[1]);
return takeFromExternrefTable0(ret[0]);
}
/**
* Releases the leases of the set `lease` names, evicting what no longer fits.
* @param {number} lease
*/
releaseFonts(lease) {
wasm.renderer_releaseFonts(this.__wbg_ptr, lease);
}
/**
* Renders a sequential animation timeline into a buffer.
* @param {RenderAnimationOptions} options
* @returns {Uint8Array<ArrayBuffer>}
*/
renderAnimation(options) {
const ret = wasm.renderer_renderAnimation(this.__wbg_ptr, options);
if (ret[3]) throw takeFromExternrefTable0(ret[2]);
var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
return v1;
}
/**
* Renders a node tree, or HTML, into a data URL.
*
* `raw` format is not supported for data URL.
* @param {Node | string | { json: string }} source
* @param {RenderOptions} options
* @returns {string}
*/
renderAsDataUrl(source, options) {
let deferred2_0;
let deferred2_1;
try {
const ret = wasm.renderer_renderAsDataUrl(this.__wbg_ptr, source, options);
var ptr1 = ret[0];
var len1 = ret[1];
if (ret[3]) {
ptr1 = 0;
len1 = 0;
throw takeFromExternrefTable0(ret[2]);
}
deferred2_0 = ptr1;
deferred2_1 = len1;
return getStringFromWasm0(ptr1, len1);
} finally {
wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
}
}
/**
* Renders a node tree, or HTML, into an SVG document string.
* @param {Node | string | { json: string }} source
* @param {SvgRenderOptions | null} [options]
* @returns {string}
*/
renderSvg(source, options) {
let deferred2_0;
let deferred2_1;
try {
const ret = wasm.renderer_renderSvg(this.__wbg_ptr, source, isLikeNone(options) ? 0 : addToExternrefTable0(options));
var ptr1 = ret[0];
var len1 = ret[1];
if (ret[3]) {
ptr1 = 0;
len1 = 0;
throw takeFromExternrefTable0(ret[2]);
}
deferred2_0 = ptr1;
deferred2_1 = len1;
return getStringFromWasm0(ptr1, len1);
} finally {
wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
}
}
/**
* Renders a node tree, or HTML, into an image buffer.
* @param {Node | string | { json: string }} source
* @param {RenderOptions | null} [options]
* @returns {Uint8Array<ArrayBuffer>}
*/
render(source, options) {
const ret = wasm.renderer_render(this.__wbg_ptr, source, isLikeNone(options) ? 0 : addToExternrefTable0(options));
if (ret[3]) throw takeFromExternrefTable0(ret[2]);
var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
return v1;
}
/**
* Removes every face registered under `family`, each `unicodeRange` subset alike, returning
* whether it had any.
* @param {string} family
* @returns {boolean}
*/
unregisterFont(family) {
const ptr0 = passStringToWasm0(family, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
return wasm.renderer_unregisterFont(this.__wbg_ptr, ptr0, len0) !== 0;
}
};
if (Symbol.dispose) Renderer$1.prototype[Symbol.dispose] = Renderer$1.prototype.free;
/**
* Keeps no glyphs in each `Renderer` created after this call when `bytes` is `0`, and glyphs again
* otherwise. Glyphs share the renderer's `cache.maxBytes` with every other kind of data.
*
* @deprecated Use `new Renderer({ cache: { glyphs: "none" } })`.
* @param {number} bytes
*/
function setGlyphCacheMaxBytes(bytes) {
wasm.setGlyphCacheMaxBytes(bytes);
}
function __wbg_get_imports() {
return {
__proto__: null,
"./takumi_wasm_bg.js": {
__proto__: null,
__wbg_Error_208446807d0d1e30: function(arg0, arg1) {
return Error(getStringFromWasm0(arg0, arg1));
},
__wbg_Number_ff192a72a0dcdf6d: function(arg0) {
return Number(arg0);
},
__wbg_String_8564e559799eccda: function(arg0, arg1) {
const ptr1 = passStringToWasm0(String(arg1), wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32((arg0 >>> 0) + 4, len1, true);
getDataViewMemory0().setInt32((arg0 >>> 0) + 0, ptr1, true);
},
__wbg___wbindgen_bigint_get_as_i64_11da4b52cd0aedef: function(arg0, arg1) {
const v = arg1;
const ret = typeof v === "bigint" ? v : void 0;
getDataViewMemory0().setBigInt64((arg0 >>> 0) + 8, isLikeNone(ret) ? BigInt(0) : ret, true);
getDataViewMemory0().setInt32((arg0 >>> 0) + 0, !isLikeNone(ret), true);
},
__wbg___wbindgen_boolean_get_4f1baf9a00be3c74: function(arg0) {
const v = arg0;
const ret = typeof v === "boolean" ? v : void 0;
return isLikeNone(ret) ? 16777215 : ret ? 1 : 0;
},
__wbg___wbindgen_debug_string_f249a2a76caa9a55: function(arg0, arg1) {
const ptr1 = passStringToWasm0(debugString(arg1), wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32((arg0 >>> 0) + 4, len1, true);
getDataViewMemory0().setInt32((arg0 >>> 0) + 0, ptr1, true);
},
__wbg___wbindgen_in_3f58a9d3b3a7eed2: function(arg0, arg1) {
return arg0 in arg1;
},
__wbg___wbindgen_is_bigint_5fa10641e039d3ef: function(arg0) {
return typeof arg0 === "bigint";
},
__wbg___wbindgen_is_function_741ff2bb612836f5: function(arg0) {
return typeof arg0 === "function";
},
__wbg___wbindgen_is_object_8b968c3ab8e96595: function(arg0) {
const val = arg0;
return typeof val === "object" && val !== null;
},
__wbg___wbindgen_is_string_fc456fee5d3317de: function(arg0) {
return typeof arg0 === "string";
},
__wbg___wbindgen_is_undefined_be5b34249ff1fc15: function(arg0) {
return arg0 === void 0;
},
__wbg___wbindgen_jsval_eq_38d7bfbe4cc84039: function(arg0, arg1) {
return arg0 === arg1;
},
__wbg___wbindgen_jsval_loose_eq_b2f214e2e4b30e36: function(arg0, arg1) {
return arg0 == arg1;
},
__wbg___wbindgen_number_get_934b640d0889af78: function(arg0, arg1) {
const obj = arg1;
const ret = typeof obj === "number" ? obj : void 0;
getDataViewMemory0().setFloat64((arg0 >>> 0) + 8, isLikeNone(ret) ? 0 : ret, true);
getDataViewMemory0().setInt32((arg0 >>> 0) + 0, !isLikeNone(ret), true);
},
__wbg___wbindgen_string_get_7ce8eee7fd327545: function(arg0, arg1) {
const obj = arg1;
const ret = typeof obj === "string" ? obj : void 0;
var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len1 = WASM_VECTOR_LEN;
getDataViewMemory0().setInt32((arg0 >>> 0) + 4, len1, true);
getDataViewMemory0().setInt32((arg0 >>> 0) + 0, ptr1, true);
},
__wbg___wbindgen_throw_4c88d8bf264fd984: function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
},
__wbg_call_40b008ba32f73991: function() {
return handleError(function(arg0, arg1) {
return arg0.call(arg1);
}, arguments);
},
__wbg_done_57e08d0be6e30c02: function(arg0) {
return arg0.done;
},
__wbg_entries_7bb1459bd9b5c2b9: function(arg0) {
return Object.entries(arg0);
},
__wbg_fromCodePoint_84793ae8d520c4b9: function() {
return handleError(function(arg0) {
return String.fromCodePoint(arg0 >>> 0);
}, arguments);
},
__wbg_get_2080c49015e35254: function() {
return handleError(function(arg0, arg1) {
return Reflect.get(arg0, arg1);
}, arguments);
},
__wbg_get_635eea311fa1a291: function() {
return handleError(function(arg0, arg1) {
return Reflect.get(arg0, arg1);
}, arguments);
},
__wbg_get_d7176cfb76d71114: function(arg0, arg1) {
return arg0[arg1 >>> 0];
},
__wbg_get_unchecked_e6325ad374eff861: function(arg0, arg1) {
return arg0[arg1 >>> 0];
},
__wbg_get_with_ref_key_fc601247060b7204: function(arg0, arg1) {
return arg0[arg1];
},
__wbg_instanceof_ArrayBuffer_12cdaa4161423e6b: function(arg0) {
let result;
try {
result = arg0 instanceof ArrayBuffer;
} catch (_) {
result = false;
}
return result;
},
__wbg_instanceof_Map_0b4fc8b62e73f163: function(arg0) {
let result;
try {
result = arg0 instanceof Map;
} catch (_) {
result = false;
}
return result;
},
__wbg_instanceof_Uint8Array_d7aeb0dcb3108fea: function(arg0) {
let result;
try {
result = arg0 instanceof Uint8Array;
} catch (_) {
result = false;
}
return result;
},
__wbg_isArray_bcf1376d0d732d08: function(arg0) {
return Array.isArray(arg0);
},
__wbg_isSafeInteger_1a35ba4d31e71d38: function(arg0) {
return Number.isSafeInteger(arg0);
},
__wbg_iterator_e4c5e8f68ada7b58: function() {
return Symbol.iterator;
},
__wbg_length_186163212ffe79c3: function(arg0) {
return arg0.length;
},
__wbg_length_b03a0fabb109b1e9: function(arg0) {
return arg0.length;
},
__wbg_new_13de428334042d26: function(arg0) {
return new Uint8Array(arg0);
},
__wbg_new_37eb45aaf5eeb820: function() {
return new Array();
},
__wbg_new_787b9fb330d55d78: function(arg0, arg1) {
return new Error(getStringFromWasm0(arg0, arg1));
},
__wbg_new_cd4348290afae586: function() {
return /* @__PURE__ */ new Object();
},
__wbg_next_178c1651c11432b3: function(arg0) {
return arg0.next;
},
__wbg_next_af5ac6a08bb0a717: function() {
return handleError(function(arg0) {
return arg0.next();
}, arguments);
},
__wbg_prototypesetcall_13162965d1fe7aa3: function(arg0, arg1, arg2) {
Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2);
},
__wbg_set_d2d33b52458e984a: function(arg0, arg1, arg2) {
arg0[arg1 >>> 0] = arg2;
},
__wbg_set_e4b9a833d288759a: function(arg0, arg1, arg2) {
arg0[arg1] = arg2;
},
__wbg_value_e0f328965e184931: function(arg0) {
return arg0.value;
},
__wbg_warn_9dfb2fd2f7fd3d4e: function() {
return handleError(function(arg0, arg1) {
let deferred0_0;
let deferred0_1;
try {
deferred0_0 = arg0;
deferred0_1 = arg1;
console.warn(getStringFromWasm0(arg0, arg1));
} finally {
wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
}
}, arguments);
},
__wbindgen_generic_0000000000000001: function(arg0) {
return arg0;
},
__wbindgen_generic_0000000000000002: function(arg0) {
return arg0;
},
__wbindgen_generic_0000000000000003: function(arg0, arg1) {
return getStringFromWasm0(arg0, arg1);
},
__wbindgen_generic_0000000000000004: function(arg0) {
return BigInt.asUintN(64, arg0);
},
__wbindgen_init_externref_table: function() {
const table = wasm.__wbindgen_externrefs;
table.set(0, void 0);
table.set(1024, void 0);
table.set(1025, null);
table.set(1026, true);
table.set(1027, false);
}
}
};
}
const RendererFinalization = typeof FinalizationRegistry === "undefined" ? {
register: () => {},
unregister: () => {}
} : new FinalizationRegistry((ptr) => wasm.__wbg_renderer_free(ptr, 1));
function addToExternrefTable0(obj) {
const idx = wasm.__externref_table_alloc();
wasm.__wbindgen_externrefs.set(idx, obj);
return idx;
}
function debugString(val) {
switch (typeof val) {
case "number":
case "boolean":
case "undefined": return `${val}`;
case "string": return JSON.stringify(val);
case "bigint": return `${val}n`;
case "symbol": return val.description !== void 0 ? `Symbol(${val.description})` : "Symbol";
case "function": return typeof val.name === "string" && val.name !== "" ? `Function(${val.name})` : "Function";
case "object": {
if (val === null) return "null";
if (Array.isArray(val)) return "[" + Array.from(val, debugString).join(", ") + "]";
if (val instanceof Error) return `${val.name}: ${val.message}\n${val.stack}`;
const toStringOutput = toString.call(val);
const className = /\[object ([^\]]+)\]/.exec(toStringOutput)?.[1];
if (className === void 0) return toStringOutput;
if (className === "Object") try {
return "Object(" + JSON.stringify(val) + ")";
} catch (_) {
return "Object";
}
return className;
}
}
}
function getArrayJsValueFromWasm0(ptr, len) {
ptr = ptr >>> 0;
const mem = getDataViewMemory0();
const result = [];
for (let i = ptr; i < ptr + 4 * len; i += 4) result.push(wasm.__wbindgen_externrefs.get(mem.getUint32(i, true)));
wasm.__externref_drop_slice(ptr, len);
return result;
}
function getArrayU8FromWasm0(ptr, len) {
ptr = ptr >>> 0;
return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
}
let cachedDataViewMemory0 = null;
function getDataViewMemory0() {
if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
return cachedDataViewMemory0;
}
function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return decodeText(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
return cachedUint8ArrayMemory0;
}
function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
const idx = addToExternrefTable0(e);
wasm.__wbindgen_exn_store(idx);
}
}
function isLikeNone(x) {
return x === void 0 || x === null;
}
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1, 1) >>> 0;
getUint8ArrayMemory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
function passArrayJsValueToWasm0(array, malloc) {
const ptr = malloc(array.length * 4, 4) >>> 0;
for (let i = 0; i < array.length; i++) {
const add = addToExternrefTable0(array[i]);
getDataViewMemory0().setUint32(ptr + 4 * i, add, true);
}
WASM_VECTOR_LEN = array.length;
return ptr;
}
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === void 0) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length, 1) >>> 0;
getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len, 1) >>> 0;
const mem = getUint8ArrayMemory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 127) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) arg = arg.slice(offset);
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
const ret = cachedTextEncoder.encodeInto(arg, view);
offset += ret.written;
ptr = realloc(ptr, len, offset, 1) >>> 0;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
function takeFromExternrefTable0(idx) {
const value = wasm.__wbindgen_externrefs.get(idx);
wasm.__externref_table_dealloc(idx);
return value;
}
let cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
cachedTextDecoder.decode();
const MAX_SAFARI_DECODE_BYTES = 2146435072;
let numBytesDecoded = 0;
function decodeText(bytes) {
numBytesDecoded += bytes.length;
if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
cachedTextDecoder.decode();
numBytesDecoded = bytes.length;
}
return cachedTextDecoder.decode(bytes);
}
const cachedTextEncoder = new TextEncoder();
if (!("encodeInto" in cachedTextEncoder)) cachedTextEncoder.encodeInto = function(arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
};
let WASM_VECTOR_LEN = 0;
let wasm;
function __wbg_finalize_init(instance, module) {
wasm = instance.exports;
cachedDataViewMemory0 = null;
cachedUint8ArrayMemory0 = null;
wasm.__wbindgen_start();
return wasm;
}
async function __wbg_load(module, imports) {
if (typeof Response === "function" && module instanceof Response) {
if (!module.ok) throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);
if (typeof WebAssembly.instantiateStreaming === "function") try {
return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) {
if (expectedResponseType(module.type) && module.headers.get("Content-Type") !== "application/wasm") console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
else throw e;
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) return {
instance,
module
};
else return instance;
}
function expectedResponseType(type) {
switch (type) {
case "basic":
case "cors":
case "default": return true;
}
return false;
}
}
function initSync(module) {
if (wasm !== void 0) return wasm;
if (module !== void 0) {
if (Object.getPrototypeOf(module) === Object.prototype) ({module} = module);
else console.warn("using deprecated parameters for `initSync()`; pass a single object instead");
}
const imports = __wbg_get_imports();
if (!(module instanceof WebAssembly.Module)) module = new WebAssembly.Module(module);
return __wbg_finalize_init(new WebAssembly.Instance(module, imports), module);
}
let __wbg_init_promise;
async function __wbg_init(module_or_path) {
if (wasm !== void 0) return wasm;
if (__wbg_init_promise === void 0) {
__wbg_init_promise = __wbg_init_once(module_or_path);
__wbg_init_promise.catch(() => {
__wbg_init_promise = void 0;
});
}
return __wbg_init_promise;
}
async function __wbg_init_once(module_or_path) {
if (module_or_path !== void 0) {
if (Object.getPrototypeOf(module_or_path) === Object.prototype) ({module_or_path} = module_or_path);
else console.warn("using deprecated parameters for the initialization function; pass a single object instead");
}
const imports = __wbg_get_imports();
if (typeof module_or_path === "string" || typeof Request === "function" && module_or_path instanceof Request || typeof URL === "function" && module_or_path instanceof URL) module_or_path = fetch(module_or_path);
const { instance, module } = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module);
}
// ../takumi-bindings-js/src/node-source.ts
const LONE_SURROGATE = /\p{Cs}/u;
/** The most arrays and objects `serde_json` reads nested inside each other. */
const MAX_DEPTH = 127;
/**
* A node tree as {@link JsonSource} when JSON keeps every value in it within {@link MAX_DEPTH}, the
* tree itself otherwise, and HTML as is.
* @internal
*/
function toNativeSource(source) {
if (typeof source === "string") return source;
const depths = /* @__PURE__ */ new WeakMap();
try {
return { json: JSON.stringify(source, function(key, value) {
if (this[key] !== value || LONE_SURROGATE.test(key) || !isJsonValue(value)) throw source;
if (typeof value === "object" && value !== null) {
const depth = (depths.get(this) ?? 0) + 1;
if (depth > MAX_DEPTH) throw source;
depths.set(value, depth);
}
return value ?? null;
}) };
} catch {
return source;
}
}
/** Whether JSON keeps `value` as the native side reads it from an object. */
function isJsonValue(value) {
switch (typeof value) {
case "string": return !LONE_SURROGATE.test(value);
case "number": return Number.isFinite(value);
case "boolean":
case "undefined": return true;
case "object": return value === null || Array.isArray(value) || [Object.prototype, null].includes(Object.getPrototypeOf(value));
default: return false;
}
}
// ../takumi-bindings-js/src/warning.ts
const shownCharacters = 20;
/** Prints `message` with `console.warn` in the form takumi's Rust warnings take. */
function warn(message) {
console.warn(`takumi: ${message}`);
}
/** The message of `cause`, which can be any thrown value. */
function messageOf(cause) {
if (cause instanceof Error) return cause.message;
try {
return String(cause);
} catch {
return "a value that has no text form";
}
}
/**
* Warns that the font `source` names, the URL of an `@font-face` file or of a font listed by URL and
* otherwise the key the renderer keeps the font under, failed to load with `error`.
*
* @internal
*/
function warnFontLoadFailed(source, error) {
warn(`Failed to load the font ${source}: ${messageOf(error)}`);
}
/**
* Warns about what a render found no font for, and about the images that failed to load.
*
* @internal
*/
function warnUndrawn(missingCharacters, unresolvedFamilies, failedImages) {
if (missingCharacters.length > 0) {
const shown = missingCharacters.slice(0, shownCharacters).join("");
const more = missingCharacters.length - shownCharacters;
warn(`No font draws "${shown}"${more > 0 ? ` or ${more} more characters` : ""}. Add a font that covers ${missingCharacters.length > 1 ? "them" : "it"} to \`fonts\`, or return one from \`loadFallbackFonts\`.`);
}
for (const family of unresolvedFamilies) warn(`No font provides the family "${family}". Add a font named "${family}" to \`fonts\`, or correct the name.`);
for (const { src, error } of failedImages) warn(`Failed to load the image ${src}: ${messageOf(error)}`);
}
// ../takumi-bindings-js/src/unicode-range.ts
/**
* The `unicodeRange` a font descriptor declares, or the deprecated `ranges`.
*
* @internal
*/
function unicodeRangeOf(font) {
if (typeof font !== "object" || font === null) return [];
if ("unicodeRange" in font && Array.isArray(font.unicodeRange)) return font.unicodeRange;
if ("ranges" in font && Array.isArray(font.ranges)) return font.ranges;
return [];
}
// ../takumi-bindings-js/src/renderer.ts
/**
* The scope of a render that lists the fonts under `listed` and saw `failed` fail. It leaves out
* what is empty, as a binding reads a present `undefined` as a value.
*
* @internal
*/
function fontScope(listed, failed) {
return {
...listed ? { listed } : {},
...failed.length > 0 ? { failed } : {}
};
}
function isBuffer(data) {
return data instanceof Uint8Array || data instanceof ArrayBuffer || typeof Buffer !== "undefined" && Buffer.isBuffer(data);
}
function asView(data) {
return data instanceof ArrayBuffer ? new Uint8Array(data) : data;
}
function extractFontBuffer(font) {
if (isBuffer(font)) return font;
if (typeof font.data !== "function") return font.data;
return font.data();
}
/** `font` with a URL string turned into a loader that downloads it with `fetch`. */
const toLoader = (font, fetch) => typeof font === "string" ? fontFromUrl(font, fetch) : font;
function createFontKey(font) {
if (isBuffer(font)) return font;
if ("key" in font && font.key) return font.key;
if (typeof font.data === "function") return faceKey(font);
return font.data;
}
/** The face descriptors `font` registers under, which a key must include to keep each face. */
function faceKey(font) {
const ranges = unicodeRangeOf(font).map(([start, end]) => `${start}-${end}`).join(",");
return [
font.subsetOf ?? font.name ?? "",
font.weight ?? "",
font.style ?? "",
ranges,
font.generic ?? ""
].join(":");
}
/**
* Normalize an {@link ImagesInput} into concrete, deduped {@link ImageSource} entries.
*
* @internal
*/
async function resolveImageLoaders(images) {
const { sources = [], cache } = Array.isArray(images) ? { sources: images } : images;
const bySrc = new Map(sources.map((image) => [image.src, image]));
return Promise.all([...bySrc.values()].map(async ({ src, data, cache: own }) => ({
src,
data: asView(typeof data === "function" ? await data() : data),
cache: own ?? cache
})));
}
/**
* The store a render's downloads go through. A caller's own `fetch` may send its credentials, so
* its downloads skip the store the renderers share.
*
* @internal
*/
function downloadStore(fetch) {
return fetch === void 0 ? defaultStore() : null;
}
/**
* A 53-bit hash of `bytes` with their length, after
* [cyrb53](https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js).
*/
function hashBytes(bytes) {
let h1 = 3735928559;
let h2 = 1103547991;
for (let index = 0; index < bytes.length; index++) {
const byte = bytes[index] ?? 0;
h1 = Math.imul(h1 ^ byte, 2654435761);
h2 = Math.imul(h2 ^ byte, 1597334677);
}
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
return `${bytes.length}:${(4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)}`;
}
/**
* Font registration shared by every backend: asks the backend whether it still holds a font before
* loading it, loads a font once however many renders ask for it at the same time, and turns a set
* of {@link FontLoader}s plus an {@link ImagesInput} into the `fontFamilies`/`images` the binding
* expects. The backend keeps the fonts and evicts them; this keeps no record of its own.
* @internal
*/
var FontRegistry = class {
backend;
loading = /* @__PURE__ */ new Map();
/** A key for each buffer passed as a font, by its bytes, since the backend only takes string keys. */
bufferKeys = /* @__PURE__ */ new WeakMap();
/** The keys of fonts loaded with `cache: "none"` that no render has asked to keep since. */
transient = /* @__PURE__ */ new Set();
/** The keys of `transient` whose renders settled, forgotten once no render leases their files. */
unkept = /* @__PURE__ */ new Set();
/** The leases `leased` holds open. */
open = /* @__PURE__ */ new Set();
constructor(backend) {
this.backend = backend;
}
/**
* Registers one font unless the backend still holds it, its file leased to the render that
* `lease` names. Without a lease, as `registerFont` registers, it is never evicted.
*/
async register(font, lease) {
const loader = toLoader(font);
const key = this.keyOf(loader);
const pinned = lease === void 0;
const keeps = pinned || isBuffer(loader) || loader.cache !== "none";
const held = this.backend.cachedFonts(key, pinned, lease);
if (held) {
if (keeps) this.keep(key);
return held;
}
const pending = this.loading.get(key);
if (pending) return pending.then(() => this.register(loader, lease));
const load = Promise.resolve(extractFontBuffer(loader)).then((data) => {
const view = asView(data);
const input = isBuffer(loader) ? view : {
...loader,
data: view
};
return lease === void 0 ? this.backend.registerFont(input, key) : this.backend.cacheFont(input, key, lease);
}).then((families) => {
if (keeps) this.keep(key);
else {
this.transient.add(key);
if (lease !== void 0 && !this.open.has(lease)) {
this.unkept.add(key);
this.dropSettled();
}
}
return families;
}).finally(() => this.loading.delete(key));
this.loading.set(key, load);
return load;
}
/** Loads each of `fonts` the backend does not hold under `load`, and returns whether any was loaded. */
async cache(fonts, load) {
const loaders = fonts.map((font) => toLoader(font)).filter((loader) => !this.backend.cachedFonts(this.keyOf(loader), false, load.lease));
await Promise.all(loaders.map((loader) => this.admit(loader, load)));
return loaders.length > 0;
}
/** {@link register} for a render's `fonts` list, adding an optional font that fails to `load` instead of rejecting. */
async admit(loader, load) {
try {
return await this.register(loader, load.lease);
} catch (error) {
if (isBuffer(loader) || !loader.optional) throw error;
const key = this.keyOf(loader);
load.failed.push(key);
warnFontLoadFailed(key, error);
return [];
}
}
/** Calls `use` with a set of leases, released once what it returns settles. */
async leased(use) {
const lease = this.backend.leaseFonts();
this.open.add(lease);
try {
return await use(lease);
} finally {
this.open.delete(lease);
this.backend.releaseFonts(lease);
}
}
/** Calls `use`, and forgets the fonts of `fonts` loaded with `cache: "none"` when it fails. */
async dropOnFailure(fonts, use) {
try {
return await use();
} catch (error) {
this.dropUnkept(fonts);
throw error;
}
}
/**
* Forgets the fonts of `fonts` loaded with `cache: "none"` that no render asked to keep, once no
* render leases their files. A render calls it after it settles, which also forgets the ones an
* earlier render left because another render leased them then.
*/
dropUnkept(fonts) {
for (const font of fonts ?? []) {
const key = this.key(font);
if (this.transient.has(key)) this.unkept.add(key);
}
this.dropSettled();
}
/** Forgets the fonts under `unkept` that no render leases, leaving the others for a later call. */
dropSettled() {
if (this.unkept.size === 0) return;
for (const key of this.backend.dropFonts([...this.unkept])) {
this.transient.delete(key);
this.unkept.delete(key);
}
}
/** Marks the font under `key` as one a render asked to keep. */
keep(key) {
this.transient.delete(key);
this.unkept.delete(key);
}
/** `fonts` as loaders, each URL string downloading with `fetch` as the render's other downloads do. */
loaders(fonts, fetch) {
return fonts.map((font) => toLoader(font, fetch));
}
/** `fonts` described for a backend's needs pass. None when no font declares a `unicodeRange`. */
listed(fonts) {
const loaders = fonts.map((font) => toLoader(font));
if (!loaders.some((loader) => unicodeRangeOf(loader).length > 0)) return;
return loaders.map((loader) => {
const key = this.keyOf(loader);
if (isBuffer(loader) || !("name" in loader)) return { key };
const { name, weight, style } = loader;
return {
key,
name,
weight,
style,
unicodeRange: unicodeRangeOf(loader)
};
});
}
/** `fonts` without the ones whose keys `failed` lists. */
without(fonts, failed) {
return failed.length > 0 ? fonts.filter((font) => !failed.includes(this.key(font))) : fonts;
}
/** The keys the backend keeps `fonts` under. */
keys(fonts) {
return fonts.map((font) => this.key(font));
}
/** Removes from `failed` the keys of `fonts`, which load again. */
clearFailures(fonts, failed) {
const keys = new Set(fonts.map((font) => this.key(font)));
failed.splice(0, failed.length, ...failed.filter((source) => !keys.has(source)));
}
/** The key the backend keeps `font` under. */
key(font) {
return this.keyOf(toLoader(font));
}
keyOf(loader) {
const key = createFontKey(loader);
if (typeof key === "string") return key;
const buffer = this.bufferKeyOf(key);
return isBuffer(loader) ? buffer : `${buffer}:${faceKey(loader)}`;
}
bufferKeyOf(buffer) {
const known = this.bufferKeys.get(buffer);
if (known) return known;
const assigned = `buffer:${hashBytes(asView(buffer))}`;
this.bufferKeys.set(buffer, assigned);
return assigned;
}
/** Leases each of the `@font-face` files `urls` the backend still holds to `lease`, returning the others. */
leaseFontFiles(urls, lease) {
return urls.filter((url) => !this.backend.cachedFontFile(url, lease));
}
/** Fetches the `@font-face` files `urls` with `fetch` and loads each under `load`, adding the ones that fail to it. */
async loadFontFiles(urls, fetch, load) {
const { images, failed } = await fetchImagesSettled({
...fetch,
urls,
store: downloadStore(fetch.fetch)
});
const fetched = new Map(images.map(({ src, data }) => [src, data]));
const errors = new Map(failed.map(({ src, error }) => [src, error]));
const failures = await Promise.all(urls.map(async (url) => {
const data = fetched.get(url);
if (data === void 0) return [[url, errors.get(url) ?? /* @__PURE__ */ new Error(`Fetching ${url} needs your own fetch`)]];
try {
await this.backend.cacheFontFile(url, asView(data), load.lease);
return [];
} catch (error) {
return [[url, error]];
}
}));
for (const [url, error] of failures.flat()) {
load.failed.push(url);
warnFontLoadFailed(url, error);
}
}
/** Leases each held file the backend still holds, and loads the others again, returning the ones that failed. */
async holdFiles({ urls, load }, lease) {
const evicted = this.leaseFontFiles(urls, lease);
return evicted.length > 0 ? load(evicted, lease) : [];
}
/**
* Registers `fonts`, resolves lazy `images`, and leases the `@font-face` `files` a prepared render
* loaded, then calls `use` with the `images` and `fontFamilies` the binding expects. Every font
* stays leased until what `use` returns settles. Explicit `fontFamilies` wins over the registered
* set.
*/
async resolveResources(fonts, images, fontFamilies, use, { files, implicitFamilies = false } = {}) {
const resolvedImages = images ? await resolveImageLoaders(images) : void 0;
const loaders = fonts?.map((font) => toLoader(font)) ?? [];
return this.leased(async (lease) => {
const load = {
lease,
failed: []
};
const families = await Promise.all(loaders.map((loader) => this.admit(loader, load)));
const failed = [...load.failed, ...files ? await this.holdFiles(files, lease) : []];
const registered = fonts && !implicitFamilies ? [...new Set(families.flat().map((family) => family.name))] : void 0;
return use({
images: resolvedImages,
fontFamilies: fontFamilies ?? registered,
fontScope: fontScope(loaders.map((loader) => this.keyOf(loader)), failed)
});
});
}
};
// ../takumi-bindings-js/src/prepared.ts
function splitExtras({ fonts, images, signal, fontFamilies, loadFallbackFonts, ...layout }) {
return {
extras: {
fonts,
images,
signal,
fontFamilies,
loadFallbackFonts
},
layout
};
}
/**
* The options and listed fonts a binding's `needs` takes for `request` on top of `layout`.
*
* @internal
*/
function needsArgs(layout, { images, fonts, fontFamilies, fontScope }) {
return [{
...layout,
images,
fontFamilies,
fontScope
}, fonts];
}
let createPrepared;
let stateOf;
/** A source with its layout options, the font subsets its text uses, and the images it draws, fetched. */
var Prepared = class Prepared {
#state;
constructor(state) {
this.#state = state;
}
static {
createPrepared = (state) => new Prepared(state);
stateOf = (prepared) => prepared.#state;
}
};
/**
* Reads what `source` needs under `layout`, then loads its font subsets and fetches the images `extras.images` lacks.
*
* @internal
*/
async function prepareSource(registry, source, layout, extras, needs) {
const state = await collect(registry, source, layout, extras, needs, true);
const failed = await registry.dropOnFailure(state.fonts, async () => {
const failedFonts = await registry.resolveResources(state.fonts && registry.loaders(state.fonts, {
...state.fontFetch,
signal: extras.signal
}), void 0, state.fontFamilies, (resolved) => resolved.fontScope.failed ?? [], { implicitFamilies: state.implicitFamilies });
extras.signal?.throwIfAborted();
return failedFonts;
});
return createPrepared({
...state,
fonts: state.fonts && registry.without(state.fonts, failed),
failedFontFiles: [...state.failedFontFiles, ...failed]
});
}
/**
* {@link prepareSource} without fetching, running `needs` only when `fonts` holds `unicodeRange` subsets.
*
* @internal
*/
async function readSource(registry, source, layout, extras, needs) {
return createPrepared(await collect(registry, source, layout, extras, needs, false));
}
/** The `items` not `seen` yet, which join them. */
function unseen(items, seen) {
const fresh = items.filter((item) => !seen.has(item));
for (const item of fresh) seen.add(item);
return fresh;
}
/**
* Leases or loads the fonts `first` reaches under `load`, then reads again with `read` and loads
* what that reaches, until a read reaches nothing new. Returns the last read. The `@font-face`
* files and optional fonts that fail join `load.failed`, which each read moves on from.
*
* A file that fails moves its rule on to its next `src`, and a listed subset without a glyph its
* `unicodeRange` claims moves the character on to the next family, as a browser does. The next read
* reports either. Each URL and listed font loads at most once, so a font the renderer evicts to fit
* another cannot loop the reads.
*/
async function loadReached(registry, first, read, { tried, fetch, uncachedOf, signal }, load) {
const reached = (urls = []) => fetch ? unseen(urls, tried) : [];
let latest = first;
for (;;) {
const pending = reached(latest?.fontFiles);
const evicted = registry.leaseFontFiles([...pending, ...reached(latest?.loadedFontFiles)], load.lease);
if (fetch && evicted.length > 0) await registry.loadFontFiles(evicted, fetch, load);
signal?.throwIfAborted();
const loadedListed = await registry.cache(uncachedOf?.(latest) ?? [], load);
signal?.throwIfAborted();
if (pending.length === 0 && evicted.length === 0 && !loadedListed) return latest;
latest = await read(load.failed);
}
}
async function collect(registry, source, layout, extras, needs, fetchMissing) {
const { fonts, fontFamilies, images = [], signal, loadFallbackFonts } = extras;
signal?.throwIfAborted();
const resolvedFonts = await fonts;
signal?.throwIfAborted();
const listed = resolvedFonts && registry.listed(resolvedFonts);
const listedKeys = resolvedFonts && registry.keys(resolvedFonts);
const request = {
fonts: listed,
fontFamilies,
fontScope: fontScope(listedKeys, [])
};
let first;
const read = () => first ??= Promise.resolve(needs(request));
const { sources = [], cache, throwOnError = true, fetchCache, ...fetchOptions } = Array.isArray(images) ? { sources: images } : images;
const provided = await resolveImageLoaders({
sources,
cache
});
const failedImages = [];
const loadImages = async (urls) => {
const options = {
...fetchOptions,
urls,
sources: provided,
store: downloadStore(fetchOptions.fetch),
fetchCache,
signal
};
if (throwOnError) return fetchImages(options);
const settled = await fetchImagesSettled(options);
failedImages.push(...settled.failed);
return settled.images;
};
const entries = (fetchMissing ? await loadImages((await read()).images) : provided).map((image) => ({
cache,
...image
}));
const readWithImages = () => entries.length > 0 ? needs({
...request,
images: entries
}) : read();
const firstReached = listed || fetchMissing ? await readWithImages() : void 0;
const tried = /* @__PURE__ */ new Set();
const cached = /* @__PURE__ */ new Set();
const failedFontFiles = [];
const fontFetch = {
...fetchOptions,
fetchCache
};
const fetch = {
...fontFetch,
signal
};
const reread = (failed) => needs({
...request,
fonts: listedWithout(listed, failed),
images: entries,
fontScope: fontScope(listedKeys, failed)
});
/** Loads every font of `fonts` as the render does, then calls `use` with the families it falls back through. */
const resolveFonts = (fonts, families, use, implicitFamilies = false) => registry.resolveResources(fonts && registry.loaders(fonts, fetch), void 0, families, ({ fontFamilies: resolved, fontScope: { listed: keys, failed = [] } }) => {
failedFontFiles.push(...failed);
return use(resolved, keys);
}, { implicitFamilies });
/** Reads the source with every font of `fonts` loaded, falling back through `families` as the render does. */
const readLoaded = (fonts, families, implicitFamilies = false) => resolveFonts(fonts, families, (resolved, keys) => needs({
images: entries,
fontFamilies: resolved,
fontScope: fontScope(keys, failedFontFiles)
}), implicitFamilies);
const fontFileFetch = fetchMissing ? fetch : void 0;
const load = (lease) => ({
lease,
failed: failedFontFiles
});
const settled = await registry.dropOnFailure(resolvedFonts, () => registry.leased(async (lease) => {
const reached = await loadReached(registry, firstReached, reread, {
tried,
fetch: fontFileFetch,
uncachedOf: (needs) => listed && resolvedFonts ? registry.loaders(unseen(needs?.fonts ?? [], cached).flatMap((id) => resolvedFonts[id] ?? []), fetch) : [],
signal
}, load(lease));
const loads = listed && reached?.fonts;
const subset = loads ? resolvedFonts?.filter((_, id) => loads.includes(id)) : resolvedFonts;
const kept = subset && registry.without(subset, failedFontFiles);
if (!fetchMissing && !loadFallbackFonts) return {
fonts: kept,
fontFamilies,
coverage: void 0,
added: [],
implicitFamilies: false
};
const coverage = listed && kept?.length === subset?.length ? reached : resolvedFonts ? await readLoaded(kept, fontFamilies) : reached ?? await readWithImages();
const characters = coverage?.missingCharacters ?? [];
const added = characters.length > 0 ? await loadFallbackFonts?.([...characters]) ?? [] : [];
signal?.throwIfAborted();
if (added.length === 0) return {
fonts: kept,
fontFamilies,
coverage,
added,
implicitFamilies: false
};
const loadable = kept && registry.without(kept, failedFontFiles);
registry.clearFailures(added, failedFontFiles);
return registry.dropOnFailure(added, async () => {
const implicitFamilies = !resolvedFonts && !fontFamilies;
const families = fontFamilies && [.../* @__PURE__ */ new Set([...fontFamilies, ...await resolveFonts(added, void 0, (registered = []) => registered)])];
const all = [...loadable ?? [], ...added];
const read = () => readLoaded(all, families, implicitFamilies);
return {
fonts: all,
fontFamilies: families,
coverage: await loadReached(registry, await read(), read, {
tried,
fetch: fontFileFetch,
signal
}, load(lease)),
added,
implicitFamilies
};
});
}));
warnUndrawn(settled.coverage?.missingCharacters ?? [], settled.coverage?.unresolvedFamilies ?? [], failedImages);
return {
source,
layout,
fonts: settled.fonts && registry.without(settled.fonts, failedFontFiles),
loadedFonts: [...(listed ? resolvedFonts?.filter((_, id) => cached.has(id)) : resolvedFonts) ?? [], ...settled.added],
fontFamilies: settled.fontFamilies,
implicitFamilies: settled.implicitFamilies,
images: entries,
fontFiles: [...tried].filter((url) => !failedFontFiles.includes(url)),
failedFontFiles,
fontFetch,
reread
};
}
/** `listed` with each font whose key `failed` lists left as a bare key, so a read reaches the family after it. */
function listedWithout(listed, failed) {
if (!listed || failed.length === 0) return listed;
return listed.map((font) => failed.includes(font.key) ? { key: font.key } : font);
}
/**
* Calls `call` with the binding options for rendering `prepared` with `output`. The layout `prepared` holds wins.
*
* @internal
*/
function renderPrepared(registry, prepared, output, call) {
const state = stateOf(prepared);
const { signal, ...encoding } = output;
signal?.throwIfAborted();
const fetch = {
...state.fontFetch,
signal
};
const files = state.fontFiles.length > 0 ? {
urls: state.fontFiles,
load: async (urls, lease) => {
const load = {
lease,
failed: [...state.failedFontFiles]
};
await registry.loadFontFiles(urls, fetch, load);
if (load.failed.length === state.failedFontFiles.length) return [];
const tried = /* @__PURE__ */ new Set([...state.fontFiles, ...load.failed]);
await loadReached(registry, await state.reread(load.failed), state.reread, {
tried,
fetch,
signal
}, load);
return load.failed.slice(state.failedFontFiles.length);
}
} : void 0;
return registry.resolveResources(state.fonts && registry.loaders(state.fonts, fetch), state.images, state.fontFamilies, ({ images, fontFamilies, fontScope: { listed, failed = [] } }) => {
signal?.throwIfAborted();
return call(state.source, {
...encoding,
...state.layout,
images,
fontFamilies,
fontScope: fontScope(listed, [...state.failedFontFiles, ...failed])
}, signal);
}, {
files,
implicitFamilies: state.implicitFamilies
}).finally(() => registry.dropUnkept(state.loadedFonts));
}
// src/export.ts
var Renderer = class {
inner;
fonts;
constructor(options) {
this.inner = new Renderer$1(options);
this.fonts = new FontRegistry(this.inner);
}
/** Reads what `source` needs under `options`, then loads its font subsets and fetches its images. */
prepare(source, options) {
const { extras, layout } = splitExtras(options ?? {});
const native = toNativeSource(source);
return prepareSource(this.fonts, native, layout, extras, (request) => this.inner.needs(native, ...needsArgs(layout, request)));
}
async render(source, options = {}) {
return renderPrepared(this.fonts, source instanceof Prepared ? source : await this.read(source, options), source instanceof Prepared ? options : { signal: options.signal }, (native, opts) => this.inner.render(native, opts));
}
async renderAsDataUrl(source, options = {}) {
return renderPrepared(this.fonts, source instanceof Prepared ? source : await this.read(source, options), source instanceof Prepared ? options : { signal: options.signal }, (native, opts) => this.inner.renderAsDataUrl(native, opts));
}
async renderSvg(source, options = {}) {
return renderPrepared(this.fonts, source instanceof Prepared ? source : await this.read(source, options), source instanceof Prepared ? options : { signal: options.signal }, (native, opts) => this.inner.renderSvg(native, opts));
}
async measure(source, options = {}) {
return renderPrepared(this.fonts, source instanceof Prepared ? source : await this.read(source, options), source instanceof Prepared ? options : { signal: options.signal }, (native, opts) => this.inner.measure(native, opts));
}
/** `source` read under `options` without fetching, for {@link render} and its siblings. */
read(source, options) {
const { extras, layout } = splitExtras(options);
const native = toNativeSource(source);
return readSource(this.fonts, native, layout, extras, (request) => this.inner.needs(native, ...needsArgs(layout, request)));
}
/** Reads what every scene needs under `options`, then loads their font subsets and fetches their images. */
prepareAnimation(options) {
return this.readAnimation(options, prepareSource);
}
async renderAnimation(source, options = {}) {
const prepared = source instanceof Prepared ? source : await this.readAnimation(source, readSource);
return renderPrepared(this.fonts, prepared, { signal: source instanceof Prepared ? options.signal : source.signal }, (scenes, opts) => this.inner.renderAnimation({
...opts,
scenes
}));
}
/** The scenes of `options` read with `collect`, which fetches their images when it prepares them. */
readAnimation(options, collect) {
const { extras, layout: { scenes, ...layout } } = splitExtras(options);
const sources = scenes.map((scene) => ({
...scene,
node: toNativeSource(scene.node)
}));
return collect(this.fonts, sources, layout, extras, (request) => this.inner.animationNeeds(...needsArgs({
...layout,
scenes: sources
}, request)));
}
registerFont(font) {
return this.fonts.register(font);
}
/**
* Removes every face registered under the family `name`, from any `registerFont` call and each
* `unicodeRange` subset alike; returns whether it had any. Takes a family `registerFont` returned
* as well. A later render that lists one of its fonts registers it again.
*/
unregisterFont(family) {
return this.inner.unregisterFont(family.name);
}
/** What the renderer's caches hold and how their lookups went since it was created. */
cacheStats() {
return this.inner.cacheStats();
}
/** Removes every registered font, leaving the bundled fallback font. */
clearFonts() {
this.inner.clearFonts();
}
/** Releases the underlying wasm renderer's memory. */
free() {
this.inner.free();
}
/** Releases the underlying wasm renderer's memory at the end of a `using` block. */
[Symbol.dispose]() {
this.free();
}
};
export { Prepared, Renderer, __wbg_init as default, __wbg_init as init, initSync, setGlyphCacheMaxBytes };
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.