@open-pencil/html-engine 0.0.0-stage → 0.17.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/chunks/engine.js +350 -0
- package/dist/chunks/engine.js.map +1 -0
- package/dist/chunks/index.js +237 -0
- package/dist/chunks/index.js.map +1 -0
- package/dist/index.d.ts +233 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/package.json +34 -4
- package/src/engine.ts +282 -0
- package/src/images.ts +136 -0
- package/src/index.ts +14 -0
- package/src/load.ts +53 -0
- package/src/runtime.ts +257 -0
- package/src/schema.ts +70 -0
- package/wasm/THIRD-PARTY-NOTICES.md +5857 -0
- package/wasm/html-engine.wasm +0 -0
- package/wasm/html-engine.wasm.sha256 +1 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { HTMLEngine } from "./engine.js";
|
|
2
|
+
import { createHeadlessCSSRuntime, parseFontFaceRules, parseStylesheetImports } from "@open-pencil/dom-css";
|
|
3
|
+
//#region src/load.ts
|
|
4
|
+
let locator = () => import.meta.resolve("@open-pencil/html-engine/wasm/html-engine.wasm");
|
|
5
|
+
let loading = null;
|
|
6
|
+
/**
|
|
7
|
+
* How long a remote module may take to arrive, so a request that never settles cannot hold every
|
|
8
|
+
* later load waiting on it; a failed load is retried by the next caller.
|
|
9
|
+
*/
|
|
10
|
+
const MODULE_LOAD_TIMEOUT_MS = 6e4;
|
|
11
|
+
/** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */
|
|
12
|
+
function setHTMLEngineLocator(locate) {
|
|
13
|
+
locator = locate;
|
|
14
|
+
loading = null;
|
|
15
|
+
}
|
|
16
|
+
async function readModule(url) {
|
|
17
|
+
if (!url.startsWith("file:")) {
|
|
18
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(MODULE_LOAD_TIMEOUT_MS) });
|
|
19
|
+
if (!response.ok) throw new Error(`html-engine.wasm failed to load from ${url}: ${response.status}`);
|
|
20
|
+
return response.arrayBuffer();
|
|
21
|
+
}
|
|
22
|
+
const { readFile } = await import(
|
|
23
|
+
/* @vite-ignore */
|
|
24
|
+
"node:fs/promises"
|
|
25
|
+
);
|
|
26
|
+
const file = await readFile(new URL(url)).catch((error) => {
|
|
27
|
+
throw new Error(`html-engine.wasm is missing at ${url}; build it with bun run build in packages/html-engine`, { cause: error });
|
|
28
|
+
});
|
|
29
|
+
return file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength);
|
|
30
|
+
}
|
|
31
|
+
/** The engine, loaded once; a failed load is retried by the next caller. */
|
|
32
|
+
function loadHTMLEngine() {
|
|
33
|
+
if (loading) return loading;
|
|
34
|
+
const load = readModule(locator()).then((bytes) => HTMLEngine.instantiate(bytes));
|
|
35
|
+
loading = load;
|
|
36
|
+
load.catch(() => {
|
|
37
|
+
if (loading === load) loading = null;
|
|
38
|
+
});
|
|
39
|
+
return load;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/runtime.ts
|
|
43
|
+
/** The viewport a document is laid out in when the caller names none, as HTML import uses. */
|
|
44
|
+
const DEFAULT_VIEWPORT = {
|
|
45
|
+
width: 1440,
|
|
46
|
+
height: 900
|
|
47
|
+
};
|
|
48
|
+
function isStylesheet(resource) {
|
|
49
|
+
return resource.contentType?.split(";")[0]?.trim().toLowerCase() === "text/css";
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* A fetch that also reads the page's `@font-face` rules, from its own CSS and every stylesheet it
|
|
53
|
+
* fetches, and passes each font they load to `onFontFace` as the engine receives it.
|
|
54
|
+
*/
|
|
55
|
+
function fontFaceFetch(engine, cssText, options) {
|
|
56
|
+
const { fetch, onFontFace } = options;
|
|
57
|
+
if (!fetch || !onFontFace) return fetch;
|
|
58
|
+
const rules = /* @__PURE__ */ new Map();
|
|
59
|
+
const stylesheets = /* @__PURE__ */ new Set();
|
|
60
|
+
const delivered = /* @__PURE__ */ new Set();
|
|
61
|
+
const learn = (css, base) => {
|
|
62
|
+
for (const rule of parseFontFaceRules(css, base)) for (const source of rule.sources) rules.set(source, [...rules.get(source) ?? [], rule]);
|
|
63
|
+
for (const url of parseStylesheetImports(css, base)) stylesheets.add(url);
|
|
64
|
+
};
|
|
65
|
+
learn(cssText, options.baseURL);
|
|
66
|
+
return async (url, signal) => {
|
|
67
|
+
const resource = await fetch(url, signal);
|
|
68
|
+
if (!resource) return null;
|
|
69
|
+
if (isStylesheet(resource) || stylesheets.has(url) || stylesheets.has(resource.url)) learn(new TextDecoder().decode(resource.bytes), resource.url);
|
|
70
|
+
const served = rules.get(url) ?? rules.get(resource.url) ?? [];
|
|
71
|
+
const bytes = served.length > 0 ? engine.decodeFont(resource.bytes) : null;
|
|
72
|
+
for (const rule of served) {
|
|
73
|
+
const face = `${url}|${rule.family}|${rule.weight}|${rule.italic}`;
|
|
74
|
+
if (!bytes || delivered.has(face)) continue;
|
|
75
|
+
delivered.add(face);
|
|
76
|
+
await onFontFace({
|
|
77
|
+
family: rule.family,
|
|
78
|
+
weight: rule.weight,
|
|
79
|
+
italic: rule.italic,
|
|
80
|
+
url,
|
|
81
|
+
bytes
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return resource;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function rect(box) {
|
|
88
|
+
const [x, y, width, height] = box;
|
|
89
|
+
return {
|
|
90
|
+
x,
|
|
91
|
+
y,
|
|
92
|
+
width,
|
|
93
|
+
height
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function hasArea(box) {
|
|
97
|
+
return box[2] > 0 && box[3] > 0;
|
|
98
|
+
}
|
|
99
|
+
/** Children of each captured node that are elements, by the node's index; generated content left out. */
|
|
100
|
+
function elementChildren(capture) {
|
|
101
|
+
const children = /* @__PURE__ */ new Map();
|
|
102
|
+
for (const [index, node] of capture.nodes.entries()) {
|
|
103
|
+
if (node.parent === void 0 || node.tag === void 0 || node.tag.startsWith("::")) continue;
|
|
104
|
+
const siblings = children.get(node.parent) ?? [];
|
|
105
|
+
siblings.push(index);
|
|
106
|
+
children.set(node.parent, siblings);
|
|
107
|
+
}
|
|
108
|
+
return children;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Elements the HTML parser inserts around others where the markup leaves them out, such as the
|
|
112
|
+
* `tbody` around a table's rows; a serialized document need not hold them.
|
|
113
|
+
*/
|
|
114
|
+
const IMPLIED_WRAPPERS = /* @__PURE__ */ new Set(["tbody"]);
|
|
115
|
+
/**
|
|
116
|
+
* Each element of the document with the captured element it was laid out as: matched in order
|
|
117
|
+
* and by tag, looking through wrappers the parser inserted. A mismatch ends the matching among
|
|
118
|
+
* those siblings, so it never pairs an element with another's box.
|
|
119
|
+
*/
|
|
120
|
+
function pairElements(document, capture) {
|
|
121
|
+
const children = elementChildren(capture);
|
|
122
|
+
const body = capture.nodes.findIndex((node) => node.tag === "body");
|
|
123
|
+
const pairs = [];
|
|
124
|
+
const pair = (elements, parent, shaderFrame = false) => {
|
|
125
|
+
const queue = [...children.get(parent) ?? []];
|
|
126
|
+
const first = queue.at(0);
|
|
127
|
+
if (shaderFrame && first !== void 0 && capture.nodes[first].tag === "img") queue.shift();
|
|
128
|
+
for (const element of elements) {
|
|
129
|
+
let node = queue.shift();
|
|
130
|
+
while (node !== void 0 && !sameTag(capture.nodes[node].tag, element.tagName)) {
|
|
131
|
+
const tag = capture.nodes[node].tag;
|
|
132
|
+
if (tag === void 0 || !IMPLIED_WRAPPERS.has(tag)) return;
|
|
133
|
+
queue.unshift(...children.get(node) ?? []);
|
|
134
|
+
node = queue.shift();
|
|
135
|
+
}
|
|
136
|
+
if (node === void 0) return;
|
|
137
|
+
pairs.push([element, capture.nodes[node]]);
|
|
138
|
+
pair(designElements(element.children), node, element.shader?.frame !== void 0);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
if (body !== -1) pair(designElements(document.children), body);
|
|
142
|
+
return pairs;
|
|
143
|
+
}
|
|
144
|
+
function sameTag(captured, tagName) {
|
|
145
|
+
return captured?.toLowerCase() === tagName.toLowerCase();
|
|
146
|
+
}
|
|
147
|
+
function designElements(nodes) {
|
|
148
|
+
return nodes.filter((node) => node.type === "element");
|
|
149
|
+
}
|
|
150
|
+
/** Shorthands a browser runtime reports, `overflow` and `gap`, built from their captured longhands. */
|
|
151
|
+
function withShorthands(style) {
|
|
152
|
+
const value = (property, initial) => Object.hasOwn(style, property) ? style[property] : initial;
|
|
153
|
+
const pair = (first, second) => first === second ? first : `${first} ${second}`;
|
|
154
|
+
const shorthands = {};
|
|
155
|
+
if (Object.hasOwn(style, "overflow-x") || Object.hasOwn(style, "overflow-y")) shorthands.overflow = pair(value("overflow-x", "visible"), value("overflow-y", "visible"));
|
|
156
|
+
if (Object.hasOwn(style, "row-gap") || Object.hasOwn(style, "column-gap")) shorthands.gap = pair(value("row-gap", "normal"), value("column-gap", "normal"));
|
|
157
|
+
return {
|
|
158
|
+
...style,
|
|
159
|
+
...shorthands
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/** White space values that keep spaces, so a line of them takes room as a line of words does. */
|
|
163
|
+
const PRESERVED_WHITE_SPACE = /* @__PURE__ */ new Set([
|
|
164
|
+
"pre",
|
|
165
|
+
"pre-wrap",
|
|
166
|
+
"break-spaces"
|
|
167
|
+
]);
|
|
168
|
+
/**
|
|
169
|
+
* A line as a browser's text rects make it: across its words, leaving out inline boxes, and
|
|
170
|
+
* nothing for a line without text. Where white space is kept, a line of spaces counts too.
|
|
171
|
+
*/
|
|
172
|
+
function textLine(line, keepsSpaces) {
|
|
173
|
+
const texts = line.runs.filter((run) => "text" in run && run.text.length > 0);
|
|
174
|
+
const words = keepsSpaces ? texts : texts.filter((run) => "text" in run && run.text.trim() !== "");
|
|
175
|
+
if (words.length === 0) return null;
|
|
176
|
+
const left = Math.min(...words.map((run) => run.x));
|
|
177
|
+
const right = Math.max(...words.map((run) => run.x + run.width));
|
|
178
|
+
return {
|
|
179
|
+
x: left,
|
|
180
|
+
y: line.y,
|
|
181
|
+
width: right - left,
|
|
182
|
+
height: line.height
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function layoutOf(node) {
|
|
186
|
+
if (!node.box) return void 0;
|
|
187
|
+
const layout = { box: rect(node.box) };
|
|
188
|
+
const fragments = node.fragments?.filter(hasArea);
|
|
189
|
+
if (fragments && fragments.length > 0) {
|
|
190
|
+
layout.fragments = fragments.map(rect);
|
|
191
|
+
return layout;
|
|
192
|
+
}
|
|
193
|
+
const whiteSpace = node.style?.["white-space"];
|
|
194
|
+
const keepsSpaces = whiteSpace !== void 0 && PRESERVED_WHITE_SPACE.has(whiteSpace);
|
|
195
|
+
const lines = (node.lines ?? []).map((line) => textLine(line, keepsSpaces)).filter((line) => line !== null);
|
|
196
|
+
if (lines.length > 0) layout.lines = lines;
|
|
197
|
+
return layout;
|
|
198
|
+
}
|
|
199
|
+
function documentHTML(body, cssText) {
|
|
200
|
+
return `<!doctype html><html><head><style>${cssText.replaceAll(/<\/style/gi, "<\\/style")}</style></head><body>${body}</body></html>`;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
|
|
204
|
+
* without one: computed styles and, when asked, the boxes, inline fragments, and text lines a
|
|
205
|
+
* browser runtime records, before transforms. Documents are parsed and serialized as the headless
|
|
206
|
+
* runtime does.
|
|
207
|
+
*/
|
|
208
|
+
function createHTMLEngineRuntime(options = {}) {
|
|
209
|
+
const markup = createHeadlessCSSRuntime();
|
|
210
|
+
const engine = options.engine ?? loadHTMLEngine;
|
|
211
|
+
return {
|
|
212
|
+
kind: "headless",
|
|
213
|
+
parseHTML: (html) => markup.parseHTML(html),
|
|
214
|
+
serializeHTML: (document) => markup.serializeHTML(document),
|
|
215
|
+
async computeStyles(document, cssText = "", compute = {}) {
|
|
216
|
+
const laidOut = await engine();
|
|
217
|
+
const capture = await laidOut.layout(documentHTML(markup.serializeHTML(document), cssText), {
|
|
218
|
+
baseURL: options.baseURL,
|
|
219
|
+
viewport: compute.viewport ?? DEFAULT_VIEWPORT,
|
|
220
|
+
fetch: fontFaceFetch(laidOut, cssText, options)
|
|
221
|
+
});
|
|
222
|
+
const styled = structuredClone(document);
|
|
223
|
+
for (const [element, node] of pairElements(styled, capture)) {
|
|
224
|
+
element.computedStyle = withShorthands({
|
|
225
|
+
...capture.initial,
|
|
226
|
+
...node.style
|
|
227
|
+
});
|
|
228
|
+
if (compute.layout) element.layout = layoutOf(node);
|
|
229
|
+
}
|
|
230
|
+
return styled;
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
//#endregion
|
|
235
|
+
export { createHTMLEngineRuntime, loadHTMLEngine, setHTMLEngineLocator };
|
|
236
|
+
|
|
237
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/load.ts","../../src/runtime.ts"],"sourcesContent":["import { HTMLEngine } from './engine'\n\n/**\n * Where the engine's module (`html-engine.wasm`) loads from. By default it is read beside this\n * package, as Node and Bun resolve it; a host that serves it elsewhere, such as a bundled app,\n * points here instead.\n */\nexport type HTMLEngineLocator = () => string\n\nlet locator: HTMLEngineLocator = () =>\n import.meta.resolve('@open-pencil/html-engine/wasm/html-engine.wasm')\n\nlet loading: Promise<HTMLEngine> | null = null\n\n/**\n * How long a remote module may take to arrive, so a request that never settles cannot hold every\n * later load waiting on it; a failed load is retried by the next caller.\n */\nconst MODULE_LOAD_TIMEOUT_MS = 60_000\n\n/** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */\nexport function setHTMLEngineLocator(locate: HTMLEngineLocator): void {\n locator = locate\n loading = null\n}\n\nasync function readModule(url: string): Promise<ArrayBuffer> {\n if (!url.startsWith('file:')) {\n const response = await fetch(url, { signal: AbortSignal.timeout(MODULE_LOAD_TIMEOUT_MS) })\n if (!response.ok)\n throw new Error(`html-engine.wasm failed to load from ${url}: ${response.status}`)\n return response.arrayBuffer()\n }\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n const file = await readFile(new URL(url)).catch((error: unknown) => {\n throw new Error(\n `html-engine.wasm is missing at ${url}; build it with bun run build in packages/html-engine`,\n { cause: error }\n )\n })\n return file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength)\n}\n\n/** The engine, loaded once; a failed load is retried by the next caller. */\nexport function loadHTMLEngine(): Promise<HTMLEngine> {\n if (loading) return loading\n const load = readModule(locator()).then((bytes) => HTMLEngine.instantiate(bytes))\n loading = load\n load.catch(() => {\n if (loading === load) loading = null\n })\n return load\n}\n","import {\n createHeadlessCSSRuntime,\n parseFontFaceRules,\n parseStylesheetImports,\n type CSSFontFaceRule,\n type CSSComputeOptions,\n type CSSRuntime,\n type DesignDocument,\n type DesignElement,\n type DesignLayout,\n type DesignStyleDeclaration,\n type DesignViewport\n} from '@open-pencil/dom-css'\nimport type { Rect } from '@open-pencil/scene-graph/primitives'\n\nimport type { HTMLEngine, HTMLEngineFetch, HTMLEngineResource } from './engine'\nimport { loadHTMLEngine } from './load'\nimport type { HTMLEngineCapture, HTMLEngineLine, HTMLEngineNode } from './schema'\n\n/** The viewport a document is laid out in when the caller names none, as HTML import uses. */\nconst DEFAULT_VIEWPORT: DesignViewport = { width: 1440, height: 900 }\n\n/** A font a page's `@font-face` rule loads: the face the rule declares, and the file as TrueType or OpenType. */\nexport interface HTMLEngineFontFace {\n family: string\n weight: number\n italic: boolean\n url: string\n bytes: Uint8Array\n}\n\nexport interface HTMLEngineRuntimeOptions {\n /** The engine to lay documents out with, with the fonts they may use registered. */\n engine?: () => Promise<HTMLEngine>\n /** The document's URL, which its relative URLs resolve against. */\n baseURL?: string\n /**\n * Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for\n * its `@font-face` rules when it comes with a CSS content type.\n */\n fetch?: HTMLEngineFetch\n /**\n * Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so\n * a host can draw that text in the same font. The layout waits for it.\n */\n onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>\n}\n\nfunction isStylesheet(resource: HTMLEngineResource): boolean {\n return resource.contentType?.split(';')[0]?.trim().toLowerCase() === 'text/css'\n}\n\n/**\n * A fetch that also reads the page's `@font-face` rules, from its own CSS and every stylesheet it\n * fetches, and passes each font they load to `onFontFace` as the engine receives it.\n */\nfunction fontFaceFetch(\n engine: HTMLEngine,\n cssText: string,\n options: HTMLEngineRuntimeOptions\n): HTMLEngineFetch | undefined {\n const { fetch, onFontFace } = options\n if (!fetch || !onFontFace) return fetch\n const rules = new Map<string, CSSFontFaceRule[]>()\n // What CSS imports is a stylesheet whatever its name or the type it is served as.\n const stylesheets = new Set<string>()\n // The engine fetches a file once per rule that names it; each face is passed on once.\n const delivered = new Set<string>()\n const learn = (css: string, base: string | undefined) => {\n for (const rule of parseFontFaceRules(css, base)) {\n for (const source of rule.sources) rules.set(source, [...(rules.get(source) ?? []), rule])\n }\n for (const url of parseStylesheetImports(css, base)) stylesheets.add(url)\n }\n learn(cssText, options.baseURL)\n return async (url, signal) => {\n const resource = await fetch(url, signal)\n if (!resource) return null\n if (isStylesheet(resource) || stylesheets.has(url) || stylesheets.has(resource.url)) {\n learn(new TextDecoder().decode(resource.bytes), resource.url)\n }\n // One file can serve several rules, such as a family and an alias of it.\n const served = rules.get(url) ?? rules.get(resource.url) ?? []\n const bytes = served.length > 0 ? engine.decodeFont(resource.bytes) : null\n for (const rule of served) {\n const face = `${url}|${rule.family}|${rule.weight}|${rule.italic}`\n if (!bytes || delivered.has(face)) continue\n delivered.add(face)\n await onFontFace({\n family: rule.family,\n weight: rule.weight,\n italic: rule.italic,\n url,\n bytes\n })\n }\n return resource\n }\n}\n\ntype Box = HTMLEngineCapture['nodes'][number]['box']\n\nfunction rect(box: NonNullable<Box>): Rect {\n const [x, y, width, height] = box\n return { x, y, width, height }\n}\n\nfunction hasArea(box: NonNullable<Box>): boolean {\n return box[2] > 0 && box[3] > 0\n}\n\n/** Children of each captured node that are elements, by the node's index; generated content left out. */\nfunction elementChildren(capture: HTMLEngineCapture): Map<number, number[]> {\n const children = new Map<number, number[]>()\n for (const [index, node] of capture.nodes.entries()) {\n if (node.parent === undefined || node.tag === undefined || node.tag.startsWith('::')) continue\n const siblings = children.get(node.parent) ?? []\n siblings.push(index)\n children.set(node.parent, siblings)\n }\n return children\n}\n\n/**\n * Elements the HTML parser inserts around others where the markup leaves them out, such as the\n * `tbody` around a table's rows; a serialized document need not hold them.\n */\nconst IMPLIED_WRAPPERS = new Set(['tbody'])\n\n/**\n * Each element of the document with the captured element it was laid out as: matched in order\n * and by tag, looking through wrappers the parser inserted. A mismatch ends the matching among\n * those siblings, so it never pairs an element with another's box.\n */\nfunction pairElements(\n document: DesignDocument,\n capture: HTMLEngineCapture\n): [DesignElement, HTMLEngineNode][] {\n const children = elementChildren(capture)\n const body = capture.nodes.findIndex((node) => node.tag === 'body')\n const pairs: [DesignElement, HTMLEngineNode][] = []\n const pair = (elements: readonly DesignElement[], parent: number, shaderFrame = false) => {\n const queue = [...(children.get(parent) ?? [])]\n // The serializer writes a shader's still frame as an image ahead of its layer's children.\n const first = queue.at(0)\n if (shaderFrame && first !== undefined && capture.nodes[first].tag === 'img') queue.shift()\n for (const element of elements) {\n let node = queue.shift()\n // The HTML parser keeps SVG's mixed-case names, such as `linearGradient`; the document may not.\n while (node !== undefined && !sameTag(capture.nodes[node].tag, element.tagName)) {\n const tag = capture.nodes[node].tag\n if (tag === undefined || !IMPLIED_WRAPPERS.has(tag)) return\n queue.unshift(...(children.get(node) ?? []))\n node = queue.shift()\n }\n if (node === undefined) return\n pairs.push([element, capture.nodes[node]])\n pair(designElements(element.children), node, element.shader?.frame !== undefined)\n }\n }\n if (body !== -1) pair(designElements(document.children), body)\n return pairs\n}\n\nfunction sameTag(captured: string | undefined, tagName: string): boolean {\n return captured?.toLowerCase() === tagName.toLowerCase()\n}\n\nfunction designElements(nodes: DesignDocument['children']): DesignElement[] {\n return nodes.filter((node): node is DesignElement => node.type === 'element')\n}\n\n/** Shorthands a browser runtime reports, `overflow` and `gap`, built from their captured longhands. */\nfunction withShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {\n // Captures leave initial values out.\n const value = (property: string, initial: string) =>\n Object.hasOwn(style, property) ? style[property] : initial\n const pair = (first: string, second: string) => (first === second ? first : `${first} ${second}`)\n const shorthands: DesignStyleDeclaration = {}\n if (Object.hasOwn(style, 'overflow-x') || Object.hasOwn(style, 'overflow-y')) {\n shorthands.overflow = pair(value('overflow-x', 'visible'), value('overflow-y', 'visible'))\n }\n if (Object.hasOwn(style, 'row-gap') || Object.hasOwn(style, 'column-gap')) {\n shorthands.gap = pair(value('row-gap', 'normal'), value('column-gap', 'normal'))\n }\n return { ...style, ...shorthands }\n}\n\n/** White space values that keep spaces, so a line of them takes room as a line of words does. */\nconst PRESERVED_WHITE_SPACE = new Set(['pre', 'pre-wrap', 'break-spaces'])\n\n/**\n * A line as a browser's text rects make it: across its words, leaving out inline boxes, and\n * nothing for a line without text. Where white space is kept, a line of spaces counts too.\n */\nfunction textLine(line: HTMLEngineLine, keepsSpaces: boolean): Rect | null {\n const texts = line.runs.filter((run) => 'text' in run && run.text.length > 0)\n const words = keepsSpaces ? texts : texts.filter((run) => 'text' in run && run.text.trim() !== '')\n if (words.length === 0) return null\n const left = Math.min(...words.map((run) => run.x))\n const right = Math.max(...words.map((run) => run.x + run.width))\n return { x: left, y: line.y, width: right - left, height: line.height }\n}\n\nfunction layoutOf(node: HTMLEngineNode): DesignLayout | undefined {\n if (!node.box) return undefined\n const layout: DesignLayout = { box: rect(node.box) }\n const fragments = node.fragments?.filter(hasArea)\n if (fragments && fragments.length > 0) {\n layout.fragments = fragments.map(rect)\n return layout\n }\n const whiteSpace = node.style?.['white-space']\n const keepsSpaces = whiteSpace !== undefined && PRESERVED_WHITE_SPACE.has(whiteSpace)\n const lines = (node.lines ?? [])\n .map((line) => textLine(line, keepsSpaces))\n .filter((line) => line !== null)\n if (lines.length > 0) layout.lines = lines\n return layout\n}\n\nfunction documentHTML(body: string, cssText: string): string {\n // `</style` would end the stylesheet early.\n const css = cssText.replaceAll(/<\\/style/gi, '<\\\\/style')\n return `<!doctype html><html><head><style>${css}</style></head><body>${body}</body></html>`\n}\n\n/**\n * A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,\n * without one: computed styles and, when asked, the boxes, inline fragments, and text lines a\n * browser runtime records, before transforms. Documents are parsed and serialized as the headless\n * runtime does.\n */\nexport function createHTMLEngineRuntime(options: HTMLEngineRuntimeOptions = {}): CSSRuntime {\n const markup = createHeadlessCSSRuntime()\n const engine = options.engine ?? loadHTMLEngine\n return {\n kind: 'headless',\n parseHTML: (html) => markup.parseHTML(html),\n serializeHTML: (document) => markup.serializeHTML(document),\n async computeStyles(document, cssText = '', compute: CSSComputeOptions = {}) {\n const laidOut = await engine()\n const capture = await laidOut.layout(documentHTML(markup.serializeHTML(document), cssText), {\n baseURL: options.baseURL,\n viewport: compute.viewport ?? DEFAULT_VIEWPORT,\n fetch: fontFaceFetch(laidOut, cssText, options)\n })\n const styled = structuredClone(document)\n for (const [element, node] of pairElements(styled, capture)) {\n // Every captured property's computed value, so none falls back to a stale inline one.\n element.computedStyle = withShorthands({ ...capture.initial, ...node.style })\n if (compute.layout) element.layout = layoutOf(node)\n }\n return styled\n }\n }\n}\n"],"mappings":";;;AASA,IAAI,gBACF,YAAY,QAAQ,gDAAgD;AAEtE,IAAI,UAAsC;;;;;AAM1C,MAAM,yBAAyB;;AAG/B,SAAgB,qBAAqB,QAAiC;CACpE,UAAU;CACV,UAAU;AACZ;AAEA,eAAe,WAAW,KAAmC;CAC3D,IAAI,CAAC,IAAI,WAAW,OAAO,GAAG;EAC5B,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,QAAQ,YAAY,QAAQ,sBAAsB,EAAE,CAAC;EACzF,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM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A,OAAO;EACT;CACF;AACF"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
import { CSSRuntime } from "@open-pencil/dom-css";
|
|
3
|
+
//#region src/schema.d.ts
|
|
4
|
+
declare const lineSchema: v.ObjectSchema<{
|
|
5
|
+
readonly x: v.NumberSchema<undefined>;
|
|
6
|
+
readonly y: v.NumberSchema<undefined>;
|
|
7
|
+
readonly width: v.NumberSchema<undefined>;
|
|
8
|
+
readonly height: v.NumberSchema<undefined>;
|
|
9
|
+
readonly baseline: v.NumberSchema<undefined>;
|
|
10
|
+
readonly runs: v.ArraySchema<v.UnionSchema<[v.ObjectSchema<{
|
|
11
|
+
/** The engine's id of the node whose text the run draws. */
|
|
12
|
+
readonly node: v.NumberSchema<undefined>;
|
|
13
|
+
readonly x: v.NumberSchema<undefined>;
|
|
14
|
+
readonly width: v.NumberSchema<undefined>;
|
|
15
|
+
readonly text: v.StringSchema<undefined>;
|
|
16
|
+
}, undefined>, v.ObjectSchema<{
|
|
17
|
+
/** The engine's id of the atomic inline, such as an `inline-block`, the line holds. */
|
|
18
|
+
readonly box: v.NumberSchema<undefined>;
|
|
19
|
+
readonly x: v.NumberSchema<undefined>;
|
|
20
|
+
readonly width: v.NumberSchema<undefined>;
|
|
21
|
+
}, undefined>], undefined>, undefined>;
|
|
22
|
+
}, undefined>;
|
|
23
|
+
declare const capturedNodeSchema: v.ObjectSchema<{
|
|
24
|
+
/** The engine's own id, which runs and inline boxes refer to. */
|
|
25
|
+
readonly id: v.NumberSchema<undefined>;
|
|
26
|
+
/** The index in `nodes` of the element holding it. */
|
|
27
|
+
readonly parent: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
28
|
+
/** Set on text nodes, which carry nothing else. */
|
|
29
|
+
readonly text: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
30
|
+
/** The element's local name, or `::before` and `::after` for generated content. */
|
|
31
|
+
readonly tag: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
32
|
+
/** Attributes by name, namespaced ones with their prefix, as `xlink:href`. */
|
|
33
|
+
readonly attrs: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
34
|
+
/** The border box, in page pixels. */
|
|
35
|
+
readonly box: v.OptionalSchema<v.TupleSchema<[v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>], undefined>, undefined>;
|
|
36
|
+
/** What the image element holds, such as `raster 640x480` or `svg`. */
|
|
37
|
+
readonly image: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
38
|
+
/**
|
|
39
|
+
* Computed values: those with a fixed initial value only when they differ from it, and always
|
|
40
|
+
* the ones whose initial value depends on the element or is inherited, such as `display`,
|
|
41
|
+
* `color`, sizes, and font properties.
|
|
42
|
+
*/
|
|
43
|
+
readonly style: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
44
|
+
/** An inline element's box on each line it spans, in page pixels. */
|
|
45
|
+
readonly fragments: v.OptionalSchema<v.ArraySchema<v.TupleSchema<[v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>], undefined>, undefined>, undefined>;
|
|
46
|
+
/** The lines of the inline formatting context the element holds, in page pixels. */
|
|
47
|
+
readonly lines: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
|
|
48
|
+
readonly x: v.NumberSchema<undefined>;
|
|
49
|
+
readonly y: v.NumberSchema<undefined>;
|
|
50
|
+
readonly width: v.NumberSchema<undefined>;
|
|
51
|
+
readonly height: v.NumberSchema<undefined>;
|
|
52
|
+
readonly baseline: v.NumberSchema<undefined>;
|
|
53
|
+
readonly runs: v.ArraySchema<v.UnionSchema<[v.ObjectSchema<{
|
|
54
|
+
/** The engine's id of the node whose text the run draws. */
|
|
55
|
+
readonly node: v.NumberSchema<undefined>;
|
|
56
|
+
readonly x: v.NumberSchema<undefined>;
|
|
57
|
+
readonly width: v.NumberSchema<undefined>;
|
|
58
|
+
readonly text: v.StringSchema<undefined>;
|
|
59
|
+
}, undefined>, v.ObjectSchema<{
|
|
60
|
+
/** The engine's id of the atomic inline, such as an `inline-block`, the line holds. */
|
|
61
|
+
readonly box: v.NumberSchema<undefined>;
|
|
62
|
+
readonly x: v.NumberSchema<undefined>;
|
|
63
|
+
readonly width: v.NumberSchema<undefined>;
|
|
64
|
+
}, undefined>], undefined>, undefined>;
|
|
65
|
+
}, undefined>, undefined>, undefined>;
|
|
66
|
+
}, undefined>;
|
|
67
|
+
/** The document the engine laid out: every node, parents before children. */
|
|
68
|
+
declare const captureSchema: v.ObjectSchema<{
|
|
69
|
+
readonly engine: v.LiteralSchema<"blitz", undefined>;
|
|
70
|
+
readonly viewport: v.TupleSchema<[v.NumberSchema<undefined>, v.NumberSchema<undefined>], undefined>;
|
|
71
|
+
/** The initial values of the properties nodes leave out of `style` when they hold them. */
|
|
72
|
+
readonly initial: v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>;
|
|
73
|
+
readonly nodes: v.ArraySchema<v.ObjectSchema<{
|
|
74
|
+
/** The engine's own id, which runs and inline boxes refer to. */
|
|
75
|
+
readonly id: v.NumberSchema<undefined>;
|
|
76
|
+
/** The index in `nodes` of the element holding it. */
|
|
77
|
+
readonly parent: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
78
|
+
/** Set on text nodes, which carry nothing else. */
|
|
79
|
+
readonly text: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
80
|
+
/** The element's local name, or `::before` and `::after` for generated content. */
|
|
81
|
+
readonly tag: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
82
|
+
/** Attributes by name, namespaced ones with their prefix, as `xlink:href`. */
|
|
83
|
+
readonly attrs: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
84
|
+
/** The border box, in page pixels. */
|
|
85
|
+
readonly box: v.OptionalSchema<v.TupleSchema<[v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>], undefined>, undefined>;
|
|
86
|
+
/** What the image element holds, such as `raster 640x480` or `svg`. */
|
|
87
|
+
readonly image: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
88
|
+
/**
|
|
89
|
+
* Computed values: those with a fixed initial value only when they differ from it, and always
|
|
90
|
+
* the ones whose initial value depends on the element or is inherited, such as `display`,
|
|
91
|
+
* `color`, sizes, and font properties.
|
|
92
|
+
*/
|
|
93
|
+
readonly style: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
|
|
94
|
+
/** An inline element's box on each line it spans, in page pixels. */
|
|
95
|
+
readonly fragments: v.OptionalSchema<v.ArraySchema<v.TupleSchema<[v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>, v.NumberSchema<undefined>], undefined>, undefined>, undefined>;
|
|
96
|
+
/** The lines of the inline formatting context the element holds, in page pixels. */
|
|
97
|
+
readonly lines: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
|
|
98
|
+
readonly x: v.NumberSchema<undefined>;
|
|
99
|
+
readonly y: v.NumberSchema<undefined>;
|
|
100
|
+
readonly width: v.NumberSchema<undefined>;
|
|
101
|
+
readonly height: v.NumberSchema<undefined>;
|
|
102
|
+
readonly baseline: v.NumberSchema<undefined>;
|
|
103
|
+
readonly runs: v.ArraySchema<v.UnionSchema<[v.ObjectSchema<{
|
|
104
|
+
/** The engine's id of the node whose text the run draws. */
|
|
105
|
+
readonly node: v.NumberSchema<undefined>;
|
|
106
|
+
readonly x: v.NumberSchema<undefined>;
|
|
107
|
+
readonly width: v.NumberSchema<undefined>;
|
|
108
|
+
readonly text: v.StringSchema<undefined>;
|
|
109
|
+
}, undefined>, v.ObjectSchema<{
|
|
110
|
+
/** The engine's id of the atomic inline, such as an `inline-block`, the line holds. */
|
|
111
|
+
readonly box: v.NumberSchema<undefined>;
|
|
112
|
+
readonly x: v.NumberSchema<undefined>;
|
|
113
|
+
readonly width: v.NumberSchema<undefined>;
|
|
114
|
+
}, undefined>], undefined>, undefined>;
|
|
115
|
+
}, undefined>, undefined>, undefined>;
|
|
116
|
+
}, undefined>, undefined>;
|
|
117
|
+
}, undefined>;
|
|
118
|
+
type HTMLEngineCapture = v.InferOutput<typeof captureSchema>;
|
|
119
|
+
type HTMLEngineNode = v.InferOutput<typeof capturedNodeSchema>;
|
|
120
|
+
type HTMLEngineLine = v.InferOutput<typeof lineSchema>;
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/engine.d.ts
|
|
123
|
+
/** A resource the document asked for, as the host fetched it: its final URL and its bytes. */
|
|
124
|
+
interface HTMLEngineResource {
|
|
125
|
+
url: string;
|
|
126
|
+
bytes: Uint8Array;
|
|
127
|
+
/** The resource's media type, such as `text/css`, when the host knows it. */
|
|
128
|
+
contentType?: string;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Fetches a stylesheet, font, or image the document refers to; null when it cannot. `signal`
|
|
132
|
+
* aborts when the request runs out of time, and the layout goes on without it.
|
|
133
|
+
*/
|
|
134
|
+
type HTMLEngineFetch = (url: string, signal: AbortSignal) => Promise<HTMLEngineResource | null>;
|
|
135
|
+
interface HTMLEngineLayoutOptions {
|
|
136
|
+
/** The document's URL, which relative URLs in it resolve against. */
|
|
137
|
+
baseURL?: string;
|
|
138
|
+
/** In whole CSS pixels. */
|
|
139
|
+
viewport: {
|
|
140
|
+
width: number;
|
|
141
|
+
height: number;
|
|
142
|
+
};
|
|
143
|
+
/** Answers the document's requests; without one, every request fails. */
|
|
144
|
+
fetch?: HTMLEngineFetch;
|
|
145
|
+
/** How long one request may take before the layout goes on without it. */
|
|
146
|
+
requestTimeoutMs?: number;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Blitz, Stylo, Taffy, and Parley compiled to WebAssembly: lays HTML out as a browser does and
|
|
150
|
+
* captures every element's box and computed styles, and the lines its text sets. The engine holds one document at a
|
|
151
|
+
* time, so layouts on one instance run one after another.
|
|
152
|
+
*/
|
|
153
|
+
declare class HTMLEngine {
|
|
154
|
+
#private;
|
|
155
|
+
private constructor();
|
|
156
|
+
/** Instantiates the module from its bytes or a compiled `WebAssembly.Module`. */
|
|
157
|
+
static instantiate(source: BufferSource | WebAssembly.Module): Promise<HTMLEngine>;
|
|
158
|
+
/**
|
|
159
|
+
* Registers a font file for layouts that start after it; `alias` also registers it under
|
|
160
|
+
* that family name, as browsers alias `-apple-system` to the system font. Returns the number
|
|
161
|
+
* of faces it holds.
|
|
162
|
+
*/
|
|
163
|
+
addFont(bytes: Uint8Array, alias?: string): number;
|
|
164
|
+
/**
|
|
165
|
+
* Sets the registered families a generic family such as `sans-serif` falls back to, in order.
|
|
166
|
+
* False when none of them is registered.
|
|
167
|
+
*/
|
|
168
|
+
setGenericFamily(generic: string, families: readonly string[]): boolean;
|
|
169
|
+
/** A font file as TrueType or OpenType, with WOFF and WOFF2 decompressed; others unchanged. */
|
|
170
|
+
decodeFont(bytes: Uint8Array): Uint8Array;
|
|
171
|
+
/** Forgets every registered font. */
|
|
172
|
+
resetFonts(): void;
|
|
173
|
+
/** Lays the document out once every resource it asks for is answered, and captures it. */
|
|
174
|
+
layout(html: string, options: HTMLEngineLayoutOptions): Promise<HTMLEngineCapture>;
|
|
175
|
+
}
|
|
176
|
+
//#endregion
|
|
177
|
+
//#region src/images.d.ts
|
|
178
|
+
/**
|
|
179
|
+
* The engine decodes no raster images, so layout learns an image's size from a stand-in SVG of
|
|
180
|
+
* the same pixel size, read from the file's header. Formats are the ones browsers lay out from
|
|
181
|
+
* their headers alone: PNG, GIF, WebP, JPEG, and AVIF.
|
|
182
|
+
*/
|
|
183
|
+
type Size = [width: number, height: number];
|
|
184
|
+
/** An image file's pixel size from its header, or null for a format it does not know. */
|
|
185
|
+
declare function rasterImageSize(bytes: Uint8Array): Size | null;
|
|
186
|
+
//#endregion
|
|
187
|
+
//#region src/load.d.ts
|
|
188
|
+
/**
|
|
189
|
+
* Where the engine's module (`html-engine.wasm`) loads from. By default it is read beside this
|
|
190
|
+
* package, as Node and Bun resolve it; a host that serves it elsewhere, such as a bundled app,
|
|
191
|
+
* points here instead.
|
|
192
|
+
*/
|
|
193
|
+
type HTMLEngineLocator = () => string;
|
|
194
|
+
/** Points the engine at the host's copy of its module. Call before the first `loadHTMLEngine`. */
|
|
195
|
+
declare function setHTMLEngineLocator(locate: HTMLEngineLocator): void;
|
|
196
|
+
/** The engine, loaded once; a failed load is retried by the next caller. */
|
|
197
|
+
declare function loadHTMLEngine(): Promise<HTMLEngine>;
|
|
198
|
+
//#endregion
|
|
199
|
+
//#region src/runtime.d.ts
|
|
200
|
+
/** A font a page's `@font-face` rule loads: the face the rule declares, and the file as TrueType or OpenType. */
|
|
201
|
+
interface HTMLEngineFontFace {
|
|
202
|
+
family: string;
|
|
203
|
+
weight: number;
|
|
204
|
+
italic: boolean;
|
|
205
|
+
url: string;
|
|
206
|
+
bytes: Uint8Array;
|
|
207
|
+
}
|
|
208
|
+
interface HTMLEngineRuntimeOptions {
|
|
209
|
+
/** The engine to lay documents out with, with the fonts they may use registered. */
|
|
210
|
+
engine?: () => Promise<HTMLEngine>;
|
|
211
|
+
/** The document's URL, which its relative URLs resolve against. */
|
|
212
|
+
baseURL?: string;
|
|
213
|
+
/**
|
|
214
|
+
* Answers the stylesheets, fonts, and images the document asks for. A stylesheet is read for
|
|
215
|
+
* its `@font-face` rules when it comes with a CSS content type.
|
|
216
|
+
*/
|
|
217
|
+
fetch?: HTMLEngineFetch;
|
|
218
|
+
/**
|
|
219
|
+
* Receives each font the page's `@font-face` rules load, as the engine lays text out in it, so
|
|
220
|
+
* a host can draw that text in the same font. The layout waits for it.
|
|
221
|
+
*/
|
|
222
|
+
onFontFace?: (face: HTMLEngineFontFace) => void | Promise<void>;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* A CSS runtime that styles and lays documents out with the HTML engine, as a browser would,
|
|
226
|
+
* without one: computed styles and, when asked, the boxes, inline fragments, and text lines a
|
|
227
|
+
* browser runtime records, before transforms. Documents are parsed and serialized as the headless
|
|
228
|
+
* runtime does.
|
|
229
|
+
*/
|
|
230
|
+
declare function createHTMLEngineRuntime(options?: HTMLEngineRuntimeOptions): CSSRuntime;
|
|
231
|
+
//#endregion
|
|
232
|
+
export { HTMLEngine, type HTMLEngineCapture, type HTMLEngineFetch, type HTMLEngineFontFace, type HTMLEngineLayoutOptions, type HTMLEngineLine, type HTMLEngineLocator, type HTMLEngineNode, type HTMLEngineResource, type HTMLEngineRuntimeOptions, createHTMLEngineRuntime, loadHTMLEngine, rasterImageSize, setHTMLEngineLocator };
|
|
233
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/schema.ts","../src/engine.ts","../src/images.ts","../src/load.ts","../src/runtime.ts"],"mappings":";;;cAmBM,YAAU,EAAA;;;;;;;;;;;;;;;;;;;cASV,oBAAkB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA4BX,eAAa,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAWd,oBAAoB,EAAE,mBAAmB;KACzC,iBAAiB,EAAE,mBAAmB;KACtC,iBAAiB,EAAE,mBAAmB;;;;UCxCjC;EACf;EACA,OAAO;;EAEP;;;;;;KAOU,mBACV,aACA,QAAQ,gBACL,QAAQ;UAEI;;EAEf;;EAEA;IAAY;IAAe;;;EAE3B,QAAQ;;EAER;;;;;;;cAuFW;;UAMJ;;SAKM,YAAY,QAAQ,eAAe,YAAY,SAAS,QAAQ;;;;;;EA8B7E,QAAQ,OAAO,YAAY;;;;;EAY3B,iBAAiB,iBAAiB;;EASlC,WAAW,OAAO,aAAa;;EAQ/B;;EAkEA,OAAO,cAAc,SAAS,0BAA0B,QAAQ;;;;;;;;;KC9Q7D,QAAQ,eAAe;;iBAoGZ,gBAAgB,OAAO,aAAa;;;;;;;;KCnGxC;;iBAcI,qBAAqB,QAAQ;;iBAuB7B,kBAAkB,QAAQ;;;;UCrBzB;EACf;EACA;EACA;EACA;EACA,OAAO;;UAGQ;;EAEf,eAAe,QAAQ;;EAEvB;;;;;EAKA,QAAQ;;;;;EAKR,cAAc,MAAM,8BAA8B;;;;;;;;iBA4LpC,wBAAwB,UAAS,2BAAgC"}
|
package/dist/index.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-pencil/html-engine",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.17.0-beta.4",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist",
|
|
7
|
+
"src",
|
|
8
|
+
"wasm",
|
|
9
|
+
"README.md"
|
|
10
|
+
],
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"@open-pencil/dom-css": "^0.17.0-beta.4",
|
|
15
|
+
"valibot": "^1.5.0"
|
|
16
|
+
},
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
"@open-pencil/scene-graph": "^0.17.0-beta.4"
|
|
19
|
+
},
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"bun": "./src/index.ts",
|
|
24
|
+
"import": "./dist/index.js",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./wasm/*": "./wasm/*"
|
|
28
|
+
},
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/open-pencil/open-pencil.git",
|
|
32
|
+
"directory": "packages/html-engine"
|
|
33
|
+
},
|
|
34
|
+
"type": "module",
|
|
35
|
+
"sideEffects": false
|
|
36
|
+
}
|