@liustack/pptfast 0.3.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -28
- package/README.zh-CN.md +33 -27
- package/dist/chunk-2ZOMS6G3.js +564 -0
- package/dist/chunk-2ZOMS6G3.js.map +1 -0
- package/dist/{chunk-ZXWCOWJI.js → chunk-7V73LHUQ.js} +3660 -1745
- package/dist/chunk-7V73LHUQ.js.map +1 -0
- package/dist/chunk-HFRNKYZ6.js +54 -0
- package/dist/chunk-HFRNKYZ6.js.map +1 -0
- package/dist/chunk-L524YK63.js +19 -0
- package/dist/chunk-L524YK63.js.map +1 -0
- package/dist/cli.js +340 -72
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +992 -210
- package/dist/index.js +42 -34
- package/dist/node.d.ts +3 -2
- package/dist/node.js +2 -2
- package/dist/pixel-audit-ZRFTV4V7.js +218 -0
- package/dist/pixel-audit-ZRFTV4V7.js.map +1 -0
- package/dist/registry-V079Jkry.d.ts +40 -0
- package/package.json +10 -3
- package/dist/chunk-G76EVNVT.js +0 -14
- package/dist/chunk-G76EVNVT.js.map +0 -1
- package/dist/chunk-SROEW6BH.js +0 -34
- package/dist/chunk-SROEW6BH.js.map +0 -1
- package/dist/chunk-ZXWCOWJI.js.map +0 -1
- package/dist/registry-CYKxZ0-U.d.ts +0 -11
package/dist/index.js
CHANGED
|
@@ -1,60 +1,66 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DeckSpecSchema,
|
|
3
|
+
PageSpecSchema,
|
|
4
|
+
PptxIRV3Schema,
|
|
5
|
+
SPEC_PAGE_COUNT_RANGE,
|
|
6
|
+
VERSION,
|
|
7
|
+
assembleDeck,
|
|
8
|
+
disassembleDeck,
|
|
9
|
+
formatSpecIssues,
|
|
10
|
+
migrateDeckPlanToSpec,
|
|
11
|
+
migrateIrV3ToV4,
|
|
12
|
+
resolveSpecThemeId,
|
|
13
|
+
specJsonSchema,
|
|
14
|
+
validateSpec
|
|
15
|
+
} from "./chunk-2ZOMS6G3.js";
|
|
1
16
|
import {
|
|
2
17
|
AUDIENCE_VALUES,
|
|
3
18
|
BUILTIN_THEME_IDS,
|
|
4
19
|
BrandConfigSchema,
|
|
5
20
|
COMPONENT_TYPES,
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
MODE_DEFINITIONS,
|
|
11
|
-
MODE_VALUES,
|
|
12
|
-
PLAN_PAGE_COUNT_RANGE,
|
|
13
|
-
PlanPageSchema,
|
|
21
|
+
DEFAULT_NARRATIVE,
|
|
22
|
+
NARRATIVE_PRESETS,
|
|
23
|
+
PACING_BUDGETS,
|
|
24
|
+
PACING_VALUES,
|
|
14
25
|
PptfastError,
|
|
15
26
|
PptxIRSchema,
|
|
16
|
-
|
|
27
|
+
STRATEGY_DEFINITIONS,
|
|
28
|
+
STRATEGY_VALUES,
|
|
17
29
|
StyleOverrideSchema,
|
|
18
30
|
ThemeSchema,
|
|
19
|
-
VERSION,
|
|
20
|
-
assembleDeck,
|
|
21
31
|
auditDeck,
|
|
22
|
-
disassembleDeck,
|
|
23
32
|
formatIssues,
|
|
24
|
-
formatPlanIssues,
|
|
25
33
|
generatePptx,
|
|
26
34
|
getInstalledThemeIds,
|
|
27
35
|
getThemeDefinition,
|
|
28
36
|
irJsonSchema,
|
|
29
37
|
listThemes,
|
|
30
|
-
planJsonSchema,
|
|
31
38
|
registerTheme,
|
|
32
39
|
renderSlideSvg,
|
|
33
|
-
|
|
34
|
-
resolveScenario,
|
|
40
|
+
resolveNarrative,
|
|
35
41
|
styleJsonSchema,
|
|
36
|
-
validateIr
|
|
37
|
-
|
|
38
|
-
} from "./chunk-ZXWCOWJI.js";
|
|
42
|
+
validateIr
|
|
43
|
+
} from "./chunk-7V73LHUQ.js";
|
|
39
44
|
import {
|
|
40
45
|
installPlatform
|
|
41
|
-
} from "./chunk-
|
|
46
|
+
} from "./chunk-L524YK63.js";
|
|
42
47
|
export {
|
|
43
48
|
AUDIENCE_VALUES,
|
|
44
49
|
BUILTIN_THEME_IDS,
|
|
45
50
|
BrandConfigSchema,
|
|
46
51
|
COMPONENT_TYPES,
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
PLAN_PAGE_COUNT_RANGE,
|
|
54
|
-
PlanPageSchema,
|
|
52
|
+
DEFAULT_NARRATIVE,
|
|
53
|
+
DeckSpecSchema,
|
|
54
|
+
NARRATIVE_PRESETS,
|
|
55
|
+
PACING_BUDGETS,
|
|
56
|
+
PACING_VALUES,
|
|
57
|
+
PageSpecSchema,
|
|
55
58
|
PptfastError,
|
|
56
59
|
PptxIRSchema,
|
|
57
|
-
|
|
60
|
+
PptxIRV3Schema,
|
|
61
|
+
SPEC_PAGE_COUNT_RANGE,
|
|
62
|
+
STRATEGY_DEFINITIONS,
|
|
63
|
+
STRATEGY_VALUES,
|
|
58
64
|
StyleOverrideSchema,
|
|
59
65
|
ThemeSchema,
|
|
60
66
|
VERSION,
|
|
@@ -62,20 +68,22 @@ export {
|
|
|
62
68
|
auditDeck,
|
|
63
69
|
disassembleDeck,
|
|
64
70
|
formatIssues,
|
|
65
|
-
|
|
71
|
+
formatSpecIssues,
|
|
66
72
|
generatePptx,
|
|
67
73
|
getInstalledThemeIds,
|
|
68
74
|
getThemeDefinition,
|
|
69
75
|
installPlatform,
|
|
70
76
|
irJsonSchema,
|
|
71
77
|
listThemes,
|
|
72
|
-
|
|
78
|
+
migrateDeckPlanToSpec,
|
|
79
|
+
migrateIrV3ToV4,
|
|
73
80
|
registerTheme,
|
|
74
81
|
renderSlideSvg,
|
|
75
|
-
|
|
76
|
-
|
|
82
|
+
resolveNarrative,
|
|
83
|
+
resolveSpecThemeId,
|
|
84
|
+
specJsonSchema,
|
|
77
85
|
styleJsonSchema,
|
|
78
86
|
validateIr,
|
|
79
|
-
|
|
87
|
+
validateSpec
|
|
80
88
|
};
|
|
81
89
|
//# sourceMappingURL=index.js.map
|
package/dist/node.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
export { P as PptfastPlatform, i as installPlatform } from './registry-
|
|
1
|
+
export { P as PptfastPlatform, i as installPlatform } from './registry-V079Jkry.js';
|
|
2
2
|
|
|
3
|
-
/** Wire Node implementations (linkedom DOM, sharp image re-encode
|
|
3
|
+
/** Wire Node implementations (linkedom DOM, sharp image re-encode + SVG
|
|
4
|
+
* rasterize) into the SDK. */
|
|
4
5
|
declare function installNodePlatform(): void;
|
|
5
6
|
|
|
6
7
|
export { installNodePlatform };
|
package/dist/node.js
CHANGED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CANVAS_H_PX,
|
|
3
|
+
CANVAS_W_PX,
|
|
4
|
+
__collectImageBackedTextRuns,
|
|
5
|
+
blendOver,
|
|
6
|
+
contrastRatio,
|
|
7
|
+
renderSlideSvg
|
|
8
|
+
} from "./chunk-7V73LHUQ.js";
|
|
9
|
+
import {
|
|
10
|
+
findRemoteAssetRef,
|
|
11
|
+
getPlatform
|
|
12
|
+
} from "./chunk-L524YK63.js";
|
|
13
|
+
|
|
14
|
+
// src/platform/browser.ts
|
|
15
|
+
function isSecurityError(e) {
|
|
16
|
+
return typeof e === "object" && e !== null && e.name === "SecurityError";
|
|
17
|
+
}
|
|
18
|
+
var IMAGE_LOAD_TIMEOUT_MS = 3e4;
|
|
19
|
+
function loadImage(url) {
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
const timer = setTimeout(() => {
|
|
22
|
+
reject(
|
|
23
|
+
new Error(
|
|
24
|
+
`rasterizeSvg: timed out after ${IMAGE_LOAD_TIMEOUT_MS}ms waiting for the browser to decode the rasterized SVG as an image (a stuck decode, never a silent hang)`
|
|
25
|
+
)
|
|
26
|
+
);
|
|
27
|
+
}, IMAGE_LOAD_TIMEOUT_MS);
|
|
28
|
+
const img = new Image();
|
|
29
|
+
img.onload = () => {
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
resolve(img);
|
|
32
|
+
};
|
|
33
|
+
img.onerror = () => {
|
|
34
|
+
clearTimeout(timer);
|
|
35
|
+
reject(new Error("rasterizeSvg: the browser could not decode the rasterized SVG as an image"));
|
|
36
|
+
};
|
|
37
|
+
img.src = url;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
function createCanvas(width, height) {
|
|
41
|
+
if (typeof OffscreenCanvas !== "undefined") {
|
|
42
|
+
return new OffscreenCanvas(width, height);
|
|
43
|
+
}
|
|
44
|
+
if (typeof document !== "undefined") {
|
|
45
|
+
const canvas = document.createElement("canvas");
|
|
46
|
+
canvas.width = width;
|
|
47
|
+
canvas.height = height;
|
|
48
|
+
return canvas;
|
|
49
|
+
}
|
|
50
|
+
throw new Error(
|
|
51
|
+
'rasterizeSvg unavailable \u2014 in Node, call installNodePlatform() from "@liustack/pptfast/node" first (the pptfast CLI does this automatically); in a browser, OffscreenCanvas or a DOM canvas is required'
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
async function rasterizeSvgInBrowser(svgMarkup, width, height) {
|
|
55
|
+
const remoteRef = findRemoteAssetRef(svgMarkup);
|
|
56
|
+
if (remoteRef) {
|
|
57
|
+
throw new Error(
|
|
58
|
+
`rasterizeSvg: refusing to rasterize an SVG that references a remote image (${remoteRef}) \u2014 only data-URI (or other local) assets are supported (a remote asset would silently drop when loaded this way, not rasterize)`
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
if (typeof Image === "undefined") {
|
|
62
|
+
throw new Error(
|
|
63
|
+
'rasterizeSvg unavailable \u2014 in Node, call installNodePlatform() from "@liustack/pptfast/node" first (the pptfast CLI does this automatically); in a browser, the Image constructor is required'
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
const blob = new Blob([svgMarkup], { type: "image/svg+xml" });
|
|
67
|
+
const url = URL.createObjectURL(blob);
|
|
68
|
+
try {
|
|
69
|
+
const img = await loadImage(url);
|
|
70
|
+
const canvas = createCanvas(width, height);
|
|
71
|
+
const ctx = canvas.getContext("2d");
|
|
72
|
+
if (!ctx) throw new Error("rasterizeSvg: could not obtain a 2d canvas context");
|
|
73
|
+
ctx.drawImage(img, 0, 0, width, height);
|
|
74
|
+
let imageData;
|
|
75
|
+
try {
|
|
76
|
+
imageData = ctx.getImageData(0, 0, width, height);
|
|
77
|
+
} catch (e) {
|
|
78
|
+
if (isSecurityError(e)) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
"rasterizeSvg: the canvas was tainted while reading back pixel data (a cross-origin or otherwise untrusted asset) \u2014 only data-URI (or other local) assets are supported"
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
throw e;
|
|
84
|
+
}
|
|
85
|
+
return { width: imageData.width, height: imageData.height, data: imageData.data };
|
|
86
|
+
} finally {
|
|
87
|
+
URL.revokeObjectURL(url);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/svg/audit/pixel-audit.ts
|
|
92
|
+
var PIXEL_CANVAS_W = CANVAS_W_PX;
|
|
93
|
+
var PIXEL_CANVAS_H = CANVAS_H_PX;
|
|
94
|
+
var PIXEL_HARD_FINDING_MAX_RATIO = 1.5;
|
|
95
|
+
var TEXT_ELEMENT_RE = /<text\b[^>]*\/>|<text\b[^>]*>[\s\S]*?<\/text>/g;
|
|
96
|
+
function stripTextNodes(markup) {
|
|
97
|
+
return markup.replace(TEXT_ELEMENT_RE, "");
|
|
98
|
+
}
|
|
99
|
+
function rgbToHex(r, g, b) {
|
|
100
|
+
const toHex = (v) => Math.round(v).toString(16).padStart(2, "0");
|
|
101
|
+
return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase();
|
|
102
|
+
}
|
|
103
|
+
var SAMPLE_ASCENT_RATIO = 0.75;
|
|
104
|
+
var SAMPLE_DESCENT_RATIO = 0.25;
|
|
105
|
+
var MIN_GUARANTEED_PATCH_PX = 10;
|
|
106
|
+
var SAMPLE_STRIDE_PX = MIN_GUARANTEED_PATCH_PX / 2;
|
|
107
|
+
var AGGREGATION_HALF_PX = 1;
|
|
108
|
+
function samplePositions(lo, hi) {
|
|
109
|
+
if (hi <= lo) return [lo];
|
|
110
|
+
const positions = [];
|
|
111
|
+
for (let v = lo; v < hi; v += SAMPLE_STRIDE_PX) positions.push(v);
|
|
112
|
+
positions.push(hi);
|
|
113
|
+
return positions;
|
|
114
|
+
}
|
|
115
|
+
function averageWindow(image, cx, cy) {
|
|
116
|
+
const x0 = Math.round(cx);
|
|
117
|
+
const y0 = Math.round(cy);
|
|
118
|
+
let sumR = 0;
|
|
119
|
+
let sumG = 0;
|
|
120
|
+
let sumB = 0;
|
|
121
|
+
let count = 0;
|
|
122
|
+
for (let dy = -AGGREGATION_HALF_PX; dy <= AGGREGATION_HALF_PX; dy++) {
|
|
123
|
+
const y = y0 + dy;
|
|
124
|
+
if (y < 0 || y >= image.height) continue;
|
|
125
|
+
for (let dx = -AGGREGATION_HALF_PX; dx <= AGGREGATION_HALF_PX; dx++) {
|
|
126
|
+
const x = x0 + dx;
|
|
127
|
+
if (x < 0 || x >= image.width) continue;
|
|
128
|
+
const i = (y * image.width + x) * 4;
|
|
129
|
+
const alpha = image.data[i + 3];
|
|
130
|
+
if (alpha < 255) continue;
|
|
131
|
+
sumR += image.data[i];
|
|
132
|
+
sumG += image.data[i + 1];
|
|
133
|
+
sumB += image.data[i + 2];
|
|
134
|
+
count++;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (count === 0) return null;
|
|
138
|
+
return { r: sumR / count, g: sumG / count, b: sumB / count };
|
|
139
|
+
}
|
|
140
|
+
function worstCaseSample(run, image) {
|
|
141
|
+
const top = run.baseline - run.fontSize * SAMPLE_ASCENT_RATIO;
|
|
142
|
+
const bottom = run.baseline + run.fontSize * SAMPLE_DESCENT_RATIO;
|
|
143
|
+
let worst = null;
|
|
144
|
+
const ys = samplePositions(top, bottom);
|
|
145
|
+
const xs = samplePositions(run.left, run.right);
|
|
146
|
+
for (const y of ys) {
|
|
147
|
+
for (const x of xs) {
|
|
148
|
+
const avg = averageWindow(image, x, y);
|
|
149
|
+
if (!avg) continue;
|
|
150
|
+
const bgHex = rgbToHex(avg.r, avg.g, avg.b);
|
|
151
|
+
const effective = blendOver(run.fill, bgHex, run.alpha);
|
|
152
|
+
const ratio = contrastRatio(effective, bgHex);
|
|
153
|
+
if (!worst || ratio < worst.ratio) worst = { ratio, background: bgHex };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return worst;
|
|
157
|
+
}
|
|
158
|
+
function pixelContrastMessage(issue) {
|
|
159
|
+
return `text "${issue.text}" has a pixel-sampled contrast ratio of ${issue.ratio.toFixed(2)}:1 against its image background (sampled ${issue.background}, target ${issue.required}:1) \u2014 this text sits directly on an image with no resolvable solid backing color; reposition it, add an opaque-enough scrim behind it, or recolor the text`;
|
|
160
|
+
}
|
|
161
|
+
function resolveRasterizer() {
|
|
162
|
+
return getPlatform().rasterizeSvg ?? rasterizeSvgInBrowser;
|
|
163
|
+
}
|
|
164
|
+
async function pixelFindingsForPage(markup, page, slideId, rasterize) {
|
|
165
|
+
const runs = __collectImageBackedTextRuns(markup);
|
|
166
|
+
if (runs.length === 0) return [];
|
|
167
|
+
const stripped = stripTextNodes(markup);
|
|
168
|
+
const image = await rasterize(stripped, PIXEL_CANVAS_W, PIXEL_CANVAS_H);
|
|
169
|
+
const findings = [];
|
|
170
|
+
for (const run of runs) {
|
|
171
|
+
const sampled = worstCaseSample(run, image);
|
|
172
|
+
if (!sampled) continue;
|
|
173
|
+
if (sampled.ratio < PIXEL_HARD_FINDING_MAX_RATIO) {
|
|
174
|
+
const issue = {
|
|
175
|
+
text: run.text,
|
|
176
|
+
fill: run.fill,
|
|
177
|
+
background: sampled.background,
|
|
178
|
+
ratio: sampled.ratio,
|
|
179
|
+
required: run.required,
|
|
180
|
+
fontSize: run.fontSize
|
|
181
|
+
};
|
|
182
|
+
findings.push({
|
|
183
|
+
page,
|
|
184
|
+
...slideId !== void 0 ? { slideId } : {},
|
|
185
|
+
code: "low-contrast",
|
|
186
|
+
message: pixelContrastMessage(issue),
|
|
187
|
+
// `source: "pixels"` distinguishes this from an SVG-color-resolved
|
|
188
|
+
// low-contrast finding's own `detail` shape (`ContrastIssue`,
|
|
189
|
+
// `deck-audit.ts`) — same `code`, since both are the same category
|
|
190
|
+
// of defect (text fails contrast against its real background), just
|
|
191
|
+
// measured through a different, more reliable source for that
|
|
192
|
+
// background's color.
|
|
193
|
+
detail: { ...issue, source: "pixels" }
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return findings;
|
|
198
|
+
}
|
|
199
|
+
var __pixelFindingsForPage = pixelFindingsForPage;
|
|
200
|
+
async function runPixelContrastAudit(ir) {
|
|
201
|
+
const rasterize = resolveRasterizer();
|
|
202
|
+
const findings = [];
|
|
203
|
+
for (let i = 0; i < ir.slides.length; i++) {
|
|
204
|
+
const slide = ir.slides[i];
|
|
205
|
+
if (slide.placeholder) continue;
|
|
206
|
+
const page = i + 1;
|
|
207
|
+
const slideId = slide.id;
|
|
208
|
+
const markup = renderSlideSvg(ir, i);
|
|
209
|
+
findings.push(...await pixelFindingsForPage(markup, page, slideId, rasterize));
|
|
210
|
+
}
|
|
211
|
+
return findings;
|
|
212
|
+
}
|
|
213
|
+
export {
|
|
214
|
+
__pixelFindingsForPage,
|
|
215
|
+
runPixelContrastAudit,
|
|
216
|
+
stripTextNodes
|
|
217
|
+
};
|
|
218
|
+
//# sourceMappingURL=pixel-audit-ZRFTV4V7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/platform/browser.ts","../src/svg/audit/pixel-audit.ts"],"sourcesContent":["import { findRemoteAssetRef, type RasterizedImage } from \"./registry\"\n\n/**\n * Browser default for `rasterizeSvg` (audit-v2 phase B, spec §4.3/§11.8) —\n * native `Image` + `OffscreenCanvas`/`<canvas>` only, zero new dependency.\n * Applied at the pixel-audit call site (`../svg/audit/pixel-audit.ts`) the\n * same way `domParser`'s `?? globalThis.DOMParser` fallback already works\n * (`deck-audit.ts`'s `parseSvg`) — nothing calls `installPlatform()`\n * automatically in a browser, so this is a plain fallback function, not\n * something wired through `installPlatform()` itself. Lives outside\n * `src/platform/node.ts` (which imports `linkedom`/`sharp`) so it can sit\n * inside `src/index.ts`'s own browser-safe dependency closure without\n * pulling in either.\n *\n * Two explicit-failure paths, both load-bearing per the audit-v2 controller\n * ruling on browser remote assets (own tests: `browser.test.ts`):\n *\n * 1. `findRemoteAssetRef` — scanned *before* ever touching `Image`/canvas.\n * An `<img>`/`Image` load of an `http(s):` asset happens in a restricted\n * context: the resource is silently dropped rather than reliably\n * tainting the canvas, so without this guard a remote-image slide would\n * rasterize to a *blank* region and get sampled as if that blank were\n * the real background — exactly the \"checked nothing, reported clean\"\n * failure this wave rules out. (`node.ts`'s Sharp implementation shares\n * this same guard for a different reason — see `findRemoteAssetRef`'s own\n * doc comment.)\n * 2. `getImageData`'s own `SecurityError` — kept as a fallback for\n * whatever the markup scan didn't anticipate (a future asset kind, a\n * same-origin-but-still-tainting edge case): caught and re-thrown as an\n * explicit, readable error rather than left as a raw `DOMException` (or,\n * worse, silently producing zeroed pixel data some engines return\n * instead of throwing).\n */\n\ninterface Minimal2dContext {\n drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void\n getImageData(sx: number, sy: number, sw: number, sh: number): ImageData\n}\n\ninterface MinimalCanvas {\n getContext(id: \"2d\"): Minimal2dContext | null\n}\n\n/** `DOMException` is *not* an `Error` subclass per the WebIDL spec (real\n * browsers: `new DOMException(\"x\", \"SecurityError\") instanceof Error` is\n * `false`) — duck-type on `.name` rather than `instanceof Error`. */\nfunction isSecurityError(e: unknown): boolean {\n return typeof e === \"object\" && e !== null && (e as { name?: unknown }).name === \"SecurityError\"\n}\n\n/**\n * Maximum time (ms) to wait for `Image.onload`/`onerror` to fire before\n * treating the decode as stuck and rejecting explicitly, rather than\n * hanging the whole `rasterizeSvgInBrowser` call forever — unlike the\n * Node/Sharp path (`node.ts`'s `rasterizeSvg`, a synchronous, bounded\n * call), a browser `Image` decode has no timeout of its own, and a\n * genuinely stuck one (a browser/OS decoder bug, an unresponsive tab) would\n * otherwise leave the caller (e.g. a pixel-contrast audit) awaiting forever\n * with no way to know why. 30s: generous for even a large local decode —\n * this rasterizer only ever reaches `Image` for a local/data-URI SVG\n * (`findRemoteAssetRef` already rejected any remote asset reference above)\n * — but short enough that a stuck decode fails loud well within any\n * interactive caller's own patience.\n */\nexport const IMAGE_LOAD_TIMEOUT_MS = 30_000\n\nfunction loadImage(url: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new Error(\n `rasterizeSvg: timed out after ${IMAGE_LOAD_TIMEOUT_MS}ms waiting for the browser to decode the rasterized SVG as an image (a stuck decode, never a silent hang)`,\n ),\n )\n }, IMAGE_LOAD_TIMEOUT_MS)\n const img = new Image()\n img.onload = () => {\n clearTimeout(timer)\n resolve(img)\n }\n img.onerror = () => {\n clearTimeout(timer)\n reject(new Error(\"rasterizeSvg: the browser could not decode the rasterized SVG as an image\"))\n }\n img.src = url\n })\n}\n\nfunction createCanvas(width: number, height: number): MinimalCanvas {\n if (typeof OffscreenCanvas !== \"undefined\") {\n return new OffscreenCanvas(width, height) as unknown as MinimalCanvas\n }\n if (typeof document !== \"undefined\") {\n const canvas = document.createElement(\"canvas\")\n canvas.width = width\n canvas.height = height\n return canvas as unknown as MinimalCanvas\n }\n throw new Error(\n 'rasterizeSvg unavailable — in Node, call installNodePlatform() from \"@liustack/pptfast/node\" first (the pptfast CLI does this automatically); in a browser, OffscreenCanvas or a DOM canvas is required',\n )\n}\n\nexport async function rasterizeSvgInBrowser(svgMarkup: string, width: number, height: number): Promise<RasterizedImage> {\n const remoteRef = findRemoteAssetRef(svgMarkup)\n if (remoteRef) {\n throw new Error(\n `rasterizeSvg: refusing to rasterize an SVG that references a remote image (${remoteRef}) — only data-URI (or other local) assets are supported (a remote asset would silently drop when loaded this way, not rasterize)`,\n )\n }\n if (typeof Image === \"undefined\") {\n throw new Error(\n 'rasterizeSvg unavailable — in Node, call installNodePlatform() from \"@liustack/pptfast/node\" first (the pptfast CLI does this automatically); in a browser, the Image constructor is required',\n )\n }\n\n const blob = new Blob([svgMarkup], { type: \"image/svg+xml\" })\n const url = URL.createObjectURL(blob)\n try {\n const img = await loadImage(url)\n const canvas = createCanvas(width, height)\n const ctx = canvas.getContext(\"2d\")\n if (!ctx) throw new Error(\"rasterizeSvg: could not obtain a 2d canvas context\")\n ctx.drawImage(img, 0, 0, width, height)\n let imageData: ImageData\n try {\n imageData = ctx.getImageData(0, 0, width, height)\n } catch (e) {\n if (isSecurityError(e)) {\n throw new Error(\n \"rasterizeSvg: the canvas was tainted while reading back pixel data (a cross-origin or otherwise untrusted asset) — only data-URI (or other local) assets are supported\",\n )\n }\n throw e\n }\n return { width: imageData.width, height: imageData.height, data: imageData.data }\n } finally {\n URL.revokeObjectURL(url)\n }\n}\n","import type { PptxIR } from \"@/ir\"\nimport { renderSlideSvg } from \"../../api\"\nimport { CANVAS_H_PX, CANVAS_W_PX } from \"../../constants\"\nimport { rasterizeSvgInBrowser } from \"../../platform/browser\"\nimport { getPlatform, type RasterizedImage } from \"../../platform/registry\"\nimport {\n __collectImageBackedTextRuns,\n blendOver,\n contrastRatio,\n type AuditFinding,\n type ImageBackedTextRun,\n} from \"./deck-audit\"\n\n/**\n * Optional pixel-level contrast audit (audit-v2 phase B, spec §4.3) — the\n * one pixel blind spot the deterministic SVG audit can't see: text painted\n * directly over a bare or too-faintly-scrimmed `<image>`, where\n * `deck-audit.ts`'s own SVG-color walk correctly gives up rather than guess\n * (`ImageBackedTextRun`, `__collectImageBackedTextRuns`). Never imported by\n * `deck-audit.ts` at the top level — `auditDeck`'s `pixels: true` branch\n * reaches this module through a lazy `import(\"./pixel-audit\")` instead\n * (that function's own doc comment explains why: this file statically\n * depends on `deck-audit.ts` for its shared primitives, so a *static*\n * import the other way would form a module cycle; nothing here needs to be\n * loaded at all for the far more common `pixels` left unset case).\n *\n * Flow per spec §4.3, steps 2-6:\n * 1. `__collectImageBackedTextRuns` — reuse the exact same background-\n * resolution walk the deterministic audit already ran, just reading its\n * \"could not resolve\" runs instead of discarding them. A page with none\n * skips rasterization entirely (no rasterizer call, no risk of that\n * page's own remote-asset guard ever firing) — real cost only where\n * there is real work to do.\n * 2. `stripTextNodes` — the \"去文字克隆\" clone.\n * 3. `rasterizeSvg(stripped, 1280, 720)` — platform primitive (Sharp in\n * Node, native canvas in a browser — see `resolveRasterizer`).\n * 4/5. `worstCaseSample` — grid-sample each run's estimated box against the\n * rasterized pixels, tracking the least-favorable (lowest-ratio) point.\n * 6. Only a sample below `PIXEL_HARD_FINDING_MAX_RATIO` becomes a finding —\n * spec §4.3's own anti-false-positive gate, see that constant's doc\n * comment.\n */\n\nconst PIXEL_CANVAS_W = CANVAS_W_PX\nconst PIXEL_CANVAS_H = CANVAS_H_PX\n\n/**\n * Below this, a pixel-sampled contrast finding is emitted regardless of the\n * real WCAG target (`ImageBackedTextRun.required`) — spec §4.3's own \"为了\n * 控制误报,首版只有低于 1.5:1 才进入 hard finding\" gate. Pixel sampling\n * carries antialiasing/rasterizer noise the SVG-only walk never has to deal\n * with (spec §11.10's determinism footnote: no cross-platform byte\n * guarantee for this layer) — `node-rasterize.test.ts`'s own transparency\n * probe found up to ~1/255-per-channel sequential-blend rounding drift,\n * nowhere near enough to move a real ratio across this floor. Deliberately\n * far below either real WCAG floor (3/4.5) so only a genuinely broken\n * pairing fires, not a borderline-but-fine one.\n */\nconst PIXEL_HARD_FINDING_MAX_RATIO = 1.5\n\n/**\n * Strip every `<text>...</text>` (and self-closing `<text/>`) element from\n * SVG markup — spec §4.3 step 2's \"去文字克隆\" (clone with text removed). A\n * plain string replace, not a DOM parse/remove/reserialize round-trip:\n * removing an element has zero effect on sibling/ancestor geometry in SVG\n * (no reflow, unlike HTML), so a round-trip would only add risk — a\n * serializer (linkedom in Node) producing markup that doesn't byte-match\n * what a real browser's `XMLSerializer` would, for zero benefit. Sound\n * under two preconditions this renderer's own architecture already\n * guarantees: `renderToStaticMarkup` (React) HTML/XML-escapes every text\n * *node*, so a literal `</text>` substring appearing in `markup` can only\n * ever be a real closing tag, never escaped slide content; and `<text>` is\n * never nested inside another `<text>` anywhere in `src/svg` (verified\n * across every emitter while building this task).\n */\nconst TEXT_ELEMENT_RE = /<text\\b[^>]*\\/>|<text\\b[^>]*>[\\s\\S]*?<\\/text>/g\n\nexport function stripTextNodes(markup: string): string {\n return markup.replace(TEXT_ELEMENT_RE, \"\")\n}\n\nfunction rgbToHex(r: number, g: number, b: number): string {\n // Rounds first: callers now include averaged (non-integer) channel values\n // (`averageWindow`'s own doc comment) alongside the original raw-integer\n // ones — `Math.round` is a no-op for the latter, so this stays byte-for-\n // byte compatible with every pre-existing call shape.\n const toHex = (v: number) => Math.round(v).toString(16).padStart(2, \"0\")\n return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase()\n}\n\n/**\n * Ascent/descent as a fraction of `fontSize`, defining the vertical band\n * `worstCaseSample` grids over — no real font metrics are available at\n * audit time (this renderer never embeds/queries a font file), so both are\n * the same kind of declared-size-relative heuristic `deck-audit.ts`'s own\n * `TEXT_DESCENT_RATIO` (0.25, used for v-overflow/derived-box-height) is —\n * `SAMPLE_DESCENT_RATIO` mirrors it exactly for consistency between the two\n * auditors' notion of \"how far below the baseline a glyph's ink extends\".\n * `SAMPLE_ASCENT_RATIO` (0.75) is this task's own addition — no existing\n * constant to mirror since nothing before this needed a text run's *top*\n * edge — a standard approximation for common UI sans-serif cap-height/\n * ascender proportion.\n */\nconst SAMPLE_ASCENT_RATIO = 0.75\nconst SAMPLE_DESCENT_RATIO = 0.25\n\n/**\n * Minimum contiguous low-contrast patch size (px, both axes, at the\n * 1280×720 rasterization scale) the sampling design below guarantees never\n * to miss — \"glyph scale\": at or below the narrowest highlight/shadow\n * sliver a single character can plausibly introduce (the deep-acceptance\n * review's own demonstrated miss used a 24px-wide patch, comfortably above\n * this floor with margin to spare). Anchors both `SAMPLE_STRIDE_PX`\n * (coverage) and the `SAMPLE_STRIDE_PX` vs `AGGREGATION_HALF_PX` margin\n * (noise robustness) — see `worstCaseSample`'s own doc comment for the\n * covering argument these three constants together satisfy.\n */\nconst MIN_GUARANTEED_PATCH_PX = 10\n\n/**\n * Sample-center spacing (px), both axes — half of `MIN_GUARANTEED_PATCH_PX`,\n * computed rather than duplicated as a literal so the two constants can\n * never drift apart. The standard \"sample at <= half the feature size\"\n * covering rule. Replaces\n * the old fixed 5×3-point grid (`SAMPLE_COLS`/`SAMPLE_ROWS`), whose own\n * justifying comment (\"15 points is already enough...\") the deep-acceptance\n * review falsified with a hand-verified repro: a real 1.03:1 contrast patch\n * sitting 35px from the nearest sample column (columns were 70px apart at\n * ImageCoverPage's real org-line scale) produced zero findings, yet the\n * identical patch was caught the moment it landed on a column — pure\n * alignment luck, not a real \"worst-case band\" guarantee. A dense,\n * position-independent stride closes that gap entirely (see the coverage\n * proof below) instead of shrinking it.\n */\nconst SAMPLE_STRIDE_PX = MIN_GUARANTEED_PATCH_PX / 2\n\n/**\n * Half-width (px) of the small square window averaged at each sample\n * center before the worst-case comparison — the noise-robustness half of\n * this design. A lone single-pixel outlier (rasterizer antialiasing noise\n * under a glyph edge, photo grain) is diluted to at most 1/9 of a 3×3\n * window's mean, never enough on its own to pull a genuinely-safe\n * surrounding patch's averaged ratio under the 1.5 hard-finding floor (this\n * file's own test: a single near-black (8) pixel inside an otherwise-232\n * 3×3 window averages to ~207.5, nowhere near dark enough to fail near-\n * black text). Small enough — window width 3, well under `SAMPLE_STRIDE_PX\n * × 2 = 10` — that it cannot itself straddle a genuine\n * `MIN_GUARANTEED_PATCH_PX`-wide bad patch and a safe neighbor closely\n * enough to dilute a real defect back above the floor (this file's own\n * test: a real 12px-wide dark patch at the same spot the noise test uses\n * still produces a finding).\n */\nconst AGGREGATION_HALF_PX = 1\n\ninterface WorstCaseSample {\n ratio: number\n background: string\n}\n\n/**\n * Dense sample-center positions from `lo` to `hi` inclusive, `SAMPLE_STRIDE_PX`\n * apart. Always includes both endpoints, even when the span isn't an exact\n * stride multiple (the last gap can be shorter than the stride, never\n * longer) — a run's own edges are never under-sampled relative to its\n * interior. `[lo]` when the span has collapsed to (or below) a point, same\n * degenerate-input guard the old fixed-fraction grid had.\n */\nfunction samplePositions(lo: number, hi: number): number[] {\n if (hi <= lo) return [lo]\n const positions: number[] = []\n for (let v = lo; v < hi; v += SAMPLE_STRIDE_PX) positions.push(v)\n positions.push(hi)\n return positions\n}\n\n/**\n * Mean RGB of the `(2*AGGREGATION_HALF_PX+1)²` pixel block centered at\n * `(cx, cy)` (rounded to the nearest pixel) — the noise-robustness\n * aggregation step, see `AGGREGATION_HALF_PX`'s own doc comment. Skips any\n * pixel that's off-canvas or below full alpha, same indeterminate rule the\n * original single-point design used; a window with at least one usable\n * pixel still contributes its partial average rather than being discarded\n * outright, maximizing real coverage near a run's own box edges. Returns\n * `null` only when the window contained zero usable pixels.\n */\nfunction averageWindow(image: RasterizedImage, cx: number, cy: number): { r: number; g: number; b: number } | null {\n const x0 = Math.round(cx)\n const y0 = Math.round(cy)\n let sumR = 0\n let sumG = 0\n let sumB = 0\n let count = 0\n for (let dy = -AGGREGATION_HALF_PX; dy <= AGGREGATION_HALF_PX; dy++) {\n const y = y0 + dy\n if (y < 0 || y >= image.height) continue\n for (let dx = -AGGREGATION_HALF_PX; dx <= AGGREGATION_HALF_PX; dx++) {\n const x = x0 + dx\n if (x < 0 || x >= image.width) continue\n const i = (y * image.width + x) * 4\n const alpha = image.data[i + 3]!\n if (alpha < 255) continue\n sumR += image.data[i]!\n sumG += image.data[i + 1]!\n sumB += image.data[i + 2]!\n count++\n }\n }\n if (count === 0) return null\n return { r: sumR / count, g: sumG / count, b: sumB / count }\n}\n\n/**\n * Grid-sample `run`'s estimated box against `image` at a dense,\n * deterministic stride (`SAMPLE_STRIDE_PX`) — each sample point itself a\n * small-window average (`averageWindow`/`AGGREGATION_HALF_PX`) rather than\n * one raw pixel — tracking the least-favorable (lowest) contrast ratio\n * found overall: spec §4.3 step 6's \"WCAG 最不利带\" (worst-case band).\n *\n * **Coverage guarantee:** any axis-aligned contiguous low-contrast patch at\n * least `MIN_GUARANTEED_PATCH_PX` (10px) wide *and* tall is always fully\n * covered by at least one sample's aggregation window, regardless of the\n * patch's position relative to the grid — no alignment/phase assumption,\n * unlike the fixed grid this replaces. Proof, one axis at a time: sample\n * centers sit at a fixed stride S=5px; a window centered at `c` is fully\n * inside a patch spanning `[a, a+10]` exactly when\n * `c ∈ [a+1, a+9]` (window half-width 1px each side) — an interval of\n * length 8 >= S, so by the covering property of a grid spaced S apart (any\n * interval of length >= S must contain a grid point, since consecutive\n * centers are only S apart), that interval always contains at least one\n * sample center. The same argument applies independently on the\n * perpendicular axis, so a 2D patch of that minimum size is always hit on\n * both axes at once. (The deep-acceptance review's demonstrated miss used a\n * 24px patch — comfortably inside this guarantee with margin to spare.)\n *\n * **Noise robustness:** see `AGGREGATION_HALF_PX`'s own doc comment — the\n * same small window that provides the guarantee above also means a single\n * noisy pixel can't flip a genuinely-safe patch into a false finding.\n *\n * Returns `null` when *no* sample window anywhere yielded any usable pixel\n * at all (every window skipped, or the run's box fell entirely outside the\n * rasterized canvas) — the caller treats that as \"nothing proven either\n * way\", not a finding.\n */\nfunction worstCaseSample(run: ImageBackedTextRun, image: RasterizedImage): WorstCaseSample | null {\n const top = run.baseline - run.fontSize * SAMPLE_ASCENT_RATIO\n const bottom = run.baseline + run.fontSize * SAMPLE_DESCENT_RATIO\n let worst: WorstCaseSample | null = null\n\n const ys = samplePositions(top, bottom)\n const xs = samplePositions(run.left, run.right)\n\n for (const y of ys) {\n for (const x of xs) {\n const avg = averageWindow(image, x, y)\n if (!avg) continue\n\n const bgHex = rgbToHex(avg.r, avg.g, avg.b)\n const effective = blendOver(run.fill, bgHex, run.alpha)\n const ratio = contrastRatio(effective, bgHex)\n if (!worst || ratio < worst.ratio) worst = { ratio, background: bgHex }\n }\n }\n return worst\n}\n\nexport interface PixelContrastIssue {\n text: string\n fill: string\n /** The small-window-averaged RGB (hex) at the worst-case sample center —\n * a rasterized-and-aggregated sample, never a resolved SVG paint (see\n * `averageWindow`). */\n background: string\n ratio: number\n required: number\n fontSize: number\n}\n\nfunction pixelContrastMessage(issue: PixelContrastIssue): string {\n return (\n `text \"${issue.text}\" has a pixel-sampled contrast ratio of ${issue.ratio.toFixed(2)}:1 against its image background ` +\n `(sampled ${issue.background}, target ${issue.required}:1) — this text sits directly on an image with no resolvable ` +\n `solid backing color; reposition it, add an opaque-enough scrim behind it, or recolor the text`\n )\n}\n\ntype Rasterizer = (svgMarkup: string, width: number, height: number) => Promise<RasterizedImage>\n\n/**\n * `getPlatform().rasterizeSvg` (Sharp once `installNodePlatform()` ran) or\n * the browser default — the exact same `?? fallback` shape `deck-audit.ts`'s\n * `parseSvg` already uses for `domParser`. Never throws itself: an\n * environment with neither capability surfaces through\n * `rasterizeSvgInBrowser`'s own curated \"rasterizeSvg unavailable\" error the\n * first time the returned function is actually called (its `Image`/canvas\n * capability guards — see `browser.ts`), which is the explicit-failure\n * contract spec §11.7's \"契约层\" asks for either way.\n */\nfunction resolveRasterizer(): Rasterizer {\n return getPlatform().rasterizeSvg ?? rasterizeSvgInBrowser\n}\n\nasync function pixelFindingsForPage(\n markup: string,\n page: number,\n slideId: string | undefined,\n rasterize: Rasterizer,\n): Promise<AuditFinding[]> {\n const runs = __collectImageBackedTextRuns(markup)\n if (runs.length === 0) return []\n\n const stripped = stripTextNodes(markup)\n const image = await rasterize(stripped, PIXEL_CANVAS_W, PIXEL_CANVAS_H)\n\n const findings: AuditFinding[] = []\n for (const run of runs) {\n const sampled = worstCaseSample(run, image)\n if (!sampled) continue\n if (sampled.ratio < PIXEL_HARD_FINDING_MAX_RATIO) {\n const issue: PixelContrastIssue = {\n text: run.text,\n fill: run.fill,\n background: sampled.background,\n ratio: sampled.ratio,\n required: run.required,\n fontSize: run.fontSize,\n }\n findings.push({\n page,\n ...(slideId !== undefined ? { slideId } : {}),\n code: \"low-contrast\",\n message: pixelContrastMessage(issue),\n // `source: \"pixels\"` distinguishes this from an SVG-color-resolved\n // low-contrast finding's own `detail` shape (`ContrastIssue`,\n // `deck-audit.ts`) — same `code`, since both are the same category\n // of defect (text fails contrast against its real background), just\n // measured through a different, more reliable source for that\n // background's color.\n detail: { ...issue, source: \"pixels\" },\n })\n }\n }\n return findings\n}\n\n/**\n * Test-only re-export (`__`-prefixed, same \"SDK-internal, not part of any\n * public barrel\" convention `deck-audit.ts`'s own `__collectBgRegions`/\n * `__pathBoundingBox` establish): lets `pixel-audit.test.ts` exercise the\n * sampling-grid + `PIXEL_HARD_FINDING_MAX_RATIO` threshold logic directly,\n * with a hand-crafted `rasterize` function returning exact, controlled\n * pixel data — real component geometry (`ImagePages.tsx`'s `DarkScrim`, in\n * particular) turned out unable to organically produce a sub-1.5 ratio for\n * *any* photo brightness at the org-line's single-scrim-layer position\n * (confirmed empirically while building this task's own test suite: even a\n * pure-white source image only reaches ~1.83), which is the calibration\n * working as designed (spec §4.3's own \"control false positives\" gate) but\n * makes the threshold-crossing branch unreachable through real IR/archetype\n * fixtures alone.\n */\nexport const __pixelFindingsForPage = pixelFindingsForPage\n\n/**\n * The pixel-audit pass over an already-valid deck — `auditDeck(ir, {pixels:\n * true})`'s own async branch (`deck-audit.ts`). Independently walks\n * `ir.slides` (skipping placeholders the same way `runDeterministicAudit`\n * does) rather than reusing that function's own loop, so this module has no\n * static dependency back on it beyond the few named imports at the top of\n * this file — `renderSlideSvg` is pure and synchronous, so re-rendering\n * each non-placeholder slide a second time costs a little CPU, never\n * correctness (spec's own \"no second renderer\" non-goal is about a\n * *different* rendering path, not calling the one true renderer twice).\n *\n * Sequential, not `Promise.all` — deliberately bounds rasterization\n * concurrency to 1 (each Sharp call is real CPU-bound work) and makes the\n * page-order-stable output an obvious property of the code rather than an\n * incidental one `Promise.all`'s array-order guarantee happens to provide.\n *\n * A rasterization failure on any one page (missing platform capability, a\n * remote asset reference, a tainted canvas) propagates out of this function\n * entirely, aborting the whole pixel pass rather than silently skipping\n * just that page — spec §11.7's \"契约层\": a requested-but-failed pixel audit\n * is an explicit failure, never a partial \"clean\".\n */\nexport async function runPixelContrastAudit(ir: PptxIR): Promise<AuditFinding[]> {\n const rasterize = resolveRasterizer()\n const findings: AuditFinding[] = []\n for (let i = 0; i < ir.slides.length; i++) {\n const slide = ir.slides[i]!\n if (slide.placeholder) continue\n const page = i + 1\n const slideId = slide.id\n const markup = renderSlideSvg(ir, i)\n findings.push(...(await pixelFindingsForPage(markup, page, slideId, rasterize)))\n }\n return findings\n}\n"],"mappings":";;;;;;;;;;;;;;AA8CA,SAAS,gBAAgB,GAAqB;AAC5C,SAAO,OAAO,MAAM,YAAY,MAAM,QAAS,EAAyB,SAAS;AACnF;AAgBO,IAAM,wBAAwB;AAErC,SAAS,UAAU,KAAwC;AACzD,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,QAAQ,WAAW,MAAM;AAC7B;AAAA,QACE,IAAI;AAAA,UACF,iCAAiC,qBAAqB;AAAA,QACxD;AAAA,MACF;AAAA,IACF,GAAG,qBAAqB;AACxB,UAAM,MAAM,IAAI,MAAM;AACtB,QAAI,SAAS,MAAM;AACjB,mBAAa,KAAK;AAClB,cAAQ,GAAG;AAAA,IACb;AACA,QAAI,UAAU,MAAM;AAClB,mBAAa,KAAK;AAClB,aAAO,IAAI,MAAM,2EAA2E,CAAC;AAAA,IAC/F;AACA,QAAI,MAAM;AAAA,EACZ,CAAC;AACH;AAEA,SAAS,aAAa,OAAe,QAA+B;AAClE,MAAI,OAAO,oBAAoB,aAAa;AAC1C,WAAO,IAAI,gBAAgB,OAAO,MAAM;AAAA,EAC1C;AACA,MAAI,OAAO,aAAa,aAAa;AACnC,UAAM,SAAS,SAAS,cAAc,QAAQ;AAC9C,WAA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,IAAI;AAAA,QACV,MAAM,IAAI;AAAA,QACV,YAAY,QAAQ;AAAA,QACpB,OAAO,QAAQ;AAAA,QACf,UAAU,IAAI;AAAA,QACd,UAAU,IAAI;AAAA,MAChB;AACA,eAAS,KAAK;AAAA,QACZ;AAAA,QACA,GAAI,YAAY,SAAY,EAAE,QAAQ,IAAI,CAAC;AAAA,QAC3C,MAAM;AAAA,QACN,SAAS,qBAAqB,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAOnC,QAAQ,EAAE,GAAG,OAAO,QAAQ,SAAS;AAAA,MACvC,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AAiBO,IAAM,yBAAyB;AAwBtC,eAAsB,sBAAsB,IAAqC;AAC/E,QAAM,YAAY,kBAAkB;AACpC,QAAM,WAA2B,CAAC;AAClC,WAAS,IAAI,GAAG,IAAI,GAAG,OAAO,QAAQ,KAAK;AACzC,UAAM,QAAQ,GAAG,OAAO,CAAC;AACzB,QAAI,MAAM,YAAa;AACvB,UAAM,OAAO,IAAI;AACjB,UAAM,UAAU,MAAM;AACtB,UAAM,SAAS,eAAe,IAAI,CAAC;AACnC,aAAS,KAAK,GAAI,MAAM,qBAAqB,QAAQ,MAAM,SAAS,SAAS,CAAE;AAAA,EACjF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A rasterized page — RGBA, 4 bytes per pixel, row-major, top-to-bottom,
|
|
3
|
+
* straight (non-premultiplied) alpha. Deliberately *not* the DOM `ImageData`
|
|
4
|
+
* type: that interface only exists as an ambient global where a canvas
|
|
5
|
+
* implementation provides it, and this shape must be constructible in Node
|
|
6
|
+
* (from sharp's raw buffer) without depending on any DOM global actually
|
|
7
|
+
* existing at runtime — only the browser implementation happens to be able
|
|
8
|
+
* to hand back a real `ImageData` object, which satisfies this shape
|
|
9
|
+
* structurally without either side needing to import the other's type.
|
|
10
|
+
*/
|
|
11
|
+
interface RasterizedImage {
|
|
12
|
+
width: number;
|
|
13
|
+
height: number;
|
|
14
|
+
data: Uint8ClampedArray;
|
|
15
|
+
}
|
|
16
|
+
/** Environment seams. The SDK entry stays browser-safe: Node implementations
|
|
17
|
+
* live in ./node and are installed explicitly (CLI does it automatically). */
|
|
18
|
+
interface PptfastPlatform {
|
|
19
|
+
/** DOMParser constructor used to parse rendered SVG markup. */
|
|
20
|
+
domParser?: typeof DOMParser;
|
|
21
|
+
/** Re-encode an image data URL to PNG (Office rejects webp and friends). */
|
|
22
|
+
recodeImageToPng?: (dataUrl: string) => Promise<string>;
|
|
23
|
+
/**
|
|
24
|
+
* Rasterize SVG markup to a fixed-size pixel buffer (audit-v2 phase B,
|
|
25
|
+
* spec §4.3/§11.7) — the one primitive the optional pixel-contrast audit
|
|
26
|
+
* needs and the *only* one Sharp/canvas-shaped work is allowed to hide
|
|
27
|
+
* behind (`src/svg/audit/pixel-audit.ts` never imports a rasterizer
|
|
28
|
+
* itself). `installNodePlatform()` wires this to Sharp; a real browser
|
|
29
|
+
* gets its own default (`./browser.ts`'s `rasterizeSvgInBrowser`) applied
|
|
30
|
+
* at the call site the same way `domParser`'s `?? globalThis.DOMParser`
|
|
31
|
+
* fallback already works — not through this seam, since nothing calls
|
|
32
|
+
* `installPlatform()` automatically in a browser. Every implementation
|
|
33
|
+
* must reject markup `findRemoteAssetRef` flags rather than touch the
|
|
34
|
+
* network or a tainted canvas.
|
|
35
|
+
*/
|
|
36
|
+
rasterizeSvg?: (svgMarkup: string, width: number, height: number) => Promise<RasterizedImage>;
|
|
37
|
+
}
|
|
38
|
+
declare function installPlatform(p: PptfastPlatform): void;
|
|
39
|
+
|
|
40
|
+
export { type PptfastPlatform as P, type RasterizedImage as R, installPlatform as i };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@liustack/pptfast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Stable, editable PPTX generation for AI agents — semantic IR in, native DrawingML out",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -26,16 +26,22 @@
|
|
|
26
26
|
"engines": {
|
|
27
27
|
"node": ">=18"
|
|
28
28
|
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
29
32
|
"scripts": {
|
|
30
33
|
"build": "tsup",
|
|
31
34
|
"typecheck": "tsc --noEmit",
|
|
32
|
-
"lint": "eslint src scripts --no-error-on-unmatched-pattern",
|
|
35
|
+
"lint": "eslint src scripts tests --no-error-on-unmatched-pattern",
|
|
33
36
|
"test": "vitest run",
|
|
34
37
|
"test:watch": "vitest",
|
|
35
38
|
"check": "pnpm typecheck && pnpm lint && pnpm test",
|
|
36
39
|
"e2e": "pnpm build && tsx scripts/e2e.mts",
|
|
40
|
+
"bench:score": "tsx tests/bench/score.mts",
|
|
37
41
|
"docs:list": "node scripts/docs-list.js",
|
|
38
|
-
"prepublishOnly": "pnpm check && pnpm
|
|
42
|
+
"prepublishOnly": "pnpm check && pnpm e2e",
|
|
43
|
+
"release:version": "changeset version && tsx scripts/sync-version.mts",
|
|
44
|
+
"bench:run": "tsx tests/bench/run.mts"
|
|
39
45
|
},
|
|
40
46
|
"keywords": [
|
|
41
47
|
"pptx",
|
|
@@ -67,6 +73,7 @@
|
|
|
67
73
|
"sharp": "^0.34.4"
|
|
68
74
|
},
|
|
69
75
|
"devDependencies": {
|
|
76
|
+
"@changesets/cli": "^2.31.1",
|
|
70
77
|
"@eslint/js": "^9.39.0",
|
|
71
78
|
"@testing-library/jest-dom": "^6.9.1",
|
|
72
79
|
"@testing-library/react": "^16.3.2",
|
package/dist/chunk-G76EVNVT.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
// src/platform/registry.ts
|
|
2
|
-
var current = {};
|
|
3
|
-
function installPlatform(p) {
|
|
4
|
-
current = { ...current, ...p };
|
|
5
|
-
}
|
|
6
|
-
function getPlatform() {
|
|
7
|
-
return current;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export {
|
|
11
|
-
installPlatform,
|
|
12
|
-
getPlatform
|
|
13
|
-
};
|
|
14
|
-
//# sourceMappingURL=chunk-G76EVNVT.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/platform/registry.ts"],"sourcesContent":["/** Environment seams. The SDK entry stays browser-safe: Node implementations\n * live in ./node and are installed explicitly (CLI does it automatically). */\nexport interface PptfastPlatform {\n /** DOMParser constructor used to parse rendered SVG markup. */\n domParser?: typeof DOMParser\n /** Re-encode an image data URL to PNG (Office rejects webp and friends). */\n recodeImageToPng?: (dataUrl: string) => Promise<string>\n}\n\nlet current: PptfastPlatform = {}\n\nexport function installPlatform(p: PptfastPlatform): void {\n current = { ...current, ...p }\n}\n\nexport function getPlatform(): PptfastPlatform {\n return current\n}\n"],"mappings":";AASA,IAAI,UAA2B,CAAC;AAEzB,SAAS,gBAAgB,GAA0B;AACxD,YAAU,EAAE,GAAG,SAAS,GAAG,EAAE;AAC/B;AAEO,SAAS,cAA+B;AAC7C,SAAO;AACT;","names":[]}
|
package/dist/chunk-SROEW6BH.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
installPlatform
|
|
3
|
-
} from "./chunk-G76EVNVT.js";
|
|
4
|
-
|
|
5
|
-
// src/platform/node.ts
|
|
6
|
-
import { DOMParser as LinkedomDOMParser } from "linkedom";
|
|
7
|
-
async function recodeWithSharp(dataUrl) {
|
|
8
|
-
let sharpMod;
|
|
9
|
-
try {
|
|
10
|
-
sharpMod = (await import("sharp")).default;
|
|
11
|
-
} catch (e) {
|
|
12
|
-
const err = e;
|
|
13
|
-
if (err?.code === "ERR_MODULE_NOT_FOUND" || /Cannot find/.test(err?.message ?? "")) {
|
|
14
|
-
throw new Error(
|
|
15
|
-
'Re-encoding non-PNG/JPEG/GIF images requires the optional dependency "sharp" (npm i sharp), or convert the image beforehand'
|
|
16
|
-
);
|
|
17
|
-
}
|
|
18
|
-
throw e;
|
|
19
|
-
}
|
|
20
|
-
const base64 = dataUrl.slice(dataUrl.indexOf(",") + 1);
|
|
21
|
-
const png = await sharpMod(Buffer.from(base64, "base64")).png().toBuffer();
|
|
22
|
-
return `data:image/png;base64,${png.toString("base64")}`;
|
|
23
|
-
}
|
|
24
|
-
function installNodePlatform() {
|
|
25
|
-
installPlatform({
|
|
26
|
-
domParser: LinkedomDOMParser,
|
|
27
|
-
recodeImageToPng: recodeWithSharp
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export {
|
|
32
|
-
installNodePlatform
|
|
33
|
-
};
|
|
34
|
-
//# sourceMappingURL=chunk-SROEW6BH.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/platform/node.ts"],"sourcesContent":["import { DOMParser as LinkedomDOMParser } from \"linkedom\"\nimport { installPlatform } from \"./registry\"\nimport type * as Sharp from \"sharp\"\n\nasync function recodeWithSharp(dataUrl: string): Promise<string> {\n let sharpMod: typeof Sharp.default\n try {\n sharpMod = (await import(\"sharp\")).default as unknown as typeof Sharp.default\n } catch (e) {\n const err = e as NodeJS.ErrnoException\n if (err?.code === \"ERR_MODULE_NOT_FOUND\" || /Cannot find/.test(err?.message ?? \"\")) {\n throw new Error(\n 'Re-encoding non-PNG/JPEG/GIF images requires the optional dependency \"sharp\" (npm i sharp), or convert the image beforehand'\n )\n }\n throw e\n }\n const base64 = dataUrl.slice(dataUrl.indexOf(\",\") + 1)\n const png = await sharpMod(Buffer.from(base64, \"base64\")).png().toBuffer()\n return `data:image/png;base64,${png.toString(\"base64\")}`\n}\n\n/** Wire Node implementations (linkedom DOM, sharp image re-encode) into the SDK. */\nexport function installNodePlatform(): void {\n installPlatform({\n domParser: LinkedomDOMParser as unknown as typeof DOMParser,\n recodeImageToPng: recodeWithSharp,\n })\n}\n"],"mappings":";;;;;AAAA,SAAS,aAAa,yBAAyB;AAI/C,eAAe,gBAAgB,SAAkC;AAC/D,MAAI;AACJ,MAAI;AACF,gBAAY,MAAM,OAAO,OAAO,GAAG;AAAA,EACrC,SAAS,GAAG;AACV,UAAM,MAAM;AACZ,QAAI,KAAK,SAAS,0BAA0B,cAAc,KAAK,KAAK,WAAW,EAAE,GAAG;AAClF,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACA,QAAM,SAAS,QAAQ,MAAM,QAAQ,QAAQ,GAAG,IAAI,CAAC;AACrD,QAAM,MAAM,MAAM,SAAS,OAAO,KAAK,QAAQ,QAAQ,CAAC,EAAE,IAAI,EAAE,SAAS;AACzE,SAAO,yBAAyB,IAAI,SAAS,QAAQ,CAAC;AACxD;AAGO,SAAS,sBAA4B;AAC1C,kBAAgB;AAAA,IACd,WAAW;AAAA,IACX,kBAAkB;AAAA,EACpB,CAAC;AACH;","names":[]}
|