Sync snapshot (2026-09-09) (#271)

- **New app: GenOffice HTML.** Open, edit and generate .html pages: a source pane with a sandboxed live preview, click-to-select elements with a floating toolbar and style panel, device-size preview, image tools and a present mode. AI generates whole pages from a brief with style directions and offers page-wide Restyle, Theme and Summarize. Export to Word runs locally through the built-in html2docx converter (native, editable OOXML; no print-to-PDF detour).
- **AI:** separate BYOK providers for web search, image generation and image/video analysis; new Codex App Server provider; Ask AI quotes the selected text and keeps it highlighted while it runs; custom AI panel text size; blocked requests retry through the Chromium network stack.
- **App:** global AutoSave setting shared by every editor; AI panel text size and chat spellcheck toggles (genoffice#249); Czech (cs) UI locale (genoffice#259); Save As defaults to the document's folder; PDF export no longer aborts on CJK file paths on Windows.
- **Docs:** Export as HTML; comments and replies edit in place from the comments pane; the caret can leave a trailing table (genoffice#266); spellcheck re-marks text as soon as it is re-enabled; AI edits are character-precise on partial selections; zoom keeps the scroll position; pasting a cell from Sheets takes the destination font.
- **Sheets:** Find no longer freezes on wide or streamed grids; Replace searches as you type; cached values of external-workbook formulas are kept instead of #ERROR! (genoffice#235); "number stored as text" is a warning, not an error (genoffice#236); paste repeats into the target range like Excel; filter criteria survive save/reopen; saves retry when Windows locks the file; many Excel-fidelity fixes for column widths, row heights, charts, slicers, number formats and CJK fonts.
- **Slides:** PDF export works for large presentations (genoffice#264); EMF/WMF picture fonts and East Asian theme fonts resolve correctly; decks with missing layouts or embedded styles still open; outline-only pie slices render.
- **PDF:** highlight and underline geometry aligns with the text; Shift+arrows extend the selection instead of paging.
- **Markdown:** Find and replace (Ctrl+F / Ctrl+H) (genoffice#253); mermaid code blocks render as diagrams (genoffice#263); better print quality.
- Thanks to community contributors @GoodScholar, @aniruddhaadak80 and @Sun8854, and to @hanyscz, @qgzln, @zyp997, @bisslot, @krakotay and @Ben03151 for the reports.

Co-authored-by: GenOffice <merrick-2002@users.noreply.github.com>
This commit is contained in:
merrick-2002
2026-09-09 18:19:13 +08:00
committed by GitHub
co-authored by GenOffice
parent fa58fff047
commit d24c964a3e
678 changed files with 75586 additions and 7492 deletions
+1 -1
View File
@@ -15,6 +15,6 @@
},
"devDependencies": {
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
}
}
+1 -1
View File
@@ -20,6 +20,6 @@
},
"devDependencies": {
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
}
}
+2
View File
@@ -14,3 +14,5 @@ export {
clampMaxOutputTokens,
} from './providers'
export { getProviderAdapter, modelLacksVision } from './registry'
export { AI_MEDIA_PROVIDERS, imageGenerationAvailable, mediaAnalysisAvailable } from './media'
export { AI_SEARCH_PROVIDERS } from './search-settings'
+171 -62
View File
@@ -18,7 +18,7 @@ interface CodexAppServerTurn {
}>
}
interface RpcMessage {
export interface RpcMessage {
id?: unknown
method?: unknown
params?: unknown
@@ -42,6 +42,10 @@ interface NativeSession {
threadId: string
signature: string
messageFingerprints: string[]
/** Created with the thread and kept alive as long as it: the thread's cwd and
* permission profile are bound to this path, and later localImage files land
* here. Removed only when the session is dropped. */
tempDir: string
}
interface ModelEntry {
@@ -136,14 +140,37 @@ async function newestManagedCodex(root: string, platform: NodeJS.Platform): Prom
return pool[0]?.path ?? null
}
/**
* Finder/Dock-launched Electron inherits a minimal PATH, so the directories
* npm, Homebrew and version managers install into are probed explicitly.
*/
async function commonUnixBinDirs(env: NodeJS.ProcessEnv): Promise<string[]> {
const home = env.HOME ?? ''
const dirs = ['/opt/homebrew/bin', '/usr/local/bin']
if (home) {
dirs.push(
join(home, '.local', 'bin'),
join(home, '.npm-global', 'bin'),
join(home, '.volta', 'bin'),
join(home, '.bun', 'bin'),
join(home, '.yarn', 'bin'),
)
const nvmRoot = join(home, '.nvm', 'versions', 'node')
const versions = await readdir(nvmRoot).catch(() => [] as string[])
for (const version of versions.sort().reverse()) dirs.push(join(nvmRoot, version, 'bin'))
}
return dirs
}
async function codexOnPath(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
): Promise<string | null> {
const pathValue = env.PATH ?? env.Path ?? env.path ?? ''
if (!pathValue) return null
const names = platform === 'win32' ? ['codex.exe'] : ['codex']
for (const directory of pathValue.split(platform === 'win32' ? ';' : delimiter)) {
const directories = pathValue ? pathValue.split(platform === 'win32' ? ';' : delimiter) : []
if (platform !== 'win32') directories.push(...(await commonUnixBinDirs(env)))
for (const directory of directories) {
const cleanDirectory = cleanCliPath(directory)
if (!cleanDirectory) continue
for (const name of names) {
@@ -228,7 +255,7 @@ function codexChildEnv(cliPath: string): NodeJS.ProcessEnv {
if (process.platform === 'win32' && !env.HOME && env.USERPROFILE) env.HOME = env.USERPROFILE
if (isAbsolute(cliPath)) {
const key = Object.keys(env).find((name) => name.toLowerCase() === 'path') ?? 'PATH'
env[key] = `${dirname(cliPath)};${env[key] ?? ''}`
env[key] = `${dirname(cliPath)}${delimiter}${env[key] ?? ''}`
}
return env
}
@@ -318,12 +345,26 @@ class CodexAppServerClient {
while (this.sessions.size > MAX_NATIVE_SESSIONS) {
const oldest = this.sessions.keys().next().value as string | undefined
if (!oldest) break
const evicted = this.sessions.get(oldest)
this.sessions.delete(oldest)
if (evicted) this.disposeSession(evicted, true)
}
}
deleteSession(id: string): void {
const session = this.sessions.get(id)
if (!session) return
this.sessions.delete(id)
this.disposeSession(session, true)
}
/** Drop a session's temp dir and, when the process is still alive, its native
* thread. `signal` is false during shutdown, where the child is already gone. */
private disposeSession(session: NativeSession, signal: boolean): void {
void rm(session.tempDir, { recursive: true, force: true }).catch(() => undefined)
if (signal && !this.closed) {
void this.requestWire('thread/delete', { threadId: session.threadId }).catch(() => undefined)
}
}
stop(): void {
@@ -409,6 +450,7 @@ class CodexAppServerClient {
pending.reject(error)
}
this.pending.clear()
for (const session of this.sessions.values()) this.disposeSession(session, false)
this.sessions.clear()
this.notificationListeners.clear()
this.onClose()
@@ -633,11 +675,14 @@ function objectValue(value: unknown): Record<string, unknown> | undefined {
}
function threadIdFrom(result: unknown): string {
const id = optionalThreadId(result)
if (!id) throw new Error('Codex app-server did not return a thread id')
return id
}
function optionalThreadId(result: unknown): string | undefined {
const thread = objectValue(objectValue(result)?.thread)
if (typeof thread?.id !== 'string' || !thread.id) {
throw new Error('Codex app-server did not return a thread id')
}
return thread.id
return typeof thread?.id === 'string' && thread.id ? thread.id : undefined
}
function finalMessageFromTurn(params: unknown): string {
@@ -650,25 +695,80 @@ function finalMessageFromTurn(params: unknown): string {
return ''
}
const CODEX_PERMISSION_PROFILE = 'genoffice'
/**
* Codex keeps its own shell tool even when told not to use it, and the plain
* read-only sandbox still lets that tool read the whole disk. A permission
* profile confines reads to platform paths plus our temp dir. An explicit
* `sandbox` would disable the profile, so it is only used in the fallback.
*/
export function codexThreadStartParams(
config: AiProviderConfig,
tempDir: string,
mode: 'profile' | 'read-only',
): Record<string, unknown> {
const base = {
...(config.model.trim() ? { model: config.model.trim() } : {}),
cwd: tempDir,
approvalPolicy: 'never',
serviceName: 'genoffice',
baseInstructions: CODEX_BASE_INSTRUCTIONS,
ephemeral: true,
}
if (mode === 'read-only') return { ...base, sandbox: 'read-only' }
return {
...base,
config: {
default_permissions: CODEX_PERMISSION_PROFILE,
permissions: {
[CODEX_PERMISSION_PROFILE]: { filesystem: { ':minimal': 'read', [tempDir]: 'read' } },
},
},
}
}
export function activePermissionProfileId(result: unknown): string | undefined {
const active = objectValue(objectValue(result)?.activePermissionProfile)
return typeof active?.id === 'string' ? active.id : undefined
}
async function startNativeThread(
client: CodexAppServerClient,
config: AiProviderConfig,
tempDir: string,
): Promise<string> {
const result = await client.request('thread/start', {
...(config.model.trim() ? { model: config.model.trim() } : {}),
cwd: tempDir,
approvalPolicy: 'never',
sandbox: 'read-only',
serviceName: 'genoffice',
baseInstructions: CODEX_BASE_INSTRUCTIONS,
ephemeral: true,
})
return threadIdFrom(result)
let profileResult: unknown
try {
profileResult = await client.request(
'thread/start',
codexThreadStartParams(config, tempDir, 'profile'),
)
if (activePermissionProfileId(profileResult) === CODEX_PERMISSION_PROFILE) {
return threadIdFrom(profileResult)
}
} catch {
// Older Codex builds reject the profile keys; fall through to the sandbox.
profileResult = undefined
}
// A user config.toml sandbox_mode or an older Codex ignored the profile. Discard
// that thread before falling back so it does not linger under looser permissions.
const abandoned = optionalThreadId(profileResult)
if (abandoned) {
await client.request('thread/delete', { threadId: abandoned }).catch(() => undefined)
}
return threadIdFrom(
await client.request('thread/start', codexThreadStartParams(config, tempDir, 'read-only')),
)
}
async function waitForTurn(
client: CodexAppServerClient,
export interface CodexTurnTransport {
request(method: string, params: unknown): Promise<unknown>
onNotification(listener: (message: RpcMessage) => void): () => void
}
export async function waitForTurn(
client: CodexTurnTransport,
threadId: string,
start: () => Promise<unknown>,
signal: AbortSignal,
@@ -720,6 +820,9 @@ async function waitForTurn(
finish()
}
} else if (message.method === 'error') {
// willRetry: a dropped model stream Codex reconnects on its own ("Reconnecting... 2/5");
// the turn is still live and ends with turn/completed.
if (params.willRetry === true) return
const error = objectValue(params.error) ?? params
finish(new Error(typeof error?.message === 'string' ? error.message : 'Codex turn failed'))
}
@@ -742,52 +845,57 @@ async function runCodexAppServer(
maxTokens: number,
cb: StreamCallbacks,
): Promise<void> {
const tempDir = await mkdtemp(join(tmpdir(), CODEX_TEMP_PREFIX))
const nativeSessionId = cb.sessionId ?? `one-shot-${randomUUID()}`
try {
await withClient(config.cliPath, async (client) => {
const signature = sessionSignature(system, tools, config.model.trim())
let session = client.getSession(nativeSessionId)
let nextMessages = incrementalMessages(session, signature, messages)
if (!session || nextMessages === null) {
session = {
threadId: await startNativeThread(client, config, tempDir),
signature,
messageFingerprints: [],
}
client.setSession(nativeSessionId, session)
nextMessages = messages
}
const imagePaths = await materializeImages(nextMessages, tempDir)
const prompt = buildCodexAppServerPrompt(system, nextMessages, tools, maxTokens)
// One-shot chats and the connection test have no reusable transport id, so
// their thread and temp dir are dropped as soon as the turn ends.
const ephemeral = cb.sessionId === undefined
await withClient(config.cliPath, async (client) => {
const signature = sessionSignature(system, tools, config.model.trim())
let session = client.getSession(nativeSessionId)
let nextMessages = incrementalMessages(session, signature, messages)
if (!session || nextMessages === null) {
if (session) client.deleteSession(nativeSessionId)
const tempDir = await mkdtemp(join(tmpdir(), CODEX_TEMP_PREFIX))
let threadId: string
try {
const raw = await waitForTurn(
client,
session.threadId,
() =>
client.request('turn/start', {
threadId: session.threadId,
input: [
{ type: 'text', text: prompt, text_elements: [] },
...imagePaths.map((path) => ({ type: 'localImage', path })),
],
outputSchema: codexAppServerOutputSchema(tools),
}),
cb.signal,
cb,
)
const turn = parseCodexAppServerTurn(raw, tools)
session.messageFingerprints = messages.map(fingerprint)
if (turn.text) cb.onDelta(turn.text)
for (const call of turn.toolCalls) cb.onToolCall(call)
threadId = await startNativeThread(client, config, tempDir)
} catch (error) {
client.deleteSession(nativeSessionId)
await rm(tempDir, { recursive: true, force: true }).catch(() => undefined)
throw error
}
})
} finally {
await rm(tempDir, { recursive: true, force: true }).catch(() => undefined)
}
session = { threadId, signature, messageFingerprints: [], tempDir }
client.setSession(nativeSessionId, session)
nextMessages = messages
}
try {
const imagePaths = await materializeImages(nextMessages, session.tempDir)
const prompt = buildCodexAppServerPrompt(system, nextMessages, tools, maxTokens)
const raw = await waitForTurn(
client,
session.threadId,
() =>
client.request('turn/start', {
threadId: session.threadId,
input: [
{ type: 'text', text: prompt, text_elements: [] },
...imagePaths.map((path) => ({ type: 'localImage', path })),
],
outputSchema: codexAppServerOutputSchema(tools),
}),
cb.signal,
cb,
)
const turn = parseCodexAppServerTurn(raw, tools)
session.messageFingerprints = messages.map(fingerprint)
if (turn.text) cb.onDelta(turn.text)
for (const call of turn.toolCalls) cb.onToolCall(call)
} catch (error) {
client.deleteSession(nativeSessionId)
throw error
} finally {
if (ephemeral) client.deleteSession(nativeSessionId)
}
})
}
export async function streamCodexAppServer(
@@ -818,9 +926,10 @@ export async function chatCodexAppServer(
signal: AbortSignal,
): Promise<AiChatResponse> {
let content = ''
// No sessionId: a one-shot chat/connection test is not reused, so it runs as
// an ephemeral turn whose thread and temp dir are dropped when it ends.
await runCodexAppServer(config, system, [{ role: 'user', text: user }], [], 1024, {
signal,
sessionId: `chat-${randomUUID()}`,
onDelta: (text) => {
content += text
},
+29 -2
View File
@@ -43,12 +43,24 @@ function withUserAgent(init: RequestInit): RequestInit {
return { ...init, headers }
}
/**
* A 403 with an HTML body is an edge block page (bot management, WAF), not an API
* answer. Those edges score the Node network stack's TLS fingerprint differently
* from Chromium's, so the rescue fetch (Electron net.fetch) often gets through.
*/
function isBlockPage(response: Response): boolean {
return (
response.status === 403 && (response.headers.get('content-type') || '').includes('text/html')
)
}
export async function aiFetch(url: string, rawInit: RequestInit): Promise<Response> {
const init = withUserAgent(rawInit)
const signal = init.signal as AbortSignal | null | undefined
let response: Response
try {
return await fetch(url, init)
response = await fetch(url, init)
} catch (primaryError) {
const signal = init.signal as AbortSignal | null | undefined
if (!rescueFetch || signal?.aborted) throw primaryError
console.warn('[ai-provider] fetch failed, retrying via rescue fetch:', String(primaryError))
try {
@@ -57,4 +69,19 @@ export async function aiFetch(url: string, rawInit: RequestInit): Promise<Respon
throw primaryError
}
}
const resendable = init.body == null || typeof init.body === 'string'
if (rescueFetch && resendable && !signal?.aborted && isBlockPage(response)) {
console.warn(
'[ai-provider] 403 block page from',
new URL(url).host,
'- retrying via rescue fetch',
)
try {
const rescued = await rescueFetch(url, init)
if (!isBlockPage(rescued)) return rescued
} catch {
// fall through to the primary response
}
}
return response
}
+14 -1
View File
@@ -9,7 +9,20 @@ export function httpBodyDetail(body: string): string {
const head = body.trimStart().slice(0, 30).toLowerCase()
const isHtml = ['<!doctype', '<html', '<head', '<body'].some((tag) => head.startsWith(tag))
if (isHtml) {
return 'the service returned a web page instead of an API response (likely a temporary network or gateway block) — check your connection and retry'
return `the service returned a web page${describeBlockPage(body)} instead of an API response (likely a temporary network or gateway block) — check your connection and retry`
}
return body.slice(0, 500)
}
/** page title plus Cloudflare's error code / Ray ID when present: enough to tell who blocked the call */
function describeBlockPage(body: string): string {
const title = /<title[^>]*>([^<]*)<\/title>/i.exec(body)?.[1]?.replace(/\s+/g, ' ').trim()
const code = /error code:?\s*(?:<[^>]+>\s*)*(\d{3,5})/i.exec(body)?.[1]
const ray = /ray id:?\s*(?:<[^>]+>\s*)*([a-f0-9]{16})/i.exec(body)?.[1]
const parts = [
title && `"${title.slice(0, 60)}"`,
code && `error code ${code}`,
ray && `ray ${ray}`,
].filter(Boolean)
return parts.length ? ` (${parts.join(', ')})` : ''
}
+43
View File
@@ -1,6 +1,15 @@
export type {
AiChatRequest,
AiChatResponse,
AiMediaProviderConfig,
AiMediaProviderId,
AiMediaProviderMeta,
AiMediaSettings,
AiAnalysisProtocol,
AiImageProtocol,
AiSearchProviderId,
AiSearchProviderMeta,
AiSearchSettings,
CodexModelCatalog,
AiProviderConfig,
AiProviderId,
@@ -24,6 +33,40 @@ export {
maxOutputTokensOf,
resolveAiSettings,
} from './providers'
export {
AI_MEDIA_PROVIDERS,
GEMINI_MEDIA_BASE_URL,
OPENAI_IMAGES_BASE_URL,
activeMediaConfig,
activeMediaProvider,
defaultAiMediaSettings,
getMediaProviderMeta,
imageGenerationAvailable,
mediaAnalysisAvailable,
mediaConfigUsable,
providerHasCapability,
resolveAiMediaSettings,
videoAnalysisAvailable,
} from './media'
export type { MediaCapability } from './media'
export {
AI_SEARCH_PROVIDERS,
activeSearchProvider,
defaultAiSearchSettings,
resolveAiSearchSettings,
} from './search-settings'
export {
analyzeMediaWithProvider,
generateImageWithProvider,
sniffImageMime,
testMediaProvider,
} from './media-protocols'
export type {
AnalyzeMediaInput,
ByokMediaProviderId,
GenerateImageInput,
MediaBlob,
} from './media-protocols'
export { AI_PROVIDER_ADAPTERS, getProviderAdapter, modelLacksVision } from './registry'
export type {
AiProtocol,
+712
View File
@@ -0,0 +1,712 @@
/**
* Wire implementations for the BYOK media providers. Image generation speaks
* four shapes — OpenAI Images (OpenAI, Ark/Seedream, Zhipu/CogView, xAI,
* custom endpoints; the vendors differ in size vocabulary and edit support),
* Gemini native output / Imagen predict, DashScope multimodal-generation
* (Qwen-Image) and MiniMax image_generation. Understanding speaks two: OpenAI
* chat completions (video via a video_url part where the vendor accepts one)
* and Gemini generateContent (inline or Files API). Genspark is not here — its
* tools go through the gsk CLI in @genoffice/ai-search.
*/
import { aiFetch } from './fetch'
import { httpBodyDetail } from './http-error'
import {
DASHSCOPE_BASE_URL,
GEMINI_MEDIA_BASE_URL,
MINIMAX_BASE_URL,
OPENAI_IMAGES_BASE_URL,
getMediaProviderMeta,
} from './media'
import type { AiMediaProviderConfig, AiMediaProviderId, AiMediaProviderMeta } from './types'
export interface MediaBlob {
bytes: Uint8Array
mime: string
name?: string
}
export interface GenerateImageInput {
prompt: string
/** 1:1 | 4:3 | 16:9 | 9:16 | 3:4 | 2:3 | 3:2 | auto (vendors get their nearest supported value) */
aspectRatio?: string | undefined
/** images to edit / draw from */
references?: MediaBlob[] | undefined
}
export interface AnalyzeMediaInput {
media: MediaBlob[]
requirements: string
}
export type ByokMediaProviderId = Exclude<AiMediaProviderId, 'genspark'>
/** image generation can take minutes on the large models */
const GENERATE_TIMEOUT_MS = 600_000
const ANALYZE_TIMEOUT_MS = 300_000
const TEST_TIMEOUT_MS = 20_000
/** Gemini caps the whole inline request at 20 MB; bigger media goes through the Files API */
const GEMINI_INLINE_LIMIT_BYTES = 18 * 1024 * 1024
const GEMINI_FILE_POLL_MS = 2_000
const GEMINI_FILE_READY_TIMEOUT_MS = 180_000
function trimSlash(url: string): string {
return url.replace(/\/+$/, '')
}
function metaOf(provider: ByokMediaProviderId): AiMediaProviderMeta {
const meta = getMediaProviderMeta(provider)
if (!meta) throw new Error(`Unknown media provider: ${provider}`)
return meta
}
/** base URL of the OpenAI-shaped endpoints (images + chat) for a provider */
function openAiBase(provider: ByokMediaProviderId, config: AiMediaProviderConfig): string {
if (provider === 'qwen') return `${dashscopeRoot(config)}/compatible-mode/v1`
const meta = metaOf(provider)
return trimSlash(config.baseUrl || meta.defaultBaseUrl || OPENAI_IMAGES_BASE_URL)
}
/** DashScope root; a pasted compatible-mode or api/v1 URL is reduced to it */
function dashscopeRoot(config: AiMediaProviderConfig): string {
return trimSlash(config.baseUrl || DASHSCOPE_BASE_URL)
.replace(/\/compatible-mode\/v1$/, '')
.replace(/\/api\/v1$/, '')
}
function geminiBase(config: AiMediaProviderConfig): string {
return trimSlash(config.baseUrl || GEMINI_MEDIA_BASE_URL)
}
function bearer(config: AiMediaProviderConfig): Record<string, string> {
return config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}
}
export function bytesToBase64(bytes: Uint8Array): string {
if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')
let binary = ''
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
}
return btoa(binary)
}
export function base64ToBytes(b64: string): Uint8Array {
if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(b64, 'base64'))
const binary = atob(b64)
const out = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i)
return out
}
function dataUrl(blob: MediaBlob): string {
return `data:${blob.mime};base64,${bytesToBase64(blob.bytes)}`
}
/** Image bytes declare their own format; vendors' declared mime is a fallback only */
export function sniffImageMime(bytes: Uint8Array, fallback = 'image/png'): string {
if (bytes.length > 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e) {
return 'image/png'
}
if (bytes.length > 3 && bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'
if (bytes.length > 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) {
return 'image/gif'
}
if (
bytes.length > 12 &&
bytes[8] === 0x57 &&
bytes[9] === 0x45 &&
bytes[10] === 0x42 &&
bytes[11] === 0x50
) {
return 'image/webp'
}
return fallback
}
/** Blob/fetch bodies want an ArrayBuffer-backed view; a subarray of a shared buffer is copied */
function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer
}
async function failFrom(label: string, resp: Response): Promise<never> {
const body = await resp.text().catch(() => '')
throw new Error(`${label} ${resp.status}: ${httpBodyDetail(body)}`)
}
function asRecord(v: unknown): Record<string, unknown> {
return v && typeof v === 'object' ? (v as Record<string, unknown>) : {}
}
function withTimeout(signal: AbortSignal | undefined, ms: number): AbortSignal {
const timeout = AbortSignal.timeout(ms)
return signal ? AbortSignal.any([signal, timeout]) : timeout
}
/** vendors that return a URL instead of bytes: download it (the links are short-lived, so right away) */
async function downloadImage(label: string, url: string, signal: AbortSignal): Promise<MediaBlob> {
const img = await aiFetch(url, { signal })
if (!img.ok) return failFrom(`${label} download`, img)
const bytes = new Uint8Array(await img.arrayBuffer())
return { bytes, mime: sniffImageMime(bytes, img.headers.get('content-type') ?? 'image/png') }
}
function fromBase64(b64: string, declaredMime?: unknown): MediaBlob {
const bytes = base64ToBytes(b64)
return {
bytes,
mime: sniffImageMime(bytes, typeof declaredMime === 'string' ? declaredMime : 'image/png'),
}
}
// ── OpenAI Images API family (openai, doubao/Ark, glm/Zhipu, xai, custom) ──
const OPENAI_SIZES: Record<string, string> = {
'1:1': '1024x1024',
'16:9': '1536x1024',
'3:2': '1536x1024',
'4:3': '1536x1024',
'9:16': '1024x1536',
'2:3': '1024x1536',
'3:4': '1024x1536',
}
/** CogView accepts a fixed grid of WxH values */
const GLM_SIZES: Record<string, string> = {
'1:1': '1024x1024',
'16:9': '1344x768',
'3:2': '1344x768',
'4:3': '1152x864',
'9:16': '768x1344',
'2:3': '768x1344',
'3:4': '864x1152',
}
/** Seedream takes the aspect ratio itself as `size` (resolution defaults to 2K) */
const ARK_RATIOS = new Set(['1:1', '3:4', '4:3', '9:16', '16:9', '2:3', '3:2', '21:9'])
interface OpenAiImagesStyle {
size(aspectRatio: string | undefined): string | undefined
/** vendor-specific fields merged into the generations body */
bodyExtras: Record<string, unknown>
/** 'multipart' = POST /images/edits with files; 'inline' = `image` data URLs in the generations body; 'none' = unsupported */
edits: 'multipart' | 'inline' | 'none'
}
function openAiImagesStyle(provider: ByokMediaProviderId): OpenAiImagesStyle {
switch (provider) {
case 'doubao':
return {
size: (r) => (r && ARK_RATIOS.has(r) ? r : '2K'),
bodyExtras: { response_format: 'b64_json', watermark: false },
edits: 'inline',
}
case 'glm':
return { size: (r) => (r ? GLM_SIZES[r] : undefined), bodyExtras: {}, edits: 'none' }
case 'xai':
// xAI rejects size/quality; bytes only on request
return { size: () => undefined, bodyExtras: { response_format: 'b64_json' }, edits: 'none' }
default:
return { size: (r) => (r ? OPENAI_SIZES[r] : undefined), bodyExtras: {}, edits: 'multipart' }
}
}
async function openAiImageResult(
label: string,
resp: Response,
signal: AbortSignal,
): Promise<MediaBlob> {
if (!resp.ok) return failFrom(label, resp)
const json = asRecord(await resp.json())
const first = asRecord((json.data as unknown[] | undefined)?.[0])
if (typeof first.b64_json === 'string' && first.b64_json) return fromBase64(first.b64_json)
if (typeof first.url === 'string' && first.url) return downloadImage(label, first.url, signal)
throw new Error(`${label} returned no image: ${JSON.stringify(json).slice(0, 200)}`)
}
async function generateImageOpenAi(
provider: ByokMediaProviderId,
config: AiMediaProviderConfig,
model: string,
input: GenerateImageInput,
signal: AbortSignal,
): Promise<MediaBlob> {
const base = openAiBase(provider, config)
const style = openAiImagesStyle(provider)
const size = style.size(input.aspectRatio)
const refs = input.references ?? []
if (refs.length && style.edits === 'none') {
throw new Error(
`${metaOf(provider).label} cannot edit or reference images here; generate from the prompt alone or pick another image provider.`,
)
}
if (refs.length === 0 || style.edits === 'inline') {
const resp = await aiFetch(`${base}/images/generations`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...bearer(config) },
body: JSON.stringify({
model,
prompt: input.prompt,
n: 1,
...(size ? { size } : {}),
...style.bodyExtras,
...(refs.length ? { image: refs.map(dataUrl) } : {}),
}),
signal,
})
return openAiImageResult('Image generation failed:', resp, signal)
}
// edits take the source images as multipart files (image[] for several)
const form = new FormData()
form.set('model', model)
form.set('prompt', input.prompt)
if (size) form.set('size', size)
refs.forEach((ref, i) => {
const ext = ref.mime.split('/')[1]?.replace('jpeg', 'jpg') ?? 'png'
form.append(
refs.length > 1 ? 'image[]' : 'image',
new Blob([toArrayBuffer(ref.bytes)], { type: ref.mime }),
ref.name ?? `ref-${i}.${ext}`,
)
})
const resp = await aiFetch(`${base}/images/edits`, {
method: 'POST',
headers: bearer(config),
body: form,
signal,
})
return openAiImageResult('Image edit failed:', resp, signal)
}
// ── DashScope multimodal-generation (Qwen-Image) ───────────────────
const DASHSCOPE_SIZES: Record<string, string> = {
'1:1': '1328*1328',
'16:9': '1664*928',
'3:2': '1664*928',
'4:3': '1472*1104',
'9:16': '928*1664',
'2:3': '928*1664',
'3:4': '1104*1472',
}
async function generateImageDashscope(
config: AiMediaProviderConfig,
model: string,
input: GenerateImageInput,
signal: AbortSignal,
): Promise<MediaBlob> {
if (input.references?.length) {
throw new Error(
'Qwen-Image here generates from the prompt alone; pick another image provider for edits.',
)
}
const size = input.aspectRatio ? DASHSCOPE_SIZES[input.aspectRatio] : undefined
const resp = await aiFetch(
`${dashscopeRoot(config)}/api/v1/services/aigc/multimodal-generation/generation`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', ...bearer(config) },
body: JSON.stringify({
model,
input: { messages: [{ role: 'user', content: [{ text: input.prompt }] }] },
parameters: { n: 1, watermark: false, ...(size ? { size } : {}) },
}),
signal,
},
)
if (!resp.ok) return failFrom('Image generation failed:', resp)
const json = asRecord(await resp.json())
if (typeof json.code === 'string' && json.code) {
throw new Error(`Image generation failed: ${json.code} ${String(json.message ?? '')}`)
}
const choice = asRecord((asRecord(json.output).choices as unknown[] | undefined)?.[0])
const content = asRecord(choice.message).content
const image = Array.isArray(content)
? content.map(asRecord).find((c) => typeof c.image === 'string')?.image
: undefined
if (typeof image !== 'string') {
throw new Error(`Image generation returned no image: ${JSON.stringify(json).slice(0, 200)}`)
}
return downloadImage('Image generation failed:', image, signal)
}
// ── MiniMax image_generation ───────────────────────────────────────
const MINIMAX_RATIOS = new Set(['1:1', '16:9', '4:3', '3:2', '2:3', '3:4', '9:16', '21:9'])
async function generateImageMinimax(
config: AiMediaProviderConfig,
model: string,
input: GenerateImageInput,
signal: AbortSignal,
): Promise<MediaBlob> {
if (input.references?.length) {
throw new Error(
'MiniMax image-01 here generates from the prompt alone; pick another image provider for edits.',
)
}
const base = trimSlash(config.baseUrl || MINIMAX_BASE_URL)
const ratio =
input.aspectRatio && MINIMAX_RATIOS.has(input.aspectRatio) ? input.aspectRatio : undefined
const resp = await aiFetch(`${base}/image_generation`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...bearer(config) },
body: JSON.stringify({
model,
prompt: input.prompt,
n: 1,
response_format: 'base64',
...(ratio ? { aspect_ratio: ratio } : {}),
}),
signal,
})
if (!resp.ok) return failFrom('Image generation failed:', resp)
const json = asRecord(await resp.json())
const status = asRecord(json.base_resp)
if (typeof status.status_code === 'number' && status.status_code !== 0) {
throw new Error(
`Image generation failed: ${status.status_code} ${String(status.status_msg ?? '')}`,
)
}
const data = asRecord(json.data)
const b64 = (data.image_base64 as unknown[] | undefined)?.[0]
if (typeof b64 === 'string' && b64) return fromBase64(b64)
const url = (data.image_urls as unknown[] | undefined)?.[0]
if (typeof url === 'string' && url) return downloadImage('Image generation failed:', url, signal)
throw new Error(`Image generation returned no image: ${JSON.stringify(json).slice(0, 200)}`)
}
// ── OpenAI-compatible chat understanding ───────────────────────────
function openAiContentText(content: unknown): string {
if (typeof content === 'string') return content
if (Array.isArray(content)) {
return content
.map((part) => {
const p = asRecord(part)
return typeof p.text === 'string' ? p.text : ''
})
.join('')
}
return ''
}
async function analyzeMediaOpenAi(
provider: ByokMediaProviderId,
config: AiMediaProviderConfig,
model: string,
input: AnalyzeMediaInput,
signal: AbortSignal,
): Promise<string> {
const meta = metaOf(provider)
const parts: unknown[] = [{ type: 'text', text: input.requirements }]
for (const m of input.media) {
if (m.mime.startsWith('image/')) {
parts.push({ type: 'image_url', image_url: { url: dataUrl(m) } })
} else if (m.mime.startsWith('video/') && meta.videoAnalysis) {
parts.push({ type: 'video_url', video_url: { url: dataUrl(m) } })
} else {
throw new Error(
`${meta.label} cannot analyze ${m.name ?? m.mime} (${m.mime}) here; ${
meta.videoAnalysis ? 'audio' : 'video and audio'
} analysis needs Gemini or Genspark.`,
)
}
}
const resp = await aiFetch(`${openAiBase(provider, config)}/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...bearer(config) },
body: JSON.stringify({ model, messages: [{ role: 'user', content: parts }] }),
signal,
})
if (!resp.ok) return failFrom('Media analysis failed:', resp)
const json = asRecord(await resp.json())
const choice = asRecord((json.choices as unknown[] | undefined)?.[0])
const text = openAiContentText(asRecord(choice.message).content).trim()
if (!text) throw new Error('Media analysis returned an empty answer')
return text
}
// ── Gemini (native image output, Imagen predict, multimodal understanding) ──
const GEMINI_ASPECT_RATIOS = new Set([
'1:1',
'2:3',
'3:2',
'3:4',
'4:3',
'4:5',
'5:4',
'9:16',
'16:9',
'21:9',
])
function geminiHeaders(config: AiMediaProviderConfig): Record<string, string> {
return { 'Content-Type': 'application/json', 'x-goog-api-key': config.apiKey }
}
function geminiParts(candidate: unknown): Record<string, unknown>[] {
const content = asRecord(asRecord(candidate).content)
return Array.isArray(content.parts) ? content.parts.map(asRecord) : []
}
function geminiBlockedReason(json: Record<string, unknown>): string {
const feedback = asRecord(json.promptFeedback)
const candidate = asRecord((json.candidates as unknown[] | undefined)?.[0])
const reason = feedback.blockReason ?? candidate.finishReason
return typeof reason === 'string' && reason !== 'STOP' ? ` (${reason})` : ''
}
async function generateImageGemini(
config: AiMediaProviderConfig,
model: string,
input: GenerateImageInput,
signal: AbortSignal,
): Promise<MediaBlob> {
const base = geminiBase(config)
const aspectRatio =
input.aspectRatio && GEMINI_ASPECT_RATIOS.has(input.aspectRatio) ? input.aspectRatio : undefined
if (model.startsWith('imagen-')) {
const resp = await aiFetch(`${base}/models/${model}:predict`, {
method: 'POST',
headers: geminiHeaders(config),
body: JSON.stringify({
instances: [{ prompt: input.prompt }],
parameters: { sampleCount: 1, ...(aspectRatio ? { aspectRatio } : {}) },
}),
signal,
})
if (!resp.ok) return failFrom('Image generation failed:', resp)
const json = asRecord(await resp.json())
const first = asRecord((json.predictions as unknown[] | undefined)?.[0])
if (typeof first.bytesBase64Encoded !== 'string') {
throw new Error(`Image generation returned no image: ${JSON.stringify(json).slice(0, 200)}`)
}
return fromBase64(first.bytesBase64Encoded, first.mimeType)
}
const resp = await aiFetch(`${base}/models/${model}:generateContent`, {
method: 'POST',
headers: geminiHeaders(config),
body: JSON.stringify({
contents: [
{
role: 'user',
parts: [
{ text: input.prompt },
...(input.references ?? []).map((ref) => ({
inline_data: { mime_type: ref.mime, data: bytesToBase64(ref.bytes) },
})),
],
},
],
generationConfig: {
responseModalities: ['TEXT', 'IMAGE'],
...(aspectRatio ? { imageConfig: { aspectRatio } } : {}),
},
}),
signal,
})
if (!resp.ok) return failFrom('Image generation failed:', resp)
const json = asRecord(await resp.json())
const parts = geminiParts((json.candidates as unknown[] | undefined)?.[0])
const image = parts
.map((p) => asRecord(p.inlineData ?? p.inline_data))
.find((d) => typeof d.data === 'string')
if (!image) {
const text = parts
.map((p) => (typeof p.text === 'string' ? p.text : ''))
.join(' ')
.trim()
throw new Error(
`Image generation returned no image${geminiBlockedReason(json)}${text ? `: ${text.slice(0, 200)}` : ''}`,
)
}
return fromBase64(image.data as string, image.mimeType ?? image.mime_type)
}
/** Files API resumable upload (start → upload+finalize → wait for ACTIVE); returns the file_data part */
async function geminiUploadFile(
config: AiMediaProviderConfig,
blob: MediaBlob,
signal: AbortSignal,
): Promise<{ file_data: { mime_type: string; file_uri: string } }> {
const base = geminiBase(config)
const root = base.replace(/\/v1(beta)?$/, '')
const start = await aiFetch(`${root}/upload/v1beta/files`, {
method: 'POST',
headers: {
...geminiHeaders(config),
'X-Goog-Upload-Protocol': 'resumable',
'X-Goog-Upload-Command': 'start',
'X-Goog-Upload-Header-Content-Length': String(blob.bytes.byteLength),
'X-Goog-Upload-Header-Content-Type': blob.mime,
},
body: JSON.stringify({ file: { display_name: blob.name ?? 'media' } }),
signal,
})
if (!start.ok) return failFrom('Media upload failed:', start)
const uploadUrl = start.headers.get('x-goog-upload-url')
if (!uploadUrl) throw new Error('Media upload failed: no upload URL returned')
const upload = await aiFetch(uploadUrl, {
method: 'POST',
headers: {
'x-goog-api-key': config.apiKey,
'Content-Length': String(blob.bytes.byteLength),
'X-Goog-Upload-Offset': '0',
'X-Goog-Upload-Command': 'upload, finalize',
},
body: toArrayBuffer(blob.bytes),
signal,
})
if (!upload.ok) return failFrom('Media upload failed:', upload)
let file = asRecord(asRecord(await upload.json()).file)
const deadline = Date.now() + GEMINI_FILE_READY_TIMEOUT_MS
// videos are transcoded server-side before they can be referenced
while (file.state === 'PROCESSING') {
if (Date.now() > deadline) {
throw new Error('Media upload timed out while the file was processing')
}
await new Promise((r) => setTimeout(r, GEMINI_FILE_POLL_MS))
const poll = await aiFetch(`${base}/${String(file.name)}`, {
headers: { 'x-goog-api-key': config.apiKey },
signal,
})
if (!poll.ok) return failFrom('Media upload failed:', poll)
file = asRecord(await poll.json())
}
if (file.state !== 'ACTIVE' || typeof file.uri !== 'string') {
throw new Error(`Media upload failed: file state ${String(file.state ?? 'unknown')}`)
}
return { file_data: { mime_type: String(file.mimeType ?? blob.mime), file_uri: file.uri } }
}
async function analyzeMediaGemini(
config: AiMediaProviderConfig,
model: string,
input: AnalyzeMediaInput,
signal: AbortSignal,
): Promise<string> {
const total = input.media.reduce((n, m) => n + m.bytes.byteLength, 0)
const inline = total <= GEMINI_INLINE_LIMIT_BYTES
const mediaParts: unknown[] = []
for (const blob of input.media) {
mediaParts.push(
inline
? { inline_data: { mime_type: blob.mime, data: bytesToBase64(blob.bytes) } }
: await geminiUploadFile(config, blob, signal),
)
}
const resp = await aiFetch(`${geminiBase(config)}/models/${model}:generateContent`, {
method: 'POST',
headers: geminiHeaders(config),
body: JSON.stringify({
contents: [{ role: 'user', parts: [...mediaParts, { text: input.requirements }] }],
}),
signal,
})
if (!resp.ok) return failFrom('Media analysis failed:', resp)
const json = asRecord(await resp.json())
const text = geminiParts((json.candidates as unknown[] | undefined)?.[0])
.map((p) => (typeof p.text === 'string' ? p.text : ''))
.join('')
.trim()
if (!text) throw new Error(`Media analysis returned an empty answer${geminiBlockedReason(json)}`)
return text
}
// ── dispatch ────────────────────────────────────────────────────────
function modelOf(
meta: AiMediaProviderMeta,
config: AiMediaProviderConfig,
field: 'imageModel' | 'analysisModel',
): string {
const model =
config[field] || (field === 'imageModel' ? meta.defaultImageModel : meta.defaultAnalysisModel)
if (!model) {
throw new Error(
`No ${field === 'imageModel' ? 'image' : 'analysis'} model configured for the ${meta.label} media provider`,
)
}
return model
}
function requireBaseUrl(meta: AiMediaProviderMeta, config: AiMediaProviderConfig): void {
if (meta.needsBaseUrl && !config.baseUrl) {
throw new Error(`The ${meta.label} media provider requires a Base URL`)
}
}
export async function generateImageWithProvider(
provider: ByokMediaProviderId,
config: AiMediaProviderConfig,
input: GenerateImageInput,
signal?: AbortSignal,
): Promise<MediaBlob> {
const meta = metaOf(provider)
requireBaseUrl(meta, config)
if (!meta.imageProtocol) throw new Error(`${meta.label} does not generate images`)
const model = modelOf(meta, config, 'imageModel')
const guard = withTimeout(signal, GENERATE_TIMEOUT_MS)
switch (meta.imageProtocol) {
case 'gemini':
return generateImageGemini(config, model, input, guard)
case 'dashscope':
return generateImageDashscope(config, model, input, guard)
case 'minimax':
return generateImageMinimax(config, model, input, guard)
case 'openai-images':
return generateImageOpenAi(provider, config, model, input, guard)
}
}
export async function analyzeMediaWithProvider(
provider: ByokMediaProviderId,
config: AiMediaProviderConfig,
input: AnalyzeMediaInput,
signal?: AbortSignal,
): Promise<string> {
const meta = metaOf(provider)
requireBaseUrl(meta, config)
if (!meta.analysisProtocol) throw new Error(`${meta.label} does not analyze media`)
const model = modelOf(meta, config, 'analysisModel')
const guard = withTimeout(signal, ANALYZE_TIMEOUT_MS)
return meta.analysisProtocol === 'gemini'
? analyzeMediaGemini(config, model, input, guard)
: analyzeMediaOpenAi(provider, config, model, input, guard)
}
/**
* Cheap credential check — the settings-UI connection test; no image is
* billed. A model listing is the closest thing every vendor has; vendors
* without one answer 404/405 to a valid key, so only 401/403 count as failure.
*/
export async function testMediaProvider(
provider: ByokMediaProviderId,
config: AiMediaProviderConfig,
signal?: AbortSignal,
): Promise<{ ok: boolean; error?: string }> {
try {
const meta = metaOf(provider)
requireBaseUrl(meta, config)
const guard = withTimeout(signal, TEST_TIMEOUT_MS)
const resp =
provider === 'gemini'
? await aiFetch(`${geminiBase(config)}/models?pageSize=1`, {
headers: { 'x-goog-api-key': config.apiKey },
signal: guard,
})
: await aiFetch(`${openAiBase(provider, config)}/models`, {
headers: bearer(config),
signal: guard,
})
if (resp.ok) return { ok: true }
const body = await resp.text().catch(() => '')
if (resp.status === 401 || resp.status === 403 || provider === 'gemini') {
return { ok: false, error: `HTTP ${resp.status}: ${httpBodyDetail(body)}` }
}
return { ok: true }
} catch (e) {
return { ok: false, error: e instanceof Error ? e.message : String(e) }
}
}
+320
View File
@@ -0,0 +1,320 @@
import type {
AiMediaProviderConfig,
AiMediaProviderId,
AiMediaProviderMeta,
AiMediaSettings,
AiSettings,
} from './types'
export const OPENAI_IMAGES_BASE_URL = 'https://api.openai.com/v1'
export const GEMINI_MEDIA_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta'
export const ARK_BASE_URL = 'https://ark.cn-beijing.volces.com/api/v3'
export const ZHIPU_BASE_URL = 'https://open.bigmodel.cn/api/paas/v4'
export const XAI_BASE_URL = 'https://api.x.ai/v1'
/** DashScope root: images ride /api/v1/services/aigc/..., understanding rides /compatible-mode/v1 */
export const DASHSCOPE_BASE_URL = 'https://dashscope.aliyuncs.com'
export const MINIMAX_BASE_URL = 'https://api.minimax.io/v1'
// Model ids verified against vendor docs 2026-09; keep chat-capable analysis
// models in step with the chat catalog in providers.ts.
export const AI_MEDIA_PROVIDERS: AiMediaProviderMeta[] = [
{
id: 'genspark',
label: 'Genspark',
description: 'Image generation, media analysis and search through your Genspark sign-in',
keyPlaceholder: 'Not required - sign in to Genspark',
defaultBaseUrl: '',
imageProtocol: 'openai-images',
imageModels: [],
defaultImageModel: '',
analysisProtocol: 'openai-chat',
analysisModels: [],
defaultAnalysisModel: '',
videoAnalysis: true,
},
{
id: 'openai',
label: 'OpenAI',
description: 'GPT Image for generation and editing; GPT chat models for image analysis',
keyPlaceholder: 'sk-...',
defaultBaseUrl: OPENAI_IMAGES_BASE_URL,
imageProtocol: 'openai-images',
imageModels: ['gpt-image-2', 'gpt-image-1.5', 'gpt-image-1', 'gpt-image-1-mini'],
defaultImageModel: 'gpt-image-2',
analysisProtocol: 'openai-chat',
analysisModels: ['gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4-mini'],
defaultAnalysisModel: 'gpt-5.6-luna',
videoAnalysis: false,
},
{
id: 'gemini',
label: 'Gemini',
description:
'Gemini native image output (Nano Banana) and Imagen; Gemini reads images, video and audio',
keyPlaceholder: 'AIza...',
defaultBaseUrl: GEMINI_MEDIA_BASE_URL,
imageProtocol: 'gemini',
imageModels: [
'gemini-3.1-flash-image',
'gemini-3-pro-image',
'gemini-3.1-flash-lite-image',
'gemini-2.5-flash-image',
],
defaultImageModel: 'gemini-3.1-flash-image',
analysisProtocol: 'gemini',
analysisModels: ['gemini-3.7-flash', 'gemini-3.1-pro-preview', 'gemini-3.6-flash'],
defaultAnalysisModel: 'gemini-3.7-flash',
videoAnalysis: true,
},
{
id: 'doubao',
label: 'Doubao (Volcengine Ark)',
description: 'Seedream image generation and editing; Doubao Seed reads images and video',
keyPlaceholder: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
defaultBaseUrl: ARK_BASE_URL,
imageProtocol: 'openai-images',
imageModels: [
'doubao-seedream-5-0-260128',
'doubao-seedream-4-5-251128',
'doubao-seedream-4-0-250828',
],
defaultImageModel: 'doubao-seedream-5-0-260128',
analysisProtocol: 'openai-chat',
analysisModels: ['doubao-seed-2-1-pro-260628', 'doubao-seed-2-1-turbo-260628'],
defaultAnalysisModel: 'doubao-seed-2-1-pro-260628',
videoAnalysis: true,
},
{
id: 'glm',
label: 'GLM (Zhipu)',
description: 'CogView image generation; GLM-V reads images and video',
keyPlaceholder: 'xxxxxxxx.xxxxxxxx',
defaultBaseUrl: ZHIPU_BASE_URL,
imageProtocol: 'openai-images',
imageModels: ['cogview-4-250304', 'cogview-3-flash'],
defaultImageModel: 'cogview-4-250304',
analysisProtocol: 'openai-chat',
analysisModels: ['glm-4.6v', 'glm-4.6v-flash'],
defaultAnalysisModel: 'glm-4.6v',
videoAnalysis: true,
},
{
id: 'xai',
label: 'Grok (xAI)',
description: 'Grok Imagine image generation; Grok reads images',
keyPlaceholder: 'xai-...',
defaultBaseUrl: XAI_BASE_URL,
imageProtocol: 'openai-images',
imageModels: ['grok-imagine-image-2.0', 'grok-2-image-1212'],
defaultImageModel: 'grok-imagine-image-2.0',
analysisProtocol: 'openai-chat',
analysisModels: ['grok-4.6', 'grok-4.5'],
defaultAnalysisModel: 'grok-4.6',
videoAnalysis: false,
},
{
id: 'qwen',
label: 'Qwen (Alibaba Cloud)',
description: 'Qwen-Image generation; Qwen-VL reads images and video (DashScope)',
keyPlaceholder: 'sk-...',
defaultBaseUrl: DASHSCOPE_BASE_URL,
imageProtocol: 'dashscope',
imageModels: ['qwen-image-plus', 'qwen-image'],
defaultImageModel: 'qwen-image-plus',
analysisProtocol: 'openai-chat',
analysisModels: ['qwen3-vl-plus', 'qwen3-vl-flash', 'qwen3.8-max', 'qwen3.7-plus'],
defaultAnalysisModel: 'qwen3-vl-plus',
videoAnalysis: true,
},
{
id: 'minimax',
label: 'MiniMax',
description:
'image-01 image generation (api.minimax.io; use api.minimaxi.com/v1 for the CN region)',
keyPlaceholder: 'eyJ...',
defaultBaseUrl: MINIMAX_BASE_URL,
imageProtocol: 'minimax',
imageModels: ['image-01'],
defaultImageModel: 'image-01',
analysisModels: [],
defaultAnalysisModel: '',
videoAnalysis: false,
},
{
id: 'custom',
label: 'Custom',
description: 'Any OpenAI-compatible endpoint: /images/generations and /chat/completions',
keyPlaceholder: 'API Key',
needsBaseUrl: true,
defaultBaseUrl: '',
imageProtocol: 'openai-images',
imageModels: [],
defaultImageModel: '',
analysisProtocol: 'openai-chat',
analysisModels: [],
defaultAnalysisModel: '',
videoAnalysis: false,
},
]
export type MediaCapability = 'image' | 'analysis' | 'video'
export function getMediaProviderMeta(id: AiMediaProviderId): AiMediaProviderMeta | undefined {
return AI_MEDIA_PROVIDERS.find((m) => m.id === id)
}
export function providerHasCapability(
meta: AiMediaProviderMeta,
capability: MediaCapability,
): boolean {
if (capability === 'image') return !!meta.imageProtocol
if (capability === 'video') return !!meta.analysisProtocol && meta.videoAnalysis
return !!meta.analysisProtocol
}
export function defaultAiMediaSettings(): AiMediaSettings {
const providers = {} as AiMediaSettings['providers']
for (const meta of AI_MEDIA_PROVIDERS) {
providers[meta.id] = {
apiKey: '',
imageModel: meta.defaultImageModel,
analysisModel: meta.defaultAnalysisModel,
baseUrl: meta.needsBaseUrl ? '' : undefined,
}
}
return {
imageProvider: 'genspark',
analysisProvider: 'genspark',
videoAnalysisProvider: 'genspark',
providers,
}
}
/**
* Merge a stored media block over defaults, trimming pasted whitespace. The
* pre-catalog `provider` field (one choice for both tools) seeds both
* per-capability choices. Unknown provider ids are kept and simply never activate.
*/
export function resolveAiMediaSettings(
stored: Partial<AiMediaSettings> | undefined,
): AiMediaSettings {
const defaults = defaultAiMediaSettings()
if (!stored) return defaults
const providers = { ...defaults.providers }
for (const [id, config] of Object.entries(stored.providers ?? {})) {
if (!config || typeof config !== 'object') continue
const base = providers[id as AiMediaProviderId]
providers[id as AiMediaProviderId] = {
apiKey: (config.apiKey ?? base?.apiKey ?? '').trim(),
imageModel: (config.imageModel ?? base?.imageModel ?? '').trim(),
analysisModel: (config.analysisModel ?? base?.analysisModel ?? '').trim(),
...(config.baseUrl !== undefined
? { baseUrl: config.baseUrl.trim() }
: base?.baseUrl !== undefined
? { baseUrl: base.baseUrl }
: {}),
}
}
const legacy = stored.provider
const analysisProvider = stored.analysisProvider ?? legacy ?? defaults.analysisProvider
return {
imageProvider: stored.imageProvider ?? legacy ?? defaults.imageProvider,
analysisProvider,
// a pre-split file used one vendor for all media analysis
videoAnalysisProvider: stored.videoAnalysisProvider ?? analysisProvider,
providers,
}
}
/** Key (or base URL for custom) present — the minimum for a BYOK media provider to be honored */
export function mediaConfigUsable(
meta: AiMediaProviderMeta,
config: AiMediaProviderConfig | undefined,
): boolean {
if (!config) return false
if (meta.needsBaseUrl) return !!config.baseUrl
return !!config.apiKey
}
/**
* The stored provider for one capability, honored only when it exists, has
* that capability and is usable; anything else falls back to genspark so a
* half-filled setup degrades to the signed-in default.
*/
export function activeMediaProvider(
settings: Pick<AiSettings, 'media'>,
capability: MediaCapability,
): AiMediaProviderId {
const media = settings.media
if (!media) return 'genspark'
const id =
capability === 'image'
? media.imageProvider
: capability === 'video'
? media.videoAnalysisProvider
: media.analysisProvider
if (!id || id === 'genspark') return 'genspark'
const meta = getMediaProviderMeta(id)
if (!meta || !providerHasCapability(meta, capability)) return 'genspark'
if (!mediaConfigUsable(meta, media.providers?.[id])) return 'genspark'
return id
}
/** the active BYOK config for one capability, or null when it runs through Genspark */
export function activeMediaConfig(
settings: Pick<AiSettings, 'media'>,
capability: MediaCapability,
): { provider: Exclude<AiMediaProviderId, 'genspark'>; config: AiMediaProviderConfig } | null {
const provider = activeMediaProvider(settings, capability)
if (provider === 'genspark') return null
return { provider, config: settings.media!.providers[provider] }
}
function byokModel(
settings: Pick<AiSettings, 'media'>,
capability: MediaCapability,
): string | null {
const active = activeMediaConfig(settings, capability)
if (!active) return null
const meta = getMediaProviderMeta(active.provider)!
return capability === 'image'
? active.config.imageModel || meta.defaultImageModel
: active.config.analysisModel || meta.defaultAnalysisModel
}
function capabilityAvailable(
settings: Pick<AiSettings, 'media' | 'gskToolsEnabled'> | null | undefined,
gskLoggedIn: boolean,
capability: MediaCapability,
): boolean {
if (!settings) return gskLoggedIn
const model = byokModel(settings, capability)
if (model !== null) return model !== ''
return gskLoggedIn && settings.gskToolsEnabled !== false
}
/** live predicate for the generate_image tool: BYOK image model configured, or gsk login + cloud tools on */
export function imageGenerationAvailable(
settings: Pick<AiSettings, 'media' | 'gskToolsEnabled'> | null | undefined,
gskLoggedIn: boolean,
): boolean {
return capabilityAvailable(settings, gskLoggedIn, 'image')
}
/** live predicate for the analyze_media tool: image analysis or video analysis reachable */
export function mediaAnalysisAvailable(
settings: Pick<AiSettings, 'media' | 'gskToolsEnabled'> | null | undefined,
gskLoggedIn: boolean,
): boolean {
return (
capabilityAvailable(settings, gskLoggedIn, 'analysis') ||
capabilityAvailable(settings, gskLoggedIn, 'video')
)
}
export function videoAnalysisAvailable(
settings: Pick<AiSettings, 'media' | 'gskToolsEnabled'> | null | undefined,
gskLoggedIn: boolean,
): boolean {
return capabilityAvailable(settings, gskLoggedIn, 'video')
}
@@ -227,6 +227,14 @@ async function anthropicTurn(
throw new Error(sseErrorText(event.error, 'Claude stream error'))
}
}
// Buffered tool arguments can take minutes; a gateway dropping the connection
// meanwhile is a billed in-progress turn, not the replayable empty stream below.
if (pendingTools.size > 0 && !stopReason) {
const received = [...pendingTools.values()].reduce((n, p) => n + p.json.length, 0)
throw new Error(
`Claude stream closed while sending tool arguments (${received} chars received); the connection was dropped`,
)
}
const lastTool = completedTools.at(-1)
if (stopReason === 'max_tokens' && lastTool) lastTool.truncated = true
for (const call of completedTools) cb.onToolCall(call)
@@ -191,6 +191,7 @@ async function openAiCompatibleTurn(
let stopReason: string | undefined
let abnormalFinish: string | undefined
let sawFinish = false
let sawDone = false
let emitted = false
const flushTools = () => {
const entries = [...pendingTools.entries()].sort(([a], [b]) => a - b)
@@ -215,7 +216,10 @@ async function openAiCompatibleTurn(
if (!line.startsWith('data:')) continue
const payload = line.slice(5).trim()
if (!payload) continue
if (payload === '[DONE]') break
if (payload === '[DONE]') {
sawDone = true
break
}
// A truncated frame or a non-JSON keep-alive from a proxy should skip
// that event, not kill the entire AI turn with a parser error.
let event
@@ -278,6 +282,16 @@ async function openAiCompatibleTurn(
flushTools()
}
}
// No finish and no [DONE] with half-received arguments: the connection dropped
if (!sawFinish && !sawDone) {
const broken = [...pendingTools.values()].filter((p) => p.name && parseToolInput(p.json).error)
if (broken.length > 0) {
const received = broken.reduce((n, p) => n + p.json.length, 0)
throw new Error(
`The model stream closed while sending tool arguments (${received} chars received); the connection was dropped`,
)
}
}
flushTools()
// e.g. finish_reason=content_filter with no output, or a stream with no
// message framing at all (gateway soft-failure) — surface both instead of an
+11 -1
View File
@@ -1,3 +1,5 @@
import { defaultAiMediaSettings, resolveAiMediaSettings } from './media'
import { defaultAiSearchSettings, resolveAiSearchSettings } from './search-settings'
import type { AiProviderId, AiProviderMeta, AiSettings, LegacyAiSettings } from './types'
/**
@@ -247,7 +249,13 @@ export function defaultAiSettings(
cliPath: meta.needsCliPath ? '' : undefined,
}
}
return { provider: 'genspark', providers, gskToolsEnabled: true }
return {
provider: 'genspark',
providers,
gskToolsEnabled: true,
media: defaultAiMediaSettings(),
search: defaultAiSearchSettings(),
}
}
/** false only on an explicit opt-out; absent (pre-toggle settings files) means on */
@@ -383,6 +391,8 @@ export function resolveAiSettings(
// the retired-id remap instead of being sent to the API verbatim.
providers: migrateRetiredModels(trimConfigs({ ...defaults.providers, ...stored.providers })),
gskToolsEnabled: stored.gskToolsEnabled ?? defaults.gskToolsEnabled ?? true,
media: resolveAiMediaSettings(stored.media ?? defaults.media),
search: resolveAiSearchSettings(stored.search ?? defaults.search),
// clamped on read: a hand-edited settings file with an absurd cap must not be
// forwarded to the endpoint verbatim
...(stored.maxOutputTokens !== undefined || defaults.maxOutputTokens !== undefined
@@ -0,0 +1,42 @@
import type {
AiSearchProviderId,
AiSearchProviderMeta,
AiSearchSettings,
AiSettings,
} from './types'
export const AI_SEARCH_PROVIDERS: AiSearchProviderMeta[] = [
{
id: 'genspark',
label: 'Genspark',
keyPlaceholder: 'Not required - sign in to Genspark',
imageSearch: true,
},
{ id: 'serper', label: 'Serper', keyPlaceholder: 'Serper API key', imageSearch: true },
{ id: 'tavily', label: 'Tavily', keyPlaceholder: 'tvly-...', imageSearch: false },
]
export function defaultAiSearchSettings(): AiSearchSettings {
return { provider: 'genspark', providers: { serper: { apiKey: '' }, tavily: { apiKey: '' } } }
}
export function resolveAiSearchSettings(
stored: Partial<AiSearchSettings> | undefined,
): AiSearchSettings {
const defaults = defaultAiSearchSettings()
if (!stored) return defaults
const providers = { ...defaults.providers }
for (const id of ['serper', 'tavily'] as const) {
const key = stored.providers?.[id]?.apiKey
if (typeof key === 'string') providers[id] = { apiKey: key.trim() }
}
return { provider: stored.provider ?? defaults.provider, providers }
}
/** the stored search provider, honored only with a key; otherwise genspark (gsk + free chain) */
export function activeSearchProvider(settings: Pick<AiSettings, 'search'>): AiSearchProviderId {
const search = settings.search
if (!search || search.provider === 'genspark') return 'genspark'
if (!AI_SEARCH_PROVIDERS.some((m) => m.id === search.provider)) return 'genspark'
return search.providers?.[search.provider]?.apiKey ? search.provider : 'genspark'
}
+75
View File
@@ -50,9 +50,84 @@ export interface AiProviderMeta {
needsCliPath?: boolean
}
/** Image generation / media analysis backends (separate from the chat provider) */
export type AiMediaProviderId =
'genspark' | 'openai' | 'gemini' | 'doubao' | 'glm' | 'xai' | 'qwen' | 'minimax' | 'custom'
/** wire shape of the image endpoint */
export type AiImageProtocol = 'openai-images' | 'gemini' | 'dashscope' | 'minimax'
/** wire shape of the understanding endpoint */
export type AiAnalysisProtocol = 'openai-chat' | 'gemini'
export interface AiMediaProviderConfig {
apiKey: string
/** required for custom; for the others it overrides the official endpoint (regional mirrors) */
baseUrl?: string | undefined
/** image generation model (empty = the provider default) */
imageModel: string
/** image/video understanding model (empty = the provider default) */
analysisModel: string
}
export interface AiMediaProviderMeta {
id: AiMediaProviderId
label: string
/** one-line English blurb shown on the provider card */
description: string
keyPlaceholder: string
needsBaseUrl?: boolean
/** '' for genspark (gsk login) and custom (user-supplied) */
defaultBaseUrl: string
/** absent = the provider does not generate images */
imageProtocol?: AiImageProtocol
imageModels: string[]
defaultImageModel: string
/** absent = the provider does not analyze media */
analysisProtocol?: AiAnalysisProtocol
analysisModels: string[]
defaultAnalysisModel: string
/** the analysis model accepts video input (Gemini natively; OpenAI-compatible vendors via a video_url part) */
videoAnalysis: boolean
}
export interface AiMediaSettings {
/** provider behind generate_image */
imageProvider: AiMediaProviderId
/** provider behind analyze_media for images */
analysisProvider: AiMediaProviderId
/** provider behind analyze_media when the input has video/audio (only video-capable vendors qualify) */
videoAnalysisProvider: AiMediaProviderId
providers: Record<AiMediaProviderId, AiMediaProviderConfig>
/** pre-catalog shape (one provider for both); migrated by resolveAiMediaSettings */
provider?: AiMediaProviderId | undefined
}
/** web/image search backends: Genspark (gsk) or a user key for Serper / Tavily */
export type AiSearchProviderId = 'genspark' | 'serper' | 'tavily'
export interface AiSearchProviderMeta {
id: AiSearchProviderId
label: string
keyPlaceholder: string
/** the backend also serves image search (otherwise image search falls back to free sources) */
imageSearch: boolean
}
export interface AiSearchSettings {
provider: AiSearchProviderId
providers: Record<Exclude<AiSearchProviderId, 'genspark'>, { apiKey: string }>
}
export interface AiSettings {
provider: AiProviderId
providers: Record<AiProviderId, AiProviderConfig>
/**
* Provider for generate_image / analyze_media. Absent (pre-media settings
* files) means Genspark, i.e. the gsk login + gskToolsEnabled gate.
*/
media?: AiMediaSettings | undefined
/** web/image search backend; absent means Genspark (gsk when signed in, then the free chain) */
search?: AiSearchSettings | undefined
/**
* Genspark cloud tools (web/image search via gsk, image generation, media
* analysis). Default true; false makes tools skip the gsk backend entirely
+2 -2
View File
@@ -42,7 +42,7 @@ describe('chatForProvider', () => {
const result = await chatForProvider('anthropic', { apiKey: 'k', model: 'm' }, 'sys', 'hi')
expect(result.ok).toBe(false)
expect(result.error).toMatch(/Claude HTTP 403/)
expect(result.error).toMatch(/web page instead of an API response/)
expect(result.error).toMatch(/web page.*instead of an API response/)
expect(result.error).not.toContain('<!doctype')
})
@@ -178,7 +178,7 @@ describe('chatForProvider', () => {
const result = await chatForProvider('anthropic', { apiKey: 'k', model: 'm' }, 'sys', 'hi')
expect(result.ok).toBe(false)
expect(result.error).toMatch(/non-JSON response/)
expect(result.error).toMatch(/web page instead of an API response/)
expect(result.error).toMatch(/web page.*instead of an API response/)
})
it('openai: a 200 with an empty body is an error, not a thrown SyntaxError', async () => {
@@ -4,13 +4,43 @@ import { join } from 'node:path'
import { tmpdir } from 'node:os'
import type { AgentToolDef } from '@genoffice/agent-core'
import {
activePermissionProfileId,
buildCodexAppServerPrompt,
codexAppServerLaunchArgs,
codexAppServerOutputSchema,
codexThreadStartParams,
parseCodexAppServerTurn,
resolveCodexCliPath,
waitForTurn,
type CodexTurnTransport,
type RpcMessage,
} from '../src/codex-app-server'
function fakeTransport(script: RpcMessage[]): CodexTurnTransport {
let listener: ((message: RpcMessage) => void) | undefined
return {
request: async (method) => {
if (method === 'turn/start') {
queueMicrotask(() => script.forEach((message) => listener?.(message)))
return { turn: { id: 't1' } }
}
return {}
},
onNotification: (next) => {
listener = next
return () => {
listener = undefined
}
},
}
}
const noopCallbacks = {
signal: new AbortController().signal,
onDelta: () => undefined,
onToolCall: () => undefined,
}
const tools: AgentToolDef[] = [
{
name: 'replace_text',
@@ -72,6 +102,28 @@ describe('Codex app-server bridge', () => {
expect(codexAppServerLaunchArgs()).toEqual(['app-server', '--listen', 'stdio://'])
})
it('confines Codex tool reads to the temp dir through a permission profile', () => {
const config = { apiKey: '', model: 'gpt-5.6-terra' }
const params = codexThreadStartParams(config, '/tmp/genoffice-codex-x', 'profile')
expect(params).not.toHaveProperty('sandbox')
expect(params.approvalPolicy).toBe('never')
expect(params.config).toEqual({
default_permissions: 'genoffice',
permissions: {
genoffice: {
filesystem: { ':minimal': 'read', '/tmp/genoffice-codex-x': 'read' },
},
},
})
expect(codexThreadStartParams(config, '/tmp/genoffice-codex-x', 'read-only')).toMatchObject({
sandbox: 'read-only',
})
expect(activePermissionProfileId({ activePermissionProfile: { id: 'genoffice' } })).toBe(
'genoffice',
)
expect(activePermissionProfileId({ activePermissionProfile: null })).toBeUndefined()
})
it('builds a strict one-turn output schema with only known tool names', () => {
const schema = codexAppServerOutputSchema(tools) as {
properties: { toolCalls: { items: { properties: { name: { enum: string[] } } } } }
@@ -135,4 +187,53 @@ describe('Codex app-server bridge', () => {
parseCodexAppServerTurn(JSON.stringify({ text: '', toolCalls: [] }), tools),
).toThrow('no content')
})
it('keeps waiting through transient stream errors Codex retries itself', async () => {
const transport = fakeTransport([
{
method: 'error',
params: {
threadId: 'th',
turnId: 't1',
willRetry: true,
error: { message: 'Reconnecting... 2/5' },
},
},
{
method: 'item/completed',
params: { threadId: 'th', turnId: 't1', item: { type: 'agentMessage', text: 'done' } },
},
{
method: 'turn/completed',
params: { threadId: 'th', turnId: 't1', turn: { id: 't1', status: 'completed' } },
},
])
await expect(
waitForTurn(
transport,
'th',
() => transport.request('turn/start', {}),
noopCallbacks.signal,
noopCallbacks,
),
).resolves.toBe('done')
})
it('fails the turn on a non-retried error notification', async () => {
const transport = fakeTransport([
{
method: 'error',
params: { threadId: 'th', turnId: 't1', willRetry: false, error: { message: 'boom' } },
},
])
await expect(
waitForTurn(
transport,
'th',
() => transport.request('turn/start', {}),
noopCallbacks.signal,
noopCallbacks,
),
).rejects.toThrow('boom')
})
})
+37
View File
@@ -71,6 +71,43 @@ describe('aiFetch', () => {
await expect(aiFetch('https://x/', {})).rejects.toThrow('primary down')
})
it('retries a 403 HTML block page over the rescue fetch', async () => {
const blocked = () =>
new Response('<!doctype html><title>Just a moment...</title>', {
status: 403,
headers: { 'content-type': 'text/html; charset=utf-8' },
})
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(blocked()))
const ok = new Response('{}', { headers: { 'content-type': 'application/json' } })
const rescue = vi.fn().mockResolvedValue(ok)
setRescueFetch(rescue)
expect(await aiFetch('https://www.genspark.ai/api/x', { method: 'POST', body: '{}' })).toBe(ok)
expect(rescue).toHaveBeenCalledOnce()
// still blocked on the rescue path: the primary answer stands
const primary = blocked()
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(primary))
setRescueFetch(vi.fn().mockResolvedValue(blocked()))
expect(await aiFetch('https://www.genspark.ai/api/x', { body: '{}' })).toBe(primary)
})
it('does not treat an API 403 or a stream body as a block page', async () => {
const denied = new Response('{"error":"forbidden"}', {
status: 403,
headers: { 'content-type': 'application/json' },
})
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(denied))
const rescue = vi.fn()
setRescueFetch(rescue)
expect(await aiFetch('https://x/', { body: '{}' })).toBe(denied)
expect(rescue).not.toHaveBeenCalled()
const html = new Response('<html>', { status: 403, headers: { 'content-type': 'text/html' } })
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(html))
expect(await aiFetch('https://x/', { body: new ReadableStream() })).toBe(html)
expect(rescue).not.toHaveBeenCalled()
})
it('does not retry an aborted request', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('aborted')))
const rescue = vi.fn()
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest'
import { httpBodyDetail } from '../src/http-error'
describe('httpBodyDetail', () => {
it('passes API error bodies through, truncated', () => {
expect(httpBodyDetail('{"error":"bad"}')).toBe('{"error":"bad"}')
expect(httpBodyDetail('x'.repeat(600))).toHaveLength(500)
})
it('names the block page instead of dumping markup', () => {
const page = `<!DOCTYPE html><html><head><title>\n Attention Required! | Cloudflare\n</title></head>
<body><span>Cloudflare Ray ID: <strong class="font-semibold">a37f69f31ff7a28e</strong></span>
<span>error code: <span>1020</span></span></body></html>`
expect(httpBodyDetail(page)).toBe(
'the service returned a web page ("Attention Required! | Cloudflare", error code 1020, ray a37f69f31ff7a28e) instead of an API response (likely a temporary network or gateway block) — check your connection and retry',
)
})
it('keeps the generic note for a bare HTML shell', () => {
expect(httpBodyDetail('<html><body></body></html>')).toBe(
'the service returned a web page instead of an API response (likely a temporary network or gateway block) — check your connection and retry',
)
})
})
+487
View File
@@ -0,0 +1,487 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
AI_MEDIA_PROVIDERS,
activeMediaConfig,
activeMediaProvider,
defaultAiMediaSettings,
imageGenerationAvailable,
mediaAnalysisAvailable,
resolveAiMediaSettings,
} from '../src/media'
import {
analyzeMediaWithProvider,
generateImageWithProvider,
sniffImageMime,
testMediaProvider,
} from '../src/media-protocols'
import { defaultAiSettings, resolveAiSettings } from '../src/providers'
import type { AiSettings } from '../src/types'
afterEach(() => {
vi.unstubAllGlobals()
})
const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])
const PNG_B64 = Buffer.from(PNG).toString('base64')
function withMedia(media: Partial<AiSettings['media']>): AiSettings {
const base = defaultAiSettings()
return { ...base, media: { ...base.media!, ...media } as AiSettings['media'] }
}
function openaiSettings(apiKey = 'sk-test', imageModel = 'gpt-image-2'): AiSettings {
const media = defaultAiMediaSettings()
media.imageProvider = 'openai'
media.analysisProvider = 'openai'
media.providers.openai = { apiKey, imageModel, analysisModel: 'gpt-5.6-luna' }
return withMedia(media)
}
describe('media settings', () => {
it('defaults every provider to its default models and genspark as the active one', () => {
const media = defaultAiMediaSettings()
expect(media.imageProvider).toBe('genspark')
expect(media.analysisProvider).toBe('genspark')
expect(media.videoAnalysisProvider).toBe('genspark')
for (const meta of AI_MEDIA_PROVIDERS) {
expect(media.providers[meta.id].imageModel).toBe(meta.defaultImageModel)
expect(media.providers[meta.id].apiKey).toBe('')
}
expect(media.providers.custom.baseUrl).toBe('')
expect(media.providers.openai.baseUrl).toBeUndefined()
})
it('is carried by defaultAiSettings and healed in from a pre-media settings file', () => {
const defaults = defaultAiSettings()
expect(defaults.media?.imageProvider).toBe('genspark')
const resolved = resolveAiSettings(
{ provider: 'genspark', providers: defaults.providers },
defaultAiSettings(),
)
expect(resolved.media).toEqual(defaultAiMediaSettings())
})
it('merges and trims a stored media block over defaults', () => {
const media = resolveAiMediaSettings({
provider: 'gemini',
providers: {
gemini: { apiKey: ' AIza ', imageModel: ' gemini-3-pro-image ', analysisModel: '' },
} as never,
})
// the pre-catalog single `provider` seeds both capabilities
expect(media.imageProvider).toBe('gemini')
expect(media.analysisProvider).toBe('gemini')
expect(
resolveAiMediaSettings({ imageProvider: 'doubao', analysisProvider: 'qwen' })
.analysisProvider,
).toBe('qwen')
// pre-split files used one vendor for all analysis
expect(
resolveAiMediaSettings({ imageProvider: 'doubao', analysisProvider: 'qwen' })
.videoAnalysisProvider,
).toBe('qwen')
expect(
resolveAiMediaSettings({ analysisProvider: 'openai', videoAnalysisProvider: 'gemini' })
.videoAnalysisProvider,
).toBe('gemini')
expect(media.providers.gemini).toEqual({
apiKey: 'AIza',
imageModel: 'gemini-3-pro-image',
analysisModel: '',
})
expect(media.providers.openai.imageModel).toBe('gpt-image-2')
})
it('activates a BYOK media provider per capability, only when usable and capable', () => {
expect(activeMediaProvider(openaiSettings(), 'image')).toBe('openai')
expect(activeMediaProvider(openaiSettings(), 'analysis')).toBe('openai')
expect(activeMediaProvider(openaiSettings(''), 'image')).toBe('genspark')
const custom = defaultAiMediaSettings()
custom.imageProvider = 'custom'
expect(activeMediaProvider(withMedia(custom), 'image')).toBe('genspark')
custom.providers.custom.baseUrl = 'http://localhost:1234/v1'
expect(activeMediaProvider(withMedia(custom), 'image')).toBe('custom')
expect(activeMediaProvider(withMedia(custom), 'analysis')).toBe('genspark')
expect(activeMediaConfig(withMedia(custom), 'image')?.provider).toBe('custom')
// MiniMax has no analysis endpoint: picking it for analysis falls back
const mm = defaultAiMediaSettings()
mm.analysisProvider = 'minimax'
mm.providers.minimax.apiKey = 'k'
expect(activeMediaProvider(withMedia(mm), 'analysis')).toBe('genspark')
// OpenAI reads images but not video: as the video provider it falls back
const oa = openaiSettings()
oa.media!.videoAnalysisProvider = 'openai'
expect(activeMediaProvider(oa, 'video')).toBe('genspark')
oa.media!.videoAnalysisProvider = 'gemini'
oa.media!.providers.gemini.apiKey = 'AIza'
expect(activeMediaProvider(oa, 'video')).toBe('gemini')
expect(activeMediaProvider({ media: undefined }, 'image')).toBe('genspark')
expect(
activeMediaProvider({ media: { imageProvider: 'nope', providers: {} } as never }, 'image'),
).toBe('genspark')
})
it('gates the tools on gsk login + toggle without BYOK, and on the BYOK model with it', () => {
const genspark = defaultAiSettings()
expect(imageGenerationAvailable(genspark, true)).toBe(true)
expect(imageGenerationAvailable(genspark, false)).toBe(false)
expect(imageGenerationAvailable({ ...genspark, gskToolsEnabled: false }, true)).toBe(false)
expect(mediaAnalysisAvailable({ ...genspark, gskToolsEnabled: false }, true)).toBe(false)
const byok = openaiSettings()
expect(imageGenerationAvailable(byok, false)).toBe(true)
expect(imageGenerationAvailable({ ...byok, gskToolsEnabled: false }, false)).toBe(true)
expect(mediaAnalysisAvailable(byok, false)).toBe(true)
// built-in vendors fall back to their default model; a custom endpoint
// without a model for one capability disables that tool alone
const noAnalysis = openaiSettings()
noAnalysis.media!.providers.openai.analysisModel = ''
expect(mediaAnalysisAvailable(noAnalysis, false)).toBe(true)
const custom = defaultAiMediaSettings()
custom.imageProvider = 'custom'
custom.analysisProvider = 'custom'
custom.providers.custom = {
apiKey: '',
baseUrl: 'http://localhost:1234/v1',
imageModel: 'flux',
analysisModel: '',
}
expect(mediaAnalysisAvailable(withMedia(custom), false)).toBe(false)
expect(imageGenerationAvailable(withMedia(custom), false)).toBe(true)
expect(imageGenerationAvailable(null, true)).toBe(true)
})
})
describe('sniffImageMime', () => {
it('reads the magic bytes and falls back to the declared type', () => {
expect(sniffImageMime(PNG)).toBe('image/png')
expect(sniffImageMime(new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0]))).toBe('image/jpeg')
expect(sniffImageMime(new Uint8Array([1, 2, 3]), 'image/webp')).toBe('image/webp')
})
})
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' },
})
}
describe('generateImageWithProvider', () => {
it('posts to the OpenAI Images API with a size derived from the aspect ratio and decodes b64_json', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ data: [{ b64_json: PNG_B64 }] }))
vi.stubGlobal('fetch', fetchMock)
const out = await generateImageWithProvider(
'openai',
{ apiKey: 'sk-1', imageModel: 'gpt-image-2', analysisModel: '' },
{ prompt: 'a cat', aspectRatio: '16:9' },
)
expect(out.mime).toBe('image/png')
expect(Array.from(out.bytes)).toEqual(Array.from(PNG))
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('https://api.openai.com/v1/images/generations')
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer sk-1')
expect(JSON.parse(init.body as string)).toEqual({
model: 'gpt-image-2',
prompt: 'a cat',
n: 1,
size: '1536x1024',
})
})
it('uses the edits endpoint (multipart) when reference images are given', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ data: [{ b64_json: PNG_B64 }] }))
vi.stubGlobal('fetch', fetchMock)
await generateImageWithProvider(
'custom',
{ apiKey: '', baseUrl: 'http://localhost:1234/v1/', imageModel: 'flux', analysisModel: '' },
{ prompt: 'remove background', references: [{ bytes: PNG, mime: 'image/png' }] },
)
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('http://localhost:1234/v1/images/edits')
expect(init.body).toBeInstanceOf(FormData)
const form = init.body as FormData
expect(form.get('model')).toBe('flux')
expect(form.get('image')).toBeInstanceOf(Blob)
expect((init.headers as Record<string, string>).Authorization).toBeUndefined()
})
it('calls Gemini generateContent with IMAGE modality and reads inlineData back', async () => {
const fetchMock = vi.fn(async () =>
jsonResponse({
candidates: [
{
content: {
parts: [
{ text: 'here you go' },
{ inlineData: { mimeType: 'image/png', data: PNG_B64 } },
],
},
},
],
}),
)
vi.stubGlobal('fetch', fetchMock)
const out = await generateImageWithProvider(
'gemini',
{ apiKey: 'AIza', imageModel: 'gemini-3.1-flash-image', analysisModel: '' },
{ prompt: 'a dog', aspectRatio: '9:16' },
)
expect(out.mime).toBe('image/png')
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe(
'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image:generateContent',
)
expect((init.headers as Record<string, string>)['x-goog-api-key']).toBe('AIza')
const body = JSON.parse(init.body as string)
expect(body.generationConfig).toEqual({
responseModalities: ['TEXT', 'IMAGE'],
imageConfig: { aspectRatio: '9:16' },
})
})
it('routes imagen-* ids to :predict', async () => {
const fetchMock = vi.fn(async () =>
jsonResponse({ predictions: [{ bytesBase64Encoded: PNG_B64, mimeType: 'image/png' }] }),
)
vi.stubGlobal('fetch', fetchMock)
await generateImageWithProvider(
'gemini',
{ apiKey: 'AIza', imageModel: 'imagen-4.0-generate-001', analysisModel: '' },
{ prompt: 'a dog' },
)
const [url] = fetchMock.mock.calls[0] as unknown as [string]
expect(url).toMatch(/imagen-4\.0-generate-001:predict$/)
})
it('surfaces HTTP errors with the body detail and refuses custom without a base URL', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ error: { message: 'invalid api key' } }, 401)),
)
await expect(
generateImageWithProvider(
'openai',
{ apiKey: 'bad', imageModel: 'gpt-image-2', analysisModel: '' },
{ prompt: 'x' },
),
).rejects.toThrow(/401.*invalid api key/)
await expect(
generateImageWithProvider(
'custom',
{ apiKey: '', imageModel: 'm', analysisModel: '' },
{ prompt: 'x' },
),
).rejects.toThrow(/Base URL/)
})
})
describe('generateImageWithProvider (vendor shapes)', () => {
const cfg = (imageModel: string, baseUrl?: string) => ({
apiKey: 'k',
imageModel,
analysisModel: '',
...(baseUrl ? { baseUrl } : {}),
})
it('Ark/Seedream: aspect ratio as size, b64 requested, references inline in the body', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ data: [{ b64_json: PNG_B64 }] }))
vi.stubGlobal('fetch', fetchMock)
await generateImageWithProvider('doubao', cfg('doubao-seedream-5-0-260128'), {
prompt: 'a fox',
aspectRatio: '16:9',
references: [{ bytes: PNG, mime: 'image/png' }],
})
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('https://ark.cn-beijing.volces.com/api/v3/images/generations')
const body = JSON.parse(init.body as string)
expect(body).toMatchObject({ size: '16:9', response_format: 'b64_json', watermark: false })
expect(body.image).toEqual([`data:image/png;base64,${PNG_B64}`])
})
it('Zhipu/CogView: fixed WxH grid, URL result downloaded, no edits', async () => {
const fetchMock = vi.fn(async (url: string) =>
url.endsWith('/images/generations')
? jsonResponse({ data: [{ url: 'https://cdn.example/x.png' }] })
: new Response(PNG, { status: 200, headers: { 'content-type': 'image/png' } }),
)
vi.stubGlobal('fetch', fetchMock)
const out = await generateImageWithProvider('glm', cfg('cogview-4-250304'), {
prompt: 'a fox',
aspectRatio: '9:16',
})
expect(out.mime).toBe('image/png')
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('https://open.bigmodel.cn/api/paas/v4/images/generations')
expect(JSON.parse(init.body as string).size).toBe('768x1344')
expect((fetchMock.mock.calls[1] as unknown as [string])[0]).toBe('https://cdn.example/x.png')
await expect(
generateImageWithProvider('glm', cfg('cogview-4-250304'), {
prompt: 'x',
references: [{ bytes: PNG, mime: 'image/png' }],
}),
).rejects.toThrow(/cannot edit/)
})
it('xAI: no size field, b64 requested', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ data: [{ b64_json: PNG_B64 }] }))
vi.stubGlobal('fetch', fetchMock)
await generateImageWithProvider('xai', cfg('grok-imagine-image-2.0'), {
prompt: 'a fox',
aspectRatio: '16:9',
})
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('https://api.x.ai/v1/images/generations')
const body = JSON.parse(init.body as string)
expect(body.size).toBeUndefined()
expect(body.response_format).toBe('b64_json')
})
it('DashScope/Qwen-Image: multimodal-generation body, W*H size, image URL in output.choices', async () => {
const fetchMock = vi.fn(async (url: string) =>
url.includes('multimodal-generation')
? jsonResponse({
output: {
choices: [{ message: { content: [{ image: 'https://oss.example/q.png' }] } }],
},
})
: new Response(PNG, { status: 200, headers: { 'content-type': 'image/png' } }),
)
vi.stubGlobal('fetch', fetchMock)
await generateImageWithProvider(
'qwen',
cfg('qwen-image-plus', 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1'),
{ prompt: 'a fox', aspectRatio: '4:3' },
)
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe(
'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation',
)
const body = JSON.parse(init.body as string)
expect(body.model).toBe('qwen-image-plus')
expect(body.input.messages[0].content[0].text).toBe('a fox')
expect(body.parameters).toEqual({ n: 1, watermark: false, size: '1472*1104' })
})
it('MiniMax: image_generation with aspect_ratio and base64 result; base_resp errors surface', async () => {
const fetchMock = vi.fn(async () =>
jsonResponse({ data: { image_base64: [PNG_B64] }, base_resp: { status_code: 0 } }),
)
vi.stubGlobal('fetch', fetchMock)
const out = await generateImageWithProvider('minimax', cfg('image-01'), {
prompt: 'a fox',
aspectRatio: '16:9',
})
expect(out.mime).toBe('image/png')
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('https://api.minimax.io/v1/image_generation')
expect(JSON.parse(init.body as string)).toMatchObject({
model: 'image-01',
aspect_ratio: '16:9',
response_format: 'base64',
})
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ base_resp: { status_code: 1004, status_msg: 'auth' } })),
)
await expect(
generateImageWithProvider('minimax', cfg('image-01'), { prompt: 'x' }),
).rejects.toThrow(/1004 auth/)
})
})
describe('analyzeMediaWithProvider', () => {
it('sends images as data URLs through chat completions and rejects video for OpenAI-style providers', async () => {
const fetchMock = vi.fn(async () =>
jsonResponse({ choices: [{ message: { content: 'two cats' } }] }),
)
vi.stubGlobal('fetch', fetchMock)
const config = { apiKey: 'sk', imageModel: '', analysisModel: 'gpt-5.6-luna' }
const text = await analyzeMediaWithProvider('openai', config, {
media: [{ bytes: PNG, mime: 'image/png' }],
requirements: 'count the cats',
})
expect(text).toBe('two cats')
const body = JSON.parse(
(fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body as string,
)
expect(body.model).toBe('gpt-5.6-luna')
expect(body.messages[0].content[1].image_url.url).toBe(`data:image/png;base64,${PNG_B64}`)
await expect(
analyzeMediaWithProvider('openai', config, {
media: [{ bytes: PNG, mime: 'video/mp4', name: 'clip.mp4' }],
requirements: 'summarize',
}),
).rejects.toThrow(/video and audio analysis needs/)
expect(fetchMock).toHaveBeenCalledTimes(1)
})
it('sends video as a video_url part for vendors that take it (Qwen via compatible-mode)', async () => {
const fetchMock = vi.fn(async () =>
jsonResponse({ choices: [{ message: { content: 'a talk' } }] }),
)
vi.stubGlobal('fetch', fetchMock)
const text = await analyzeMediaWithProvider(
'qwen',
{ apiKey: 'k', imageModel: '', analysisModel: 'qwen3-vl-plus' },
{ media: [{ bytes: PNG, mime: 'video/mp4' }], requirements: 'summarize' },
)
expect(text).toBe('a talk')
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions')
const body = JSON.parse(init.body as string)
expect(body.messages[0].content[1]).toEqual({
type: 'video_url',
video_url: { url: `data:video/mp4;base64,${PNG_B64}` },
})
await expect(
analyzeMediaWithProvider(
'qwen',
{ apiKey: 'k', imageModel: '', analysisModel: 'qwen3-vl-plus' },
{ media: [{ bytes: PNG, mime: 'audio/mpeg' }], requirements: 'x' },
),
).rejects.toThrow(/audio analysis needs/)
})
it('inlines small media for Gemini and joins the text parts', async () => {
const fetchMock = vi.fn(async () =>
jsonResponse({ candidates: [{ content: { parts: [{ text: 'a ' }, { text: 'talk' }] } }] }),
)
vi.stubGlobal('fetch', fetchMock)
const text = await analyzeMediaWithProvider(
'gemini',
{ apiKey: 'AIza', imageModel: '', analysisModel: 'gemini-3.7-flash' },
{ media: [{ bytes: PNG, mime: 'video/mp4' }], requirements: 'summarize' },
)
expect(text).toBe('a talk')
const body = JSON.parse(
(fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body as string,
)
expect(body.contents[0].parts[0].inline_data.mime_type).toBe('video/mp4')
expect(body.contents[0].parts[1].text).toBe('summarize')
})
})
describe('testMediaProvider', () => {
it('lists models as a credential check and reports failures as text', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ data: [] }))
vi.stubGlobal('fetch', fetchMock)
expect(
await testMediaProvider('openai', { apiKey: 'sk', imageModel: '', analysisModel: '' }),
).toEqual({ ok: true })
expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(
'https://api.openai.com/v1/models',
)
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ error: 'nope' }, 403)),
)
const failed = await testMediaProvider('gemini', {
apiKey: 'x',
imageModel: '',
analysisModel: '',
})
expect(failed.ok).toBe(false)
expect(failed.error).toMatch(/403/)
})
})
@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest'
import { defaultAiSettings, resolveAiSettings } from '../src/providers'
import {
activeSearchProvider,
defaultAiSearchSettings,
resolveAiSearchSettings,
} from '../src/search-settings'
describe('search settings', () => {
it('defaults to genspark with empty keys and rides along in defaultAiSettings', () => {
expect(defaultAiSearchSettings()).toEqual({
provider: 'genspark',
providers: { serper: { apiKey: '' }, tavily: { apiKey: '' } },
})
expect(defaultAiSettings().search?.provider).toBe('genspark')
const resolved = resolveAiSettings(
{ provider: 'genspark', providers: {} as never },
defaultAiSettings(),
)
expect(resolved.search).toEqual(defaultAiSearchSettings())
})
it('merges and trims stored keys', () => {
const s = resolveAiSearchSettings({
provider: 'tavily',
providers: { tavily: { apiKey: ' tvly-1 ' } } as never,
})
expect(s.provider).toBe('tavily')
expect(s.providers.tavily.apiKey).toBe('tvly-1')
expect(s.providers.serper.apiKey).toBe('')
})
it('activates a BYOK search provider only with a key', () => {
expect(activeSearchProvider({ search: undefined })).toBe('genspark')
expect(
activeSearchProvider({
search: {
provider: 'serper',
providers: { serper: { apiKey: '' }, tavily: { apiKey: '' } },
},
}),
).toBe('genspark')
expect(
activeSearchProvider({
search: {
provider: 'serper',
providers: { serper: { apiKey: 'k' }, tavily: { apiKey: '' } },
},
}),
).toBe('serper')
expect(activeSearchProvider({ search: { provider: 'bing', providers: {} } as never })).toBe(
'genspark',
)
})
})
+68 -1
View File
@@ -413,7 +413,7 @@ describe('streamForProvider: anthropic', () => {
const { cb } = collector()
await expect(
streamForProvider('anthropic', { apiKey: 'k', model: 'm' }, 'sys', [], [], 100, cb),
).rejects.toThrow(/Claude HTTP 403: .*web page instead of an API response/)
).rejects.toThrow(/Claude HTTP 403: .*web page.*instead of an API response/)
})
})
@@ -1079,3 +1079,70 @@ describe('streamForProvider: interleaved-thinking reasoning', () => {
expect('reasoning_content' in assistant).toBe(false)
})
})
describe('streamForProvider: a connection dropped mid tool arguments is not an empty stream', () => {
// Tool arguments are buffered upstream; the Genspark gateway closes the SSE
// after ~125s of that silence. The turn was billed and in progress, so it
// must not match the "(empty stream)" contract that agent-core replays.
it('anthropic: open tool_use block with no stop_reason rejects as a dropped connection', async () => {
const body = sseStream([
'data: {"type":"message_start","message":{}}',
'data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t1","name":"write_html"}}',
'data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":""}}',
'data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"html\\":\\"<!doc"}}',
])
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(okResponse(body)))
const { cb, toolCalls } = collector()
const run = streamForProvider(
'anthropic',
{ apiKey: 'k', model: 'claude-sonnet-5' },
'sys',
[],
[],
100,
cb,
)
await expect(run).rejects.toThrow(/connection was dropped/)
await expect(run).rejects.not.toThrow(/empty stream/)
expect(toolCalls).toEqual([])
})
it('openai-compatible: half-received tool arguments with no finish reject as a dropped connection', async () => {
const body = sseStream([
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"write_html","arguments":"{\\"html\\":"}}]}}]}',
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\\"<!doctype"}}]}}]}',
])
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(okResponse(body)))
const { cb, toolCalls } = collector()
const run = streamForProvider(
'openai',
{ apiKey: 'k', model: 'gpt-4.1-mini' },
'sys',
[],
[],
100,
cb,
)
await expect(run).rejects.toThrow(/connection was dropped/)
await expect(run).rejects.not.toThrow(/empty stream/)
expect(toolCalls).toEqual([])
})
it('openai-compatible: complete arguments without a finish reason still flush as a tool call', async () => {
const body = sseStream([
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"ping","arguments":"{\\"a\\":1}"}}]}}]}',
])
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(okResponse(body)))
const { cb, toolCalls } = collector()
await streamForProvider(
'openai',
{ apiKey: 'k', model: 'gpt-4.1-mini' },
'sys',
[],
[],
100,
cb,
)
expect(toolCalls.map((c) => [c.name, c.input])).toEqual([['ping', { a: 1 }]])
})
})
+3 -1
View File
@@ -14,11 +14,13 @@
"test:watch": "vitest"
},
"dependencies": {
"@genoffice/ai-provider": "*",
"@genoffice/electron-utils": "*",
"@genspark/cli": "^1.4.2"
},
"devDependencies": {
"@types/node": "^24.10.1",
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
}
}
+133 -80
View File
@@ -18,24 +18,130 @@ import { gskImageSearch, gskWebSearch, hasGskAuth } from './gsk'
export type { ImageSearchResult, WebSearchResult } from './shared'
export * from './gsk'
export * from './genoffice-auth'
export * from './media-tools'
export * from './search-tools'
const SERPER_KEY = () => process.env.SERPER_API_KEY ?? ''
const TAVILY_KEY = () => process.env.TAVILY_API_KEY ?? ''
/**
* Backend selection for one search. Keys default to the SERPER_API_KEY /
* TAVILY_API_KEY env vars; settings-driven callers (search-tools.ts) pass the
* user's key and turn gsk off so the chosen backend runs first.
*/
export interface SearchOptions {
/** false = skip the Genspark backend (cloud tools off, or a BYOK search provider is active) */
useGsk?: boolean
serperKey?: string
tavilyKey?: string
/** which keyed backend to try first (default serper) */
prefer?: 'serper' | 'tavily'
}
function normalizeOptions(opts: boolean | SearchOptions | undefined): Required<SearchOptions> {
const o = typeof opts === 'boolean' ? { useGsk: opts } : (opts ?? {})
return {
useGsk: o.useGsk ?? true,
serperKey: o.serperKey ?? SERPER_KEY(),
tavilyKey: o.tavilyKey ?? TAVILY_KEY(),
prefer: o.prefer ?? 'serper',
}
}
type WebSearchResponse = {
results: WebSearchResult[]
answer?: string
method: string
error?: string
}
/** Serper Google web search; null when the key is empty, the call fails, or nothing comes back */
async function serperWebSearch(
key: string,
query: string,
maxResults: number,
): Promise<WebSearchResponse | null> {
if (!key) return null
try {
const resp = await fetchWithTimeout('https://google.serper.dev/search', {
method: 'POST',
headers: { 'X-API-KEY': key, 'Content-Type': 'application/json' },
body: JSON.stringify({ q: query, num: maxResults, gl: 'us', hl: 'en' }),
})
if (!resp.ok) return null
const data = asRecord(await resp.json())
const organic: unknown[] = Array.isArray(data.organic) ? data.organic : []
const results: WebSearchResult[] = organic.slice(0, maxResults).map((item) => {
const o = asRecord(item)
return {
title: String(o.title ?? ''),
url: String(o.link ?? ''),
snippet: String(o.snippet ?? ''),
}
})
const answerBox = asRecord(data.answerBox)
const answerRaw =
answerBox.answer || answerBox.snippet || asRecord(data.knowledgeGraph).description
const answer = typeof answerRaw === 'string' && answerRaw ? answerRaw : undefined
if (!results.length) return null
return answer !== undefined
? { results, answer, method: 'serper' }
: { results, method: 'serper' }
} catch {
return null
}
}
async function tavilyWebSearch(
key: string,
query: string,
maxResults: number,
): Promise<WebSearchResponse | null> {
if (!key) return null
try {
const resp = await fetchWithTimeout('https://api.tavily.com/search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
api_key: key,
query,
max_results: maxResults,
include_answer: true,
}),
})
if (!resp.ok) return null
const data = asRecord(await resp.json())
const raw: unknown[] = Array.isArray(data.results) ? data.results : []
const results: WebSearchResult[] = raw.slice(0, maxResults).map((item) => {
const o = asRecord(item)
return {
title: String(o.title ?? ''),
url: String(o.url ?? ''),
snippet: String(o.content ?? ''),
}
})
const answerRaw = data.answer
const answer = typeof answerRaw === 'string' && answerRaw ? answerRaw : undefined
if (!results.length) return null
return answer !== undefined
? { results, answer, method: 'tavily' }
: { results, method: 'tavily' }
} catch {
return null
}
}
// ── Web search ──────────────────────────────────────────────────────
export async function webSearch(
query: string,
maxResults = 6,
useGsk = true,
): Promise<{
results: WebSearchResult[]
answer?: string
method: string
error?: string
}> {
// useGsk=false: the user turned Genspark cloud tools off — skip straight to the free backends
if (useGsk && hasGskAuth()) {
options: boolean | SearchOptions = true,
): Promise<WebSearchResponse> {
const o = normalizeOptions(options)
// useGsk=false: the user turned Genspark cloud tools off or picked their own
// search key — skip straight to the keyed/free backends
if (o.useGsk && hasGskAuth()) {
try {
const r = await gskWebSearch(query, maxResults)
if (r.results.length) return { ...r, method: 'gsk' }
@@ -43,74 +149,19 @@ export async function webSearch(
/* fall back to Serper/Tavily/DuckDuckGo */
}
}
const key = SERPER_KEY()
if (key) {
try {
const resp = await fetchWithTimeout('https://google.serper.dev/search', {
method: 'POST',
headers: { 'X-API-KEY': key, 'Content-Type': 'application/json' },
body: JSON.stringify({ q: query, num: maxResults, gl: 'us', hl: 'en' }),
})
if (resp.ok) {
const data = asRecord(await resp.json())
const organic: unknown[] = Array.isArray(data.organic) ? data.organic : []
const results: WebSearchResult[] = organic.slice(0, maxResults).map((item) => {
const o = asRecord(item)
return {
title: String(o.title ?? ''),
url: String(o.link ?? ''),
snippet: String(o.snippet ?? ''),
}
})
const answerBox = asRecord(data.answerBox)
const answerRaw =
answerBox.answer || answerBox.snippet || asRecord(data.knowledgeGraph).description
const answer = typeof answerRaw === 'string' && answerRaw ? answerRaw : undefined
if (results.length) {
return answer !== undefined
? { results, answer, method: 'serper' }
: { results, method: 'serper' }
}
}
} catch {
/* fall back to Tavily/DuckDuckGo */
}
}
const tavilyKey = TAVILY_KEY()
if (tavilyKey) {
try {
const resp = await fetchWithTimeout('https://api.tavily.com/search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
api_key: tavilyKey,
query,
max_results: maxResults,
include_answer: true,
}),
})
if (resp.ok) {
const data = asRecord(await resp.json())
const raw: unknown[] = Array.isArray(data.results) ? data.results : []
const results: WebSearchResult[] = raw.slice(0, maxResults).map((item) => {
const o = asRecord(item)
return {
title: String(o.title ?? ''),
url: String(o.url ?? ''),
snippet: String(o.content ?? ''),
}
})
const answerRaw = data.answer
const answer = typeof answerRaw === 'string' && answerRaw ? answerRaw : undefined
if (results.length) {
return answer !== undefined
? { results, answer, method: 'tavily' }
: { results, method: 'tavily' }
}
}
} catch {
/* fall back to DuckDuckGo */
}
const keyed =
o.prefer === 'tavily'
? [
() => tavilyWebSearch(o.tavilyKey, query, maxResults),
() => serperWebSearch(o.serperKey, query, maxResults),
]
: [
() => serperWebSearch(o.serperKey, query, maxResults),
() => tavilyWebSearch(o.tavilyKey, query, maxResults),
]
for (const attempt of keyed) {
const r = await attempt()
if (r) return r
}
try {
return { results: await duckWebSearch(query, maxResults), method: 'duckduckgo' }
@@ -125,13 +176,14 @@ export async function webSearch(
export async function imageSearch(
query: string,
maxResults = 8,
useGsk = true,
options: boolean | SearchOptions = true,
): Promise<{
images: ImageSearchResult[]
method: string
error?: string
}> {
if (useGsk && hasGskAuth()) {
const o = normalizeOptions(options)
if (o.useGsk && hasGskAuth()) {
try {
const images = await gskImageSearch(query, maxResults)
if (images.length) return { images, method: 'gsk' }
@@ -139,7 +191,8 @@ export async function imageSearch(
/* fall back to Serper/DuckDuckGo */
}
}
const key = SERPER_KEY()
// Tavily has no image endpoint; Serper is the only keyed image backend
const key = o.serperKey
if (key) {
try {
const resp = await fetchWithTimeout('https://google.serper.dev/images', {
+197
View File
@@ -0,0 +1,197 @@
/**
* generate_image / analyze_media for the five editors' main processes: one
* place that reads ai-settings.json live, routes to the BYOK media provider
* when one is configured, and otherwise to the Genspark CLI behind the usual
* login + cloud-tools gate. BYOK providers answer with bytes; those land in
* the local generated-image store and come back as a file:// URL that the
* insert pipelines' fetchRemoteImage accepts.
*/
import { existsSync, readFileSync, statSync } from 'node:fs'
import { basename, extname } from 'node:path'
import {
activeMediaConfig,
analyzeMediaWithProvider,
cloudToolsEnabled,
defaultAiSettings,
generateImageWithProvider,
resolveAiSettings,
type AiSettings,
type LegacyAiSettings,
type MediaBlob,
} from '@genoffice/ai-provider'
import {
fetchRemoteImage,
fetchWithSsrfGuard,
readGeneratedImage,
storeGeneratedImage,
} from '@genoffice/electron-utils'
import { gskAnalyzeMedia, gskGenerateImage, hasGskAuth, type GskGenerateImageOptions } from './gsk'
export const GSK_NOT_LOGGED_IN_ERROR =
'Genspark account is not logged in on this machine; ask the user to log in first'
export const GSK_TOOLS_OFF_ERROR =
'Genspark cloud tools are turned off in Settings (AI Model); enable them or configure an image provider under Settings (AI Media) to use this tool'
/** 200 MB: enough for a long clip through the Gemini Files API, small enough to hold in memory */
const MAX_MEDIA_BYTES = 200 * 1024 * 1024
/** the only load failure that may hand the request back to Genspark; validation failures never do */
export class MediaTooLargeError extends Error {}
const MIME_BY_EXT: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
'.heic': 'image/heic',
'.mp4': 'video/mp4',
'.mov': 'video/quicktime',
'.webm': 'video/webm',
'.m4v': 'video/mp4',
'.mkv': 'video/x-matroska',
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
'.m4a': 'audio/mp4',
'.aac': 'audio/aac',
'.ogg': 'audio/ogg',
'.flac': 'audio/flac',
}
export function readAiSettingsFile(path: string): AiSettings {
let stored: Partial<AiSettings> & LegacyAiSettings = {}
try {
if (existsSync(path)) stored = JSON.parse(readFileSync(path, 'utf-8'))
} catch {
/* corrupted settings file: defaults */
}
return resolveAiSettings(stored, defaultAiSettings())
}
type Gate = { error: string } | null
/** the Genspark route's preconditions; null when it may proceed */
function gskGate(settings: AiSettings, notLoggedInError: string): Gate {
if (!hasGskAuth()) return { error: notLoggedInError }
if (!cloudToolsEnabled(settings)) return { error: GSK_TOOLS_OFF_ERROR }
return null
}
function errorText(err: unknown): string {
return err instanceof Error ? err.message : String(err)
}
/**
* Resolves a tool-supplied media reference to bytes: an https URL (SSRF-guarded),
* a file:// URL from the generated-image store, or a local media file
* (attachments). Only media extensions are read locally — the model must not be
* able to ship arbitrary files to a vendor.
*/
export async function loadMediaReference(ref: string): Promise<MediaBlob> {
if (/^https?:\/\//i.test(ref)) {
const resp = await (ref.match(/\.(png|jpe?g|gif|webp)(\?|$)/i)
? fetchRemoteImage(ref)
: fetchWithSsrfGuard(ref, { headers: { 'User-Agent': 'Mozilla/5.0' } }))
if (!resp || !resp.ok) throw new Error(`Could not download ${ref}`)
const declared = Number(resp.headers.get('content-length') ?? 0)
if (declared > MAX_MEDIA_BYTES) throw new MediaTooLargeError(`${ref} is too large to analyze`)
const bytes = new Uint8Array(await resp.arrayBuffer())
if (bytes.byteLength > MAX_MEDIA_BYTES) {
throw new MediaTooLargeError(`${ref} is too large to analyze`)
}
const ct = resp.headers.get('content-type')?.split(';')[0]?.trim()
const name = basename(new URL(ref).pathname) || undefined
const mime =
ct && ct !== 'application/octet-stream' ? ct : MIME_BY_EXT[extname(name ?? '').toLowerCase()]
if (!mime) throw new Error(`Could not tell the media type of ${ref}`)
return { bytes, mime, ...(name ? { name } : {}) }
}
if (ref.startsWith('file:')) {
const local = readGeneratedImage(ref)
if (!local) throw new Error(`Not an accessible image: ${ref}`)
return { bytes: new Uint8Array(local.bytes), mime: local.mime }
}
const mime = MIME_BY_EXT[extname(ref).toLowerCase()]
if (!mime) throw new Error(`Unsupported media file: ${ref} (images, video and audio only)`)
if (!existsSync(ref)) throw new Error(`File not found: ${ref}`)
if (statSync(ref).size > MAX_MEDIA_BYTES) {
throw new MediaTooLargeError(`${ref} is too large to analyze`)
}
return { bytes: new Uint8Array(readFileSync(ref)), mime, name: basename(ref) }
}
export interface MediaToolOptions {
/** localized replacement for the default signed-out message */
notLoggedInError?: string
}
export async function generateImageTool(
settingsPath: string,
op: GskGenerateImageOptions,
options: MediaToolOptions = {},
): Promise<{ url?: string; error?: string }> {
const prompt = String(op.prompt ?? '').trim()
if (!prompt) return { error: 'prompt must not be empty' }
const settings = readAiSettingsFile(settingsPath)
const byok = activeMediaConfig(settings, 'image')
try {
if (!byok) {
const gate = gskGate(settings, options.notLoggedInError ?? GSK_NOT_LOGGED_IN_ERROR)
if (gate) return gate
return { url: (await gskGenerateImage({ ...op, prompt })).url }
}
// `model` names Genspark-only special models (fal-*); BYOK uses the configured image model
const references = await Promise.all((op.referenceImageUrls ?? []).map(loadMediaReference))
const image = await generateImageWithProvider(byok.provider, byok.config, {
prompt,
aspectRatio: op.aspectRatio,
references,
})
return { url: storeGeneratedImage(image.bytes, image.mime) }
} catch (err) {
return { error: errorText(err) }
}
}
export async function analyzeMediaTool(
settingsPath: string,
op: { mediaUrls: string[]; requirements: string },
options: MediaToolOptions = {},
): Promise<{ text?: string; error?: string }> {
const mediaUrls = (op.mediaUrls ?? []).map(String).filter(Boolean)
const requirements = String(op.requirements ?? '').trim()
if (!mediaUrls.length) return { error: 'mediaUrls must not be empty' }
if (!requirements) return { error: 'requirements must not be empty' }
const settings = readAiSettingsFile(settingsPath)
const imageByok = activeMediaConfig(settings, 'analysis')
const videoByok = activeMediaConfig(settings, 'video')
try {
const viaGsk = async () => {
const gate = gskGate(settings, options.notLoggedInError ?? GSK_NOT_LOGGED_IN_ERROR)
if (gate) return gate
return { text: await gskAnalyzeMedia({ mediaUrls, requirements }) }
}
if (!imageByok && !videoByok) return await viaGsk()
// route on the loaded bytes' real MIME, not the URL spelling: images go to the
// image-analysis provider, anything with video/audio to the video one
let media: MediaBlob[]
try {
media = await Promise.all(mediaUrls.map(loadMediaReference))
} catch (err) {
// only the size cap hands the request back to Genspark (the CLI streams large
// files itself); scheme / path / SSRF rejections stay rejections
if (err instanceof MediaTooLargeError && (!imageByok || !videoByok)) return await viaGsk()
return { error: errorText(err) }
}
const hasVideo = media.some((m) => !m.mime.startsWith('image/'))
const byok = hasVideo ? videoByok : imageByok
if (!byok) return await viaGsk()
return {
text: await analyzeMediaWithProvider(byok.provider, byok.config, { media, requirements }),
}
} catch (err) {
return { error: errorText(err) }
}
}
+55
View File
@@ -0,0 +1,55 @@
/**
* ai:web-search / ai:image-search for the editors' main processes: reads
* ai-settings.json live and turns the search provider choice into
* SearchOptions — Genspark keeps the historic chain (gsk when signed in and
* cloud tools are on, then env keys, then DuckDuckGo); a user Serper / Tavily
* key runs first and skips gsk.
*/
import {
activeSearchProvider,
cloudToolsEnabled,
type AiSearchProviderId,
type AiSettings,
} from '@genoffice/ai-provider'
import { imageSearch, webSearch, type SearchOptions } from './index'
import { readAiSettingsFile } from './media-tools'
export function searchOptionsFromSettings(settings: AiSettings): SearchOptions {
const provider = activeSearchProvider(settings)
if (provider === 'genspark') return { useGsk: cloudToolsEnabled(settings) }
const key = settings.search!.providers[provider].apiKey
return provider === 'tavily'
? { useGsk: false, tavilyKey: key, prefer: 'tavily' }
: { useGsk: false, serperKey: key }
}
export function webSearchTool(settingsPath: string, query: string, maxResults = 6) {
return webSearch(query, maxResults, searchOptionsFromSettings(readAiSettingsFile(settingsPath)))
}
export function imageSearchTool(settingsPath: string, query: string, maxResults = 8) {
return imageSearch(query, maxResults, searchOptionsFromSettings(readAiSettingsFile(settingsPath)))
}
/** settings-UI test: one minimal query against the given key must be answered by that backend */
export async function testSearchProvider(
provider: AiSearchProviderId,
apiKey: string,
): Promise<{ ok: boolean; error?: string }> {
if (provider === 'genspark') return { ok: true }
if (!apiKey) return { ok: false, error: 'API key is empty' }
const options: SearchOptions =
provider === 'tavily'
? { useGsk: false, tavilyKey: apiKey, serperKey: '', prefer: 'tavily' }
: { useGsk: false, serperKey: apiKey, tavilyKey: '' }
const r = await webSearch('GenOffice', 1, options)
if (r.method === provider) return { ok: true }
return {
ok: false,
error:
r.method === 'error'
? (r.error ?? 'search failed')
: `${provider} did not answer (key rejected or quota exhausted); fell back to ${r.method}`,
}
}
+86
View File
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'
import { webSearch, imageSearch } from '../src/index'
import { searchOptionsFromSettings, testSearchProvider } from '../src/search-tools'
import { defaultAiSettings } from '@genoffice/ai-provider'
// These cases only test the Serper/DuckDuckGo paths; a local gsk login would take priority, so disable it explicitly
beforeAll(() => {
@@ -181,3 +183,87 @@ describe('imageSearch (Serper)', () => {
})
})
})
describe('webSearch (SearchOptions)', () => {
it('uses a caller-supplied Serper key instead of the env var', async () => {
const seen: string[] = []
mockFetch((url, init) => {
seen.push(String((init?.headers as Record<string, string>)['X-API-KEY']))
return { ok: true, json: { organic: [{ title: 'A', link: 'https://a.com', snippet: 's' }] } }
})
const r = await webSearch('q', 3, { useGsk: false, serperKey: 'user-key' })
expect(r.method).toBe('serper')
expect(seen).toEqual(['user-key'])
})
it('tries Tavily first when preferred and never touches Serper on success', async () => {
const urls: string[] = []
mockFetch((url) => {
urls.push(url)
return { ok: true, json: { results: [{ title: 'T', url: 'https://t.com', content: 'c' }] } }
})
const r = await webSearch('q', 3, {
useGsk: false,
tavilyKey: 'tv',
serperKey: 'sp',
prefer: 'tavily',
})
expect(r.method).toBe('tavily')
expect(urls).toEqual(['https://api.tavily.com/search'])
})
})
describe('search-tools', () => {
it('maps the settings block onto SearchOptions', () => {
const base = defaultAiSettings()
expect(searchOptionsFromSettings(base)).toEqual({ useGsk: true })
expect(searchOptionsFromSettings({ ...base, gskToolsEnabled: false })).toEqual({
useGsk: false,
})
const serper = {
...base,
search: {
provider: 'serper' as const,
providers: { serper: { apiKey: 'k' }, tavily: { apiKey: '' } },
},
}
expect(searchOptionsFromSettings(serper)).toEqual({ useGsk: false, serperKey: 'k' })
const tavily = {
...base,
search: {
provider: 'tavily' as const,
providers: { serper: { apiKey: '' }, tavily: { apiKey: 't' } },
},
}
expect(searchOptionsFromSettings(tavily)).toEqual({
useGsk: false,
tavilyKey: 't',
prefer: 'tavily',
})
// no key → genspark chain
const empty = {
...base,
search: {
provider: 'serper' as const,
providers: { serper: { apiKey: '' }, tavily: { apiKey: '' } },
},
}
expect(searchOptionsFromSettings(empty)).toEqual({ useGsk: true })
})
it('reports a rejected key as a failure instead of the silent free fallback', async () => {
mockFetch((url) => {
if (url.includes('serper')) return { ok: false }
return { ok: true, text: '<a class="result__a" href="/l/?uddg=https%3A%2F%2Fx.com">X</a>' }
})
const bad = await testSearchProvider('serper', 'wrong')
expect(bad.ok).toBe(false)
expect(bad.error).toMatch(/serper/)
mockFetch(() => ({
ok: true,
json: { organic: [{ title: 'A', link: 'https://a.com', snippet: 's' }] },
}))
expect(await testSearchProvider('serper', 'right')).toEqual({ ok: true })
expect(await testSearchProvider('tavily', '')).toEqual({ ok: false, error: 'API key is empty' })
})
})
+1 -1
View File
@@ -26,6 +26,6 @@
"@types/node": "^24.10.1",
"tsx": "^4.21.0",
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
}
}
+1 -1
View File
@@ -16,7 +16,7 @@
},
"devDependencies": {
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
},
"dependencies": {
"parse5": "^8.0.1"
+18 -1
View File
@@ -43,7 +43,7 @@ const EN: Labels = {
}
// Shared table, same rationale as context-menu.ts: one copy instead of
// 15 keys × 19 languages per app dictionary.
// 15 keys × 20 languages per app dictionary.
const LABELS: Record<string, Labels> = {
zh: {
window: '窗口',
@@ -267,6 +267,23 @@ const LABELS: Record<string, Labels> = {
zoomOut: 'Pomniejsz',
fullscreen: 'Pełny ekran',
},
cs: {
window: 'Okno',
minimize: 'Minimalizovat',
closeWindow: 'Zavřít okno',
edit: 'Úpravy',
undo: 'Zpět',
redo: 'Znovu',
delete: 'Odstranit',
view: 'Zobrazení',
reload: 'Znovu načíst',
forceReload: 'Vynutit znovunačtení',
toggleDevTools: 'Nástroje pro vývojáře',
actualSize: 'Skutečná velikost',
zoomIn: 'Přiblížit',
zoomOut: 'Oddálit',
fullscreen: 'Celá obrazovka',
},
nl: {
window: 'Venster',
minimize: 'Minimaliseren',
+2 -1
View File
@@ -13,7 +13,7 @@ export interface ContextMenuLabels {
const EN: ContextMenuLabels = { cut: 'Cut', copy: 'Copy', paste: 'Paste', selectAll: 'Select All' }
// One shared table instead of 4 keys × 19 languages duplicated into every
// One shared table instead of 4 keys × 20 languages duplicated into every
// app's main-process dictionary; strings match the docs Edit menu.
const LABELS: Record<string, ContextMenuLabels> = {
zh: { cut: '剪切', copy: '复制', paste: '粘贴', selectAll: '全选' },
@@ -30,6 +30,7 @@ const LABELS: Record<string, ContextMenuLabels> = {
pt: { cut: 'Recortar', copy: 'Copiar', paste: 'Colar', selectAll: 'Selecionar Tudo' },
it: { cut: 'Taglia', copy: 'Copia', paste: 'Incolla', selectAll: 'Seleziona tutto' },
pl: { cut: 'Wytnij', copy: 'Kopiuj', paste: 'Wklej', selectAll: 'Zaznacz wszystko' },
cs: { cut: 'Vyjmout', copy: 'Kopírovat', paste: 'Vložit', selectAll: 'Vybrat vše' },
nl: { cut: 'Knippen', copy: 'Kopiëren', paste: 'Plakken', selectAll: 'Alles selecteren' },
ms: { cut: 'Potong', copy: 'Salin', paste: 'Tampal', selectAll: 'Pilih Semua' },
he: { cut: 'גזור', copy: 'העתק', paste: 'הדבק', selectAll: 'בחר הכול' },
@@ -58,6 +58,20 @@ export async function showOpenDialogWithMemory(
return result
}
/**
* Save As suggestion for a document that was opened from `sourcePath`: the
* same folder with the suggested name (Word parity — Save As starts where the
* document lives, not in the last-used or default folder). Falls back to the
* bare name, which `withRememberedDirectory` then anchors, when the document
* has never been on disk.
*/
export function saveAsSuggestion(
sourcePath: string | null | undefined,
defaultName: string,
): string {
return sourcePath ? join(dirname(sourcePath), defaultName) : defaultName
}
export async function showSaveDialogWithMemory(
dialog: Dialog,
parent: BrowserWindow | null | undefined,
+1 -1
View File
@@ -16,7 +16,7 @@ export const DROP_OPEN_CHANNEL = 'app:open-dropped-files'
/** Extensions routed by apps/shell routeDocumentPath — keep in sync there and
* with OPEN_DIALOG_EXTENSIONS / OPEN_LOCAL_EXTENSIONS on the home screen. */
export const OPENABLE_DOC_RE = /\.(docx|xlsx|xlsm|xls|csv|pptx|pdf|md|markdown)$/i
export const OPENABLE_DOC_RE = /\.(docx|xlsx|xlsm|xls|csv|pptx|pdf|md|markdown|html|htm)$/i
/** Recognized-but-unsupported formats: kept in the sent payload so the shell
* can show its "not supported" dialog instead of dropping them silently.
@@ -0,0 +1,85 @@
/// Local store for AI-generated images that arrive as bytes (BYOK image
/// providers answer with base64, unlike the Genspark CDN URLs the insert
/// pipelines were built around). The bytes are written to a fixed temp
/// directory and handed back as a file:// URL, which is the only file:// shape
/// fetchRemoteImage accepts — anything outside this directory stays refused.
import { randomUUID } from 'node:crypto'
import { mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join, resolve, sep } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
export const GENERATED_IMAGE_DIR = join(tmpdir(), 'genoffice-ai-images')
const MIME_BY_EXT: Record<string, string> = {
png: 'image/png',
jpg: 'image/jpeg',
gif: 'image/gif',
webp: 'image/webp',
}
const EXT_BY_MIME: Record<string, string> = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
'image/gif': 'gif',
'image/webp': 'webp',
}
const FILE_NAME_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.(png|jpg|gif|webp)$/
const MAX_AGE_MS = 24 * 60 * 60 * 1000
/** Best-effort sweep of yesterday's images; the directory is a cache, not a document store */
function pruneOld(now = Date.now()): void {
let names: string[]
try {
names = readdirSync(GENERATED_IMAGE_DIR)
} catch {
return
}
for (const name of names) {
if (!FILE_NAME_RE.test(name)) continue
const path = join(GENERATED_IMAGE_DIR, name)
try {
if (now - statSync(path).mtimeMs > MAX_AGE_MS) unlinkSync(path)
} catch {
/* another process may have removed it */
}
}
}
export function storeGeneratedImage(bytes: Uint8Array, mime: string): string {
const ext = EXT_BY_MIME[mime.toLowerCase()] ?? 'png'
mkdirSync(GENERATED_IMAGE_DIR, { recursive: true })
pruneOld()
const path = join(GENERATED_IMAGE_DIR, `${randomUUID()}.${ext}`)
writeFileSync(path, bytes)
return pathToFileURL(path).toString()
}
/**
* Reads a file:// URL back only when it names an image this store wrote:
* inside GENERATED_IMAGE_DIR, uuid-named, image extension. Returns null for
* every other URL so a prompt-injected file:///etc/passwd never gets read.
*/
export function readGeneratedImage(rawUrl: string): { bytes: Buffer; mime: string } | null {
let path: string
try {
const url = new URL(rawUrl)
if (url.protocol !== 'file:') return null
path = resolve(fileURLToPath(url))
} catch {
return null
}
const dir = resolve(GENERATED_IMAGE_DIR)
if (!path.startsWith(dir + sep)) return null
const name = basename(path)
if (!FILE_NAME_RE.test(name) || path !== join(dir, name)) return null
try {
const bytes = readFileSync(path)
return { bytes, mime: MIME_BY_EXT[name.slice(name.lastIndexOf('.') + 1)] ?? 'image/png' }
} catch {
return null
}
}
+6 -1
View File
@@ -14,7 +14,11 @@ export {
type AppMenuLabels,
} from './app-menu'
export { GITHUB_REPO_URL } from './github-menu'
export { showOpenDialogWithMemory, showSaveDialogWithMemory } from './dialog-memory'
export {
saveAsSuggestion,
showOpenDialogWithMemory,
showSaveDialogWithMemory,
} from './dialog-memory'
export {
DEFAULT_SAVE_DIR_KEY,
configuredDefaultSaveDir,
@@ -40,6 +44,7 @@ export {
type FetchWithSsrfGuardOptions,
} from './safe-remote-url'
export { fetchRemoteImage, remoteImageHeaders } from './remote-image'
export { GENERATED_IMAGE_DIR, readGeneratedImage, storeGeneratedImage } from './generated-images'
export {
buildPrintableHtml,
printHtmlToPdf,
@@ -3,6 +3,7 @@
/// requests; browser-like headers plus a Referer on genspark hosts and a couple
/// of retries turn most of those transient failures into successful inserts.
import { readGeneratedImage } from './generated-images'
import { fetchWithSsrfGuard, type FetchWithSsrfGuardOptions } from './safe-remote-url'
const RETRY_DELAYS_MS: readonly number[] = [500, 1500]
@@ -39,6 +40,15 @@ export async function fetchRemoteImage(
} = {},
): Promise<Response | null> {
const { retryDelaysMs = RETRY_DELAYS_MS, ...guardOptions } = options
// BYOK-generated images live in the local store; only its own files resolve
if (rawUrl.startsWith('file:')) {
const local = readGeneratedImage(rawUrl)
if (!local) return null
return new Response(new Uint8Array(local.bytes), {
status: 200,
headers: { 'content-type': local.mime, 'content-length': String(local.bytes.byteLength) },
})
}
const headers = remoteImageHeaders(rawUrl)
for (let attempt = 0; ; attempt++) {
let resp: Response | null = null
@@ -33,6 +33,7 @@ const LANGS = [
'pt',
'it',
'pl',
'cs',
'nl',
'ms',
'he',
@@ -50,7 +51,7 @@ beforeEach(() => {
})
describe('appMenuLabels', () => {
it('covers all 19 languages with every key non-empty', () => {
it('covers all 20 languages with every key non-empty', () => {
const keys = Object.keys(en) as (keyof AppMenuLabels)[]
for (const lang of LANGS) {
const labels = appMenuLabels(lang)
@@ -2,7 +2,7 @@ import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { showOpenDialogWithMemory, showSaveDialogWithMemory } from '../src/index'
import { saveAsSuggestion, showOpenDialogWithMemory, showSaveDialogWithMemory } from '../src/index'
import type { Dialog } from 'electron'
@@ -115,3 +115,33 @@ describe('showSaveDialogWithMemory', () => {
expect(dialog.showSaveDialog).toHaveBeenCalledWith({ defaultPath: '/docs/tab.pdf' })
})
})
describe('saveAsSuggestion', () => {
it('suggests the source document folder with the new name (Word parity)', () => {
expect(saveAsSuggestion(join('/work', 'report.docx'), 'report.docx')).toBe(
join('/work', 'report.docx'),
)
expect(saveAsSuggestion(join('/work', 'report.docx'), 'copy.docx')).toBe(
join('/work', 'copy.docx'),
)
})
it('falls back to the bare name for a document that was never on disk', () => {
expect(saveAsSuggestion(null, 'Untitled.docx')).toBe('Untitled.docx')
expect(saveAsSuggestion(undefined, 'Untitled.docx')).toBe('Untitled.docx')
expect(saveAsSuggestion('', 'Untitled.pptx')).toBe('Untitled.pptx')
})
it('beats the remembered directory when threaded through the save dialog', async () => {
const dialog = fakeDialog({ showSaveDialog: pickedSave(join('/elsewhere', 'x.docx')) })
// a pick in /elsewhere seeds the remembered directory…
await showSaveDialogWithMemory(dialog, undefined, { defaultPath: 'x.docx' })
// …but Save As of a document living in /work still opens in /work
await showSaveDialogWithMemory(dialog, undefined, {
defaultPath: saveAsSuggestion(join('/work', 'report.docx'), 'report.docx'),
})
expect(dialog.showSaveDialog).toHaveBeenLastCalledWith({
defaultPath: join('/work', 'report.docx'),
})
})
})
@@ -0,0 +1,41 @@
import { writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { describe, expect, it } from 'vitest'
import {
GENERATED_IMAGE_DIR,
readGeneratedImage,
storeGeneratedImage,
} from '../src/generated-images'
import { fetchRemoteImage } from '../src/remote-image'
const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3])
describe('generated image store', () => {
it('round-trips bytes through a file URL inside the store directory', async () => {
const url = storeGeneratedImage(PNG, 'image/png')
expect(url.startsWith('file://')).toBe(true)
expect(url).toMatch(/\.png$/)
const back = readGeneratedImage(url)
expect(back?.mime).toBe('image/png')
expect(Array.from(back!.bytes)).toEqual(Array.from(PNG))
const resp = await fetchRemoteImage(url)
expect(resp?.ok).toBe(true)
expect(resp?.headers.get('content-type')).toBe('image/png')
expect(new Uint8Array(await resp!.arrayBuffer())).toEqual(PNG)
})
it('refuses file URLs outside the store, foreign names inside it, and traversal', async () => {
expect(readGeneratedImage('file:///etc/passwd')).toBeNull()
const stray = join(GENERATED_IMAGE_DIR, 'notes.txt')
writeFileSync(stray, 'x')
expect(readGeneratedImage(pathToFileURL(stray).toString())).toBeNull()
expect(
readGeneratedImage(
pathToFileURL(join(GENERATED_IMAGE_DIR, '..', 'genoffice-ai-images', 'x.png')).toString(),
),
).toBeNull()
expect(readGeneratedImage('https://example.com/a.png')).toBeNull()
expect(await fetchRemoteImage('file:///etc/hosts')).toBeNull()
})
})
+1 -1
View File
@@ -25,6 +25,6 @@
"devDependencies": {
"@types/node": "^24.10.1",
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
}
}
+1 -1
View File
@@ -15,6 +15,6 @@
},
"devDependencies": {
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
}
}
+719
View File
@@ -0,0 +1,719 @@
# HTML → DOCX Conversion Logic and Architecture
This document describes the conversion logic implemented in `packages/html2docx`. It is not a strict attribute-by-attribute translator from the HTML spec to the OOXML spec, but a hybrid converter based on "real browser rendering + document intent recognition + native Word reconstruction".
## 1. Goals and basic principles
The goals of the converter are:
1. Run on Linux or macOS without depending on Microsoft Word.
2. Keep body text, headings, lists, tables, and forms editable as much as possible.
3. Keep layout and visual effects as close as possible to the HTML rendered in Chromium.
4. Use local screenshots for effects that Word is not good at expressing, rather than rasterizing the whole page.
5. Keep the converter independent and not modify existing business code.
The most important design principle currently is "structure first, visual fallback second":
- Content that can be reliably mapped to Word is generated as native OOXML.
- Gradients, complex SVGs, badges, and pure decoration that cannot be reliably mapped are rendered as local images.
- Page backgrounds and absolute-positioned decorations are generated as floating images that do not enter the body text flow.
- No PDF intermediate format is used, to avoid losing semantics, text structure, and editability.
## 2. Overall pipeline
```text
HTML file or URL
│
▼
Headless Chromium loads the page
│
├─ Wait for network resources and web fonts
├─ Detect the HTML's design width
└─ Re-render at the design width
│
▼
Read the DOM, computed style, and real geometric dimensions
│
▼
Recognize document structure, generate an intermediate representation (IR)
│
├─ Editable structures: paragraphs, headings, lists, tables, cards, forms
└─ Image fallback: gradients, SVG, badges, page decoration, backgrounds
│
▼
Collect DOM elements that need screenshots according to the IR
│
▼
Use the docx library to generate native OOXML
│
▼
DOCX
│
▼
Microsoft Word exports PDF/PNG, compared against HTML screenshots for regression
```
Code responsibilities:
- `tools/cli.ts`: command-line entry point (Playwright driver over a local Chrome).
- `src/convert.ts`: orchestrates browser loading, IR extraction, screenshot collection, and the generation flow.
- `src/extract.ts`: a lightweight assembly entry point for the browser extraction functions.
- `src/browser/core/`: shared-scope extraction modules for style, text, lists, layout, classifiers, etc.
- `src/browser/`: independent browser modules for tables, pages, form media, and visual fallback.
- `src/generate.ts`: a lightweight orchestration entry point for the DOCX generation flow.
- `src/generate/`: modules for page setup, rendering context, Word styles, streaming nodes, and table rendering.
Because the browser extraction layer needs to be serialized by `page.evaluate` into a single self-contained function, `src/browser/core/` uses function-body fragments split by responsibility, which `extract.ts` assembles on the Node side in a fixed order. Peripheral, independent capabilities are injected via `page.addScriptTag`, rather than stuffing every implementation back into a single file.
## 3. Browser rendering stage
### 3.1 Chrome selection
`convert.ts` looks for a browser in the following order:
1. The `CHROME_PATH` environment variable
2. Google Chrome on macOS
3. Common Google Chrome / Chromium paths on Linux
The package talks to the browser through the `BrowserDriver` interface (`src/driver.ts`); the CLI and tests use the Playwright implementation over a locally installed Chrome, the app uses Electron's own webContents. Nothing downloads Chromium. When deploying to Linux, Chromium must be installed in the image, or `CHROME_PATH` must be set.
### 3.2 Initial A4 viewport
The initial viewport is:
```text
794 × 1123 CSS px
```
This is the approximate size of A4 at 96 DPI. `deviceScaleFactor` is set to 2 to improve the clarity of local screenshots.
### 3.3 Design-width detection
Many AI-generated documents use:
```css
body {
max-width: 880px;
}
```
If extraction is done directly in a 794px-wide viewport, extra line wrapping occurs, and table row heights are also enlarged. The current logic reads the computed `max-width` of `body`:
- If the design width is greater than the initial A4 viewport;
- and does not exceed 1600px;
- then the page is reloaded using a design viewport no smaller than 1024px.
This way, the line wrapping and line height extracted reflect the author's designed size, rather than the result of being squeezed by an overly narrow viewport beforehand.
If a flow document is roughly 0.96-1.22 page-heights tall in the browser (converted to an A4 ratio based on the design canvas width), it is treated as having single-page design intent, and `pageFitSqueeze` applies a light, whole-document compression to geometry and fonts, to avoid Word's slightly looser layout pushing the last block (an invoice stamp, a footer note) onto a second page. Table-heavy documents do not get the benefit of "Word layout being denser," so above 1.05 pages, no compression discount is applied. When generating OOXML, native font size, spacing, padding, line height, and borders are then scaled by `target page width / design viewport width`; local screenshots are scaled proportionally to the target content-area width.
### 3.4 Waiting for resources
While the page loads:
- it prefers to wait for `networkidle0`;
- after a timeout it proceeds with the conversion anyway, to avoid external resources blocking the whole task;
- it waits for `document.fonts.ready`;
- then waits for a brief settling period to let layout and fonts finish reflowing.
Inaccessible images are identified as broken during extraction and discarded.
## 4. Extraction layer: DOM and computed style
The `extractIR` function assembled by `extract.ts` is injected into the browser page and executed there, so it can directly access:
- DOM nodes;
- `getComputedStyle`;
- `getBoundingClientRect`;
- `::before` / `::after` pseudo-elements;
- image loading state;
- the real coordinates of text nodes.
The extracted content falls into four categories.
### 4.1 Text runs
Text is not handled crudely by DOM tag alone; instead it is converted into styled runs. Currently supported:
- font family and size;
- bold, italic, underline, strikethrough;
- font color;
- inline background color;
- letter spacing;
- superscript, subscript;
- `text-transform: uppercase`;
- hyperlinks;
- line breaks (including author line breaks split by line inside `white-space: pre-wrap/pre-line` text);
- small inline images;
- column positions and tab stops produced by wide spaces.
Consecutive text nodes and inline elements are merged into a single paragraph, so that not every `<span>` produces a separate paragraph.
### 4.2 Paragraph styling
Paragraph-level styling includes:
- left, center, right, and justified alignment;
- spacing above/below;
- line-height ratio;
- left indent;
- background color;
- left and bottom borders;
- the exact height of single-line color bars;
- CJK and Latin text markers.
The converter distinguishes between Word font leading for English and CJK:
- Latin line spacing uses a smaller compensation;
- CJK line spacing uses a larger compensation;
- single-line background heading bars use an exact line height, to prevent Word from stretching the color bar taller.
### 4.3 Geometry information
Structural nodes store the browser's measured dimensions, for example:
- table column widths;
- table row heights;
- flex/grid child widths;
- card padding;
- block margins;
- image width/height;
- absolute-positioned element coordinates;
- page content-area width/height;
- body's four-sided margins.
This data is used to suppress Word's AutoFit and default paragraph leading.
### 4.4 Page setup
After extraction, a `docsettings` node is generated, which stores body's actual four-sided margins:
```js
{
type: 'docsettings',
marginsPx: {
top,
bottom,
left,
right,
},
}
```
The DOCX no longer uniformly uses a fixed 2cm top/bottom margin; instead it tries to use the HTML's actual page padding. This resolves the issue of "the content size is correct, but the last form box is pushed to a second page by the fixed page margin."
## 5. Intent-recognition layer: DOM → IR
The IR is an intermediate representation between browser structure and Word structure. It proactively discards unimportant HTML implementation details and retains only the document intent needed to generate Word output.
Current main node types:
| IR type | Meaning | Word output |
| ------------- | ------------------------------------------- | ----------------------------------------------- |
| `docsettings` | Page margins | Section page margin |
| `heading` | Heading | Heading Paragraph |
| `para` | Ordinary paragraph | Paragraph + TextRun |
| `list` | Ordered/unordered list | Native Word numbering |
| `table` | HTML/CSS Grid table | Fixed-layout Word Table |
| `card` | Card with background, border, and padding | Single-cell Table |
| `kpirow` | flex/grid horizontal layout | Single-row, multi-column table |
| `formfield` | Input box, textarea, select box | Underlined paragraph or single-cell table |
| `code` | Multi-line monospace text | Monospace-shaded paragraph |
| `image` | Ordinary image or local screenshot | Inline ImageRun |
| `floatimg` | Page decoration, signature, footer | Floating ImageRun |
| `pagebg` | Page background | Floating image/background color behind the page |
| `pagebreak` | Forced page break | PageBreak |
| `hr` | Horizontal rule or pseudo-element color bar | Paragraph bottom border |
| `spacer` | Large vertical blank space | Empty paragraph with exact height |
### 5.1 Classification order
The classification order matters a great deal. `processElement` currently handles things roughly in the following priority:
1. Skip invisible elements and irrelevant tags such as `script/style`.
2. Recognize large signatures at the bottom of the page.
3. Recognize absolute-positioned or fixed decoration.
4. Extract page breaks and large top-of-page blank space.
5. Handle native semantic tags:
- headings;
- HTML tables;
- lists;
- code;
- HR;
- images;
- forms.
6. Handle SVG, canvas, checkbox/radio.
7. Recognize badges, pills, decorative leaves, and gradient containers.
8. Recognize CSS Grid tables.
9. Recognize page-level multi-column layout.
10. Recognize multi-row, structurally uniform grid/flex layouts.
11. Recognize single-row flex/grid layouts.
12. Recognize cards.
13. Fall back to an ordinary paragraph and recurse into child nodes.
High-fidelity rules must come before generic block-level recursion; otherwise a complex component would be split into ordinary paragraphs prematurely.
## 6. Main structure-recognition logic
### 6.1 HTML tables
A native `<table>` has the following extracted:
- measured width of each column;
- measured height of each row;
- colspan;
- cell padding;
- borders on all four sides;
- background color;
- horizontal and vertical alignment;
- header rows;
- paragraphs or nested structures inside cells.
When generating:
- a fixed table layout is used;
- table grid column widths are written;
- cell widths are written at the same time;
- adjacent grid widths are merged according to colspan;
- row heights use the browser's measured values;
- `HeightRule.EXACT` is used when strict fidelity is required.
Setting both the table grid and cell widths at the same time is meant to stop Word's AutoFit from redistributing column widths based on text length.
### 6.2 CSS Grid tables
If a container contains multiple rows of a structurally identical Grid:
- the number of visible child items is the same in each row;
- the number of columns is within a reasonable range;
- the widths of each row are close to each other;
- there are enough rows or a clear outer border;
then it is converted into a `table`, rather than a set of independent text blocks.
This is used for questionnaires, class schedules, survey forms, and other templates that don't use `<table>`.
### 6.3 Flex/Grid horizontal rows
Side-by-side KPIs, personal-info bars, tag rows, page headers, etc. are converted into `kpirow`:
- column widths are computed from the real bounds of the child elements and the midpoints of the gaps between them;
- the left/center/right position of each child element within its corresponding column is detected;
- the parent container's row height and padding are stored;
- on the Word side, a fixed-layout, single-row, multi-column table is generated.
The default cap on child-element height is 500px (taller than that is treated as a page-level two-column layout); however, tall card rows (pricing plans) with ≥3 columns of similar width are relaxed to 950px — a Word page can still fit one such row, preserving the side-by-side structure.
If there is an absolute-positioned color block on the left side of the container:
- the color block becomes the first column on its own;
- the body content becomes the second column;
- the color block's width uses the browser's measured value;
- the body's left indent, which was originally relative to the whole container, is corrected.
This is how the header color block on the Service Evaluation page is handled.
### 6.4 Cards
Blocks with a background, border, left accent line, or noticeable padding are recognized as a `card`.
Cards are output as single-cell Word tables, preserving:
- background color;
- full border;
- left or top accent border;
- padding on all four sides;
- top/bottom margin;
- editable inner content.
A table rather than paragraph shading is used because Word's paragraph shading cannot reliably express four-sided padding and a complete card border.
**Flattening**: a light-colored top-level card (a full-page section) that is taller than half a page and allowed to break across pages cannot be expressed as a single-row table — Word nested tables cannot break across pages — so it is flattened into a sequential paragraph flow. During flattening, the card's shading is propagated to all child blocks: paragraph shading for para/heading, spacer paragraphs, list items, kpirow cells and gaps, and table cells; the spacing before/after each child block itself is marked with `ambientShading` for the surrounding section's background color, to avoid exposing the page background and creating stripes.
### 6.5 Page-level two columns
Page-level two-column layouts such as resumes are output as:
- a single row, two columns;
- a borderless Word table;
- each column placed in full inside its corresponding cell;
- table rows are allowed to break across pages;
- column background and inner padding are preserved.
The page is not sliced into a large number of small rows by Y coordinate, because that approach is prone to left/right column misalignment once Word paginates.
Paragraph and card spacing within columns is moderately compressed, to reduce extra pages caused by differences between the HTML and Word pagination engines.
### 6.6 Forms
Currently, real Word Content Controls are not generated; instead, visually editable forms are generated:
- input boxes with only a bottom border → a paragraph with a bottom border;
- boxed inputs, textareas, selects → a single-cell table;
- width/height, border, background, padding, and existing text are preserved;
- checkbox/radio → Unicode box or circle characters.
This approach is highly compatible but lacks the validation and field properties of real Word form controls.
### 6.7 Lists
Two sources are supported:
1. native `<ul>` / `<ol>`;
2. pseudo-lists exported by Word, e.g. Symbol-font characters such as "·", "•", "▪".
For pseudo-lists, the fake bullet is stripped from the text and converted into native Word numbering, avoiding duplicate dots.
### 6.8 Horizontal rules and pseudo-elements
`<hr>` and qualifying `::before` / `::after` bars have the following extracted:
- width proportion;
- height;
- color;
- left-aligned or centered.
On the Word side, these are rebuilt using an indented paragraph bottom border.
## 7. Image fallback strategy
### 7.1 Why not screenshot everything
A full-page screenshot achieves the highest static visual consistency, but leads to:
- text that cannot be edited;
- inability to search and copy;
- large file size;
- inability to paginate normally;
- unsuitability as a DOCX.
For this reason, only the local areas that Word struggles to express are currently screenshotted.
### 7.2 Content that gets screenshotted
Mainly includes:
- ordinary `<img>`;
- SVG and canvas;
- gradient-background containers;
- rounded pills and complex badges;
- small decorative shapes;
- icon-font elements with no text, whose glyph lives in `::before/::after`;
- complex badge grids;
- page background images;
- absolute-positioned decoration;
- oversized bottom signatures.
Elements to be screenshotted are given a unique `data-h2d-id`. `convert.ts` walks the IR to collect these IDs, then screenshots the corresponding DOM elements via Puppeteer.
### 7.3 Page background
The page background is copied to an offscreen backdrop:
- background color, image, size, position, and repeat mode are preserved;
- body/html backgrounds are supported;
- simple `::before` background overlays are supported.
While screenshotting, the other body child elements are temporarily hidden and only the background is kept, to avoid the body content being captured twice into the background image.
When generating the DOCX, the background image is placed behind the page as a behind-document floating image.
### 7.4 Absolute-positioned decoration
Absolute-positioned or fixed elements do not enter the body flow. Elements that satisfy the size and page-range limits are:
- screenshotted locally;
- stored with coordinates relative to the body content area;
- stored with the content area's width/height;
- scaled proportionally to the content area in Word;
- positioned as a floating image in the page-margin coordinate system.
Absolute-positioned elements that don't fall within the safe range are discarded, to avoid incorrect decoration covering the body content.
**In-ancestor decoration (`inParent`)**: if a decoration falls entirely within the nearest positioned ancestor box (a leaf icon to the right of a banner, a watermark numeral in the top-left corner of a section), the classifier additionally records its coordinates and the ancestor's width/height relative to that ancestor. Note that the positioned ancestor must be found by manually walking the parent chain — SVG elements have no `offsetParent`. On the generation side, when that ancestor is rendered as a card, the decoration is anchored to the card cell (`relativeFrom: column/paragraph`) and drawn on top of the shading (an underlying image would otherwise be covered by the cell shading); when the card is flattened, it is anchored to the zero-height anchor paragraph at the start of the flattened output, and the top blank space is only compressed down to a height that can still accommodate the decoration. This kind of decoration is not subject to the "first page only" restriction; when there is no card context to fall back on and it falls beyond the page-anchored path, decoration beyond the first page is discarded by the generation side (consistent with prior behavior).
## 8. DOCX generation logic
### 8.1 Units
Under the 794px A4 viewport, the base conversion relationships are:
```text
1 CSS px ≈ 15 twips
1 CSS px ≈ 1.5 half-points
1 CSS px ≈ 9525 EMU
```
Used respectively for:
- paragraphs, margins, table width/height;
- font size;
- floating-image coordinates.
When the HTML uses a wider design viewport, the above text and box-model sizes are also multiplied by the page scale ratio. Fonts retain a small amount of width compensation, because Word's Arial is usually narrower than Inter/Roboto as rendered in the browser; without this, the original line wrapping would be lost.
### 8.2 Font mapping
Word and browsers have different available fonts, so the generator includes a font-family mapping:
- monospace → Consolas;
- common sans-serif / Inter → Arial;
- common serif → Times New Roman;
- DM Serif / Playfair / Cormorant → Georgia;
- Archivo / Bebas / Oswald → Arial Narrow;
- script/cursive → Segoe Script;
- CJK sans-serif → Microsoft YaHei;
- CJK serif → SimSun.
If a Latin-font run actually contains CJK characters, it is switched to the corresponding CJK font, to avoid arbitrary Word fallback.
### 8.3 Paragraphs
Paragraph generation handles:
- TextRun styling;
- hyperlinks;
- tab stops;
- alignment;
- indentation;
- spacing above/below;
- line spacing;
- background and border;
- native bullets.
Headings enable `keepNext` and `keepLines`, to reduce cases where a heading lands at the bottom of a page and the body text gets pushed to the next page.
### 8.4 Tables
Word tables are the core of the current layout system, used not only for HTML tables but also for:
- flex horizontal rows;
- cards;
- page two-column layouts;
- form boxes;
- KPIs;
- color-block titles.
This makes it possible to take advantage of Word's:
- fixed column widths;
- cell shading;
- cell margins;
- row height;
- vertical alignment;
- row pagination control.
### 8.5 Spacing
Ordinary paragraphs use Word paragraph spacing.
A table itself cannot reliably carry block-level margin above/below, so a spacer paragraph with an exact height is inserted before and after the table. Small spacing is not forced to write a visible character; larger spacing uses a zero-width character to prevent Word from collapsing it.
The current spacing priority is:
1. HTML computed margin;
2. HTML padding;
3. the browser's measured line height;
4. Word's minimum compatible default value.
Uniformly compressing all table padding to force a single page is no longer done, because it makes tables, cards, and body content overly cramped as a whole.
### 8.6 Pagination
The current pagination strategy:
- CSS `break-before: page` → an explicit page break;
- headings try to stay with the following paragraph;
- ordinary data-table rows are not split by default;
- page-level two-column tables are allowed to break across pages;
- KPI horizontal rows are kept whole;
- large cards are preferentially moved to the next page as a whole;
- a signature at the bottom of the page can be converted into a floating image fixed at the bottom.
Word and Chromium use different line-breaking algorithms, so pagination can only be approximated, not made mathematically identical.
## 9. Core lessons from current quality fixes
### 9.1 Color blocks becoming narrower
Cause:
- setting only the Table Grid width is not enough;
- Word's AutoFit keeps squeezing blank columns narrower.
Fix:
- use a fixed table layout;
- set both the grid column width and cell width at the same time;
- sum the actual spanned width for colspan.
### 9.2 Tables becoming overall too cramped
Cause:
- cell padding was once uniformly compressed in order to keep everything on a single page;
- table rows did not use the browser's measured height.
Fix:
- restore the computed padding;
- preserve the browser's row height;
- use an exact row height when strict fidelity is required;
- prioritize fixing the page margins instead of compressing the body content.
### 9.3 Incorrect line spacing
Cause:
- Word's built-in font leading;
- Latin and CJK have different leading;
- uniformly using the CJK compensation makes English text too cramped.
Fix:
- detect CJK per paragraph;
- use different line-height compensation for Latin and CJK;
- use an exact line height for single-line color blocks.
### 9.4 Content pushed to a second page
Cause:
- the DOCX fixedly used roughly a 2cm top/bottom page margin;
- the HTML actually might have only 32px of page padding.
Fix:
- extract the actual four-sided margins from body;
- write them into the DOCX section margin;
- preserve the content size instead of solving pagination by compressing tables.
### 9.5 A narrow viewport produces extra line wrapping
Cause:
- the template is designed at 880px;
- extracting directly in a 794px A4 viewport causes premature line wrapping.
Fix:
- detect body's `max-width`;
- re-render at the author's designed width;
- then map the structure onto an A4 Word page.
## 10. Verification process
Final quality must be judged against Microsoft Word:
1. Chrome captures a screenshot of the source HTML.
2. Run the converter to generate the DOCX.
3. Open the DOCX with Microsoft Word.
4. Word exports a PDF.
5. Convert the PDF to PNG.
6. Generate an HTML/Word side-by-side comparison image per page.
7. Check:
- number of document pages;
- page margins;
- font, font size, and line spacing;
- color block size;
- table column width and row height;
- card padding and inter-block spacing;
- image size and position;
- whether the content is still editable.
LibreOffice can quickly check whether a file is corrupted, but it cannot serve as the visual regression baseline, because its pagination, font, table, and background rules differ from Word's.
Regression baselines (source HTML, converted `.docx`, the PDF Word exports from it, and a side-by-side comparison image per template) are kept outside the repository.
## 11. Known limitations
### 11.1 Word and the browser are not the same layout engine
The following cannot be guaranteed to match exactly:
- automatic line wrapping;
- font fallback;
- font leading;
- pagination;
- the free-form layout of flex/grid;
- margin collapsing.
### 11.2 CSS support is not a complete spec implementation
This is currently not a general-purpose CSS-to-OOXML engine; it focuses on the high-frequency structures found in document templates. Complex selectors themselves are handled by the browser, but the mapping from computed style to Word properties remains a limited set.
### 11.3 Screenshotted areas are not editable
Fallback areas such as gradients, SVG, badges, page decoration, and backgrounds become images.
Native Word tables do not support the CSS `border-radius`. Currently, wide rounded title bars use a local screenshot while keeping the body text editable; the light-colored outer border of a rounded card is preferentially omitted, rather than outputting an incorrect right-angle border. If the rounded outer border must be fully preserved, a decorative background image or a screenshot of the whole card is needed as a further step.
### 11.4 Real Word forms are not yet implemented
Currently, forms are editable text and table appearances, not Content Controls, Legacy Form Fields, or ActiveX controls.
### 11.5 Multi-page backgrounds
Page background images are currently handled with the page-floating-image approach; a complete section/background model for complex, different backgrounds across multiple pages has not yet been formed.
### 11.6 Headers and footers
Currently, absolute-positioned headers/footers are mainly handled as page floating decoration, and have not been converted into native Word Header/Footer Parts.
### 11.7 Nesting depth
When cards and tables are nested too deeply, they are downgraded to ordinary paragraphs, to avoid generating deeply nested tables that Word doesn't support or that are extremely unstable.
## 12. Future direction
Suggested order for continued improvement:
1. Establish automated Word regression testing over a fixed set of templates.
2. Output the IR as JSON, to make it easier to pinpoint whether an issue is in extraction or generation.
3. Add element-level diagnostic logging: DOM selector → IR node → OOXML node.
4. Support native Word Header/Footer.
5. Support real Content Control forms.
6. Add multi-section, landscape pages, and custom paper sizes.
7. Establish font-availability detection and a font-substitution configuration.
8. Establish separate visual-diff thresholds for images, cards, and tables.
9. Consolidate template special cases into configurable rules, to reduce hardcoding.
10. Add timeouts, a browser pool, and resource-size and concurrency limits when running on a server.
## 13. Usage
Command line:
```bash
npx tsx packages/html2docx/tools/cli.ts input.html output.docx --verbose
```
Linux:
```bash
CHROME_PATH=/usr/bin/chromium npx tsx packages/html2docx/tools/cli.ts input.html output.docx
```
As a module: see [README.md](./README.md) — `convertHtmlToDocx({ url }, driver, options)` returns the DOCX bytes together with the IR and stats; the IR can be saved for debugging, rule analysis, or as a test snapshot.
## 14. Empirically observed behavior of the Word (Mac) pagination engine (measured in experiments, 2026-07)
The following conclusions were all obtained by manually constructing variant docx files and rendering/comparing them with the same build of Word; they are the basis for several defensive design choices in the converter — read this section before touching related code.
1. **A forced ~26px inset at the top of the page**: even with `pgMar top=0`, the first line still starts roughly 26px (~405 twips) below the top of the page, and this is unrelated to image height, paragraph-mark font size, or docGrid. Full-page screenshot slicing must therefore reserve a margin for this: the slice budget is 96% of the page height (pages.js), and the rendering fallback is content height − 45px (renderer.js pageScale). Otherwise the bottom ~25px of a slice gets silently cut off (this once caused the last line of a resume's CONTACT card to be lost).
2. **`keepNext` semantics only extend to the next paragraph**: when a heading has `keepNext` plus an ordinary spacer paragraph, Word only guarantees that "heading + spacer" stay on the same page — the body text still gets paginated away → an orphaned heading. Every spacer (and at most one subheading paragraph) between the heading and the body must carry `keepNext`.
3. **A keep-chain fallback drags along the table before it**: when the large block at the tail of a keepNext chain (a `cantSplit` card row) doesn't fit, Word doesn't just move the chain to the next page — it also drags along the table before the chain, even across paragraphs with kn=0 in between (neither empty paragraphs nor ZWSP paragraphs stop this). Therefore the trailing spacer must never carry `keepNext`, otherwise the entire document links into one chain, and Word paginates at an absurd point (an entire page with nothing but a heading).
4. **Body text ending with a table produces a ghost blank page**: when the last block in the body is a `tbl`, Word automatically appends a paragraph mark with the default line height; if the table happens to exactly fill the last page, that mark overflows into an entire extra page with nothing but the background. The generation layer must terminate with a 1px EXACT empty paragraph (page-settings.js renderSection); the same applies to table cells (the docx library likewise appends a default paragraph to a cell that ends with a table).
5. **Screenshots of transparent wrapper elements get embedded at the full box height**: a stretched photo container in a column layout (box height 1591px, with only the top ~300px actually visible) embedded as an inline image occupies space at the full box height, immediately pushing out an extra page. `markForScreenshot` crops elements that have "no own drawing, box height ≥600, and an invisible tail ≥150px" down to the bottom of the visible content.
## 15. Findings from the fourth round of fixes (2026-07-20, 30 samples)
1. **`w:lang w:val="zh-CN"` makes Word break Latin words character-by-character using CJK rules** (e.g. "Report" → "Rep/ort"). Controlled experiments show that the `w:wordWrap` element runs in the opposite direction and doesn't rescue this (val=0 = allow character-level breaking; under CJK lang, val=1 is also ineffective); the only effective fix is to keep docDefaults' `w:lang w:val` fixed at en-US, marking only `eastAsia` as CJK (page-settings.js). Note that the docx library silently drops the wordWrap option for ordinary paragraphs.
2. **Nested fixed-layout tables must have an explicit `tcW`**: Word for Mac collapses a nested fixed-layout table without `tcW` down to the grid's placeholder width (a ~100dxa sliver). `renderCard` now always emits the trio FIXED + columnWidths + cell width; an autofit nested card can get blown out by an unbreakable inner run (an nbsp used to fill a blank line) and pushed out past the right edge of its container, getting clipped.
3. **The centering offset from a wide-viewport reload is not a page margin**: after reloading at 1024px, body's auto-margin centers it; `docsettings` uses `canvasWidth = min(innerWidth, max(pageSizePx, bodyWidth))` as the measurement baseline and strips out the `centerOffset` — otherwise the whole document ends up narrowed by ~20% plus a false ~3cm margin.
4. **`oneLineWidthPx` must re-measure using the font after Word's mapping**: `convert.ts` injects `__h2dWordFontLineWidth` (with FONT_RULES serialized into the page); Cormorant → Georgia is 15-40% wider, and measuring directly with the browser's narrower font causes heading letters to drop to the next line (e.g. "EDUCATIO/N").
5. **`kpirow` widening order**: gap track → spare room in generator.avail (widen the table) → compress sibling columns. Widening the table directly when there's already spare room in the browser's layout is faithful to the source.
6. **Inline merging for deep flatten (`inlineCellPara`)**: a single para / a small checkbox formfield (box mode ≤20px) / a nested kpirow are recursively merged into one line of runs; the checkbox run must carry `text: ''` (`tabStopsFor` assumes `text` exists). This restored horizontal layouts such as "COMBUSTIBLE: ☐ GASOLINA ☐ DIÉSEL ☐ GAS".
7. **List bullet determination looks at the `li`, not the `ul`**: frameworks such as pico.css set `list-style: none` on `ul` but set the marker individually on `li`; `extractList` decides plain based on the `li`'s computed `listStyleType` (tables-lists.js).
8. **Circular badges** (`circularBadge`: border-radius ≥ height/2, width and height similar, no whitespace-only text): `display:flex` can also be screenshotted inline (`inlineBgHex` rejects non-inline, needing `bgHex` as a fallback), and the displayed size is capped at the parent font size × 1.35 — otherwise a 42px badge embedded at its original height raises the line box, pushing an ~800px `cantSplit` card (with Word's ×1.2 factor) over the page limit, producing an isolated hint-box page plus a fully blank page. After capping, 12 pages return to normal. Rectangular text chips still go through the text-run path so they remain searchable.
9. **`isBoxRow` column-count limit only counts child elements wider than 40px**: a "step ▶ step" flow diagram with 7 child elements (4 steps + 3 arrows) is no longer stacked vertically; geometric symbols such as ▶◀◆ (U+25A0-25FF) now go through SYMBOL_RE and render as text glyphs (Arial Unicode MS + FE0E), instead of turning into blue emoji; `align-self: center` child elements are mapped to cell-level `vAlign`.
10. **The hallucination rate of vision-LLM scoring is measured to be extremely high**: in this round, more than half of the "below-100" findings were disproved programmatically (line-merging in a `pdftotext` count, a `document.xml` count, an actual render). Review discipline: for any "missing content" finding, first run a `pdftotext | tr -d '\n' | grep -o` count and compare it against the HTML source before deciding whether to fix it.
+46
View File
@@ -0,0 +1,46 @@
# @genoffice/html2docx
HTML → DOCX conversion for the HTML app's "Export as Word": the page is rendered
in a real browser, reduced to a document intent tree (headings, paragraphs,
lists, tables, cards, KPI rows, form fields, page backgrounds…) and written out
as native OOXML with the `docx` library. Only visuals that have no Word
counterpart (charts, icons, decorated boxes) are screenshotted.
See [ARCHITECTURE.md](./ARCHITECTURE.md) for the pipeline, IR and OOXML
mapping.
## Usage
```ts
import { convertHtmlToDocx } from '@genoffice/html2docx'
const { docx, stats } = await convertHtmlToDocx({ url }, driver, {
onProgress: ({ stage, pct }) => …, // load | extract | screenshot | generate
signal, // AbortSignal
})
```
`driver` is a `BrowserDriver` (`src/driver.ts`): the host owns the browser and
supplies a page-like adapter. `src/drivers/playwright.ts` implements it over
playwright-core and a locally installed Chrome for tests and the CLI; the app
supplies an Electron `webContents` implementation. The converter never closes
the driver.
CLI (single file, needs Chrome; `CHROME_PATH` overrides the lookup):
```bash
npx tsx packages/html2docx/tools/cli.ts input.html output.docx --verbose
```
## Layout
- `src/browser/` — in-page code, plain JS kept verbatim: `core/*.js` are slices
of one `extractIR()` function body (assembled in `src/extract.ts` from `?raw`
imports), the other files install `__html2docx*` helper globals.
- `src/convert.ts` — orchestration: viewport/authored-width detection, lazy
image warm-up, extractor injection, element screenshots, generation.
- `src/generate/` — IR → OOXML (`docx` library).
- `tests/features.test.ts` — 66 end-to-end cases, each rendering in Chrome.
The generation layer was ported from untyped CommonJS with `strict: false`;
types are tightened file by file without logic changes.
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@genoffice/html2docx",
"version": "0.1.0",
"license": "Apache-2.0",
"private": true,
"type": "module",
"description": "HTML \u2192 DOCX conversion: in-browser intent-tree extraction, screenshots for unmappable visuals, native OOXML generation",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"docx": "^9.7.1"
},
"devDependencies": {
"@types/node": "^24.10.1",
"jszip": "^3.10.1",
"playwright-core": "^1.61.1",
"typescript": "^5.9.3",
"vite": "^7.3.6",
"vitest": "^4.1.11"
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,245 @@
// Rendered math (KaTeX / MathJax / MathML): the internal spans are layout
// hacks — walking them yields garbage text runs ("y=ncx"). Screenshot the
// whole formula instead.
function isMathContainer(el) {
const tag = el.tagName;
if (tag === 'MATH' || tag === 'MJX-CONTAINER') return true;
const cls = el.classList;
return Boolean(
cls && (cls.contains('katex') || cls.contains('katex-display') || cls.contains('MathJax')),
);
}
function pseudoBullet(el) {
const s = getComputedStyle(el, '::before');
if (!s || s.content === 'none' || s.content === 'normal') return false;
const content = s.content.replace(/^['"]|['"]$/g, '').trim();
return BULLET_GLYPHS.has(content);
}
// Real-element twin of the painted ::before dot below: a small empty
// painted first child (<div class="dot"></div>) is a list marker, not a
// block — classifier would silently drop it.
function chipBulletRun(el) {
const first = [...el.children].find((child) => isVisible(child));
if (!first || first.childElementCount || (first.innerText || '').trim()) return null;
const r = first.getBoundingClientRect();
if (r.width < 4 || r.width > 14 || r.height < 4 || r.height > 14) return null;
const color = toHex(cs(first).backgroundColor);
if (!color) return null;
const round = parseFloat(cs(first).borderRadius) >= r.width / 2 - 1;
return {
text: `${round ? '●' : '■'} `,
color,
// the dot glyph inks ~60% of its em box: scale up to match the chip
sizePx: Math.max(8, Math.round(Math.min(r.width, r.height) / 0.6)),
};
}
function pseudoBulletRun(el) {
const s = getComputedStyle(el, '::before');
if (!s || s.content === 'none' || s.content === 'normal') return null;
const content = s.content.replace(/^['"]|['"]$/g, '').trim();
if (!content) {
// Painted dot bullet: empty ::before drawn as a small colored circle
// or square \u2014 emit an equivalent colored glyph run.
const dotW = parseFloat(s.width);
const dotH = parseFloat(s.height);
const dotColor = toHex(s.backgroundColor);
// Composite icon: ::before circle + ::after strokes (check-in-circle
// list markers) \u2014 a flat glyph drops the checkmark, so clip-screenshot
// the drawn icon box instead.
const after = getComputedStyle(el, '::after');
const afterPaints =
after &&
after.content !== 'none' &&
(parseFloat(after.borderLeftWidth) >= 1 ||
parseFloat(after.borderBottomWidth) >= 1 ||
Boolean(toHex(after.backgroundColor)));
if (
dotColor &&
afterPaints &&
s.position === 'absolute' &&
dotW >= 10 &&
dotW <= 28 &&
dotH >= 10 &&
dotH <= 28
) {
const host = el.getBoundingClientRect();
const x = host.left + (parseFloat(s.left) || 0);
const y = host.top + (parseFloat(s.top) || 0);
if (x >= 0 && y >= 0) {
const gapPx = 6;
return {
text: '',
inlineImage: true,
shotId: `h2d-${shotCounter++}`,
clip: {
x: Math.round(x),
y: Math.round(y),
width: Math.round(dotW + gapPx),
height: Math.round(dotH),
},
width: Math.round(dotW + gapPx),
height: Math.round(dotH),
};
}
}
if (dotColor && dotW >= 4 && dotW <= 14 && dotH >= 4 && dotH <= 14) {
const round = parseFloat(s.borderRadius) >= dotW / 2 - 1;
return {
text: `${round ? '\u25cf' : '\u25a0'}\u00a0`,
color: dotColor,
// the dot glyph inks ~60% of its em box: scale up to match the chip
sizePx: Math.max(8, Math.round(Math.min(dotW, dotH) / 0.6)),
};
}
return null;
}
// Numbered circle badge: content:counter(x) painted as a colored circle
// with a light number.
if (content.includes('counter(') && el.parentElement) {
const badgeW = parseFloat(s.width);
// gradient badges have a transparent backgroundColor: take the first
// gradient stop as the representative color
const gradientStop = s.backgroundImage.match(/rgba?\([^)]+\)|#[0-9a-f]{3,8}/i)?.[0];
const badgeColor =
toHex(s.backgroundColor) ||
(gradientStop && toHex(gradientStop, { dropWhite: false }));
// Pseudo-elements have no DOM node to screenshot, but an absolutely
// positioned badge's rendered box is computable from the host rect +
// its own offsets/size — clip-screenshot it so size and gradient
// survive exactly.
const badgeH = parseFloat(s.height) || badgeW;
if (
badgeColor &&
s.position === 'absolute' &&
badgeW >= 14 &&
badgeW <= 72 &&
badgeH >= 14 &&
badgeH <= 72 &&
parseFloat(s.borderRadius) >= badgeW / 2 - 2
) {
const host = el.getBoundingClientRect();
const x = host.left + (parseFloat(s.left) || 0);
const y = host.top + (parseFloat(s.top) || 0);
if (x >= 0 && y >= 0) {
const gapPx = 8; // right whitespace baked in as the text gap
return {
text: '',
inlineImage: true,
shotId: `h2d-${shotCounter++}`,
clip: {
x: Math.round(x),
y: Math.round(y),
width: Math.round(badgeW + gapPx),
height: Math.round(badgeH),
},
width: Math.round(badgeW + gapPx),
height: Math.round(badgeH),
};
}
}
// Word has no circular chips — a negative circled digit (❶❷…) in the
// badge color reads the same.
if (badgeColor && badgeW >= 14 && parseFloat(s.borderRadius) >= badgeW / 2 - 2) {
const siblings = [...el.parentElement.children].filter(
(sibling) => sibling.tagName === el.tagName && isVisible(sibling),
);
const index = siblings.indexOf(el) + 1;
const glyph =
index >= 1 && index <= 10
? String.fromCodePoint(0x2775 + index)
: `${index}.`;
return {
text: `${glyph} `,
color: badgeColor,
sizePx: Math.max(10, Math.round(parseFloat(s.fontSize) * 1.15) || 16),
};
}
}
// Authored visible text prefixes ("◆ SLIDE ") count too, not only
// single-glyph markers.
const literalListMarker =
content.length <= 24 &&
!content.includes('counter(') &&
!content.includes('attr(') &&
!content.includes('url(');
if (!BULLET_GLYPHS.has(content) && !literalListMarker) return null;
return {
text: `${content}\u00a0`,
color: toHex(s.color) || undefined,
sizePx: parseFloat(s.fontSize) || undefined,
fontFamily: BULLET_GLYPHS.has(content) ? s.fontFamily || undefined : 'Arial Unicode MS',
};
}
function hrNode(el) {
const s = cs(el);
const r = el.getBoundingClientRect();
const body = document.body.getBoundingClientRect();
const border = borderSideOf(el, 'top') || borderSideOf(el, 'bottom');
return {
type: 'hr',
color: border?.color || bgHex(el) || 'CCCCCC',
heightPx: border?.widthPx || Math.max(1, Math.min(r.height, 8)),
widthFrac: body.width > 0 ? Math.min(1, r.width / body.width) : 1,
align:
Math.abs(r.left + r.width / 2 - (body.left + body.width / 2)) < 12
? 'center'
: 'left',
};
}
function thinRuleNode(el) {
if ((el.innerText || '').trim() || el.children.length) return null;
const r = el.getBoundingClientRect();
const parentWidth = el.parentElement?.getBoundingClientRect().width || r.width;
if (r.height < 1 || r.height > 8 || r.width < parentWidth * 0.5) return null;
const border = borderSideOf(el, 'top') || borderSideOf(el, 'bottom');
const color = border?.color || bgHex(el);
if (!color) return null;
return {
type: 'hr',
color,
heightPx: border?.widthPx || Math.max(1, r.height),
widthFrac: Math.min(1, r.width / document.body.getBoundingClientRect().width),
align: 'left',
spacingBeforePx: Math.max(0, Math.round(parseFloat(cs(el).marginTop) || 0)),
spacingAfterPx: Math.max(0, Math.round(parseFloat(cs(el).marginBottom) || 0)),
};
}
function isOverlaidInfographic(el) {
const rect = el.getBoundingClientRect();
if (rect.width < 200 || rect.height < 160 || rect.width > 1000 || rect.height > 1000) {
return false;
}
const children = [...el.children].filter((child) => isVisible(child));
const layoutChild = children.find((child) => {
const display = cs(child).display;
return display === 'grid' || display === 'flex';
});
if (!layoutChild) return false;
const layoutRect = layoutChild.getBoundingClientRect();
return children.some((child) => {
if (child === layoutChild || cs(child).position !== 'absolute') return false;
const childRect = child.getBoundingClientRect();
if (childRect.width < 40 || childRect.height < 40) return false;
return (
childRect.left < layoutRect.right &&
childRect.right > layoutRect.left &&
childRect.top < layoutRect.bottom &&
childRect.bottom > layoutRect.top
);
});
}
function needsVisualEffectScreenshot(el) {
return globalThis.__html2docxVisualEffects.needsScreenshot(el, {
bgHex,
cs,
fullBorderOf,
});
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,294 @@
function makePara(runs, style) {
const first = runs[0];
const marker = first && first.text.trim();
if (marker && BULLET_GLYPHS.has(marker)) {
if (first.color && first.color !== '000000') {
return { type: 'para', runs, style };
}
let rest = runs.slice(1);
// swallow the separator gap right after the marker
if (rest.length && !rest[0].text.replace(/[\s\u00a0\t]/g, '')) rest = rest.slice(1);
if (rest.length) return { type: 'para', runs: rest, style: { ...style, bullet: true } };
}
if (first && /^[·•●▪‣◦∙]\s+/.test(first.text)) {
if (first.color && first.color !== '000000') {
return { type: 'para', runs, style };
}
const runsCopy = runs.slice();
runsCopy[0] = { ...first, text: first.text.replace(/^[·•●▪‣◦∙]\s+/, '') };
return { type: 'para', runs: runsCopy, style: { ...style, bullet: true } };
}
return { type: 'para', runs, style };
}
function makeParaNodes(runs, style) {
if (style.align !== 'justify' || !runs.some((run) => (run.text || '').includes('\n'))) {
return [makePara(runs, style)];
}
const lines = [[]];
for (const run of runs) {
if (run.inlineImage) {
lines[lines.length - 1].push(run);
continue;
}
const parts = (run.text || '').split('\n');
parts.forEach((part, index) => {
if (part) lines[lines.length - 1].push({ ...run, text: part });
if (index < parts.length - 1) lines.push([]);
});
}
const nonEmptyLines = lines.filter((line) => line.length);
if (nonEmptyLines.length <= 1) return [makePara(runs, style)];
return nonEmptyLines.map((line, index) => {
const lineStyle = { ...style };
if (index < nonEmptyLines.length - 1) delete lineStyle.align;
if (index > 0) delete lineStyle.spacingBeforePx;
if (index < nonEmptyLines.length - 1) delete lineStyle.spacingAfterPx;
return makePara(line, lineStyle);
});
}
function paraNodesFrom(el, decorations = true) {
// A painted display:block span inside a paragraph (scripture-line quote
// boxes with border-left + tint) renders as its own bordered block in
// the browser — merging it into the parent's runs loses both the
// paragraph break and the decoration. Split the paragraph around it.
const paintedBlocks = [...el.children].filter((child) => {
if (SKIP_TAGS.has(child.tagName) || !isVisible(child)) return false;
const childStyle = cs(child);
const painted = Boolean(bgHex(child)) || Boolean(borderLeftOf(child));
if (!painted) return false;
if (childStyle.display === 'block') return true;
// Inline quote box (scripture-line): border/tint + padding wrapping
// multiple lines reads as a block quote even at display:inline —
// short painted chips stay inline via the single-line guard.
if (parseFloat(childStyle.paddingLeft) < 6) return false;
if ((child.innerText || '').trim().length < 40) return false;
const lineHeight = parseFloat(childStyle.lineHeight) || 20;
return child.getBoundingClientRect().height > lineHeight * 1.4;
});
if (paintedBlocks.length && el.children.length <= 8) {
const style = paraStyleOf(el, decorations);
const nodes = [];
let pending = [];
const flushPending = () => {
const runs = trimRuns(runsFromNodes(pending, el));
pending = [];
if (runs.length) nodes.push(...makeParaNodes(runs, { ...style }));
};
for (const node of el.childNodes) {
if (paintedBlocks.includes(node)) {
flushPending();
const quoteRuns = trimRuns(runsFromNodes([...node.childNodes], node));
if (quoteRuns.length) {
const quoteStyle = paraStyleOf(node, decorations);
const bl = borderLeftOf(node);
if (bl) quoteStyle.borderLeft = bl;
const shading = bgHex(node);
if (shading) quoteStyle.shading = shading;
const padLeft = parseFloat(cs(node).paddingLeft) || 0;
const marginLeft = parseFloat(cs(node).marginLeft) || 0;
if (padLeft + marginLeft > 2) quoteStyle.indentLeftPx = Math.round(padLeft + marginLeft);
nodes.push(...makeParaNodes(quoteRuns, quoteStyle));
}
} else pending.push(node);
}
flushPending();
if (nodes.length) return nodes;
}
const runs = collectRuns(el);
if (!runs.length) return [];
if (el.tagName !== 'LI') {
const pseudoRun = pseudoBulletRun(el);
if (pseudoRun) runs.unshift(pseudoRun);
}
return makeParaNodes(runs, paraStyleOf(el, decorations));
}
const PHRASING_TAGS = new Set([
'STRONG', 'B', 'EM', 'I', 'U', 'S', 'SPAN', 'A', 'CODE', 'SMALL', 'SUB', 'SUP', 'MARK', 'ABBR', 'Q', 'CITE', 'KBD',
]);
function isInlineNode(node) {
if (node.nodeType === Node.TEXT_NODE) return true;
if (node.nodeType !== Node.ELEMENT_NODE) return false;
if (SKIP_TAGS.has(node.tagName)) return false;
if (node.tagName === 'IMG' || node.tagName === 'CANVAS' || node.tagName === 'svg') return false;
if (node.tagName === 'IFRAME' || node.tagName === 'VIDEO' || node.tagName === 'AUDIO') return false;
if (node.tagName === 'TEXTAREA' || node.tagName === 'SELECT') return false;
// checkbox inputs flow inline with their label; other inputs are blocks
if (node.tagName === 'INPUT') return isCheckboxLike(node);
// Compact circular number badges (30×30 inline-flex chips) must go through
// processElement for screenshot — otherwise they flatten to white bars.
// Wider tag pills stay inline so wrap/flow is preserved.
if (isCompactCircleBadge(node)) return false;
const d = cs(node).display;
if (
d === 'inline-block' &&
node.getBoundingClientRect().width >= 120 &&
fullBorderOf(node) &&
(parseFloat(cs(node).paddingLeft) >= 2 || parseFloat(cs(node).paddingTop) >= 2)
) {
return false;
}
if (d === 'inline' || d.startsWith('inline-') || d === 'contents') return true;
// Chrome reports display:block for phrasing elements that are actually
// laid out inline (flex containers blockify children; some elements
// compute block with no matching rule at all). Trust the geometry: if
// the element shares a line with adjacent text, it flows inline.
if (PHRASING_TAGS.has(node.tagName) && node.children.length === 0) {
const sameLine = (textNode, textEdge) => {
try {
const range = document.createRange();
range.selectNodeContents(textNode);
const rects = range.getClientRects();
const box = textEdge === 'last' ? rects[rects.length - 1] : rects[0];
const r = node.getBoundingClientRect();
if (!box) return false;
if (textEdge === 'last') return r.top < box.bottom - 2 && r.left >= box.right - 4;
return box.top < r.bottom - 2 && box.left >= r.right - 4;
} catch (e) {
return false;
}
};
const prev = node.previousSibling;
if (prev && prev.nodeType === Node.TEXT_NODE && prev.textContent.trim() && sameLine(prev, 'last')) {
return true;
}
const next = node.nextSibling;
if (next && next.nodeType === Node.TEXT_NODE && next.textContent.trim() && sameLine(next, 'first')) {
return true;
}
}
return false;
}
function attachBookmark(nodes, id) {
if (!id) return false;
for (const node of nodes) {
if (node.type === 'para' || node.type === 'heading') {
node.bookmarks = [...new Set([...(node.bookmarks || []), id])];
return true;
}
if (node.type === 'list' && node.items?.length) {
const item = node.items[0];
item.bookmarks = [...new Set([...(item.bookmarks || []), id])];
return true;
}
if (node.children && attachBookmark(node.children, id)) return true;
for (const cell of node.cells || []) {
if (cell.children && attachBookmark(cell.children, id)) return true;
}
}
return false;
}
// Walk a block container: consecutive inline siblings merge into one paragraph,
// block-level children are classified recursively.
function processChildren(el, depth, opts = {}) {
const decorations = opts.decorations !== false;
const out = [];
const containerStyle = cs(el);
const singleColumnGrid =
containerStyle.display === 'grid' &&
containerStyle.gridTemplateColumns.split(' ').filter(Boolean).length === 1;
const columnFlex =
containerStyle.display === 'flex' &&
(containerStyle.flexDirection === 'column' || containerStyle.flexDirection === 'column-reverse');
const stackGapPx =
singleColumnGrid || columnFlex
? Math.min(
120,
Math.max(
0,
parseFloat(containerStyle.rowGap) || parseFloat(containerStyle.gap) || 0,
),
)
: 0;
let emittedGroup = false;
let inlineBuffer = [];
const appendGroup = (nodes) => {
if (!nodes.length) return;
if (emittedGroup && stackGapPx > 0) out.push({ type: 'spacer', px: stackGapPx });
out.push(...nodes);
emittedGroup = true;
};
const flush = () => {
if (!inlineBuffer.length) return;
const runs = trimRuns(runsFromNodes(inlineBuffer, el));
if (runs.length) appendGroup(makeParaNodes(runs, paraStyleOf(el, decorations)));
inlineBuffer = [];
};
// CSS `order` / *-reverse reorders flex/grid items visually without
// touching the DOM: walking childNodes would emit e.g. the photo/content
// stack in authored order while the browser shows the reverse. Only
// reorder when the author opted in and no bare text is in play.
let iterNodes = el.childNodes;
if (
(containerStyle.display === 'grid' || containerStyle.display === 'flex') &&
([...el.children].some((c) => (parseInt(cs(c).order, 10) || 0) !== 0) ||
containerStyle.flexDirection.endsWith('-reverse')) &&
[...el.childNodes].every(
(n) => n.nodeType !== Node.TEXT_NODE || !n.textContent.trim(),
)
) {
iterNodes = [...el.children].sort((a, b) => {
const ra = a.getBoundingClientRect();
const rb = b.getBoundingClientRect();
return ra.top - rb.top || (DOC_RTL ? rb.left - ra.left : ra.left - rb.left);
});
}
for (const node of iterNodes) {
if (isInlineNode(node)) {
// An inline-block that starts on a fresh line below the buffered
// content is a visual block (inline-block heading + inline-block
// paragraph stacked by wrapping): break the paragraph between them.
if (
inlineBuffer.length &&
node.nodeType === Node.ELEMENT_NODE &&
cs(node).display.startsWith('inline-')
) {
const r = node.getBoundingClientRect();
// skip buffered whitespace-only text nodes to find the last element
let prevEl = null;
for (let i = inlineBuffer.length - 1; i >= 0; i--) {
const b = inlineBuffer[i];
if (b.nodeType === Node.TEXT_NODE && !b.textContent.trim()) continue;
if (b.nodeType === Node.ELEMENT_NODE) prevEl = b;
break;
}
const pr = prevEl && prevEl.getBoundingClientRect();
if (
pr &&
r.height > 0 &&
pr.height > 0 &&
r.top >= pr.bottom - 2 &&
r.width >= el.getBoundingClientRect().width * 0.4
) {
flush();
appendGroup(processElement(node, depth));
continue;
}
}
inlineBuffer.push(node);
} else if (node.nodeType === Node.ELEMENT_NODE) {
flush();
const children = processElement(node, depth);
attachBookmark(children, node.id);
appendGroup(children);
}
}
flush();
return out;
}
return globalThis.__html2docxPages.build({
cs,
docRTL: DOC_RTL,
isVisible,
markForScreenshot,
nextShotId: () => `h2d-${shotCounter++}`,
processChildren,
processElement,
toHex,
});
@@ -0,0 +1,745 @@
// Regional_Indicator pairs (flag emoji \uD83C\uDDEC\uD83C\uDDE7) are not Extended_Pictographic, so
// match them explicitly or they stay in the body-font run and render as the
// bare letters ("GB").
const EMOJI_RE = /\p{Extended_Pictographic}|\p{Regional_Indicator}/u;
const EMOJI_SEQUENCE_RE =
/(\p{Regional_Indicator}{2}|\p{Extended_Pictographic}(?:\uFE0E|\uFE0F)?(?:\p{Emoji_Modifier})?(?:\u200D\p{Extended_Pictographic}(?:\uFE0E|\uFE0F)?(?:\p{Emoji_Modifier})?)*)/gu;
// Arrows and misc technical symbols (↔ → ⇄ …): CJK body fonts often lack
// the glyph in Word and render a box. Split them into symbol-font runs.
const SYMBOL_RE = /[←-⇿■-◿⤀-⥿⬀-⯿]/;
const SYMBOL_SEQUENCE_RE = /([←-⇿■-◿⤀-⥿⬀-⯿]+)/g;
function splitEmojiRuns(runs) {
return runs
.flatMap((run) => {
// Arrows first: U+2194-21FF are Extended_Pictographic, but in prose
// they are text glyphs — the emoji font would paint them as blue
// emoji chips.
if (!run.text || !SYMBOL_RE.test(run.text)) return [run];
return run.text
.split(SYMBOL_SEQUENCE_RE)
.filter(Boolean)
// No VS15 injection: the symbol-font assignment already forces text
// presentation, and the selector pollutes copied/searched text.
.map((text) =>
SYMBOL_RE.test(text) ? { ...run, text, symbol: true } : { ...run, text },
);
})
.flatMap((run) => {
if (run.symbol || !run.text || !EMOJI_RE.test(run.text)) return [run];
return run.text
.split(EMOJI_SEQUENCE_RE)
.filter(Boolean)
.map((text) => ({ ...run, text, emoji: isColorEmoji(text) }));
});
}
// Only default-emoji-presentation glyphs (📘 🇬🇧 ⭐), a VS16-forced one
// (★️), or a flag pair get the unset-font color-emoji path. Text-presentation
// dingbats (★ ☆ ● ■ U+2605…) stay in the body font so they keep the run's
// color instead of turning into a colored emoji star.
const COLOR_EMOJI_RE = /\p{Emoji_Presentation}|\p{Regional_Indicator}/u;
function isColorEmoji(text) {
return COLOR_EMOJI_RE.test(text) || /️/.test(text);
}
// Collect styled text runs from a list of DOM nodes (text + inline elements).
// baseEl provides the coordinate frame for tab-stop measurement.
function runsFromNodes(nodes, baseEl) {
const runs = [];
const baseRect = baseEl ? baseEl.getBoundingClientRect() : null;
function walk(node) {
if (node.nodeType === Node.TEXT_NODE) {
// A long run of spaces/nbsp is a column separator (Word-exported HTML
// spreads columns and right-aligns dates this way). Emit a tab marker
// and measure where the following content actually starts so the
// generator can place an equivalent tab stop.
const raw = node.textContent;
// newline-preserving white-space (pre-wrap message bodies): authored
// \n are real line/paragraph breaks, not collapsible spaces
if (raw.includes('\n') && node.parentElement) {
const ws = cs(node.parentElement).whiteSpace || '';
if (ws.startsWith('pre') || ws === 'break-spaces') {
const style = runStyleOf(node.parentElement);
raw.split('\n').forEach((line, i) => {
if (i) runs.push({ text: '\n', ...style });
const text = line.replace(/\s+/g, ' ');
if (text.trim()) runs.push({ text, ...style });
});
return;
}
}
const parts = raw.split(/(\s{6,})/);
let offset = 0;
for (const part of parts) {
if (part) {
let isSeparator = false;
let tabFrac = null;
if (/^\s{6,}$/.test(part) && baseRect && baseRect.width > 0) {
// Only a *rendered* wide gap is a column separator. Raw source
// may contain long space runs that the browser collapses to a
// single space (Word-exported HTML) — those must stay spaces.
try {
const range = document.createRange();
range.setStart(node, offset);
range.setEnd(node, offset + part.length);
const rect = range.getBoundingClientRect();
if (rect && rect.width > 14) {
isSeparator = true;
tabFrac = (rect.right - baseRect.left) / baseRect.width;
}
} catch (e) { /* fall through as plain space */ }
}
if (isSeparator && tabFrac != null && tabFrac >= 0.6) {
// Gap pushing content to the far right: right-aligned tab (dates).
runs.push({ text: '\t', tabFrac, ...runStyleOf(node.parentElement) });
} else if (isSeparator) {
// Mid-line column gap: fixed wide space (tab stops in Word are
// too fragile to reproduce arbitrary column positions).
runs.push({ text: '\u00a0\u00a0\u00a0 ', ...runStyleOf(node.parentElement) });
} else {
const text = part.replace(/\s+/g, ' ');
if (text) runs.push({ text, ...runStyleOf(node.parentElement) });
}
}
offset += part.length;
}
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
if (SKIP_TAGS.has(node.tagName)) return;
if (node.tagName === 'BR') {
// BR has a 0x0 rect, so this must come before the visibility check
runs.push({ text: '\n', ...runStyleOf(node.parentElement) });
return;
}
// Empty underline blanks can report ~1px height and fail isVisible.
{
const fillInEarly = fillInLineNode(node);
if (fillInEarly?.inline) {
const style = cs(node);
const fontSize = parseFloat(style.fontSize) || 14;
const spaceWidth = Math.max(3, fontSize * 0.45);
const count = Math.max(3, Math.round(fillInEarly.width / spaceWidth));
const bottom = fillInEarly.borders?.bottom;
runs.push({
text: '\u00a0'.repeat(count),
underline: true,
underlineStyle: bottom?.style || 'solid',
color: bottom?.color || '000000',
sizePx: fontSize,
preserveWhitespace: true,
});
return;
}
}
if (!isVisible(node)) return;
// Preceding content glued to this element in the source (no whitespace
// text node): a block child renders on its own LINE in the browser
// (August 16<span class="h3-sub" style="display:block">Arrival…), and
// an inline sibling separated by CSS margin needs a space — without
// either, the words fuse in Word ("August 16Arrival").
if (
runs.length &&
runs[runs.length - 1].text &&
!/\s$/.test(runs[runs.length - 1].text)
) {
if (cs(node).display === 'block') {
runs.push({ text: '\n', ...runStyleOf(node.parentElement || node) });
} else {
const prevSibling = node.previousSibling;
if (
prevSibling &&
prevSibling.nodeType === Node.TEXT_NODE &&
/\S$/.test(prevSibling.textContent)
) {
try {
const lastGlyph = document.createRange();
lastGlyph.setStart(prevSibling, prevSibling.textContent.length - 1);
lastGlyph.setEnd(prevSibling, prevSibling.textContent.length);
const prevRight = lastGlyph.getBoundingClientRect().right;
const glyphs = document.createRange();
glyphs.selectNodeContents(node);
const nodeLeft = glyphs.getBoundingClientRect().left;
if (nodeLeft - prevRight >= 3) {
runs.push({ text: ' ', ...runStyleOf(node.parentElement || node) });
}
} catch (e) {
/* no gap detected, nothing to add */
}
}
}
}
if (isMathContainer(node)) {
const r = node.getBoundingClientRect();
if (r.width >= 3 && r.height >= 6) {
const shot = markForScreenshot(node);
runs.push({
text: '',
inlineImage: true,
shotId: shot.shotId,
width: shot.width,
height: shot.height,
});
}
return;
}
if (node.tagName === 'SVG' || node.tagName === 'svg' || node.tagName === 'IMG') {
const r = node.getBoundingClientRect();
if (r.width <= 64 && r.height <= 64) {
const shot = markForScreenshot(node);
runs.push({
text: '',
inlineImage: true,
shotId: shot.shotId,
width: shot.width,
height: shot.height,
});
const style = cs(node);
const parentStyle = node.parentElement ? cs(node.parentElement) : null;
const gapPx = Math.max(
parseFloat(style.marginRight) || 0,
parseFloat(parentStyle?.columnGap) || parseFloat(parentStyle?.gap) || 0,
);
if (gapPx >= 4) {
const spaceWidth = Math.max(3, (parseFloat(parentStyle?.fontSize) || 14) * 0.3);
const count = Math.max(1, Math.round((gapPx - spaceWidth) / spaceWidth));
runs.push({
text: '\u00a0'.repeat(count),
...runStyleOf(node.parentElement || node),
preserveWhitespace: true,
});
}
}
return;
}
// Empty painted chip (legend color swatch, status dot): no text, no
// children, just a small background/border box \u2014 dropping it loses the
// color-to-meaning key, so inline-embed it like a small icon.
{
const chipStyle = cs(node);
const r = node.getBoundingClientRect();
if (
!node.childElementCount &&
!(node.innerText || '').trim() &&
r.width >= 4 && r.width <= 28 &&
r.height >= 4 && r.height <= 28 &&
(bgHex(node) ||
(chipStyle.backgroundImage || '').includes('gradient') ||
(parseFloat(chipStyle.borderTopWidth) > 0 && parseFloat(chipStyle.borderRadius) > 0))
) {
const shot = markForScreenshot(node);
runs.push({
text: '',
inlineImage: true,
shotId: shot.shotId,
width: shot.width,
height: shot.height,
});
const parentStyle = node.parentElement ? cs(node.parentElement) : null;
const gapPx = Math.max(
parseFloat(chipStyle.marginRight) || 0,
parseFloat(parentStyle?.columnGap) || parseFloat(parentStyle?.gap) || 0,
);
if (gapPx >= 4) {
const spaceWidth = Math.max(3, (parseFloat(parentStyle?.fontSize) || 14) * 0.3);
const count = Math.max(1, Math.round((gapPx - spaceWidth) / spaceWidth));
runs.push({
text: '\u00a0'.repeat(count),
...runStyleOf(node.parentElement || node),
preserveWhitespace: true,
});
}
return;
}
}
if (isCheckboxLike(node)) {
runs.push(checkboxNode(node));
return;
}
const nodeStyle = cs(node);
const nodeRect = node.getBoundingClientRect();
// A circular painted badge (numbered day markers) has no text-run
// equivalent — the round paint is the point. Plain rectangular chips
// stay text so they remain searchable.
const circularBadge =
(parseFloat(nodeStyle.borderRadius) || 0) >= nodeRect.height / 2 - 1 &&
Math.abs(nodeRect.width - nodeRect.height) <= nodeRect.height * 0.4 &&
!/\s/.test((node.innerText || '').trim());
const compactPaintedLabel =
(['inline-block', 'inline-flex', 'inline-grid'].includes(nodeStyle.display) ||
// a circular badge centering its digit with flex/grid still sits
// inline in its heading row
(circularBadge && ['flex', 'grid'].includes(nodeStyle.display))) &&
(nodeStyle.whiteSpace === 'nowrap' || circularBadge) &&
// inlineBgHex rejects non-inline displays; a flex badge paints its
// own background directly
Boolean(inlineBgHex(node) || (circularBadge && bgHex(node))) &&
(node.innerText || '').trim().length <= 30 &&
nodeRect.width >= 12 &&
nodeRect.width <= 220 &&
nodeRect.height >= 12 &&
nodeRect.height <= 50;
if (compactPaintedLabel) {
const shot = markForScreenshot(node);
// Label crushed by a too-narrow column (letters stacked vertically):
// ask the screenshot pass to relax it to its natural one-line size,
// and record that relaxed size (measured under nowrap) so the docx
// shows the image at its true aspect.
const crushed = node.scrollWidth > node.clientWidth + 2;
if (crushed) {
shot.unwrap = true;
const previousWhiteSpace = node.style.whiteSpace;
node.style.whiteSpace = 'nowrap';
shot.width = Math.min(220, node.scrollWidth + 2);
shot.height = node.clientHeight || shot.height;
node.style.whiteSpace = previousWhiteSpace || '';
}
// A circular badge taller than its line's text inflates the Word row
// height and pushes near-page-height cards past the page. Display it
// at the surrounding text's line scale; the PNG keeps full detail.
let displayWidth = shot.width;
let displayHeight = shot.height;
if (circularBadge && node.parentElement) {
const parentFont = parseFloat(cs(node.parentElement).fontSize) || 16;
const cap = Math.round(parentFont * 1.35);
if (displayHeight > cap) {
displayWidth = Math.round((shot.width * cap) / shot.height);
displayHeight = cap;
}
}
runs.push({
text: '',
inlineImage: true,
shotId: shot.shotId,
width: displayWidth,
height: displayHeight,
unwrap: shot.unwrap,
});
return;
}
if (
!(node.innerText || '').trim() &&
node.children.length === 0 &&
(nodeStyle.display === 'inline' || nodeStyle.display === 'inline-block') &&
nodeRect.width >= 4 &&
nodeRect.width <= 32 &&
nodeRect.height >= 4 &&
nodeRect.height <= 32
) {
const swatch = bgHex(node);
if (swatch) {
runs.push({
text: '\u25a0 ',
color: swatch,
sizePx: Math.max(nodeRect.width, nodeRect.height),
});
return;
}
}
const highlightedInline =
nodeStyle.display.startsWith('inline-') &&
Boolean(inlineBgHex(node)) &&
Boolean((node.innerText || '').trim());
const paddedSpaces = (px) => {
if (px < 2) return '';
const spaceWidth = Math.max(3, (parseFloat(nodeStyle.fontSize) || 14) * 0.3);
return '\u00a0'.repeat(Math.max(1, Math.round(px / spaceWidth)));
};
if (highlightedInline) {
const leftPad = paddedSpaces(parseFloat(nodeStyle.paddingLeft) || 0);
if (leftPad) runs.push({ text: leftPad, ...runStyleOf(node), preserveWhitespace: true });
}
const inlinePseudoRun = pseudoBulletRun(node);
if (inlinePseudoRun) runs.push(inlinePseudoRun);
for (const child of node.childNodes) walk(child);
// Symmetric to the block-BEFORE rule above: a block child also ends
// its own line, so following content (an eyebrow <span
// class="section-num" style="display:block"> glued before heading
// text) must not fuse onto it. trimRuns drops a trailing break.
if (
nodeStyle.display === 'block' &&
runs.length &&
runs[runs.length - 1].text &&
!/\n$/.test(runs[runs.length - 1].text)
) {
runs.push({ text: '\n', ...runStyleOf(node.parentElement || node) });
}
if (highlightedInline) {
const rightPad = paddedSpaces(parseFloat(nodeStyle.paddingRight) || 0);
if (rightPad) runs.push({ text: rightPad, ...runStyleOf(node), preserveWhitespace: true });
}
// Inline chip followed directly by text with no space character in the
// source (<span class="q-mark">Q</span>How...): the visual gap comes
// from min-width/margin/padding. Keep a space or the words glue.
const next = node.nextSibling;
if (
next &&
next.nodeType === Node.TEXT_NODE &&
/^\S/.test(next.textContent) &&
runs.length &&
runs[runs.length - 1].text &&
!/\s$/.test(runs[runs.length - 1].text)
) {
try {
const glyphs = document.createRange();
glyphs.selectNodeContents(node);
const glyphRight = glyphs.getBoundingClientRect().right;
const first = document.createRange();
first.setStart(next, 0);
first.setEnd(next, 1);
const nextLeft = first.getBoundingClientRect().left;
if (nextLeft - glyphRight >= 3) {
runs.push({ text: ' ', ...runStyleOf(node.parentElement || node) });
}
} catch (e) {
/* no gap detected, nothing to add */
}
}
}
for (const node of nodes) walk(node);
// Latin fragments with neutral punctuation inside an RTL context get
// bidi-reordered by Word ("Motorola 68010, supplier A" -> "Motorola
// supplier ,68010 A"): bracket them with LRM so the whole fragment
// stays one LTR segment. Runs carrying RTL script keep native ordering.
const isolated = runs.map((run) => {
if (!run.rtl || !run.text || run.inlineImage) return run;
if (/[֐-ࣿיִ-ﻼ]/.test(run.text)) return run;
if (!/[A-Za-z0-9]/.test(run.text)) return run;
if (!/[()[\]{}+*/,.:%~=-]/.test(run.text)) return run;
return { ...run, text: `‎${run.text}‎` };
});
return splitEmojiRuns(isolated);
}
// Measured gap between the element's left edge and its first visible glyph
// (covers both CSS padding-left and leading nbsp used as manual inset).
function textInsetLeft(el, rect) {
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
const m = node.textContent.match(/[^\s\u00a0]/);
if (!m) continue;
try {
const range = document.createRange();
range.setStart(node, m.index);
range.setEnd(node, m.index + 1);
const glyph = range.getBoundingClientRect();
if (glyph.width > 0) return glyph.left - rect.left;
} catch (e) {
return 0;
}
return 0;
}
return 0;
}
function trimRuns(runs) {
if (runs.length) {
if (!runs[0].preserveWhitespace) runs[0].text = runs[0].text.replace(/^\s+/, '');
if (!runs[runs.length - 1].preserveWhitespace) {
runs[runs.length - 1].text = runs[runs.length - 1].text.replace(/\s+$/, '');
}
}
return runs.filter((r) => r.inlineImage || r.text.length > 0);
}
function collectRuns(el) {
return trimRuns(runsFromNodes([...el.childNodes], el));
}
function hasBlockChildren(el) {
let prevRect = null;
for (const child of el.children) {
if (SKIP_TAGS.has(child.tagName)) continue;
const d = cs(child).display;
if (d !== 'inline' && !d.startsWith('inline-')) return true;
// Two wide inline-blocks that render on separate lines (an inline-block
// heading too wide to share its line with the following inline-block
// paragraph) are visually blocks; merging them glues the texts. The
// width guard keeps small wrapping chips/badges on the inline path.
if (d.startsWith('inline-')) {
const r = child.getBoundingClientRect();
const wide = r.width >= el.getBoundingClientRect().width * 0.4;
if (prevRect && wide && r.height > 0 && r.top >= prevRect.bottom - 2) return true;
if (r.height > 0 && wide) prevRect = r;
else if (r.height > 0) prevRect = null;
}
}
return false;
}
// Replaced elements (img/svg/canvas) are excluded from inline runs, so a
// wrapper holding only an inline <img> must still walk children as blocks
// or the image silently disappears.
function isReplacedTag(el) {
const t = el.tagName;
if (
t === 'IMG' ||
t === 'CANVAS' ||
t === 'SVG' ||
t === 'svg' ||
t === 'IFRAME' ||
t === 'VIDEO' ||
t === 'AUDIO'
) {
return true;
}
if (t === 'TEXTAREA' || t === 'SELECT') return true;
if (t === 'INPUT') return !isCheckboxLike(el);
return false;
}
function hasReplacedDescendant(el) {
if (isReplacedTag(el)) return true;
for (const d of el.querySelectorAll(
'img, svg, canvas, iframe, video, audio, textarea, select, input:not([type=checkbox]):not([type=radio])',
)) {
if (isVisible(d)) return true;
}
return false;
}
// needs full block walk (vs a single merged paragraph)
function needsBlockWalk(el) {
return hasBlockChildren(el) || hasReplacedDescendant(el);
}
// decorations=false: only text-level styling (align/spacing/line-height).
// Used for paragraphs inside cards/cells where the container already owns
// the border and shading (avoids double-drawn vertical bars).
function paraStyleOf(el, decorations = true) {
const s = cs(el);
const style = {};
style.cjk = /[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\uff00-\uffef]/.test(
el.textContent || '',
);
if (isRTL(el)) style.rtl = true;
const align = textAlignOf(el);
if (align) style.align = align;
const mb = parseFloat(s.marginBottom);
if (mb > 2) style.spacingAfterPx = Math.min(mb, 40);
const mt = parseFloat(s.marginTop);
if (mt > 2) style.spacingBeforePx = Math.min(mt, 40);
if (
style.spacingBeforePx &&
el.parentElement === document.body &&
!el.nextElementSibling
) {
// Large decorative signatures/flourishes at the end of a one-page
// document should use the remaining page space, not force a blank page.
style.spacingBeforePx = Math.min(style.spacingBeforePx, 2);
}
const ti = parseFloat(s.textIndent);
if (ti > 2) style.firstLineIndentPx = Math.min(ti, 100);
const lh = parseFloat(s.lineHeight);
const fsz = parseFloat(s.fontSize);
if (lh && fsz && lh / fsz > 1.25) style.lineRatio = Math.min(lh / fsz, 2.2);
if (style.cjk && lh && fsz) style.exactLineHeightPx = lh;
// Heading-like paragraph (bold, short, followed by content): keep it on
// the same page as what it introduces - FAQ questions, styled pseudo-
// headings etc. are divs/ps in HTML but behave like headings in print.
const headText = (el.innerText || '').trim();
if (
parseFloat(s.fontWeight) >= 600 &&
headText.length > 0 &&
headText.length <= 120 &&
!headText.includes('\n') &&
el.nextElementSibling
) {
style.keepNext = true;
// A short bold heading-like line must also not split across pages
// mid-word ("EDUCATIO" / "N").
style.keepLines = true;
}
// Short text rendered on ONE browser line: record the measured width so
// the generator can size narrow cells (or shrink display banners)
// instead of letting Word wrap "Sub Total :" or "INVOICE" mid-word.
if (fsz >= 10 && headText.length > 0 && headText.length <= 40 && !headText.includes('\n')) {
try {
const range = document.createRange();
range.selectNodeContents(el);
const textRect = range.getBoundingClientRect();
if (textRect.width > 0 && textRect.height <= fsz * 2.1) {
// Word's substituted font may run much wider than the webfont.
const wordWidth = window.__h2dWordFontLineWidth
? window.__h2dWordFontLineWidth(el)
: 0;
style.oneLineWidthPx = Math.round(Math.max(textRect.width, wordWidth));
}
} catch (e) {
/* leave unset */
}
}
if (!decorations) {
// decorations=false suppresses the container-owned paint, but a child
// with its own distinct background (label chips, "OBJECTION 1 OF 6"
// bars inside cards) must keep it.
const ownBg = bgHex(el);
if (ownBg && (!el.parentElement || ownBg !== bgHex(el.parentElement))) {
style.shading = ownBg;
}
return style;
}
// manual left inset (decoration: containers that own their inset skip it)
const padL = parseFloat(s.paddingLeft) + parseFloat(s.marginLeft);
if (padL >= 12) style.indentLeftPx = Math.min(padL, 200);
let shading = paintedBgHex(el);
// authored vertical padding on unshaded wrappers (e.g. a card body div)
// reads as spacing; shaded bars handle their padding via exact height
if (!shading) {
const pt = parseFloat(s.paddingTop) || 0;
const pb = parseFloat(s.paddingBottom) || 0;
if (pt > 2) style.spacingBeforePx = Math.min((style.spacingBeforePx || 0) + pt, 40);
if (pb > 2) style.spacingAfterPx = Math.min((style.spacingAfterPx || 0) + pb, 40);
}
if (shading) {
const textColor = toHex(s.color) || '000000';
const shadeLum = hexLuminance(shading);
const textLum = hexLuminance(textColor);
// Near-white chip on a colored parent + light text would become an
// invisible full-width white bar (benefit-num / step circles). Skip.
if (shadeLum > 230 && textLum > 200) {
shading = null;
}
}
if (shading) {
style.shading = shading;
// Word's single spacing for CJK fonts has much taller leading than the
// browser's, which fattens shaded bars. For single-line shaded
// paragraphs, pin the rendered height as an exact line height.
// Elements with a left accent border are note cards, not header bars -
// the color bar table would drop the accent, keep them as paragraphs.
const rect = el.getBoundingClientRect();
const lineH = lh || fsz * 1.35;
const radius = parseFloat(s.borderTopLeftRadius) || 0;
// Compact circular badges are not full-width header bars.
const compactBadge = rect.width > 0 && rect.width <= 72 && radius >= rect.height * 0.4;
if (
rect.height > 0 &&
lineH &&
rect.height < lineH * 1.9 &&
!borderLeftOf(el) &&
!compactBadge
) {
style.exactLineHeightPx = rect.height;
// single-line bar: safe to render as a fixed-height color bar table.
// (exactLineHeightPx alone also gets set for CJK line control and
// must NOT trigger the bar path - it would clip multi-line text.)
style.colorBar = true;
// Text inset inside the bar (padding-left and/or leading nbsp runs,
// which trimRuns strips from the text itself).
const inset = textInsetLeft(el, rect);
if (inset > 1) style.barInsetLeftPx = Math.min(inset, 60);
}
}
const bl = borderLeftOf(el);
if (bl) {
style.borderLeft = bl;
const paddingLeft = parseFloat(s.paddingLeft) || 0;
if (paddingLeft > 0) style.borderLeftSpacePx = Math.min(paddingLeft, 40);
}
const br = borderRightOf(el);
if (br) {
style.borderRight = br;
const paddingRight = parseFloat(s.paddingRight) || 0;
if (paddingRight > 0) style.borderRightSpacePx = Math.min(paddingRight, 40);
}
const bt = borderSideOf(el, 'top');
if (bt) style.borderTop = bt;
const bw = parseFloat(s.borderBottomWidth);
if (bw >= 1 && s.borderBottomStyle !== 'none') {
const color = toHex(s.borderBottomColor);
if (color) {
style.borderBottom = { color, widthPx: bw };
// dotted/dashed TOC separators must not harden into solid rules
if (s.borderBottomStyle === 'dotted' || s.borderBottomStyle === 'dashed') {
style.borderBottom.style = s.borderBottomStyle;
}
}
}
return style;
}
// Lowest visible pixel row (relative to the element top) of the element's
// own paint and descendants: text lines, replaced elements, painted boxes.
function visibleContentBottom(el, rect) {
let bottom = rect.top;
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const textNode = walker.currentNode;
if (!textNode.textContent.trim()) continue;
const range = document.createRange();
range.selectNodeContents(textNode);
for (const lineRect of range.getClientRects()) {
if (lineRect.height > 0 && lineRect.width > 0) bottom = Math.max(bottom, lineRect.bottom);
}
}
for (const child of el.querySelectorAll('*')) {
if (!isVisible(child)) continue;
const childRect = child.getBoundingClientRect();
if (childRect.height <= 0 || childRect.width <= 0) continue;
const childStyle = cs(child);
const painted =
child.matches('img, svg, canvas, video, iframe, input, textarea, select, button, hr') ||
childStyle.backgroundImage !== 'none' ||
childStyle.boxShadow !== 'none' ||
Boolean(toHex(childStyle.backgroundColor, { dropWhite: false })) ||
parseFloat(childStyle.borderTopWidth) > 0 ||
parseFloat(childStyle.borderBottomWidth) > 0;
if (painted) bottom = Math.max(bottom, Math.min(childRect.bottom, rect.bottom));
}
return bottom - rect.top;
}
function markForScreenshot(el) {
const id = `h2d-${shotCounter++}`;
el.setAttribute('data-h2d-id', id);
const r = el.getBoundingClientRect();
const s = cs(el);
const body = document.body.getBoundingClientRect();
const offLeft = r.left - body.left;
const offRight = body.right - r.right;
const align =
offLeft > 8 && offRight > 8 && Math.abs(offLeft - offRight) < Math.max(12, r.width * 0.08)
? 'center'
: offLeft > offRight * 3
? 'right'
: 'left';
// A transparent wrapper much taller than its visible content (e.g. a
// photo container stretched by the column) would embed a page-height
// mostly-empty image and strand a phantom page. Crop the invisible tail;
// painted elements keep their full box (the paint IS content).
let height = Math.round(r.height);
let clip;
const paintedSelf =
s.backgroundImage !== 'none' ||
s.boxShadow !== 'none' ||
Boolean(toHex(s.backgroundColor, { dropWhite: false })) ||
parseFloat(s.borderTopWidth) > 0 ||
parseFloat(s.borderBottomWidth) > 0;
if (r.height >= 600 && !paintedSelf) {
const contentBottom = visibleContentBottom(el, r);
if (contentBottom > 0 && r.height - contentBottom >= 150) {
height = Math.round(Math.min(r.height, contentBottom + 12));
clip = {
x: Math.max(0, Math.round(r.left)),
y: Math.max(0, Math.round(r.top)),
width: Math.round(r.width),
height,
};
}
}
return {
type: 'image',
shotId: id,
width: Math.round(r.width),
height,
...(clip ? { clip } : {}),
align,
spacingBeforePx: Math.max(0, Math.round(parseFloat(s.marginTop) || 0)),
spacingAfterPx: Math.max(0, Math.round(parseFloat(s.marginBottom) || 0)),
};
}
@@ -0,0 +1,460 @@
const SKIP_TAGS = new Set([
'SCRIPT', 'STYLE', 'LINK', 'META', 'NOSCRIPT', 'TEMPLATE', 'HEAD', 'TITLE',
]);
let shotCounter = 0;
const styleCache = new WeakMap();
function cs(el) {
if (!styleCache.has(el)) styleCache.set(el, getComputedStyle(el));
return styleCache.get(el);
}
function isVisible(el) {
const s = cs(el);
if (s.display === 'none' || s.visibility === 'hidden' || parseFloat(s.opacity) === 0) return false;
const r = el.getBoundingClientRect();
return r.width > 1 && r.height > 1;
}
function parseColor(colorStr) {
if (!colorStr) return null;
const m = colorStr.match(/rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)(?:[,\s/]+([\d.]+))?\s*\)/);
if (!m) return null;
return {
r: +m[1],
g: +m[2],
b: +m[3],
a: m[4] === undefined ? 1 : parseFloat(m[4]),
};
}
function compositeRgb(color, backdrop) {
const a = color.a;
return {
r: Math.round(color.r * a + backdrop.r * (1 - a)),
g: Math.round(color.g * a + backdrop.g * (1 - a)),
b: Math.round(color.b * a + backdrop.b * (1 - a)),
a: 1,
};
}
function backdropRgbOf(el) {
const ancestors = [];
for (let cur = el?.parentElement; cur; cur = cur.parentElement) ancestors.push(cur);
let backdrop = { r: 255, g: 255, b: 255, a: 1 };
for (const ancestor of ancestors.reverse()) {
let color = parseColor(cs(ancestor).backgroundColor);
// A gradient-painted ancestor (background-image, not backgroundColor)
// is invisible to this walk otherwise: a translucent white overlay
// nested inside it composites against the default white backdrop and
// reads as near-white, so paintedBgHex's white-preserve fallback then
// hardcodes opaque FFFFFF — white text on a white cell, content
// effectively invisible. Approximate with the first gradient stop,
// same fallback bgHex uses for the gradient element itself.
if (!color || color.a < 0.05) {
const stop = gradientBaseStop(cs(ancestor).backgroundImage);
if (stop) color = parseColor(stop);
}
if (color && color.a >= 0.05) backdrop = compositeRgb(color, backdrop);
}
return backdrop;
}
// 'rgb(a)' -> 'RRGGBB' hex, or null for transparent / near-white.
// Light documents retain white-backed tints; dark documents pass their
// resolved ancestor paint so alpha colors keep their authored contrast.
function toHex(colorStr, { dropWhite = false, backdrop = null } = {}) {
const color = parseColor(colorStr);
if (!color) return null;
let { r, g, b, a } = color;
if (a < 0.05) return null;
if (a < 1) {
({ r, g, b } = compositeRgb(color, backdrop || { r: 255, g: 255, b: 255 }));
}
if (dropWhite && r > 250 && g > 250 && b > 250) return null;
const hex = (n) => n.toString(16).padStart(2, '0');
return (hex(r) + hex(g) + hex(b)).toUpperCase();
}
function hexLuminance(hex) {
if (!hex || hex.length < 6) return 0;
const n = parseInt(hex.slice(0, 6), 16);
if (Number.isNaN(n)) return 0;
const r = (n >> 16) & 255;
const g = (n >> 8) & 255;
const b = n & 255;
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// Representative paint of a (possibly multi-layer) gradient background:
// the first sufficiently-opaque stop of the BOTTOM layer. CSS paints the
// first listed layer on top, so decorative low-alpha radial accents come
// first and the base gradient last — grabbing the first color in the whole
// string painted a dark hero with its 0.18-alpha gold accent (near-white
// shading under white text) instead of its dark base.
function gradientBaseStop(bgImage) {
if (!bgImage || !bgImage.includes('gradient')) return null;
const lastLayerStart = bgImage.lastIndexOf('-gradient(');
const layer = lastLayerStart >= 0 ? bgImage.slice(lastLayerStart) : bgImage;
let first = null;
for (const match of layer.matchAll(/rgba?\([^)]+\)|#[0-9a-fA-F]{3,8}/g)) {
first = first || match[0];
const color = parseColor(match[0]);
// #hex tokens don't parse -> opaque; skip translucent overlay stops
if (!color || color.a >= 0.5) return match[0];
}
return first;
}
function bgHex(el) {
const solid = toHex(cs(el).backgroundColor, { dropWhite: true, backdrop: backdropRgbOf(el) });
if (solid) return solid;
// gradient-painted box with no solid backgroundColor: approximate with
// a representative stop, or light foreground text lands on a white page
const stop = gradientBaseStop(cs(el).backgroundImage);
if (stop) return toHex(stop, { dropWhite: true });
return null;
}
// True when el sits on a solid tint or a CSS background-image/gradient.
// White cards on those surfaces must keep FFFFFF or the backdrop shows through.
function hasTintedBackdrop(el) {
let anc = el.parentElement;
while (anc) {
if (bgHex(anc)) return true;
const s = cs(anc);
if (s.backgroundImage && s.backgroundImage !== 'none') return true;
if (anc === document.documentElement) break;
anc = anc.parentElement;
}
return false;
}
// Like bgHex, but keeps authored white/near-white paint when it covers a
// tinted or gradient backdrop (page wash, section band, etc.).
function paintedBgHex(el) {
const shaded = bgHex(el);
if (shaded) return shaded;
const raw = toHex(cs(el).backgroundColor);
if (!raw || !hasTintedBackdrop(el)) return null;
return 'FFFFFF';
}
// A compact painted pill/badge (inline-block, nowrap, own background):
// shared signal that a container's exact visual row must be screenshot.
function isCompactPaintedLabel(child) {
const childStyle = cs(child);
return (
childStyle.display === 'inline-block' &&
childStyle.whiteSpace === 'nowrap' &&
Boolean(bgHex(child)) &&
(child.innerText || '').trim().length <= 30 &&
child.getBoundingClientRect().height <= 50
);
}
function isMono(s) {
return /mono|consolas|courier|menlo|jetbrains/i.test(s.fontFamily);
}
const DOC_RTL =
getComputedStyle(document.body).direction === 'rtl' ||
getComputedStyle(document.documentElement).direction === 'rtl';
function isRTL(el) {
return cs(el).direction === 'rtl';
}
// Resolve text-align to a physical alignment, accounting for direction.
// In an RTL block, 'start' (the browser default) means the right side —
// Word's w:bidi paragraphs already default to right, so return undefined
// and let the bidi default apply; an explicit left/end must survive as
// physical left.
function textAlignOf(el) {
const s = cs(el);
const ta = s.textAlign;
if (ta === 'center') return 'center';
if (ta.startsWith('justify')) return 'justify';
if (s.direction === 'rtl') {
if (ta === 'left' || ta === 'end') return 'left';
return undefined; // start / right == bidi paragraph default
}
if (ta === 'right' || ta === 'end') return 'right';
return undefined;
}
function borderLeftOf(el) {
const s = cs(el);
const w = parseFloat(s.borderLeftWidth);
if (w >= 2 && s.borderLeftStyle !== 'none') {
const color = toHex(s.borderLeftColor);
if (color) return { color, widthPx: w };
}
// ::before painted as a narrow vertical accent bar (▎ section headings,
// timeline rails): visually a left border, but authored as a
// pseudo-element; gradient rails take their first color stop.
const before = getComputedStyle(el, '::before');
if (before && before.content === '""') {
const bw = parseFloat(before.width);
const bh = parseFloat(before.height);
const gradientStop = before.backgroundImage.match(/rgba?\([^)]+\)|#[0-9a-fA-F]{3,8}/)?.[0];
const color = toHex(before.backgroundColor) || (gradientStop && toHex(gradientStop));
if (color && bw >= 2 && bw <= 10 && bh >= 10) {
return { color, widthPx: bw };
}
}
return null;
}
function borderRightOf(el) {
const s = cs(el);
const w = parseFloat(s.borderRightWidth);
if (w >= 2 && s.borderRightStyle !== 'none') {
const color = toHex(s.borderRightColor);
if (color) return { color, widthPx: w };
}
return null;
}
// ::before/::after painted as a full-width horizontal bar (decorative
// section rules). Not in the DOM, so probed via computed pseudo styles.
function pseudoBar(el, which) {
const s = getComputedStyle(el, which);
if (!s || s.content === 'none') return null;
if (s.position === 'fixed') return null;
const h = parseFloat(s.height);
if (!(h >= 1 && h <= 8)) return null;
const w = parseFloat(s.width);
const elW = el.getBoundingClientRect().width;
const fullRule = w >= elW * 0.5;
// absolute pseudos are usually dropped (not in flow), but a thin
// full-width bar hugging the element is a decorative underline that
// should survive (section-title::after { position:absolute; bottom:-5px })
if (s.position === 'absolute') {
const top = Math.abs(parseFloat(s.top));
const bottom = Math.abs(parseFloat(s.bottom));
const hugsEdge = Math.min(isNaN(top) ? 99 : top, isNaN(bottom) ? 99 : bottom) <= 12;
if (!fullRule || !hugsEdge) return null;
}
if (s.position !== 'absolute' && s.display !== 'block') return null;
const shortAccent = w >= 20 && w <= 120;
if (!(w > 0) || (!fullRule && !shortAccent)) return null;
const color = toHex(s.backgroundColor, { dropWhite: true });
if (!color) return null;
return {
type: 'hr',
color,
heightPx: h,
widthFrac: Math.min(1, w / elW),
short: shortAccent && !fullRule,
spacingBeforePx: Math.max(0, parseFloat(s.marginTop) || 0),
spacingAfterPx: Math.max(0, parseFloat(s.marginBottom) || 0),
};
}
function pseudoMarker(el) {
for (const which of ['::before', '::after']) {
const s = getComputedStyle(el, which);
if (!s || s.content === 'none' || s.content === 'normal') continue;
const content = s.content.replace(/^['"]|['"]$/g, '');
if (content.trim()) continue;
const width = parseFloat(s.width);
const height = parseFloat(s.height);
if (
width < 5 ||
width > 24 ||
height < 5 ||
height > 24 ||
Math.abs(width - height) > 6
) {
continue;
}
const color =
toHex(s.backgroundColor, { dropWhite: true }) ||
toHex(s.borderTopColor, { dropWhite: true });
if (!color) continue;
return {
text: s.transform && s.transform !== 'none' ? '\u25c6 ' : '\u25a0 ',
color,
sizePx: Math.max(width, height),
bold: false,
};
}
return null;
}
// Timeline entry decorations: an absolutely positioned pseudo dot (round
// marker) and/or a thin vertical connector rail in the left padding gutter.
// Both are position:absolute, so the flow rules drop them; callers
// reproduce the rail as a paragraph left border and the dot as a colored
// disc run.
function timelineDecorOf(el) {
const s = cs(el);
if (s.position !== 'relative') return null;
const padL = parseFloat(s.paddingLeft) || 0;
if (padL < 12 || padL > 60) return null;
let dot = null;
let rail = null;
for (const which of ['::before', '::after']) {
const p = getComputedStyle(el, which);
if (!p || p.content === 'none' || p.content === 'normal') continue;
if (p.position !== 'absolute') continue;
if (p.content.replace(/^['"]|['"]$/g, '').trim()) continue;
const w = parseFloat(p.width);
const h = parseFloat(p.height);
const left = parseFloat(p.left);
if (!(left >= -2 && left < padL)) continue;
const color = toHex(p.backgroundColor, { dropWhite: true });
if (!color) continue;
if (w >= 5 && w <= 24 && h >= 5 && h <= 24 && Math.abs(w - h) <= 6) {
dot = { color, sizePx: Math.max(w, h) };
} else if (w >= 1 && w <= 4 && h > 30) {
rail = { color, widthPx: Math.max(1, Math.round(w)), leftPx: left };
}
}
return dot || rail ? { dot, rail, padL, railLeftPx: rail?.leftPx } : null;
}
function borderTopOf(el) {
const s = cs(el);
const w = parseFloat(s.borderTopWidth);
if (w >= 2 && s.borderTopStyle !== 'none') {
const color = toHex(s.borderTopColor);
if (color) return { color, widthPx: w };
}
return null;
}
function borderSideOf(el, side) {
const s = cs(el);
const cap = side[0].toUpperCase() + side.slice(1);
const width = parseFloat(s[`border${cap}Width`]);
if (width < 1 || s[`border${cap}Style`] === 'none') return null;
const color = toHex(s[`border${cap}Color`]);
return color ? { color, widthPx: width, style: s[`border${cap}Style`] } : null;
}
function bordersOf(el) {
const borders = {};
for (const side of ['top', 'bottom', 'left', 'right']) {
const border = borderSideOf(el, side);
if (border) borders[side] = border;
}
return Object.keys(borders).length ? borders : null;
}
function cellPaddingOf(el) {
const s = cs(el);
return {
top: Math.max(0, Math.round(parseFloat(s.paddingTop) || 0)),
bottom: Math.max(0, Math.round(parseFloat(s.paddingBottom) || 0)),
left: Math.max(0, Math.round(parseFloat(s.paddingLeft) || 0)),
right: Math.max(0, Math.round(parseFloat(s.paddingRight) || 0)),
};
}
// Background painted by an *inline* ancestor (text highlight). Block-level
// backgrounds are handled as paragraph/cell shading, so stop at the first
// non-inline ancestor to avoid double-painting.
// Marker-pen highlight: linear-gradient(transparent 60%, color 40%) on an
// inline span. Word has no partial-height run shading, so the marker color
// becomes a full-height run highlight.
function markerGradientHex(el) {
const bgImage = cs(el).backgroundImage;
if (!bgImage || !bgImage.startsWith('linear-gradient')) return null;
const stops = [...bgImage.matchAll(/rgba?\(([\d.\s,]+)\)/g)];
if (!stops.length) return null;
const last = stops[stops.length - 1][1].split(',').map(parseFloat);
const [r, g, b, a = 1] = last;
if (!(a >= 0.15)) return null;
const mix = (c) => Math.round(c * a + 255 * (1 - a));
return toHex(`rgb(${mix(r)}, ${mix(g)}, ${mix(b)})`, { dropWhite: true });
}
function inlineBgHex(el) {
let cur = el;
while (cur && cur.nodeType === Node.ELEMENT_NODE) {
const d = cs(cur).display;
if (!(d === 'inline' || d.startsWith('inline-') || d === 'contents')) return null;
const bg = bgHex(cur) || markerGradientHex(cur);
if (bg) return bg;
cur = cur.parentElement;
}
return null;
}
function runStyleOf(el) {
const s = cs(el);
const style = {
bold: parseInt(s.fontWeight, 10) >= 600,
italic: s.fontStyle === 'italic',
underline: s.textDecorationLine.includes('underline'),
strike: s.textDecorationLine.includes('line-through'),
color: toHex(s.color) || '000000',
sizePx: parseFloat(s.fontSize),
mono: isMono(s),
letterSpacing: parseFloat(s.letterSpacing) || 0,
fontFamily: s.fontFamily,
};
// Inline(-block) span underlined via border-bottom (recipient names,
// signature lines): text-decoration never sees it, so map the lone
// bottom border to a run underline. Boxed chips (any other side) skip.
if (
!style.underline &&
(s.display || '').startsWith('inline') &&
s.borderBottomStyle !== 'none' &&
parseFloat(s.borderBottomWidth) >= 1 &&
s.borderTopStyle === 'none' &&
s.borderLeftStyle === 'none' &&
s.borderRightStyle === 'none'
) {
style.underline = true;
if (s.borderBottomStyle === 'dotted' || s.borderBottomStyle === 'dashed') {
style.underlineStyle = s.borderBottomStyle;
}
const underlineHex = toHex(s.borderBottomColor);
if (underlineHex) style.underlineColor = underlineHex;
}
// Inline boxed chip (O/X answer labels, small tags): a same-color border
// on every side of a short inline element is a character box — map it to a
// run border (w:bdr). Word can't round the corners, but the frame survives.
// Restricted to short text so a bordered inline phrase isn't boxed whole.
if (
(s.display || '').startsWith('inline') &&
(el.innerText || '').trim().length <= 8 &&
parseFloat(s.borderTopWidth) >= 1 &&
s.borderTopStyle !== 'none'
) {
const bc = toHex(s.borderTopColor);
if (
bc &&
toHex(s.borderRightColor) === bc &&
toHex(s.borderBottomColor) === bc &&
toHex(s.borderLeftColor) === bc
) {
style.charBorder = { color: bc, widthPx: parseFloat(s.borderTopWidth) };
}
}
const hl = inlineBgHex(el);
if (hl) style.highlight = hl;
if (s.verticalAlign === 'super' || el.closest('sup')) style.superscript = true;
else if (s.verticalAlign === 'sub' || el.closest('sub')) style.subscript = true;
if (s.textTransform === 'uppercase') style.uppercase = true;
if (s.direction === 'rtl') style.rtl = true;
const a = el.closest('a[href]');
if (a) {
const href = a.getAttribute('href') || '';
if (href.startsWith('#') && href.length > 1) {
try {
style.anchor = decodeURIComponent(href.slice(1));
} catch {
style.anchor = href.slice(1);
}
} else if (href && !/^javascript:/i.test(href)) {
style.href = a.href;
}
}
return style;
}
@@ -0,0 +1,516 @@
function extractTable(el) {
const rect = el.getBoundingClientRect();
const hasCompactPaintedLabel = [...el.querySelectorAll('td *, th *')].some(isCompactPaintedLabel);
if (hasCompactPaintedLabel && rect.height <= 900) return markForScreenshot(el);
return globalThis.__html2docxTable.extractTable(el, {
bgHex,
isCompactPaintedLabel,
bordersOf,
cellPaddingOf,
collectRuns,
cs,
hasBlockChildren,
isRTL,
isVisible,
markForScreenshot,
processChildren,
textAlignOf,
toHex,
});
}
// A CSS-grid table whose direct children are grid rows with the same number
// of columns (for example a Likert survey built from divs instead of table).
function gridTableRows(el) {
const rows = [...el.children].filter((c) => !SKIP_TAGS.has(c.tagName) && isVisible(c));
if (rows.length < 2) return null;
const cssTable =
cs(el).display === 'table' &&
rows.every(
(row) =>
cs(row).display === 'table-row' &&
[...row.children]
.filter((cell) => !SKIP_TAGS.has(cell.tagName) && isVisible(cell))
.every((cell) => cs(cell).display === 'table-cell'),
);
const counts = rows.map((row) => {
const s = cs(row);
if (s.display !== 'grid' && !(cssTable && s.display === 'table-row')) return 0;
return [...row.children].filter((c) => !SKIP_TAGS.has(c.tagName) && isVisible(c)).length;
});
const base = Math.max(...counts);
if (base < 2 || base > 12) return null;
// CSS tables tolerate short rows (a lone header cell): the browser leaves
// the missing columns empty, so extractGridTable pads them with fillers.
// Grid rows keep the strict equal-count rule.
if (counts.some((count) => count !== base && !(cssTable && count >= 1))) return null;
if (counts.filter((count) => count === base).length < 2) return null;
const widths = rows.map((row) => Math.round(row.getBoundingClientRect().width));
if (Math.max(...widths) - Math.min(...widths) > 8) return null;
// Cells must sit in the same columns in every row: alternating layouts
// (timeline cards flipping left/right around a center rail) are grids of
// rows too, but mapping their cells positionally scrambles the columns.
const leftsOf = (row) =>
[...row.children]
.filter((c) => !SKIP_TAGS.has(c.tagName) && isVisible(c))
.map((c) => Math.round(c.getBoundingClientRect().left))
.sort((a, b) => a - b);
const firstLefts = leftsOf(rows[counts.indexOf(base)]);
for (const row of rows) {
const lefts = leftsOf(row);
if (lefts.length === base) {
if (lefts.some((left, i) => Math.abs(left - firstLefts[i]) > 12)) return null;
} else if (
lefts.some((left) => !firstLefts.some((columnLeft) => Math.abs(left - columnLeft) <= 12))
) {
return null;
}
}
// Avoid classifying arbitrary stacks of small grids as a data table.
if (!cssTable && rows.length < 4 && !fullBorderOf(el)) return null;
return rows;
}
function extractGridTable(el, gridRows, depth) {
const cellsOf = (row) =>
[...row.children].filter((c) => !SKIP_TAGS.has(c.tagName) && isVisible(c));
const baseRow = gridRows.reduce(
(best, row) => (cellsOf(row).length > cellsOf(best).length ? row : best),
gridRows[0],
);
const firstCells = cellsOf(baseRow);
const colWidths = firstCells.map((c) => Math.round(c.getBoundingClientRect().width));
const colLefts = firstCells.map((c) => Math.round(c.getBoundingClientRect().left));
const rows = gridRows.map((row, rowIdx) => {
const domCells = cellsOf(row);
let cells = domCells.map((cell) => {
const textAlign = textAlignOf(cell);
const entry = {
shading: bgHex(cell) || bgHex(row),
borders: bordersOf(cell),
padPx: cellPaddingOf(cell),
vAlign: cs(row).alignItems === 'center' ? 'center' : undefined,
rtl: isRTL(cell) || undefined,
};
if (textAlign === 'center' || textAlign === 'right') entry.align = textAlign;
entry.children = needsBlockWalk(cell)
? processChildren(cell, depth + 1, { decorations: false })
: paraNodesFrom(cell, false);
return entry;
});
// Short row (lone header cell in a CSS table): seat each cell in its
// geometric column and fill the rest with empty cells — unshaded, so
// they inherit the table background, same as the browser leaves them.
if (cells.length && cells.length < colWidths.length) {
const placed = new Array(colWidths.length).fill(null);
domCells.forEach((cell, i) => {
const left = Math.round(cell.getBoundingClientRect().left);
let col = colLefts.findIndex((columnLeft) => Math.abs(columnLeft - left) <= 12);
if (col < 0 || placed[col]) col = placed.findIndex((slot) => !slot);
placed[col] = cells[i];
});
cells = placed.map((entry) => entry || { children: [] });
}
const renderedHeight = Math.round(row.getBoundingClientRect().height);
return {
cells,
// Let text-driven rows use Word's natural compact height. Preserve
// only genuinely tall visual rows (planners / empty writing areas).
heightPx: renderedHeight >= 80 ? renderedHeight : undefined,
// Only a short strip reads as a repeatable header; a tall first row
// is content (card stacks) and would reprint on every page.
header: rowIdx === 0 && renderedHeight < 60,
};
});
return [{
type: 'table',
gridTable: true,
rows,
colWidths,
outerBorder: bordersOf(el),
shading: bgHex(el),
padPx: cellPaddingOf(el),
heightPx: Math.round(el.getBoundingClientRect().height),
rtl: isRTL(el) || undefined,
}];
}
function extractCode(el) {
const shading = bgHex(el) || 'F5F5F5';
const lines = el.innerText.replace(/\n$/, '').split('\n');
const { color, sizePx } = runStyleOf(el);
return [{ type: 'code', lines, shading, color, sizePx }];
}
function extractList(el, ordered, depth = 1) {
const listItems = [...el.children].filter((li) => li.tagName === 'LI' && isVisible(li));
// list-style:none -> the author wants plain paragraphs, not numbering.
// Judge by the items, not the UL: frameworks (pico.css) re-style the LI
// marker even when the UL itself says none.
const plain = listItems.length
? listItems.every(
(li) => cs(li).listStyleType === 'none' || cs(li).display !== 'list-item',
)
: cs(el).listStyleType === 'none';
const needsExactPseudoMarker = (li) =>
/[☑☐❋]/u.test(pseudoBulletRun(li)?.text || '');
const hasCompactPaintedLabels = listItems.some((li) =>
[...li.querySelectorAll(':scope > *')].some(isCompactPaintedLabel),
);
if (hasCompactPaintedLabels) return [markForScreenshot(el)];
// CSS multi-column list (columns: 2 on a TOC): reproduce as a layout
// table with one cell per rendered column. Numbering continues across
// columns, so synthesize literal number prefixes instead of Word lists.
const columnCount = parseInt(cs(el).columnCount, 10);
if (
depth <= 2 &&
Number.isFinite(columnCount) &&
columnCount >= 2 &&
listItems.length >= columnCount &&
listItems.every((li) => !hasBlockChildren(li))
) {
const lefts = listItems.map((li) => Math.round(li.getBoundingClientRect().left));
const uniqueLefts = [...new Set(lefts)].sort((a, b) => a - b);
if (uniqueLefts.length >= 2) {
const groups = uniqueLefts.map(() => []);
listItems.forEach((li, index) => {
groups[uniqueLefts.indexOf(lefts[index])].push({ li, index });
});
const cells = groups.map((group) => ({
children: group.flatMap(({ li, index }) => {
if (plain && needsExactPseudoMarker(li)) return [markForScreenshot(li)];
const runs = collectRuns(li);
if (!runs.length) return [];
const pseudoRun = pseudoBulletRun(li);
let prefixed = Boolean(pseudoRun);
if (pseudoRun) runs.unshift(pseudoRun);
else if (ordered) {
runs.unshift({ text: `${index + 1}. `, ...runStyleOf(li) });
prefixed = true;
} else if (!plain) {
runs.unshift({ text: '\u2022\u00a0', ...runStyleOf(li) });
prefixed = true;
}
const style = { ...paraStyleOf(el, false), ...paraStyleOf(li, false) };
delete style.indentLeftPx;
if (prefixed) {
const em = parseFloat(cs(li).fontSize) || 16;
style.indentHangingPx = Math.round(em * (ordered ? 1.1 : 0.8));
}
return [{ type: 'para', runs, style }];
}),
}));
const width = el.getBoundingClientRect().width || 1;
return [{
type: 'table',
layout: true,
rows: [{ cells: cells.map((cell, i) => ({ ...cell, gridStart: i, colspan: 1 })) }],
colWidths: uniqueLefts.map((left, i) =>
Math.round((i + 1 < uniqueLefts.length ? uniqueLefts[i + 1] : el.getBoundingClientRect().right) - left) || Math.round(width / uniqueLefts.length),
),
}];
}
}
// Layout list: display:flex items (numbered chip + content column) need
// the full classifier. Flattening them to runs drops the chip and
// inlines nested callout boxes into the text. Items too tall for a table
// row (isBoxRow rejects them) still get a block walk so nested dialogue
// bubbles / sub-lists survive.
// CSS-counter numbering ("counter(toc-counter)") never resolves through
// getComputedStyle; synthesize it from the item's position.
const counterPrefix = (li, index) => {
const pseudoStyle = getComputedStyle(li, '::before');
const content = pseudoStyle.content || '';
const counterStart = content.indexOf('counter(');
if (counterStart < 0) return null;
const counterEnd = content.indexOf(')', counterStart);
const quotedText = (part) =>
[...part.matchAll(/"([^"]*)"|'([^']*)'/g)]
.map((match) => match[1] ?? match[2] ?? '')
.join('');
const prefix = quotedText(content.slice(0, counterStart));
const suffix = quotedText(content.slice(counterEnd + 1));
let value = `${prefix}${index + 1}${suffix}`;
if (pseudoStyle.textTransform === 'uppercase') value = value.toUpperCase();
if (pseudoStyle.textTransform === 'lowercase') value = value.toLowerCase();
return value.endsWith(' ') ? value : `${value} `;
};
if (plain && listItems.some((li) => isBoxRow(li) || hasBlockChildren(li))) {
return listItems.flatMap((li, index) => {
if (isBoxRow(li)) return processElement(li, depth + 1);
// A counter badge glyph (❶) already carries the number — adding the
// synthesized plain counter text would double-number the item.
const bulletRun = pseudoBulletRun(li) || chipBulletRun(li);
const prefix = bulletRun ? null : counterPrefix(li, index);
if (hasBlockChildren(li)) {
const nodes = processChildren(li, depth + 1);
const first = nodes.find((n) => n.type === 'para');
if (first && bulletRun) first.runs = [bulletRun, ...first.runs];
if (first && prefix) first.runs = [{ text: prefix, ...runStyleOf(li) }, ...first.runs];
return nodes;
}
const runs = collectRuns(li);
if (!runs.length) return [];
if (prefix) runs.unshift({ text: prefix, ...runStyleOf(li) });
if (bulletRun) runs.unshift(bulletRun);
const style = { ...paraStyleOf(el), ...paraStyleOf(li) };
return [{ type: 'para', runs, style }];
});
}
const nativeMarkerOf = (li) => {
const itemStyle = cs(li);
if (itemStyle.display !== 'list-item' || itemStyle.listStyleType === 'none') return null;
const glyphs = {
disc: '\u2022',
circle: '\u25e6',
square: '\u25aa',
};
const glyph = glyphs[itemStyle.listStyleType];
if (!glyph) return null;
const runStyle = runStyleOf(li);
return {
run: {
text: `${glyph}\u00a0`,
color: runStyle.color,
sizePx: runStyle.sizePx,
fontFamily: runStyle.fontFamily,
},
widthPx: Math.max(10, Math.round((runStyle.sizePx || 14) * 1.05)),
};
};
const markers = listItems.map((li) => {
const first = [...li.children].find((child) => isVisible(child));
const nativeMarker = nativeMarkerOf(li);
if (first && isCheckboxLike(first)) {
const rect = first.getBoundingClientRect();
const itemStyle = cs(li);
return {
element: first,
widthPx: rect.width,
gapPx: parseFloat(itemStyle.columnGap) || parseFloat(itemStyle.gap) || 8,
nativeMarker,
};
}
const marker = pseudoCheckbox(li);
return marker ? { ...marker, nativeMarker } : null;
});
const checklist =
plain &&
listItems.length > 1 &&
markers.every(Boolean);
if (checklist) {
const listRect = el.getBoundingClientRect();
const firstColWidth = Math.round(
Math.max(
...markers.map(
(marker) => marker.widthPx + marker.gapPx + (marker.nativeMarker?.widthPx || 0),
),
),
);
const rows = listItems.map((li, index) => {
const children = [...li.children].filter((child) => isVisible(child));
const marker = markers[index];
const label = marker.element ? children.find((child) => child !== marker.element) : null;
const rowBorders = bordersOf(li);
const pad = cellPaddingOf(li);
const itemStyle = cs(li);
const itemParaStyle = paraStyleOf(li);
delete itemParaStyle.spacingBeforePx;
delete itemParaStyle.spacingAfterPx;
// The marker table already consumes the list item's left padding.
// Keeping it on the label paragraph would indent the text twice.
delete itemParaStyle.indentLeftPx;
const markerRuns = [];
if (marker.nativeMarker) markerRuns.push(marker.nativeMarker.run);
markerRuns.push(marker.element ? checkboxNode(marker.element) : checkboxRun(marker));
return {
heightPx: Math.round(
li.getBoundingClientRect().height + Math.max(0, parseFloat(itemStyle.marginBottom) || 0),
),
cells: [
{
runs: markerRuns,
borders: rowBorders || {},
padPx: { top: pad.top, bottom: pad.bottom, left: 0, right: marker.gapPx },
},
{
runs: label ? collectRuns(label) : collectRuns(li),
style: itemParaStyle,
borders: rowBorders || {},
padPx: { top: pad.top, bottom: pad.bottom, left: 0, right: 0 },
},
],
last: index === listItems.length - 1,
};
});
const listStyle = cs(el);
return [{
type: 'table',
checklist: true,
noHeader: true,
rows,
colWidths: [firstColWidth, Math.max(1, Math.round(listRect.width) - firstColWidth)],
spacingBeforePx: Math.max(0, Math.round(parseFloat(listStyle.marginTop) || 0)),
spacingAfterPx: Math.max(0, Math.round(parseFloat(listStyle.marginBottom) || 0)),
rtl: isRTL(el) || undefined,
}];
}
const items = [];
for (const li of listItems) {
items.push({ runs: collectRuns(li), style: paraStyleOf(li) });
}
if (!items.length) return [];
if (plain) {
return items
.filter((it) => it.runs.length)
.map((it, index) => {
const li = listItems[index];
if (needsExactPseudoMarker(li)) return markForScreenshot(li);
const style = { ...paraStyleOf(el), ...it.style };
const itemStyle = cs(li);
const paddingTop = parseFloat(itemStyle.paddingTop) || 0;
const paddingBottom = parseFloat(itemStyle.paddingBottom) || 0;
if (paddingTop > 0) style.spacingBeforePx = (style.spacingBeforePx || 0) + paddingTop;
if (paddingBottom > 0) style.spacingAfterPx = (style.spacingAfterPx || 0) + paddingBottom;
const bulletRun = pseudoBulletRun(li) || chipBulletRun(li);
if (bulletRun) it.runs.unshift(bulletRun);
else {
// list-style:none + ::before counter() (self-numbered rule
// lists): the marker lives in the pseudo-element, not the runs
const prefix = counterPrefix(li, index);
if (prefix) {
const pseudoWeight = parseInt(getComputedStyle(li, '::before').fontWeight, 10);
it.runs.unshift({
text: prefix,
...runStyleOf(li),
...(pseudoWeight >= 600 ? { bold: true } : {}),
});
const em = parseFloat(itemStyle.fontSize) || 16;
style.indentHangingPx = Math.round(em * 1.1);
}
}
return { type: 'para', runs: it.runs, style };
});
}
// <ol start="951">: Word numbering always restarts at 1 (startOverride
// is fixed), so lists with an authored start keep literal number
// prefixes instead — the TOC must match the 951-975 headings it links.
const startAt = ordered ? parseInt(el.getAttribute('start'), 10) : NaN;
if (Number.isFinite(startAt) && startAt !== 1 && listItems.every((li) => !hasBlockChildren(li))) {
return listItems.flatMap((li, index) => {
const runs = collectRuns(li);
if (!runs.length) return [];
runs.unshift({ text: `${startAt + index}. `, ...runStyleOf(li) });
const style = { ...paraStyleOf(el, false), ...paraStyleOf(li, false) };
const em = parseFloat(cs(li).fontSize) || 16;
style.indentHangingPx = Math.round(em * 1.6);
return [{ type: 'para', runs, style }];
});
}
const nestedItems = [];
// liIndex = ordinal of the top-level li each item came from, so column
// slicing can split a tall bullet list at li boundaries.
const appendListItems = (listEl, level, parentIndentPx, rootIndex) => {
const listStyle = cs(listEl);
const indentLeftPx = parentIndentPx + Math.max(0, parseFloat(listStyle.paddingLeft) || 0);
const childItems = [...listEl.children].filter(
(child) => child.tagName === 'LI' && isVisible(child),
);
for (let liOrdinal = 0; liOrdinal < childItems.length; liOrdinal++) {
const li = childItems[liOrdinal];
const liIndex = level === 0 ? liOrdinal : rootIndex;
// Walk li children in DOM order, splitting content around nested
// lists: text after a nested list must stay after it (a trailing
// "to perform..." clause hoisted above its sub-items inverts the
// reading order).
const segments = [];
let current = [];
for (const node of li.childNodes) {
const isList =
node.nodeType === Node.ELEMENT_NODE &&
(node.tagName === 'UL' || node.tagName === 'OL');
if (isList) {
if (isVisible(node)) {
segments.push({ content: current });
current = [];
segments.push({ list: node });
}
} else current.push(node);
}
segments.push({ content: current });
const style = paraStyleOf(li);
if (segments.some((seg) => seg.list)) delete style.spacingAfterPx;
let leading = true;
for (const seg of segments) {
if (seg.list) {
appendListItems(seg.list, level + 1, indentLeftPx, liIndex);
continue;
}
const runs = trimRuns(runsFromNodes(seg.content, li));
if (!runs.length) continue;
// A justified li with an explicit <br> keeps the break as \n in one
// paragraph — Word stretches the line BEFORE a manual break under
// justify (CSS never does), blowing huge gaps into short label
// lines. Split at the breaks like makeParaNodes: only the final
// fragment keeps justify (Word never stretches a last line).
const fragments = [runs];
if (style.align === 'justify' && runs.some((run) => (run.text || '').includes('\n'))) {
fragments.length = 0;
let currentLine = [];
for (const run of runs) {
const parts = (run.text || '').split('\n');
parts.forEach((part, partIndex) => {
if (part) currentLine.push({ ...run, text: part });
if (partIndex < parts.length - 1 && currentLine.length) {
fragments.push(currentLine);
currentLine = [];
}
});
}
if (currentLine.length) fragments.push(currentLine);
if (!fragments.length) fragments.push(runs);
}
fragments.forEach((fragmentRuns, fragmentIndex) => {
const fragmentStyle =
fragments.length > 1 && fragmentIndex < fragments.length - 1
? { ...style, align: undefined }
: style;
if (leading) {
nestedItems.push({
runs: fragmentRuns,
style: fragmentStyle,
level,
// ::before counter() numbering counts as ordered even on a UL
ordered:
listEl.tagName === 'OL' ||
(getComputedStyle(li, '::before').content || '').includes('counter('),
markerType: cs(li).listStyleType || listStyle.listStyleType,
indentLeftPx,
liIndex,
});
leading = false;
} else {
// continuation text of the same li: no marker, text-aligned indent
nestedItems.push({
runs: fragmentRuns,
style: fragmentStyle,
level,
continuation: true,
indentLeftPx,
liIndex,
});
}
});
}
}
};
appendListItems(el, 0, 0, 0);
return [{
type: 'list',
ordered,
items: nestedItems,
rtl: isRTL(el) || undefined,
}];
}
// A horizontal row of >=2 similar boxes (flex row / grid columns) -> kpirow
@@ -0,0 +1,176 @@
(function installFormsAndMediaExtractor(global) {
// Empty block/inline with only a bottom border is a fill-in underline
// (consent forms, contract blanks). Without this they collapse away.
function fillInLineNode(el, deps) {
const { bordersOf, cs } = deps;
if ((el.innerText || '').trim() || el.children.length) return null;
const borders = bordersOf(el);
// A signature rule drawn as border-top on a zero-height div is the same
// fill-in line as a border-bottom one.
const line =
borders?.bottom && !borders.top && !borders.left && !borders.right
? borders.bottom
: borders?.top && !borders.bottom && !borders.left && !borders.right
? borders.top
: null;
if (!line) return null;
const rect = el.getBoundingClientRect();
const style = cs(el);
const display = style.display;
const inline = display === 'inline' || display.startsWith('inline-');
// Empty inline blanks often report ~1px height (border only) while
// min-width still reserves the fill-in gap in the line.
const minWidth = parseFloat(style.minWidth) || 0;
const width = Math.max(rect.width, minWidth);
if (inline) {
if (width < 24 || width > 480 || rect.height > 40) return null;
} else if (width < 40 || rect.height > 48) {
return null;
}
return {
type: 'formfield',
mode: 'line',
controlType: 'text',
width: Math.round(width),
height: Math.round(Math.max(rect.height, 16)),
runs: [],
borders: { bottom: line },
inline,
};
}
// Empty fully-bordered writing area (form answer boxes with min-height).
// These are not checkboxes and must keep their authored height.
function fillInBoxNode(el, deps) {
const { bordersOf, cs, toHex, paintedBgHex, runStyleOf } = deps;
if ((el.innerText || '').trim() || el.children.length) return null;
const borders = bordersOf(el);
if (!borders?.top || !borders?.bottom || !borders?.left || !borders?.right) {
return null;
}
const style = cs(el);
const rect = el.getBoundingClientRect();
// An image container is not a fill-in blank: a div painted by
// background-image (even one whose URL now 404s and shows only the
// border ring) or shaped as a circle must stay on the screenshot path —
// as a formfield it rendered an opaque white box over the title.
if ((style.backgroundImage || '').includes('url(')) return null;
const radius = String(style.borderTopLeftRadius || '');
const radiusValue = parseFloat(radius) || 0;
// computed border-radius keeps authored percentages ("50%") as-is
const circle = radius.includes('%')
? radiusValue >= 40
: radiusValue >= Math.min(rect.width, rect.height) * 0.4;
if (circle) return null;
const minH = parseFloat(style.minHeight) || 0;
const height = Math.max(rect.height, minH);
if (height < 28 || rect.width < 48) return null;
// checkbox-sized squares stay on the checkbox path
if (rect.width <= 32 && height <= 32) return null;
const rawBg = toHex(style.backgroundColor);
// contenteditable answer boxes show their hint via
// :empty::before { content: attr(data-placeholder) } — resolve it so
// the box isn't exported empty
let placeholder = '';
const pseudo = getComputedStyle(el, '::before');
const pseudoContent = pseudo?.content || '';
const attrRef = pseudoContent.match(/attr\(([-\w]+)\)/);
if (attrRef) placeholder = el.getAttribute(attrRef[1]) || '';
else if (pseudoContent && pseudoContent !== 'none' && pseudoContent !== 'normal') {
placeholder = pseudoContent.replace(/^["']|["']$/g, '');
}
const placeholderColor = placeholder && pseudo ? toHex(pseudo.color) : null;
return {
type: 'formfield',
mode: 'box',
controlType: 'multiline',
width: Math.round(rect.width),
height: Math.round(height),
value: placeholder || undefined,
valueColor: placeholderColor || undefined,
runs: placeholder
? [{
text: placeholder,
...(runStyleOf ? runStyleOf(el) : {}),
...(placeholderColor ? { color: placeholderColor } : {}),
}]
: [],
borders,
shading: (paintedBgHex && paintedBgHex(el)) || rawBg || 'FFFFFF',
};
}
function formFieldNode(el, deps) {
const { bgHex, bordersOf, cellPaddingOf, cs, runStyleOf } = deps;
const rect = el.getBoundingClientRect();
cs(el);
const value = el.value || el.getAttribute('placeholder') || '';
const inputType = (el.getAttribute('type') || 'text').toLowerCase();
const controlType =
el.tagName === 'SELECT'
? 'dropdown'
: el.tagName === 'TEXTAREA'
? 'multiline'
: inputType === 'checkbox'
? 'checkbox'
: inputType === 'radio'
? 'radio'
: 'text';
const borders = bordersOf(el);
const hasOnlyBottomBorder =
borders &&
borders.bottom &&
!borders.top &&
!borders.left &&
!borders.right;
return {
type: 'formfield',
mode: hasOnlyBottomBorder ? 'line' : 'box',
controlType,
name: el.name || el.id || undefined,
alias: el.getAttribute('aria-label') || el.name || el.id || undefined,
value,
checked: Boolean(el.checked),
options:
el.tagName === 'SELECT'
? [...el.options].map((option) => ({
value: option.value,
label: option.textContent || option.value,
selected: option.selected,
}))
: undefined,
width: Math.round(rect.width),
height: Math.round(rect.height),
runs: value ? [{ text: value, ...runStyleOf(el) }] : [],
borders,
shading: bgHex(el),
padPx: cellPaddingOf(el),
};
}
function embeddedMediaNode(el, { markForScreenshot }) {
const rawHref =
el.tagName === 'IFRAME'
? el.src
: el.tagName === 'VIDEO' || el.tagName === 'AUDIO'
? el.currentSrc || el.src
: '';
const href = /^https?:/i.test(rawHref || '') ? rawHref : undefined;
return {
...markForScreenshot(el),
mediaType: el.tagName.toLowerCase(),
href,
fallbackText:
el.getAttribute('title') ||
el.getAttribute('aria-label') ||
`${el.tagName === 'IFRAME' ? 'Embedded content' : el.tagName === 'VIDEO' ? 'Video' : 'Audio'}`,
};
}
global.__html2docxFormsMedia = {
embeddedMediaNode,
fillInBoxNode,
fillInLineNode,
formFieldNode,
};
})(globalThis);
+779
View File
@@ -0,0 +1,779 @@
(function installPageExtractor(global) {
function build(deps) {
const {
cs,
docRTL,
isVisible,
markForScreenshot,
nextShotId,
processChildren,
processElement,
toHex,
} = deps;
const rootBodyStyle = cs(document.body);
const absoluteRootChildren = [...document.body.children].filter(
(child) => isVisible(child) && cs(child).position === 'absolute',
);
const bodyHeight = document.body.getBoundingClientRect().height;
const visibleBodyChildren = [...document.body.children].filter(isVisible);
const authoredPageRoots = visibleBodyChildren.filter(
(child) => child.hasAttribute('data-docx-page') || child.hasAttribute('data-page'),
);
const inferredPageRoots = visibleBodyChildren.filter((child) => {
if (authoredPageRoots.includes(child)) return false;
if (!isVisible(child)) return false;
const style = cs(child);
const rect = child.getBoundingClientRect();
return (
(style.breakAfter === 'page' || style.pageBreakAfter === 'always') &&
rect.width >= 300 &&
rect.height >= 400
);
});
const multiPageComposition = authoredPageRoots.length >= 2;
const mixedPageComposition = !multiPageComposition && inferredPageRoots.length >= 2;
const renderedPageHeight = window.innerHeight;
// Fixed-composition slide pages: page-sized relative sections whose
// direct children are absolutely positioned (coordinate layouts authored
// without data-docx-page). Flow classification drops the positioned
// content entirely, so rasterize each page like authored pages.
const slidePageRoots = visibleBodyChildren.filter((child) => {
if (authoredPageRoots.includes(child)) return false;
const style = cs(child);
if (style.position !== 'relative' && style.position !== 'absolute') return false;
const rect = child.getBoundingClientRect();
if (Math.abs(rect.height - renderedPageHeight) > renderedPageHeight * 0.08) return false;
if (rect.width < window.innerWidth * 0.8) return false;
const absoluteKids = [...child.children].filter(
(kid) => isVisible(kid) && cs(kid).position === 'absolute',
);
return absoluteKids.length >= 2 && (child.innerText || '').trim().length >= 20;
});
const slidePageComposition =
!multiPageComposition &&
!mixedPageComposition &&
slidePageRoots.length >= 2 &&
slidePageRoots.length >= visibleBodyChildren.length - 1;
const multiPageAbsoluteComposition =
!multiPageComposition &&
!mixedPageComposition &&
bodyHeight > renderedPageHeight &&
bodyHeight <= renderedPageHeight * 10 &&
absoluteRootChildren.some(
(child) => child.getBoundingClientRect().top >= renderedPageHeight - 2,
);
const activePageView = [...document.body.children].find(
(child) =>
isVisible(child) &&
child.classList.contains('page-view') &&
child.classList.contains('active-page'),
);
const fixedNavigation = [...document.body.children].some((child) => {
if (!isVisible(child)) return false;
const style = cs(child);
return (
(child.tagName === 'NAV' || child.tagName === 'HEADER') &&
(style.position === 'fixed' || style.position === 'sticky')
);
});
const webPageComposition =
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
Boolean(activePageView) &&
fixedNavigation &&
bodyHeight > renderedPageHeight &&
activePageView.querySelector('img') &&
activePageView.querySelector('.container, .row, [class*="grid"]');
const pageComposition =
(rootBodyStyle.position === 'relative' || rootBodyStyle.position === 'absolute') &&
rootBodyStyle.overflow === 'hidden' &&
bodyHeight >= 700 &&
bodyHeight <= 1600 &&
absoluteRootChildren.length >= 3 &&
(document.body.innerText || '').trim().length >= 20;
const singleVisualPageRoot = visibleBodyChildren.length === 1 ? visibleBodyChildren[0] : null;
const singleVisualPageRect = singleVisualPageRoot?.getBoundingClientRect();
const singleVisualPageStyle = singleVisualPageRoot ? cs(singleVisualPageRoot) : null;
const singleVisualPagePaint =
singleVisualPageStyle &&
(singleVisualPageStyle.backgroundImage !== 'none' ||
Boolean(toHex(singleVisualPageStyle.backgroundColor, { dropWhite: true })));
const singleVisualPageLayout = singleVisualPageRoot
? [...singleVisualPageRoot.querySelectorAll('*')].some((element) => {
const style = cs(element);
return (
(style.display === 'grid' && style.gridTemplateColumns.split(' ').length >= 2) ||
(style.display === 'flex' &&
(style.flexDirection === 'row' || style.flexDirection === ''))
);
})
: false;
const flowingVisualComposition =
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
!webPageComposition &&
!pageComposition &&
Boolean(singleVisualPageRoot) &&
singleVisualPageStyle.position === 'relative' &&
(singleVisualPageStyle.overflow === 'hidden' ||
singleVisualPageStyle.overflow === 'clip') &&
singleVisualPagePaint &&
singleVisualPageLayout &&
singleVisualPageRect.width >= window.innerWidth * 0.7 &&
singleVisualPageRect.height > renderedPageHeight * 1.05 &&
singleVisualPageRect.height <= renderedPageHeight * 3 &&
(singleVisualPageRoot.innerText || '').trim().length >= 20;
const singlePageVisualComposition =
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
!webPageComposition &&
!pageComposition &&
!flowingVisualComposition &&
Boolean(singleVisualPageRoot) &&
(singleVisualPageStyle.position === 'relative' ||
singleVisualPageStyle.position === 'absolute') &&
(singleVisualPageStyle.overflow === 'hidden' ||
singleVisualPageStyle.overflow === 'clip') &&
singleVisualPagePaint &&
singleVisualPageRect.width >= window.innerWidth * 0.7 &&
singleVisualPageRect.height >= renderedPageHeight * 0.7 &&
singleVisualPageRect.height <= renderedPageHeight * 1.35 &&
(singleVisualPageRoot.innerText || '').trim().length >= 20;
const bodySinglePageVisualComposition =
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
!webPageComposition &&
!pageComposition &&
!singlePageVisualComposition &&
rootBodyStyle.position === 'relative' &&
rootBodyStyle.backgroundImage !== 'none' &&
rootBodyStyle.maxWidth !== 'none' &&
visibleBodyChildren.length >= 2 &&
visibleBodyChildren.length <= 5 &&
bodyHeight >= renderedPageHeight * 0.7 &&
bodyHeight <= renderedPageHeight * 1.35 &&
(document.body.innerText || '').trim().length >= 20;
const bodyRect = document.body.getBoundingClientRect();
// Word (Mac) insets the first line ~26px below the page top even at zero
// margins, so a slice scaled to the full content height loses its bottom
// rows to the page edge. Budget slices below the page height so the
// width-driven scale governs every slice (uniform scale across pages)
// and Word never clips a pixel row. Matches the 45px renderer headroom:
// 1 - 45/1123.
const sliceBudget = Math.round(renderedPageHeight * 0.96);
// Bands (y ranges relative to body top) a slice boundary must not cross:
// text lines and replaced elements always; painted card boxes when small
// enough to move to the next page whole.
const collectCutBands = () => {
const lineBands = [];
const boxBands = [];
const push = (bands, rect) => {
if (rect.height > 0 && rect.width > 0) {
bands.push({ top: rect.top - bodyRect.top, bottom: rect.bottom - bodyRect.top });
}
};
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const textNode = walker.currentNode;
if (!textNode.textContent.trim()) continue;
const range = document.createRange();
range.selectNodeContents(textNode);
for (const rect of range.getClientRects()) push(lineBands, rect);
}
for (const element of document.body.querySelectorAll('*')) {
if (!isVisible(element)) continue;
const rect = element.getBoundingClientRect();
if (rect.height <= 0 || rect.width <= 0) continue;
if (
element.matches('img, svg, canvas, video, iframe, input, textarea, select, button')
) {
push(lineBands, rect);
continue;
}
if (rect.height < 40 || rect.height > sliceBudget * 0.9) continue;
const style = cs(element);
// dropWhite:false — an explicit white card on a tinted page is still
// a visual card whose rows must not be split across pages.
const painted =
style.backgroundImage !== 'none' ||
style.boxShadow !== 'none' ||
Boolean(toHex(style.backgroundColor, { dropWhite: false })) ||
parseFloat(style.borderTopWidth) > 0 ||
parseFloat(style.borderBottomWidth) > 0;
if (painted) push(boxBands, rect);
}
return { lineBands, boxBands };
};
const chooseCut = (ideal, minCut, bands) => {
const clearance = 3;
for (let y = ideal; y >= minCut; y -= 2) {
const blocked = bands.some(
(band) => band.top < y + clearance && band.bottom > y - clearance,
);
if (!blocked) return y;
}
return null;
};
const sliceBoundaries = () => {
// A composition only slightly taller than one page reads as a
// single-page design (e.g. a resume): render one full slice and let
// the renderer's page scale absorb the few percent, instead of
// stranding a couple of lines on a second page.
if (bodyHeight <= sliceBudget * 1.12) return [Math.round(bodyHeight)];
const { lineBands, boxBands } = collectCutBands();
const allBands = [...lineBands, ...boxBands];
const boundaries = [];
let cursor = 0;
while (bodyHeight - cursor > sliceBudget) {
const ideal = cursor + sliceBudget;
const minCut = cursor + Math.round(sliceBudget * 0.6);
// Whole cards move to the next page when a gap exists; otherwise cut
// between text lines inside the card; otherwise hard-cut.
const cut =
chooseCut(ideal, minCut, allBands) ??
chooseCut(ideal, minCut, lineBands) ??
ideal;
boundaries.push(cut);
cursor = cut;
}
boundaries.push(Math.round(bodyHeight));
// Trailing sliver: absorb a short final slice into the previous page
// when the merged slice still fits with a small page-scale shrink.
if (boundaries.length >= 2) {
const previousStart = boundaries.length >= 3 ? boundaries[boundaries.length - 3] : 0;
const lastStart = boundaries[boundaries.length - 2];
if (
bodyHeight - lastStart <= sliceBudget * 0.25 &&
bodyHeight - previousStart <= sliceBudget * 1.12
) {
boundaries.splice(boundaries.length - 2, 1);
}
}
return boundaries;
};
const screenshotPageSlices = ({ authoredPageHeights = false } = {}) => {
// Absolutely-positioned multi-page canvases are authored in exact
// viewport-height pages: gap-aware cuts would shift authored page
// boundaries, so slice at the authored pitch and let the renderer
// headroom shrink each page to fit.
const boundaries = authoredPageHeights
? Array.from(
{ length: Math.ceil(bodyHeight / renderedPageHeight) },
(_, index) => Math.min(bodyHeight, (index + 1) * renderedPageHeight),
)
: sliceBoundaries();
// Decorative absolutes bleeding past the body's box (half-out hero
// circles) get flat-cut by a body-width clip. Extend the horizontal
// extent to overhanging descendants that still touch the body band —
// capped so parked off-screen decorations (left/right: -10000px)
// never drag the clip away.
let paintLeft = bodyRect.left;
let paintRight = bodyRect.right;
const maxBleed = 200;
for (const d of document.body.querySelectorAll('*')) {
const dr = d.getBoundingClientRect();
if (!dr.width || !dr.height) continue;
if (dr.right <= bodyRect.left - maxBleed || dr.left >= bodyRect.right + maxBleed) continue;
if (dr.left < paintLeft) paintLeft = Math.max(dr.left, bodyRect.left - maxBleed);
if (dr.right > paintRight) paintRight = Math.min(dr.right, bodyRect.right + maxBleed);
}
paintLeft = Math.max(0, Math.round(paintLeft));
const paintWidth = Math.round(paintRight - paintLeft);
let previousBoundary = 0;
return boundaries.map((boundary) => {
const sliceHeight = Math.round(boundary - previousBoundary);
const sliceTop = previousBoundary;
previousBoundary = boundary;
return {
type: 'image',
shotId: nextShotId(),
width: paintWidth,
height: sliceHeight,
align: 'center',
pageComposition: true,
capturesDocumentText: true,
clip: {
x: paintLeft,
y: Math.max(0, Math.round(bodyRect.top + sliceTop)),
width: paintWidth,
height: sliceHeight,
},
};
});
};
const buildMixedPageIr = () => {
const output = [];
const pageRoots = new Set(inferredPageRoots);
let pendingPageBreak = false;
let previousPageRootFillsPage = false;
const append = (nodes) => {
for (const node of nodes) {
if (
node.type === 'pagebreak' &&
(!output.length || output[output.length - 1].type === 'pagebreak')
) {
continue;
}
output.push(node);
}
};
for (const child of visibleBodyChildren) {
const style = cs(child);
const isPageRoot = pageRoots.has(child);
const breaksBefore =
style.breakBefore === 'page' || style.pageBreakBefore === 'always';
const naturalPageAdvance = pendingPageBreak && previousPageRootFillsPage;
if (
!naturalPageAdvance &&
(pendingPageBreak || (isPageRoot && breaksBefore)) &&
output.length
) {
append([{ type: 'pagebreak' }]);
}
const nodes = isPageRoot
? [{ ...markForScreenshot(child), pageComposition: true }]
: processElement(child, 0);
if (naturalPageAdvance && nodes[0]?.type === 'pagebreak') nodes.shift();
append(nodes);
pendingPageBreak =
style.breakAfter === 'page' || style.pageBreakAfter === 'always';
previousPageRootFillsPage =
isPageRoot &&
child.getBoundingClientRect().height >= renderedPageHeight - 12;
}
return output;
};
const ir = multiPageComposition
? authoredPageRoots.flatMap((page, index) => [
...(index > 0 ? [{ type: 'pagebreak' }] : []),
{ ...markForScreenshot(page), pageComposition: true },
])
: slidePageComposition
? slidePageRoots.flatMap((page, index) => [
...(index > 0 ? [{ type: 'pagebreak' }] : []),
{ ...markForScreenshot(page), pageComposition: true },
])
: mixedPageComposition
? buildMixedPageIr()
: webPageComposition
? screenshotPageSlices()
: multiPageAbsoluteComposition
? screenshotPageSlices({ authoredPageHeights: true })
: flowingVisualComposition
? screenshotPageSlices()
: singlePageVisualComposition
? [{ ...markForScreenshot(singleVisualPageRoot), pageComposition: true }]
: bodySinglePageVisualComposition
? [{ ...markForScreenshot(document.body), pageComposition: true }]
: pageComposition
? [{ ...markForScreenshot(document.body), pageComposition: true }]
: processChildren(document.body, 0);
while (ir.length && ir[0].type === 'pagebreak') ir.shift();
for (let index = ir.length - 1; index >= 0; index--) {
const node = ir[index];
if (
node.type !== 'image' ||
node.clip ||
node.pageComposition ||
node.height <= 1000
) {
continue;
}
const element = document.querySelector(`[data-h2d-id="${node.shotId}"]`);
if (!element) continue;
const rect = element.getBoundingClientRect();
const maxSliceHeight = 700;
const sliceCount = Math.ceil(rect.height / maxSliceHeight);
const slices = Array.from({ length: sliceCount }, (_, sliceIndex) => {
const sliceHeight = Math.min(
maxSliceHeight,
rect.height - sliceIndex * maxSliceHeight,
);
return {
...node,
shotId: sliceIndex === 0 ? node.shotId : nextShotId(),
height: Math.round(sliceHeight),
spacingBeforePx: sliceIndex === 0 ? node.spacingBeforePx : 0,
spacingAfterPx:
sliceIndex === sliceCount - 1 ? node.spacingAfterPx : 0,
clip: {
x: Math.max(0, Math.round(rect.left)),
y: Math.max(0, Math.round(rect.top + sliceIndex * maxSliceHeight)),
width: Math.round(rect.width),
height: Math.round(sliceHeight),
},
};
});
ir.splice(index, 1, ...slices);
}
// A centered "paper sheet" holding all the content on a tinted desk
// backdrop (body bg + one max-width/box-shadow child): the desk color is
// screen chrome, the sheet IS the page — take its paint instead.
const paperSheet = (() => {
const kids = [...document.body.children].filter(
(child) =>
isVisible(child) &&
((child.innerText || '').trim() || child.querySelector('img,svg,canvas,table')),
);
if (kids.length !== 1) return null;
const el = kids[0];
const st = cs(el);
if (!toHex(st.backgroundColor, { dropWhite: false })) return null;
const rect = el.getBoundingClientRect();
const centered = Math.abs(rect.left - (window.innerWidth - rect.right)) <= 24;
const coversContent = rect.height >= document.body.scrollHeight * 0.8;
const sheetLike = st.boxShadow !== 'none' || parseFloat(st.maxWidth) > 0;
return centered && coversContent && sheetLike ? el : null;
})();
const bodyBackground = toHex(cs(document.body).backgroundColor, {
dropWhite: false,
});
// The desk-vs-sheet call only holds for neutral backdrops: a saturated
// color or gradient behind the sheet is poster design, not screen chrome.
const backdropDesigned = (() => {
if (cs(document.body).backgroundImage.includes('gradient')) return true;
if (!bodyBackground) return false;
const channels = [0, 2, 4].map((i) => parseInt(bodyBackground.slice(i, i + 2), 16));
return Math.max(...channels) - Math.min(...channels) > 24;
})();
const deskSheet = backdropDesigned ? null : paperSheet;
const pageBg = deskSheet
? toHex(cs(deskSheet).backgroundColor, { dropWhite: true })
: bodyBackground
? toHex(cs(document.body).backgroundColor, { dropWhite: true })
: toHex(cs(document.documentElement).backgroundColor, { dropWhite: true });
const bodyHasPaint =
!deskSheet &&
(cs(document.body).backgroundImage !== 'none' || Boolean(bodyBackground));
const bgSource = bodyHasPaint ? document.body : document.documentElement;
const bgStyle = cs(bgSource);
const pagePseudoPaints = (which) => {
const pseudo = getComputedStyle(bgSource, which);
if (!pseudo || pseudo.content === 'none' || pseudo.content === 'normal') return false;
const hasBorder = ['Top', 'Right', 'Bottom', 'Left'].some(
(side) =>
parseFloat(pseudo[`border${side}Width`]) >= 1 &&
pseudo[`border${side}Style`] !== 'none',
);
return (
hasBorder ||
pseudo.backgroundImage !== 'none' ||
Boolean(toHex(pseudo.backgroundColor, { dropWhite: true }))
);
};
// a flat solid body color needs no backdrop screenshot: w:background
// renders the exact hex, while the header-image route's resampled tone
// visibly differs from same-color shading fills on content blocks
const backdropHasArt =
bgStyle.backgroundImage !== 'none' ||
pagePseudoPaints('::before') ||
pagePseudoPaints('::after') ||
Boolean(paperSheet && backdropDesigned);
if (
!pageComposition &&
!multiPageComposition &&
!mixedPageComposition &&
!multiPageAbsoluteComposition &&
!webPageComposition &&
!flowingVisualComposition &&
!singlePageVisualComposition &&
!bodySinglePageVisualComposition &&
backdropHasArt
) {
const backdrop = document.createElement('div');
const width = window.innerWidth;
const height = window.innerHeight;
// park off-screen on the side the document ignores for overflow:
// in RTL, left-side overflow extends the scrollable area and shifts
// the capture surface origin, blanking every later element screenshot
const rtlDoc =
cs(document.documentElement).direction === 'rtl' ||
cs(document.body).direction === 'rtl';
Object.assign(backdrop.style, {
position: 'absolute',
[rtlDoc ? 'right' : 'left']: '-10000px',
top: '0',
width: `${width}px`,
height: `${height}px`,
backgroundColor: pageBg ? `#${pageBg}` : bgStyle.backgroundColor,
backgroundImage: bgStyle.backgroundImage,
backgroundSize: bgStyle.backgroundSize,
backgroundPosition: bgStyle.backgroundPosition,
backgroundRepeat: bgStyle.backgroundRepeat,
pointerEvents: 'none',
});
const appendPagePseudo = (which) => {
const pseudo = getComputedStyle(bgSource, which);
if (!pseudo || pseudo.content === 'none' || pseudo.content === 'normal') return;
const hasBorder = ['Top', 'Right', 'Bottom', 'Left'].some(
(side) =>
parseFloat(pseudo[`border${side}Width`]) >= 1 &&
pseudo[`border${side}Style`] !== 'none',
);
const hasPaint =
pseudo.backgroundImage !== 'none' ||
Boolean(toHex(pseudo.backgroundColor, { dropWhite: true }));
if (!hasBorder && !hasPaint) return;
const overlay = document.createElement('div');
Object.assign(overlay.style, {
position: 'absolute',
top: pseudo.top === 'auto' ? '0' : pseudo.top,
right: pseudo.right === 'auto' ? '0' : pseudo.right,
bottom: pseudo.bottom === 'auto' ? '0' : pseudo.bottom,
left: pseudo.left === 'auto' ? '0' : pseudo.left,
boxSizing: 'border-box',
backgroundColor: pseudo.backgroundColor,
backgroundImage: pseudo.backgroundImage,
backgroundSize: pseudo.backgroundSize,
backgroundPosition: pseudo.backgroundPosition,
backgroundRepeat: pseudo.backgroundRepeat,
borderTop: pseudo.borderTop,
borderRight: pseudo.borderRight,
borderBottom: pseudo.borderBottom,
borderLeft: pseudo.borderLeft,
opacity: pseudo.opacity,
});
backdrop.appendChild(overlay);
};
appendPagePseudo('::before');
appendPagePseudo('::after');
// Designed backdrop with a content sheet on top (poster on gradient):
// paint the sheet's box into the backdrop so page chrome = backdrop +
// sheet, and the flowing text keeps its readable card behind it.
if (paperSheet && backdropDesigned) {
const sheetRect = paperSheet.getBoundingClientRect();
const sheetStyle = cs(paperSheet);
const sheet = document.createElement('div');
Object.assign(sheet.style, {
position: 'absolute',
left: `${Math.round(sheetRect.left)}px`,
top: `${Math.round(Math.max(0, sheetRect.top))}px`,
width: `${Math.round(sheetRect.width)}px`,
height: `${Math.round(Math.max(100, height - Math.max(0, sheetRect.top)))}px`,
backgroundColor: sheetStyle.backgroundColor,
borderRadius: sheetStyle.borderRadius,
boxShadow: sheetStyle.boxShadow,
});
backdrop.appendChild(sheet);
}
document.body.appendChild(backdrop);
const shot = markForScreenshot(backdrop);
ir.unshift({
type: 'pagebg',
color: pageBg,
shotId: shot.shotId,
width,
height,
});
} else if (pageBg) {
ir.unshift({ type: 'pagebg', color: pageBg });
}
for (let index = ir.length - 1; index > 0; index--) {
if (ir[index].type === 'pagebreak' && ir[index - 1].type === 'spacer') {
ir.splice(index - 1, 1);
}
}
// Section boundaries stack spacers (padding-bottom + divider walk +
// padding-top emitted by different branches): the real CSS gap is the
// two paddings, so keep the two largest of a run and drop the rest.
for (let index = ir.length - 1; index >= 0; index--) {
if (ir[index].type !== 'spacer' || ir[index].bindsNeighbors) continue;
let first = index;
while (first > 0 && ir[first - 1].type === 'spacer' && !ir[first - 1].bindsNeighbors) first--;
if (first === index) continue;
const run = ir.slice(first, index + 1).map((node) => node.px || 0).sort((a, b) => b - a);
const merged = Math.min(260, run[0] + (run[1] || 0));
ir.splice(first, index - first + 1, { type: 'spacer', px: merged });
index = first;
}
const lastContent = ir[ir.length - 1];
if (lastContent?.spacingAfterPx != null) lastContent.spacingAfterPx = 0;
if (lastContent?.style?.spacingAfterPx != null) lastContent.style.spacingAfterPx = 0;
const bodyStyle = cs(document.body);
const cssLengthPx = (value) => {
const match = String(value || '').trim().match(/^([\d.]+)(px|pt|in|cm|mm)?$/i);
if (!match) return null;
const amount = parseFloat(match[1]);
return (
amount *
({ px: 1, pt: 96 / 72, in: 96, cm: 96 / 2.54, mm: 96 / 25.4 }[
(match[2] || 'px').toLowerCase()
] || 1)
);
};
const namedPageSizes = {
a3: [1123, 1587],
a4: [794, 1123],
a5: [559, 794],
letter: [816, 1056],
legal: [816, 1344],
tabloid: [1056, 1632],
ledger: [1632, 1056],
};
let pageSizePx = null;
for (const sheet of [...document.styleSheets]) {
let rules;
try {
rules = [...sheet.cssRules];
} catch {
continue;
}
for (const rule of rules) {
if (rule.type !== CSSRule.PAGE_RULE) continue;
const parts = (rule.style.getPropertyValue('size') || '').trim().toLowerCase().split(/\s+/);
const orientation = parts.find((part) => part === 'landscape' || part === 'portrait');
const named = parts.find((part) => namedPageSizes[part]);
if (named) {
pageSizePx = [...namedPageSizes[named]];
} else {
const lengths = parts.map(cssLengthPx).filter((value) => value != null);
if (lengths.length >= 2) pageSizePx = [lengths[0], lengths[1]];
else if (lengths.length === 1) pageSizePx = [lengths[0], lengths[0] * Math.SQRT2];
}
if (pageSizePx && orientation === 'landscape' && pageSizePx[0] < pageSizePx[1]) {
pageSizePx.reverse();
}
if (pageSizePx && orientation === 'portrait' && pageSizePx[0] > pageSizePx[1]) {
pageSizePx.reverse();
}
break;
}
if (pageSizePx) break;
}
if (!pageSizePx && (multiPageComposition || mixedPageComposition)) {
const pageRect = (authoredPageRoots[0] || inferredPageRoots[0]).getBoundingClientRect();
pageSizePx = [pageRect.width, pageRect.height];
} else if (!pageSizePx && multiPageAbsoluteComposition) {
pageSizePx = [bodyRect.width, renderedPageHeight];
} else if (!pageSizePx && pageComposition) {
pageSizePx = [bodyRect.width, bodyRect.height];
}
pageSizePx ||= [794, 1123];
const composed =
pageComposition ||
multiPageComposition ||
slidePageComposition ||
mixedPageComposition ||
multiPageAbsoluteComposition ||
webPageComposition ||
flowingVisualComposition ||
singlePageVisualComposition ||
bodySinglePageVisualComposition;
// A natively-rendered flow document slightly taller than one page (e.g. a
// resume that strands two lines on page 2) reads as a one-page design.
// Word lays such docs out ~10% denser than the browser proxy (narrower
// Arial + width scale), so browser ratios up to ~1.22 are recoverable
// with a small whole-document squeeze applied to geometry and fonts.
// ratio against the page height at the ACTUAL viewport width — the
// viewport height is not resized when the authored width differs, so
// innerHeight is the wrong denominator there (880-wide doc in a
// 1024-proportioned window read as 0.95 pages instead of 1.11)
const flowCanvasWidth = Math.min(
window.innerWidth,
Math.max(Math.round(pageSizePx[0]), Math.ceil(bodyRect.width)),
);
const flowPageHeight = flowCanvasWidth * (pageSizePx[1] / pageSizePx[0]);
const flowRatio = bodyHeight / flowPageHeight;
const squeezableFlow = !composed && !authoredPageRoots.length && !inferredPageRoots.length;
(globalThis.__h2dTrace ||= []).push({
where: 'pageFitSqueeze',
flowRatio: Math.round(flowRatio * 1000) / 1000,
bodyHeight: Math.round(bodyHeight),
renderedPageHeight,
composed: Boolean(composed),
authoredRoots: authoredPageRoots.length,
inferredRoots: inferredPageRoots.length,
});
// Word lays text-heavy docs ~10% denser than the browser proxy (narrower
// Arial), which the 0.9 fudge credits. Table/fixed-height-heavy docs get
// no such densening, so past ~1.05 the fudge under-squeezes and the last
// block still strands (invoice stamp boxes) — taper the credit away.
const pageFitSqueeze =
squeezableFlow && flowRatio > 1.05 && flowRatio <= 1.22
? // table/fixed-height-heavy docs (invoices) get none of the Arial
// densening the 0.9 fudge below assumes — squeeze at face value
// plus slack so the trailing block doesn't strand by one line
// 0.90/0.82 (was 0.92/0.84): Word (Mac) lays these table-heavy
// docs up to ~9% taller than the browser proxy — the old floor
// left a marginal one-pager's footer stranding on page 2
Math.max(0.8, Math.min(1, 0.88 / flowRatio))
: squeezableFlow && flowRatio > 1.02 && flowRatio <= 1.05
? Math.max(0.88, Math.min(1, 0.98 / (flowRatio * 0.9)))
: // A doc filling exactly one browser page (invoices, forms) is a
// one-page design; Word's layout runs a few percent taller (table
// leading, min row heights), so squeeze preemptively.
squeezableFlow && flowRatio > 0.96 && flowRatio <= 1.02
? 0.94
: 1;
// A viewport wider than the authored canvas (1024 reload of a
// letter-width design) centers the body with auto margins — a viewport
// artifact, not an authored page margin. Measure against the canvas and
// strip the centering offset, or the page gets ~3cm fake margins and the
// content shrinks by the canvas/viewport ratio.
const canvasWidth = Math.min(
window.innerWidth,
Math.max(Math.round(pageSizePx[0]), Math.ceil(bodyRect.width)),
);
const centerOffset = Math.max(0, (window.innerWidth - canvasWidth) / 2);
// flowed documents get a small margin floor: an authored padding:0 body
// puts Word text hard against the physical page edge, which no print
// layout intends; composed pages keep exact geometry. The floor widens
// the margins beyond the measured geometry, so the reported canvas must
// widen by the same amount or the px->page scale over-sizes the content
// and Word clips it at the right margin.
const rawLeftPx = composed
? Math.max(0, Math.round(bodyRect.left - centerOffset))
: Math.max(
0,
Math.round(bodyRect.left - centerOffset + (parseFloat(bodyStyle.paddingLeft) || 0)),
);
const rawRightPx = Math.max(
0,
composed
? Math.round(canvasWidth - (bodyRect.right - centerOffset))
: Math.round(
canvasWidth -
(bodyRect.right - centerOffset) +
(parseFloat(bodyStyle.paddingRight) || 0),
),
);
const leftPx = composed ? rawLeftPx : Math.max(24, rawLeftPx);
const rightPx = composed ? rawRightPx : Math.max(24, rawRightPx);
const metaContent = (name) =>
document.querySelector(`meta[name="${name}" i]`)?.content?.trim() || undefined;
ir.unshift({
type: 'docsettings',
viewportWidthPx: canvasWidth + (leftPx - rawLeftPx) + (rightPx - rawRightPx),
rtl: docRTL || undefined,
lang: document.documentElement.lang || undefined,
meta: {
title: (document.title || '').trim() || undefined,
author: metaContent('author'),
description: metaContent('description'),
keywords: metaContent('keywords'),
},
composed: composed || undefined,
pageFitSqueeze: pageFitSqueeze < 1 ? pageFitSqueeze : undefined,
pageSizePx: { width: Math.round(pageSizePx[0]), height: Math.round(pageSizePx[1]) },
marginsPx: {
top: composed
? Math.max(0, Math.round(bodyRect.top))
: Math.max(24, Math.round(bodyRect.top + (parseFloat(bodyStyle.paddingTop) || 0))),
bottom: composed
? 0
: Math.max(24, Math.round(parseFloat(bodyStyle.paddingBottom) || 0)),
left: leftPx,
right: rightPx,
},
});
return ir;
}
global.__html2docxPages = { build };
})(globalThis);
+295
View File
@@ -0,0 +1,295 @@
(function installHtmlTableExtractor(global) {
function extractTable(el, deps) {
const {
bgHex,
isCompactPaintedLabel,
bordersOf,
cellPaddingOf,
collectRuns,
cs,
hasBlockChildren,
isRTL,
isVisible,
markForScreenshot,
processChildren,
textAlignOf,
toHex,
} = deps;
// Gradient-painted cells (th { background: linear-gradient(...) }) have a
// transparent backgroundColor; approximate with the first gradient stop so
// white header text doesn't land on a white cell.
const gradHex = (node) => {
const bgImage = cs(node).backgroundImage;
if (!bgImage || !bgImage.includes('gradient')) return null;
const m = bgImage.match(/rgba?\([^)]*\)|#[0-9a-fA-F]{3,8}/);
return m ? toHex(m[0]) : null;
};
const cellShading = (cell, tr) => {
const own = bgHex(cell) || gradHex(cell);
if (own) return own;
const behind = bgHex(tr) || gradHex(tr);
if (!behind) return null;
// A cell's own opaque paint (even white, which bgHex drops) covers the
// row color — without this the row bleeds through and the cell's dark
// text lands on dark row shading.
return toHex(cs(cell).backgroundColor) || behind;
};
const rows = [];
const boundarySamples = [];
const activeSpans = [];
let gridColumnCount = 0;
const tableRect = el.getBoundingClientRect();
const tableRows = [...el.querySelectorAll(
':scope > thead > tr, :scope > tbody > tr, :scope > tfoot > tr, :scope > tr',
)];
for (let rowIndex = 0; rowIndex < tableRows.length; rowIndex++) {
const tr = tableRows[rowIndex];
if (!isVisible(tr)) continue;
const cells = [];
const rowBorders = bordersOf(tr);
const occupied = new Set();
for (const span of activeSpans) {
if (span.endRow <= rowIndex) continue;
for (let col = span.gridStart; col < span.gridStart + span.colspan; col++) {
occupied.add(col);
}
cells.push({
...span.cell,
runs: [],
children: undefined,
gridStart: span.gridStart,
verticalMerge: 'continue',
});
}
const directCells = [...tr.children].filter(
(cell) => cell.tagName === 'TD' || cell.tagName === 'TH',
);
const exactVisualRow = directCells.some(
(cell) => [...cell.children].filter(isCompactPaintedLabel).length >= 2,
);
if (exactVisualRow && !activeSpans.some((span) => span.endRow > rowIndex)) {
const colspan = directCells.reduce((sum, cell) => sum + (cell.colSpan || 1), 0);
cells.push({
colspan,
rowspan: 1,
gridStart: 0,
children: [markForScreenshot(tr)],
borders: {},
padPx: { top: 0, right: 0, bottom: 0, left: 0 },
});
const rect = tr.getBoundingClientRect();
(boundarySamples[0] ||= []).push(rect.left - tableRect.left);
(boundarySamples[colspan] ||= []).push(rect.right - tableRect.left);
gridColumnCount = Math.max(gridColumnCount, colspan);
rows.push({ cells, heightPx: Math.round(rect.height) });
continue;
}
let nextColumn = 0;
for (const cell of tr.children) {
if (cell.tagName !== 'TD' && cell.tagName !== 'TH') continue;
const colspan = cell.colSpan || 1;
while (
[...Array(colspan).keys()].some((offset) => occupied.has(nextColumn + offset))
) {
nextColumn++;
}
const rowspan = cell.rowSpan || 1;
const entry = {
colspan,
rowspan,
gridStart: nextColumn,
verticalMerge: rowspan > 1 ? 'restart' : undefined,
shading: cellShading(cell, tr),
bold: cell.tagName === 'TH' || undefined,
borders: bordersOf(cell) || rowBorders,
padPx: cellPaddingOf(cell),
rtl: isRTL(cell) || undefined,
};
const textAlign = textAlignOf(cell);
if (textAlign === 'center' || textAlign === 'right') entry.align = textAlign;
const verticalAlign = cs(cell).verticalAlign;
if (verticalAlign === 'middle') entry.vAlign = 'center';
else if (verticalAlign === 'bottom') entry.vAlign = 'bottom';
// decorations: false - the cell entry already owns border/shading;
// paragraphs merged from the cell's inline children must not inherit
// the td's border as a paragraph border (drew stray lines inside cells)
if (hasBlockChildren(cell)) {
entry.children = processChildren(cell, 2, { decorations: false });
}
else {
entry.runs = collectRuns(cell);
// CJK cell text: with no explicit line height Word applies the CJK
// font's own leading (Yu Mincho ≈1.7x) — uncapped, invoice rows
// balloon and push a one-page layout onto a second page. Pin the
// browser's line box; skip tight leadings that EXACT would clip.
const lineHeightPx = parseFloat(cs(cell).lineHeight);
const fontSizePx = parseFloat(cs(cell).fontSize);
const hasCJK = (entry.runs || []).some((run) =>
/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\uff00-\uffef]/.test(run.text || ''),
);
if (hasCJK && lineHeightPx && fontSizePx && lineHeightPx / fontSizePx >= 1.3) {
entry.style = { ...entry.style, cjk: true, exactLineHeightPx: lineHeightPx };
}
}
// Empty cell showing placeholder text via ::before content
// ("Click to edit..." on contenteditable template cells): keep the
// rendered placeholder so the grid doesn't collapse into blank space.
if (!entry.children && !(entry.runs || []).length) {
const pseudo = getComputedStyle(cell, '::before');
const m = (pseudo.content || '').match(/^"(.*)"$/);
if (m && m[1].trim()) {
const run = { text: m[1], color: toHex(pseudo.color) || '999999' };
if (pseudo.fontStyle === 'italic') run.italic = true;
const sz = parseFloat(pseudo.fontSize);
if (sz) run.sizePx = sz;
entry.runs = [run];
}
}
// Short cell content ("Wave 1" pills, "11." numbers): record the
// forced single-line width (nowrap min-content, works even when the
// browser already crushed the column) so the generator can guarantee
// the column never wraps it letter-by-letter into a fake vertical
// stack.
{
const cellText = (cell.innerText || '').trim();
if (cellText && cellText.length <= 40 && !cellText.includes('\n')) {
// nowrap + Range: the true single-line CONTENT width. Plain
// scrollWidth reports the stretched layout width for uncrushed
// cells, which would inflate every column's floor equally.
// inner width BEFORE forcing nowrap — nowrap reflows the auto
// table layout and stretches the cell to fit the text
const pad = cellPaddingOf(cell);
const innerWidth =
cell.getBoundingClientRect().width - (pad.left || 0) - (pad.right || 0);
const previousWhiteSpace = cell.style.whiteSpace;
cell.style.whiteSpace = 'nowrap';
try {
const range = document.createRange();
range.selectNodeContents(cell);
let textWidth = range.getBoundingClientRect().width;
// Only short label-like content that the browser itself renders
// on one line gets a keep-on-one-line floor. A cell the browser
// already wrapped must be allowed to wrap in Word too — floors
// from wrapped cells starve the remaining columns (a 5-column
// table's last column collapsed to 600 twips).
if (textWidth > 0 && textWidth <= 160 && textWidth <= innerWidth + 2) {
// Word's substituted font may run much wider than the webfont.
const wordWidth = window.__h2dWordFontLineWidth
? window.__h2dWordFontLineWidth(cell)
: 0;
entry.oneLineWidthPx = Math.round(Math.max(textWidth, wordWidth));
}
} catch (e) {
/* leave unset */
}
cell.style.whiteSpace = previousWhiteSpace || '';
}
}
cells.push(entry);
const rect = cell.getBoundingClientRect();
const startPx = isRTL(el) ? tableRect.right - rect.right : rect.left - tableRect.left;
const endPx = isRTL(el) ? tableRect.right - rect.left : rect.right - tableRect.left;
(boundarySamples[nextColumn] ||= []).push(startPx);
(boundarySamples[nextColumn + colspan] ||= []).push(endPx);
if (rowspan > 1) {
activeSpans.push({
gridStart: nextColumn,
colspan,
endRow: rowIndex + rowspan,
cell: {
colspan,
shading: entry.shading,
borders: entry.borders,
padPx: entry.padPx,
rtl: entry.rtl,
align: entry.align,
vAlign: entry.vAlign,
},
});
for (let col = nextColumn; col < nextColumn + colspan; col++) occupied.add(col);
}
nextColumn += colspan;
}
if (!cells.length) continue;
cells.sort((a, b) => a.gridStart - b.gridStart);
gridColumnCount = Math.max(
gridColumnCount,
...cells.map((cell) => cell.gridStart + (cell.colspan || 1)),
);
const renderedHeight = Math.round(tr.getBoundingClientRect().height);
const rowText = (tr.innerText || '').trim();
// Only a real header row repeats across pages: flagging plain first
// rows duplicates a data row at every page break.
const isHeaderRow =
tr.parentElement?.tagName === 'THEAD' ||
(directCells.length > 0 && directCells.every((cell) => cell.tagName === 'TH'));
rows.push({
cells,
header: isHeaderRow || undefined,
rawHeightPx: renderedHeight,
// Compact text rows should use Word's natural height. Keeping the
// browser's measured minimum double-counts small font-metric/padding
// differences and makes ordinary data tables visibly too loose.
heightPx:
renderedHeight >= 80 || (renderedHeight >= 30 && !rowText)
? renderedHeight
: undefined,
});
}
if (!rows.length) return [];
// Uniform form grid (fill-in sheets sized for handwriting): the author
// gave every body row the same generous height. Preserving it only on
// the EMPTY rows (rule above) makes filled rows collapse to text height
// and the grid uneven — carry the shared height to all of them.
{
const body = rows.slice(1);
const heights = body.map((row) => row.rawHeightPx);
if (
body.length >= 4 &&
Math.min(...heights) >= 32 &&
Math.max(...heights) - Math.min(...heights) <= 4
) {
for (const row of body) row.heightPx = row.rawHeightPx;
}
for (const row of rows) delete row.rawHeightPx;
}
const boundaries = Array(gridColumnCount + 1).fill(null);
boundaries[0] = 0;
boundaries[gridColumnCount] = tableRect.width;
for (let index = 1; index < gridColumnCount; index++) {
const samples = boundarySamples[index];
if (samples?.length) {
const sorted = [...samples].sort((a, b) => a - b);
boundaries[index] = sorted[Math.floor(sorted.length / 2)];
}
}
let previousKnown = 0;
for (let index = 1; index <= gridColumnCount; index++) {
if (boundaries[index] == null) continue;
const span = index - previousKnown;
const start = boundaries[previousKnown];
const end = boundaries[index];
for (let fill = 1; fill < span; fill++) {
boundaries[previousKnown + fill] = start + ((end - start) * fill) / span;
}
previousKnown = index;
}
const colWidths = boundaries
.slice(0, -1)
.map((start, index) => Math.max(1, Math.round(boundaries[index + 1] - start)));
return [{
type: 'table',
rows,
colWidths,
outerBorder: bordersOf(el),
shading: bgHex(el),
preserveRowHeights: true,
// rendered height drives the keep-together call: a table that fits on
// one page should jump to the next page whole instead of splitting
heightPx: Math.round(tableRect.height),
rtl: isRTL(el) || undefined,
}];
}
global.__html2docxTable = { extractTable };
})(globalThis);
@@ -0,0 +1,51 @@
(function installVisualEffectClassifier(global) {
function needsScreenshot(el, deps) {
const { bgHex, cs, fullBorderOf } = deps;
// A broken image's rendered box is Chrome's placeholder chrome (icon +
// clipped alt text), never the author's design — even when transformed
// or shadowed, let the IMG branch fall back to alt text instead.
if (el.tagName === 'IMG' && (!el.complete || el.naturalWidth === 0)) return false;
const style = cs(el);
const rect = el.getBoundingClientRect();
if (rect.width < 20 || rect.height < 12 || rect.width > 1000 || rect.height > 1000) {
return false;
}
const transformed = style.transform && style.transform !== 'none';
const shadowed = style.boxShadow && style.boxShadow !== 'none';
const filtered =
(style.filter && style.filter !== 'none') ||
(style.backdropFilter && style.backdropFilter !== 'none');
const radii = [
style.borderTopLeftRadius,
style.borderTopRightRadius,
style.borderBottomRightRadius,
style.borderBottomLeftRadius,
].map((value) => parseFloat(value) || 0);
const complexRadius =
Math.max(...radii) >= 8 &&
(Boolean(bgHex(el)) || Boolean(fullBorderOf(el))) &&
(new Set(radii.map((radius) => Math.round(radius))).size > 1 ||
style.overflow === 'hidden' ||
Math.max(...radii) >= Math.min(rect.width, rect.height) * 0.25);
// Text-heavy cards must stay editable/searchable: soft shadows, filters
// and rounded corners are not worth rasterizing paragraphs of content.
// Transforms still rasterize (flowed text would land in the wrong place).
// CJK counts double: a 60-char Japanese question carries as much content
// as a 120-char English sentence.
const text = (el.innerText || '').trim();
const cjkCount = (text.match(/[\u3000-\u9fff\uf900-\ufaff\uff66-\uff9f]/g) || []).length;
const weightedTextLength = text.length + cjkCount;
// Many short lines (schedule cards, subject lists) are as content-heavy
// as long prose \u2014 a 5-day timetable trapped in pixels is uneditable.
const lineCount = text ? text.split('\n').filter((line) => line.trim()).length : 0;
const textHeavy = weightedTextLength > 80 || (lineCount >= 4 && text.length >= 30);
const compactRoundedCard =
complexRadius && rect.height <= 160 && weightedTextLength <= 200 && lineCount < 4;
return Boolean(
transformed ||
((shadowed || filtered || complexRadius) && (!textHeavy || compactRoundedCard)),
);
}
global.__html2docxVisualEffects = { needsScreenshot };
})(globalThis);
+499
View File
@@ -0,0 +1,499 @@
/**
* Orchestration: render the HTML in the host's browser, extract the intent
* tree, screenshot image-like elements, generate the DOCX.
*/
import type { BrowserDriver, ClipRect } from './driver'
import { BROWSER_HELPER_SCRIPTS, EXTRACTOR_CALL } from './extract'
import { generateDocx } from './generate'
import { FONT_RULES } from './generate/fonts'
export type ConvertStage = 'load' | 'extract' | 'screenshot' | 'generate'
export interface ConvertOptions {
onProgress?: (progress: { stage: ConvertStage; pct: number }) => void
signal?: AbortSignal
log?: (message: string) => void
/** Debug: in-page probes record `__h2dTrace` entries for elements matching this selector. */
traceSelector?: string
/** Debug: receives the extracted IR and trace probes before generation. */
onIr?: (ir: any[], trace: unknown[]) => void
}
export interface ConvertResult {
docx: Uint8Array
ir: any[]
/** Text that only survives as pixels (inside screenshots); lets evaluations
* tell "intentionally rasterized" from "actually lost". */
screenshotText: string
stats: { screenshots: number; rasterizedDocumentText: boolean }
}
/** A4 at 96dpi so layout (line wraps, column gaps) matches print. */
const A4_VIEWPORT = { width: 794, height: 1123, deviceScaleFactor: 2 }
const NAVIGATION_TIMEOUT_MS = 30000
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) throw new DOMException('html2docx conversion aborted', 'AbortError')
}
export async function convertHtmlToDocx(
input: { url: string },
driver: BrowserDriver,
options: ConvertOptions = {},
): Promise<ConvertResult> {
const { signal, traceSelector, onIr } = options
const log = options.log ?? (() => {})
const progress = (stage: ConvertStage, pct: number) => options.onProgress?.({ stage, pct })
const { url } = input
progress('load', 0)
await driver.setViewport(A4_VIEWPORT)
if (traceSelector) {
await driver.addInitScript(`globalThis.__h2dTraceSelector = ${JSON.stringify(traceSelector)};`)
}
log(`[html2docx] loading ${url}`)
await driver.goto(url, { timeoutMs: NAVIGATION_TIMEOUT_MS })
await driver.evaluate(() => document.fonts.ready.catch(() => {}))
await sleep(300)
throwIfAborted(signal)
// Authoring templates commonly use an 880px design canvas and are then
// scaled to A4. Extract at that authored width so narrower A4 reflow does
// not create artificial wraps and inflated table-row heights.
const authoredWidth = await driver.evaluate<number | null>(() => {
// Some document templates constrain body directly; responsive webpages
// more often constrain repeated `.inner`/`.container` wrappers. At the
// initial A4 viewport those pages may already have crossed into their
// mobile breakpoint, destroying desktop grids before extraction.
const candidates = [document.body, ...document.body.querySelectorAll('*')]
const widths = candidates.flatMap((el) => {
const rect = el.getBoundingClientRect()
const maxWidth = parseFloat(getComputedStyle(el).maxWidth)
return Number.isFinite(maxWidth) &&
maxWidth > window.innerWidth &&
maxWidth <= 1600 &&
rect.width >= window.innerWidth * 0.55 &&
rect.height >= 20
? [maxWidth]
: []
})
return widths.length ? Math.round(Math.max(...widths)) : null
})
// Content that overflows the A4 viewport horizontally (a 6-column table
// whose last column collapses to 1px) renders broken at 794px while the
// evaluation baseline at 1024px shows it intact. Reload wider whenever
// the layout visibly does not fit.
const overflowsA4 =
!authoredWidth &&
(await driver.evaluate<boolean>(() => {
if (document.documentElement.scrollWidth > window.innerWidth + 8) return true
if (
[...document.querySelectorAll('table')].some(
(table) => table.scrollWidth > table.clientWidth + 4,
)
) {
return true
}
// table-layout:auto absorbs overflow by crushing cells instead of
// scrolling — a cell whose content no longer fits on one word is the
// telltale ("Wave 1" pills stacking letter-by-letter).
return [...document.querySelectorAll('td, th')].some(
(cell) => cell.scrollWidth > cell.clientWidth + 2,
)
}))
if (authoredWidth || overflowsA4) {
const renderWidth = Math.max(1024, authoredWidth || 0)
await driver.setViewport({
width: renderWidth,
height: Math.round((1123 * renderWidth) / 794),
deviceScaleFactor: 2,
})
await driver.goto(url, { timeoutMs: NAVIGATION_TIMEOUT_MS })
await driver.evaluate(() => document.fonts.ready.catch(() => {}))
await sleep(300)
}
throwIfAborted(signal)
progress('load', 60)
// Offscreen website images may remain deferred even without an explicit
// loading="lazy" attribute. Visit the full page before screenshot-based
// extraction, then wait for every reachable image to decode.
await driver.evaluate(async () => {
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
const originalY = window.scrollY
const htmlScrollBehavior = document.documentElement.style.scrollBehavior
const bodyScrollBehavior = document.body.style.scrollBehavior
document.documentElement.style.scrollBehavior = 'auto'
document.body.style.scrollBehavior = 'auto'
const maxY = Math.max(0, document.documentElement.scrollHeight - window.innerHeight)
const step = Math.max(400, Math.round(window.innerHeight * 0.75))
for (let y = 0; y <= maxY; y += step) {
window.scrollTo(0, y)
await wait(60)
}
window.scrollTo(0, maxY)
await wait(100)
const imageWaits = [...document.images].map((image) => {
if (image.complete && image.naturalWidth > 0) {
return image.decode?.().catch(() => {})
}
return new Promise<void>((resolve) => {
const finish = () => resolve()
image.addEventListener('load', finish, { once: true })
image.addEventListener('error', finish, { once: true })
setTimeout(finish, 15000)
})
})
await Promise.all(imageWaits)
window.scrollTo(0, originalY)
await wait(100)
document.documentElement.style.scrollBehavior = htmlScrollBehavior
document.body.style.scrollBehavior = bodyScrollBehavior
})
await sleep(200)
throwIfAborted(signal)
progress('load', 100)
// Word substitutes unavailable webfonts (Cormorant → Georgia, Playfair →
// Georgia, …) with often much wider glyphs. Expose a measurement helper
// that re-measures a one-line label under the substituted font so width
// floors reflect what Word will render, not the authored webfont.
await driver.evaluate(
(rules: [string, string, string][]) => {
const parsed = rules.map(
([source, flags, name]) => [new RegExp(source, flags), name] as [RegExp, string],
)
const w = window as any
w.__h2dWordFontLineWidth = (el: HTMLElement) => {
let family: string
try {
family = getComputedStyle(el).fontFamily || ''
} catch {
return 0
}
let mapped = 'Arial'
for (const [re, name] of parsed) {
if (re.test(family)) {
mapped = name
break
}
}
const prevFont = el.style.fontFamily
const prevWhiteSpace = el.style.whiteSpace
let width = 0
try {
el.style.fontFamily = mapped
el.style.whiteSpace = 'nowrap'
const range = document.createRange()
range.selectNodeContents(el)
width = range.getBoundingClientRect().width
} catch {
/* keep 0 */
}
el.style.fontFamily = prevFont || ''
el.style.whiteSpace = prevWhiteSpace || ''
return width
}
},
FONT_RULES.map(([re, name]) => [re.source, re.flags, name]),
)
for (const source of BROWSER_HELPER_SCRIPTS) {
await driver.addScript(source)
}
log('[html2docx] extracting intent tree')
progress('extract', 0)
const ir = await driver.evaluate<any[]>(EXTRACTOR_CALL)
if (onIr) {
const trace = await driver.evaluate<unknown[]>(() => (globalThis as any).__h2dTrace || [])
onIr(ir, trace)
}
log(`[html2docx] extracted ${ir.length} top-level nodes`)
throwIfAborted(signal)
progress('extract', 100)
// Broken images render Chrome's placeholder chrome (icon + clipped alt
// text) — never authored design. Hide them so they can't bleed into any
// element screenshot (extraction already emitted their alt-text fallback).
await driver.evaluate(() => {
for (const img of document.querySelectorAll('img')) {
if (!img.complete || img.naturalWidth === 0) img.style.visibility = 'hidden'
}
})
// screenshot every element marked as image-like
const images: Record<string, Uint8Array> = {}
const shotIds: string[] = []
const shotNodes = new Map<string, any>()
const pageBgShotIds = new Set<string>(
ir.filter((node) => node.type === 'pagebg' && node.shotId).map((node) => node.shotId),
)
const collectRunShots = (runs: any[] | undefined) => {
for (const run of runs || []) {
if (run.inlineImage && run.shotId) {
shotIds.push(run.shotId)
if (run.unwrap || run.clip) shotNodes.set(run.shotId, run)
}
}
}
;(function collectShots(nodes: any[]) {
for (const n of nodes) {
if (n.type === 'image' || n.type === 'floatimg' || (n.type === 'pagebg' && n.shotId)) {
shotIds.push(n.shotId)
shotNodes.set(n.shotId, n)
}
collectRunShots(n.runs)
for (const item of n.items || []) collectRunShots(item.runs)
for (const key of ['children', 'cells']) {
if (Array.isArray(n[key])) {
for (const sub of n[key]) {
collectRunShots(sub.runs)
if (sub.children) collectShots(sub.children)
}
if (key === 'children') collectShots(n[key])
}
}
if (n.rows) {
for (const row of n.rows) {
for (const cell of row.cells) {
collectRunShots(cell.runs)
if (cell.children) collectShots(cell.children)
}
}
}
}
})(ir)
const uniqueShotIds = [...new Set(shotIds)]
let shotIndex = 0
for (const id of uniqueShotIds) {
throwIfAborted(signal)
progress('screenshot', Math.round((shotIndex++ / Math.max(1, uniqueShotIds.length)) * 100))
const shotNode = shotNodes.get(id)
const selector = `[data-h2d-id="${id}"]`
const hasElement = shotNode?.clip ? false : await driver.elementExists(selector)
if (!hasElement && !shotNode?.clip) continue
try {
if (shotNode?.unwrap) {
// Crushed inline label (letters stacked in a too-narrow column):
// relax to its natural one-line size for the screenshot.
await driver.evaluate((shotId: string) => {
const target = document.querySelector<HTMLElement>(`[data-h2d-id="${shotId}"]`)
if (!target) return
target.setAttribute('data-h2d-unwrap-style', target.getAttribute('style') || '')
target.style.whiteSpace = 'nowrap'
target.style.width = 'max-content'
target.style.maxWidth = 'none'
}, id)
}
if (shotNode?.isolate) {
await driver.evaluate((shotId: string) => {
const target = document.querySelector<HTMLElement>(`[data-h2d-id="${shotId}"]`)
if (!target) return
for (const candidate of document.body.querySelectorAll<HTMLElement>('*')) {
if (candidate === target || candidate.contains(target) || target.contains(candidate)) {
continue
}
candidate.setAttribute('data-h2d-isolate-visibility', candidate.style.visibility || '')
candidate.style.visibility = 'hidden'
}
// surrounding paint must not leak into the shot: the page and
// the target's ancestors (white content sheet) otherwise give
// the capture an opaque bounding box that occludes neighboring
// floats in Word
let scrub = target.parentElement
while (scrub) {
scrub.setAttribute('data-h2d-isolate-bg', scrub.getAttribute('style') || '')
scrub.style.background = 'transparent'
scrub = scrub.parentElement
}
}, id)
}
if (pageBgShotIds.has(id)) {
await driver.evaluate((shotId: string) => {
const backdrop = document.querySelector<HTMLElement>(`[data-h2d-id="${shotId}"]`)!
for (const child of document.body.children as HTMLCollectionOf<HTMLElement>) {
child.setAttribute('data-h2d-old-visibility', child.style.visibility || '')
child.style.visibility = child === backdrop ? 'visible' : 'hidden'
}
backdrop.setAttribute('data-h2d-old-style', backdrop.getAttribute('style') || '')
Object.assign(backdrop.style, {
position: 'fixed',
left: '0',
top: '0',
zIndex: '2147483647',
visibility: 'visible',
})
}, id)
}
// Badges/ribbons absolutely positioned to overhang their card's box
// (top: -12px "MOST VALUE" pills) are cut in half by an element
// screenshot — expand the capture to the union of the element and
// its near overhanging children, and resize the node to match.
let overhang: ClipRect | null = null
if (hasElement && shotNode?.type === 'image' && !shotNode.pageComposition && !shotNode.clip) {
overhang = await driver.evaluate<ClipRect | null>((shotId: string) => {
const target = document.querySelector<HTMLElement>(`[data-h2d-id="${shotId}"]`)
if (!target) return null
const ts = getComputedStyle(target)
if (ts.overflow === 'hidden' || ts.overflow === 'clip') return null
const r = target.getBoundingClientRect()
const box = { left: r.left, top: r.top, right: r.right, bottom: r.bottom }
for (const d of target.querySelectorAll('*')) {
if (getComputedStyle(d).position !== 'absolute') continue
const dr = d.getBoundingClientRect()
if (!dr.width || !dr.height) continue
// near overhangs only — far-flung decorations stay dropped
if (
dr.left < r.left - 48 ||
dr.right > r.right + 48 ||
dr.top < r.top - 48 ||
dr.bottom > r.bottom + 48
)
continue
box.left = Math.min(box.left, dr.left)
box.top = Math.min(box.top, dr.top)
box.right = Math.max(box.right, dr.right)
box.bottom = Math.max(box.bottom, dr.bottom)
}
if (
box.left >= r.left - 1 &&
box.top >= r.top - 1 &&
box.right <= r.right + 1 &&
box.bottom <= r.bottom + 1
)
return null
// rects are viewport-relative and earlier element screenshots
// may have scrolled the page; the clip needs page coordinates.
// In RTL the horizontal overflow hides LEFT of the viewport, so
// page x = viewport x + overflow + scrollLeft (scrollLeft <= 0).
const doc = document.documentElement
const rtlShift =
getComputedStyle(doc).direction === 'rtl' ||
getComputedStyle(document.body).direction === 'rtl'
? Math.max(0, doc.scrollWidth - doc.clientWidth)
: 0
const x = Math.max(0, Math.round(box.left + window.scrollX + rtlShift))
const y = Math.max(0, Math.round(box.top + window.scrollY))
return {
x,
y,
width: Math.round(box.right - box.left),
height: Math.round(box.bottom - box.top),
}
}, id)
}
if (overhang) {
images[id] = await driver.screenshot({ clip: overhang })
shotNode.width = overhang.width
shotNode.height = overhang.height
} else if (shotNode?.clip) {
images[id] = await driver.screenshot({ clip: shotNode.clip })
} else {
// Element screenshots hand viewport coordinates to CDP, whose clip
// origin is the LEFTMOST scrollable content. An RTL document with
// horizontal overflow hides that overflow left of the viewport, so
// the two origins differ by the overflow width and the capture
// lands shifted (TOC numbers / line starts cut off). Take an
// explicit page-coordinate clip instead.
const rtlBox = await driver.evaluate<ClipRect | null>((shotId: string) => {
const doc = document.documentElement
const rtl =
getComputedStyle(doc).direction === 'rtl' ||
getComputedStyle(document.body).direction === 'rtl'
const shift = rtl ? Math.max(0, doc.scrollWidth - doc.clientWidth) : 0
if (!shift) return null
const target = document.querySelector(`[data-h2d-id="${shotId}"]`)
if (!target) return null
const r = target.getBoundingClientRect()
return {
x: Math.max(0, Math.round(r.left + shift + doc.scrollLeft)),
y: Math.max(0, Math.round(r.top + window.scrollY)),
width: Math.round(r.width),
height: Math.round(r.height),
}
}, id)
const omitBackground = Boolean(shotNode?.isolate)
const shot = rtlBox
? await driver.screenshot({ clip: rtlBox, omitBackground })
: await driver.screenshotElement(selector, { omitBackground })
if (shot) images[id] = shot
}
if (images[id]) log(`[html2docx] screenshot ${id}: ${images[id].length} bytes`)
} catch (e) {
log(`[html2docx] screenshot ${id} failed: ${e instanceof Error ? e.message : String(e)}`)
} finally {
if (shotNode?.unwrap) {
await driver.evaluate((shotId: string) => {
const target = document.querySelector(`[data-h2d-id="${shotId}"]`)
if (!target) return
target.setAttribute('style', target.getAttribute('data-h2d-unwrap-style') || '')
target.removeAttribute('data-h2d-unwrap-style')
}, id)
}
if (shotNode?.isolate) {
await driver.evaluate(() => {
for (const candidate of document.querySelectorAll<HTMLElement>(
'[data-h2d-isolate-visibility]',
)) {
candidate.style.visibility = candidate.getAttribute('data-h2d-isolate-visibility') || ''
candidate.removeAttribute('data-h2d-isolate-visibility')
}
for (const scrubbed of document.querySelectorAll('[data-h2d-isolate-bg]')) {
scrubbed.setAttribute('style', scrubbed.getAttribute('data-h2d-isolate-bg') || '')
scrubbed.removeAttribute('data-h2d-isolate-bg')
}
})
}
if (pageBgShotIds.has(id)) {
await driver.evaluate((shotId: string) => {
const backdrop = document.querySelector(`[data-h2d-id="${shotId}"]`)
if (backdrop) {
backdrop.setAttribute('style', backdrop.getAttribute('data-h2d-old-style') || '')
backdrop.removeAttribute('data-h2d-old-style')
}
for (const child of document.body.children as HTMLCollectionOf<HTMLElement>) {
child.style.visibility = child.getAttribute('data-h2d-old-visibility') || ''
child.removeAttribute('data-h2d-old-visibility')
}
}, id)
}
}
}
progress('screenshot', 100)
// Text living inside rasterized elements: it is present in the DOCX as
// pixels, not as runs. Exported for evaluation so text-coverage checks
// can distinguish "intentionally rasterized" from "actually lost".
const rasterizedDocumentText = [...shotNodes.values()].some((node) => node.capturesDocumentText)
const screenshotText = await driver.evaluate<string>((includeBodyText: boolean) => {
const parts: string[] = []
if (includeBodyText) {
const bodyText = (document.body.innerText || '').trim()
if (bodyText) parts.push(bodyText)
}
for (const el of document.querySelectorAll<HTMLElement>('[data-h2d-id]')) {
const text = (
el.innerText ||
(el.tagName === 'IMG' ? el.getAttribute('alt') : '') ||
''
).trim()
if (text) parts.push(text)
}
return parts.join('\n')
}, rasterizedDocumentText)
throwIfAborted(signal)
log('[html2docx] generating docx')
progress('generate', 0)
const docx = new Uint8Array(await generateDocx(ir, images))
log(`[html2docx] generated ${docx.length} bytes`)
progress('generate', 100)
return {
docx,
ir,
screenshotText,
stats: { screenshots: Object.keys(images).length, rasterizedDocumentText },
}
}
+46
View File
@@ -0,0 +1,46 @@
/**
* The browser the converter renders in. The extraction layer runs inside the
* page (DOM + computed style + element screenshots), so the host supplies a
* page-like driver: Playwright for tests and the CLI, Electron's webContents
* in the app. Implementations share the contract test in tests/.
*/
export interface Viewport {
width: number
height: number
deviceScaleFactor: number
}
export interface ClipRect {
x: number
y: number
width: number
height: number
}
export interface ScreenshotOptions {
/** Page-coordinate clip; captures beyond the viewport. */
clip?: ClipRect
/** Transparent instead of the page background (isolated floats). */
omitBackground?: boolean
}
export interface BrowserDriver {
setViewport(viewport: Viewport): Promise<void>
/** Resolves once the network is idle; a timeout resolves too (the page is used as-is). */
goto(url: string, options: { timeoutMs: number }): Promise<void>
/** `fn` is serialized with toString() and gets one JSON-serializable argument; a string is evaluated as an expression. */
evaluate<T>(fn: string | ((arg?: any) => T | Promise<T>), arg?: unknown): Promise<T>
/** Inject a classic script (the in-page extractor helpers). */
addScript(source: string): Promise<void>
/** Runs before any page script on every navigation (debug tracing only). */
addInitScript(source: string): Promise<void>
screenshot(options: ScreenshotOptions): Promise<Uint8Array>
/** Screenshot of the first element matching `selector`'s box (even when hidden or
* zero-opacity — never wait for visibility); null when absent or empty. */
screenshotElement(
selector: string,
options: Pick<ScreenshotOptions, 'omitBackground'>,
): Promise<Uint8Array | null>
elementExists(selector: string): Promise<boolean>
close(): Promise<void>
}
@@ -0,0 +1,119 @@
/**
* BrowserDriver over playwright-core driving a locally installed Chrome. Used
* by the tests and the CLI; the app uses the Electron driver instead. Not
* re-exported from the package index so app bundles never pull in Playwright.
*/
import { existsSync } from 'node:fs'
import { chromium } from 'playwright-core'
import type { Browser, BrowserContext, Page } from 'playwright-core'
import type { BrowserDriver, ScreenshotOptions, Viewport } from '../driver'
const CHROME_CANDIDATES = [
process.env.CHROME_PATH,
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/google-chrome',
'/usr/bin/google-chrome-stable',
'/usr/bin/chromium',
'/usr/bin/chromium-browser',
].filter((p): p is string => Boolean(p))
export function findChrome(): string {
const found = CHROME_CANDIDATES.find((p) => existsSync(p))
if (!found) throw new Error('Chrome/Chromium not found. Set the CHROME_PATH env variable.')
return found
}
export function launchChrome(): Promise<Browser> {
return chromium.launch({
executablePath: findChrome(),
headless: true,
args: ['--no-sandbox', '--disable-dev-shm-usage', '--force-device-scale-factor=2'],
})
}
export class PlaywrightDriver implements BrowserDriver {
private constructor(
private readonly context: BrowserContext,
private readonly page: Page,
) {}
/** One isolated context per conversion; the browser is shared by the caller. */
static async create(browser: Browser, viewport: Viewport): Promise<PlaywrightDriver> {
const context = await browser.newContext({
viewport: { width: viewport.width, height: viewport.height },
deviceScaleFactor: viewport.deviceScaleFactor,
})
return new PlaywrightDriver(context, await context.newPage())
}
async setViewport(viewport: Viewport): Promise<void> {
// deviceScaleFactor is fixed per context (set in create); the converter
// only ever changes width/height afterwards.
await this.page.setViewportSize({ width: viewport.width, height: viewport.height })
}
async goto(url: string, { timeoutMs }: { timeoutMs: number }): Promise<void> {
try {
await this.page.goto(url, { waitUntil: 'networkidle', timeout: timeoutMs })
} catch {
// network never went idle: convert whatever has rendered (matches the CLI's behavior)
}
}
evaluate<T>(fn: string | ((arg?: any) => T | Promise<T>), arg?: unknown): Promise<T> {
if (typeof fn === 'string') return this.page.evaluate(fn) as Promise<T>
return this.page.evaluate(fn as (arg: unknown) => T, arg)
}
async addScript(source: string): Promise<void> {
await this.page.addScriptTag({ content: source })
}
async addInitScript(source: string): Promise<void> {
await this.page.addInitScript(source)
}
async screenshot(options: ScreenshotOptions): Promise<Uint8Array> {
// fullPage makes `clip` a document-coordinate rect captured beyond the
// viewport (CDP captureBeyondViewport); without it Playwright trims the
// clip to the viewport and below-the-fold shots come back empty.
return this.page.screenshot({
type: 'png',
fullPage: Boolean(options.clip),
clip: options.clip,
omitBackground: options.omitBackground,
})
}
async screenshotElement(
selector: string,
options: Pick<ScreenshotOptions, 'omitBackground'>,
): Promise<Uint8Array | null> {
const el = await this.page.$(selector)
if (!el) return null
// Not elementHandle.screenshot(): that waits for the element to be visible
// and stable, but the converter also shoots boxes it has just hidden
// (broken-image placeholders). Clip the element's page box instead.
// Origin clamped like the converter's own clips: a box overhanging the
// document's top/left edge is captured from the edge instead.
const box = await el.evaluate((node) => {
const r = node.getBoundingClientRect()
return {
x: Math.max(0, Math.round(r.left + window.scrollX)),
y: Math.max(0, Math.round(r.top + window.scrollY)),
width: Math.round(r.width),
height: Math.round(r.height),
}
})
if (box.width <= 0 || box.height <= 0) return null
return this.screenshot({ clip: box, omitBackground: options.omitBackground })
}
async elementExists(selector: string): Promise<boolean> {
return (await this.page.$(selector)) !== null
}
async close(): Promise<void> {
await this.context.close()
}
}
+41
View File
@@ -0,0 +1,41 @@
/**
* The in-page extractor is one self-contained function: every core fragment
* is a slice of its body (they share one scope), assembled here at build time
* from raw sources. The helper scripts install `__html2docx*` globals the body
* calls into, so they are injected first.
*/
import stylesSource from './browser/core/styles.js?raw'
import runsScreenshotsSource from './browser/core/runs-screenshots.js?raw'
import tablesListsSource from './browser/core/tables-lists.js?raw'
import layoutsControlsSource from './browser/core/layouts-controls.js?raw'
import decoratorsSource from './browser/core/decorators.js?raw'
import classifierSource from './browser/core/classifier.js?raw'
import paragraphsDocumentSource from './browser/core/paragraphs-document.js?raw'
import tableHelperSource from './browser/table.js?raw'
import formsMediaHelperSource from './browser/forms-media.js?raw'
import visualEffectsHelperSource from './browser/visual-effects.js?raw'
import pagesHelperSource from './browser/pages.js?raw'
const EXTRACTOR_BODY = [
stylesSource,
runsScreenshotsSource,
tablesListsSource,
layoutsControlsSource,
decoratorsSource,
classifierSource,
paragraphsDocumentSource,
].join('\n')
/** Source of `function extractIR() { … }`; evaluate `${EXTRACTOR_SOURCE}` then call it. */
export const EXTRACTOR_SOURCE = `function extractIR() {\n${EXTRACTOR_BODY}\n}`
/** Expression that runs the extractor in the page and yields the IR. */
export const EXTRACTOR_CALL = `(${EXTRACTOR_SOURCE})()`
/** Classic scripts to inject before running the extractor, in order. */
export const BROWSER_HELPER_SCRIPTS: readonly string[] = [
tableHelperSource,
formsMediaHelperSource,
visualEffectsHelperSource,
pagesHelperSource,
]
+32
View File
@@ -0,0 +1,32 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
/**
* Generation layer: intent tree (IR) -> native OOXML via the `docx` library.
*
* Layout vocabulary used (deliberately no floating text boxes):
* card -> single-cell borderless table with shading / left border
* kpirow -> single-row N-column borderless table
* code -> shaded paragraphs with a monospace font
*/
import { Packer } from 'docx'
import {
addPageBackgroundFloat,
createDocument,
partitionIr,
renderSection,
} from './generate/page-settings'
import { createRenderContext } from './generate/render-context'
import { Generator } from './generate/renderer'
async function generateDocx(ir, images) {
const parts = partitionIr(ir)
const context = createRenderContext(parts.docSettings)
const generator = new Generator(images, context)
addPageBackgroundFloat(generator, parts.pageBgNode)
const rendered = renderSection(generator, parts)
const document = createDocument(context, parts, rendered, generator)
return Packer.toBuffer(document)
}
export { generateDocx }
@@ -0,0 +1,25 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import { Bookmark } from 'docx'
function bookmarkName(id) {
const value = String(id || '')
let hash = 2166136261
for (const char of value) {
hash ^= char.codePointAt(0)
hash = Math.imul(hash, 16777619)
}
const safe = value.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24) || 'anchor'
return `h2d_${safe}_${(hash >>> 0).toString(36)}`.slice(0, 40)
}
function withBookmarks(children, bookmarks = []) {
let wrapped = children
for (const id of [...bookmarks].reverse()) {
wrapped = [new Bookmark({ id: bookmarkName(id), children: wrapped })]
}
return wrapped
}
export { bookmarkName, withBookmarks }
@@ -0,0 +1,60 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import { CheckBox, ImportedXmlComponent, TextRun } from 'docx'
function createContentControlFactory(startId = 1000) {
let nextId = startId
return function contentControl(node) {
if (node.controlType === 'checkbox') {
return new CheckBox({
alias: node.alias || node.name || 'Checkbox',
checked: Boolean(node.checked),
})
}
if (node.controlType === 'radio') {
return new TextRun({ text: node.checked ? '\u25c9' : '\u25cb', noProof: true })
}
const sdt = new ImportedXmlComponent('w:sdt')
const properties = new ImportedXmlComponent('w:sdtPr')
if (node.alias || node.name) {
properties.push(new ImportedXmlComponent('w:alias', { 'w:val': node.alias || node.name }))
}
if (node.name) {
properties.push(new ImportedXmlComponent('w:tag', { 'w:val': node.name }))
}
properties.push(new ImportedXmlComponent('w:id', { 'w:val': String(nextId++) }))
if (node.controlType === 'dropdown') {
const dropdown = new ImportedXmlComponent('w:dropDownList')
for (const option of node.options || []) {
dropdown.push(
new ImportedXmlComponent('w:listItem', {
'w:displayText': option.label,
'w:value': option.value,
}),
)
}
properties.push(dropdown)
} else {
properties.push(
new ImportedXmlComponent('w:text', {
'w:multiLine': node.controlType === 'multiline' ? '1' : '0',
}),
)
}
const content = new ImportedXmlComponent('w:sdtContent')
content.push(
new TextRun({
text: node.value || '\u00a0',
noProof: true,
// placeholder hints keep their authored light gray
color: node.valueColor || undefined,
}),
)
sdt.push(properties)
sdt.push(content)
return sdt
}
}
export { createContentControlFactory }
@@ -0,0 +1,69 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import { CJK_RE } from './fonts'
function forEachRunText(ir, fn) {
;(function walk(nodes) {
for (const node of nodes) {
for (const run of node.runs || []) fn(run.text || '')
if (node.children) walk(node.children)
if (node.cells) for (const cell of node.cells) walk(cell.children || [])
if (node.rows) {
for (const row of node.rows) {
for (const cell of row.cells) walk(cell.children || (cell.runs ? [cell] : []))
}
}
if (node.items) {
for (const item of node.items) {
walk([{ runs: Array.isArray(item) ? item : item.runs }])
}
}
}
})(ir)
}
function detectCJK(ir) {
let cjk = 0
let total = 0
forEachRunText(ir, (text) => {
total += text.length
for (const char of text) if (CJK_RE.test(char)) cjk++
})
return total > 0 && cjk / total > 0.05
}
// w:lang eastAsia drives Word's CJK line breaking and proofing. The html
// lang attribute is declared intent; script counting is the fallback for
// the common lang-less AI page.
function eastAsiaLangOf(lang = '', ir = []) {
const lower = lang.toLowerCase()
const primary = lower.split('-')[0]
if (primary === 'ja') return 'ja-JP'
if (primary === 'ko') return 'ko-KR'
if (primary === 'zh') {
return /hant|tw|hk|mo/.test(lower) ? 'zh-TW' : 'zh-CN'
}
let kana = 0
let hangul = 0
forEachRunText(ir, (text) => {
for (const char of text) {
const code = char.codePointAt(0)
if ((code >= 0x3040 && code <= 0x30ff) || (code >= 0x31f0 && code <= 0x31ff)) kana++
else if ((code >= 0xac00 && code <= 0xd7af) || (code >= 0x1100 && code <= 0x11ff)) hangul++
}
})
if (hangul > kana && hangul > 10) return 'ko-KR'
if (kana > 10) return 'ja-JP'
return 'zh-CN'
}
function bidiLangOf(lang = '') {
const primary = lang.toLowerCase().split('-')[0]
return (
{ ar: 'ar-SA', he: 'he-IL', fa: 'fa-IR', ur: 'ur-PK' }[primary] ||
(lang.includes('-') ? lang : 'ar-SA')
)
}
export { bidiLangOf, detectCJK, eastAsiaLangOf }
+60
View File
@@ -0,0 +1,60 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
// Han + kana + Hangul: Korean previously fell outside this class and whole
// Korean documents took the Latin/Arial branch (serif Hangul fallback).
const CJK_RE =
/[\u1100-\u11ff\u3000-\u30ff\u3130-\u318f\u3400-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/
const HANGUL_RE = /[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/
const KANA_RE = /[\u3040-\u30ff\u31f0-\u31ff]/
const FONT_RULES: Array<[RegExp, string]> = [
[/jetbrains|consolas|menlo|courier|mono/i, 'Consolas'],
[/fredoka/i, 'Arial Rounded MT Bold'],
[
/brush script|lucida handwriting|pacifico|dancing script|great vibes|cursive|comic sans/i,
'Segoe Script',
],
[/dm serif|playfair|cormorant/i, 'Georgia'],
[/archivo|bebas|oswald/i, 'Arial Narrow'],
[/malgun|맑은/i, 'Malgun Gothic'],
[/yu gothic|meiryo|hiragino kaku|ms gothic|noto sans jp/i, 'Yu Gothic'],
[/batang|바탕|noto serif kr/i, 'Batang'],
[/yu mincho|ms mincho|hiragino mincho|noto serif jp/i, 'Yu Mincho'],
[
/noto sans cjk|noto sans sc|noto sans tc|noto sans kr|yahei|pingfang|heiti|source han sans|\u5fae\u8f6f\u96c5\u9ed1|\u9ed1\u4f53/i,
'Microsoft YaHei',
],
[
/noto serif cjk|noto serif sc|songti|stsong|simsun|kaiti|fangsong|source han serif|\u5b8b\u4f53/i,
'SimSun',
],
[/arial unicode/i, 'Arial Unicode MS'],
[/arial|helvetica|verdana|tahoma|segoe|roboto|inter|lato|open sans|sans/i, 'Arial'],
[/times|georgia|garamond|cambria|palatino|book antiqua|serif/i, 'Times New Roman'],
[/.*/, 'Arial'],
]
function mapFont(fontFamily = '', mono = false, text = '') {
if (mono) return 'Consolas'
let font = 'Arial'
for (const [pattern, name] of FONT_RULES) {
if (pattern.test(fontFamily)) {
font = name
break
}
}
if (CJK_RE.test(text)) {
const sans = HANGUL_RE.test(text)
? 'Malgun Gothic'
: KANA_RE.test(text)
? 'Yu Gothic'
: 'Microsoft YaHei'
const serif = HANGUL_RE.test(text) ? 'Batang' : KANA_RE.test(text) ? 'Yu Mincho' : 'SimSun'
if (font === 'Arial') font = sans
if (font === 'Times New Roman') font = serif
}
return font
}
export { CJK_RE, HANGUL_RE, KANA_RE, FONT_RULES, mapFont }
@@ -0,0 +1,77 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import { LevelFormat, LevelSuffix } from 'docx'
function orderedNumberingLevels(format: any = LevelFormat.DECIMAL) {
return Array.from({ length: 9 }, (_, level) => ({
level,
format,
text: `%${level + 1}.`,
suffix: LevelSuffix.SPACE,
start: 1,
style: {
paragraph: {
indent: { left: 360 * (level + 1), hanging: 240 },
},
},
}))
}
function orderedReference(markerType) {
return (
{
'decimal-leading-zero': 'h2d-ol-decimal-zero',
'lower-alpha': 'h2d-ol-lower-letter',
'lower-latin': 'h2d-ol-lower-letter',
'upper-alpha': 'h2d-ol-upper-letter',
'upper-latin': 'h2d-ol-upper-letter',
'lower-roman': 'h2d-ol-lower-roman',
'upper-roman': 'h2d-ol-upper-roman',
}[markerType] || 'h2d-ol'
)
}
function bulletNumberingLevels(text) {
return Array.from({ length: 9 }, (_, level) => ({
level,
format: LevelFormat.BULLET,
text,
style: {
paragraph: {
indent: { left: 360 * (level + 1), hanging: 240 },
},
},
}))
}
function buildNumberingConfig() {
return [
{ reference: 'h2d-ol', levels: orderedNumberingLevels() },
{
reference: 'h2d-ol-decimal-zero',
levels: orderedNumberingLevels(LevelFormat.DECIMAL_ZERO),
},
{
reference: 'h2d-ol-lower-letter',
levels: orderedNumberingLevels(LevelFormat.LOWER_LETTER),
},
{
reference: 'h2d-ol-upper-letter',
levels: orderedNumberingLevels(LevelFormat.UPPER_LETTER),
},
{
reference: 'h2d-ol-lower-roman',
levels: orderedNumberingLevels(LevelFormat.LOWER_ROMAN),
},
{
reference: 'h2d-ol-upper-roman',
levels: orderedNumberingLevels(LevelFormat.UPPER_ROMAN),
},
{ reference: 'h2d-ul', levels: bulletNumberingLevels('\u2022') },
{ reference: 'h2d-ul-circle', levels: bulletNumberingLevels('\u25e6') },
{ reference: 'h2d-ul-square', levels: bulletNumberingLevels('\u25aa') },
]
}
export { buildNumberingConfig, orderedReference }
@@ -0,0 +1,280 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import {
Document,
Footer,
Header,
ImageRun,
LineRuleType,
Paragraph,
Table,
TextWrappingType,
} from 'docx'
import { bidiLangOf, detectCJK, eastAsiaLangOf } from './document-meta'
import { buildNumberingConfig } from './numbering'
import { spacerParagraph } from './word-utils'
import zlib from 'node:zlib'
function partitionIr(ir) {
const docSettings = ir.find((node) => node.type === 'docsettings')
const pageBgNode = ir.find((node) => node.type === 'pagebg')
const headerNode = ir.find((node) => node.type === 'headerpart')
const footerNode = ir.find((node) => node.type === 'footerpart')
const bodyIr = ir.filter(
(node) =>
node.type !== 'docsettings' &&
node.type !== 'pagebg' &&
node.type !== 'headerpart' &&
node.type !== 'footerpart',
)
return { bodyIr, docSettings, footerNode, headerNode, pageBgNode }
}
// Word ignores <w:background> when printing / exporting PDF, so a plain
// page color must also become a behind-text float. A 1×1 PNG stretched to
// page size costs ~70 bytes.
function solidColorPng(hex) {
const rgb = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16) || 0)
const chunk = (type, data) => {
const body = Buffer.concat([Buffer.from(type, 'ascii'), data])
const out = Buffer.alloc(body.length + 8)
out.writeUInt32BE(data.length, 0)
body.copy(out, 4)
out.writeUInt32BE(zlib.crc32(body) >>> 0, body.length + 4)
return out
}
const ihdr = Buffer.alloc(13)
ihdr.writeUInt32BE(1, 0)
ihdr.writeUInt32BE(1, 4)
ihdr[8] = 8 // bit depth
ihdr[9] = 2 // color type: RGB
const idat = zlib.deflateSync(Buffer.from([0, ...rgb]))
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', ihdr),
chunk('IDAT', idat),
chunk('IEND', Buffer.alloc(0)),
])
}
function addPageBackgroundFloat(generator, pageBgNode) {
const shotData = pageBgNode?.shotId ? generator.images[pageBgNode.shotId] : null
const data = shotData || (pageBgNode?.color ? solidColorPng(pageBgNode.color) : null)
if (!data) return
const context = generator.context
generator.pageBackgroundFloat = new ImageRun({
type: 'png',
data,
transformation: {
width: Math.round(context.pageWidthDxa / 15),
height: Math.round(context.pageHeightDxa / 15),
},
floating: {
horizontalPosition: { relative: 'page', offset: 0 },
verticalPosition: { relative: 'page', offset: 0 },
behindDocument: true,
wrap: { type: TextWrappingType.NONE },
margins: { top: 0, bottom: 0, left: 0, right: 0 },
},
})
}
function renderSection(generator, { bodyIr, footerNode, headerNode }) {
const headerChildren = []
if (generator.pageBackgroundFloat) {
headerChildren.push(
new Paragraph({
children: [generator.pageBackgroundFloat],
spacing: { before: 0, after: 0, line: 1, lineRule: LineRuleType.EXACT },
}),
)
}
if (headerNode) {
headerChildren.push(...generator.render(withPageNumberFields(headerNode.children || [])))
}
const footerChildren = footerNode
? generator.render(withPageNumberFields(footerNode.children || []))
: []
const children = generator.render(bodyIr)
// Trailing spacers render nothing at document end but can overflow onto a
// phantom background-only last page when the content fills its final page.
// A table must not end the body either: Word then auto-inserts a
// default-height paragraph mark, which overflows the same way. End on one
// minimal explicit paragraph instead.
while (children.length > 1 && children[children.length - 1]?.__h2dSpacerPx) {
children.pop()
}
if (!(children[children.length - 1] instanceof Paragraph)) {
children.push(
new Paragraph({
children: [],
spacing: { before: 0, after: 0, line: 1, lineRule: LineRuleType.EXACT },
}),
)
}
// Final-card top margin: a closing footer card stranded on a fresh page
// still shows its authored top gap, so the gap buys nothing — collapse the
// whole run of spacers before it to improve the chance the card fits the
// previous page's tail instead.
let lastBlock = children.length - 1
while (lastBlock >= 0 && children[lastBlock] instanceof Paragraph) lastBlock--
if (children[lastBlock] instanceof Table) {
let firstSpacer = lastBlock
while (firstSpacer > 0 && children[firstSpacer - 1]?.__h2dSpacerPx) firstSpacer--
const runPx = children
.slice(firstSpacer, lastBlock)
.reduce((sum, spacer) => sum + spacer.__h2dSpacerPx, 0)
if (runPx > 16) {
children.splice(firstSpacer, lastBlock - firstSpacer, spacerParagraph(generator.context, 8))
}
}
if (generator.floats.length) {
children.unshift(
new Paragraph({
children: generator.floats,
spacing: { before: 0, after: 0, line: 1, lineRule: LineRuleType.EXACT },
}),
)
}
return { children, footerChildren, headerChildren }
}
// Literal page numbers in a real header/footer ("Page 1 of 3" and the CJK
// "page N / total M" form) are frozen at whatever the browser rendered — replace the
// digits with native PAGE / NUMPAGES fields so Word keeps them true.
const LATIN_PAGE_RE = /\b((?:page|pg\.?|p\.)\s*)(\d+)((?:\s*(?:of|\/|de)\s*)(\d+))?/i
const CJK_PAGE_RE =
/(\u7b2c\s*)(\d+)(\s*[\u9875\u9801])((?:\s*[,\uff0c/]?\s*\u5171\s*)(\d+)(\s*[\u9875\u9801]))?/
function pageFieldSegments(run) {
const text = run.text || ''
const match = LATIN_PAGE_RE.exec(text) || CJK_PAGE_RE.exec(text)
if (!match) return null
const isCjk = match.length > 5
const segments = []
const push = (t) => t && segments.push({ ...run, text: t })
push(text.slice(0, match.index) + match[1])
segments.push({ ...run, text: '', pageNumberField: 'current' })
if (isCjk) {
push(match[3])
if (match[5]) {
push(match[4].slice(0, match[4].length - match[5].length - match[6].length))
segments.push({ ...run, text: '', pageNumberField: 'total' })
push(match[6])
}
push(text.slice(match.index + match[0].length))
} else {
if (match[4]) {
push(match[3].slice(0, match[3].length - match[4].length))
segments.push({ ...run, text: '', pageNumberField: 'total' })
}
push(text.slice(match.index + match[0].length))
}
return segments
}
function withPageNumberFields(nodes) {
const mapCells = (cells) =>
(cells || []).map((cell) => ({
...cell,
runs: cell.runs ? cell.runs.flatMap((run) => pageFieldSegments(run) || [run]) : cell.runs,
children: cell.children ? withPageNumberFields(cell.children) : cell.children,
}))
return (nodes || []).map((node) => {
const mapped = { ...node }
if (node.runs) {
mapped.runs = node.runs.flatMap((run) => pageFieldSegments(run) || [run])
}
if (node.children) mapped.children = withPageNumberFields(node.children)
if (node.rows) {
mapped.rows = node.rows.map((row) => ({ ...row, cells: mapCells(row.cells) }))
}
if (node.cells) mapped.cells = mapCells(node.cells)
if (node.items) mapped.items = withPageNumberFields(node.items)
return mapped
})
}
function createDocument(context, parts, rendered, generator) {
const isCJK = detectCJK(parts.bodyIr)
const docRTL = Boolean(parts.docSettings?.rtl)
const bidiLang = docRTL ? bidiLangOf(parts.docSettings?.lang) : undefined
// A solid-color pagebg (no shotId) still becomes a header-anchored float
// via addPageBackgroundFloat's solidColorPng fallback — the header-distance
// reservation must be zeroed for that case too, or Word pads a ~1.25cm gap
// above the body on every page (the header area is reserved regardless of
// how empty its content looks).
const hasPageBackgroundHeader = Boolean(generator?.pageBackgroundFloat) && !parts.headerNode
const needsTopBleed = hasPageBackgroundHeader && context.pageMargins.top === 0
const pageMargins = hasPageBackgroundHeader
? {
...context.pageMargins,
top: needsTopBleed ? -context.pxToTwips(14) : context.pageMargins.top,
header: 0,
}
: context.pageMargins
const meta = parts.docSettings?.meta || {}
return new Document({
title: meta.title,
creator: meta.author || 'html2docx',
description: meta.description,
keywords: meta.keywords,
background: parts.pageBgNode?.color ? { color: parts.pageBgNode.color } : undefined,
numbering: { config: buildNumberingConfig() },
styles: {
default: {
document: {
// OOXML default is OFF unless a style sets it; Word's own new-doc
// template enables it — match that so no stranded single lines
paragraph: { widowControl: true } as any,
run: isCJK
? {
// ascii/hAnsi stay Latin-proportional: a CJK font on Latin
// runs renders SimSun-style monospaced glyphs.
font: {
ascii: 'Arial',
hAnsi: 'Arial',
eastAsia:
{ 'ja-JP': 'Yu Gothic', 'ko-KR': 'Malgun Gothic' }[
eastAsiaLangOf(parts.docSettings?.lang, parts.bodyIr)
] || 'Microsoft YaHei',
},
size: Math.round(21 * context.fontScale),
// w:lang w:val must stay Latin: tagging it zh-CN makes Word
// apply CJK line breaking to Latin words ("Rep/ort").
language: {
value: 'en-US',
eastAsia: eastAsiaLangOf(parts.docSettings?.lang, parts.bodyIr),
},
}
: {
font: 'Arial',
size: Math.round(21 * context.fontScale),
language: docRTL
? { value: bidiLang, bidirectional: bidiLang }
: { value: 'en-US' },
},
},
},
},
sections: [
{
properties: {
page: {
size: { width: context.pageWidthDxa, height: context.pageHeightDxa },
margin: pageMargins,
},
},
headers: rendered.headerChildren.length
? { default: new Header({ children: rendered.headerChildren }) }
: undefined,
footers: rendered.footerChildren.length
? { default: new Footer({ children: rendered.footerChildren }) }
: undefined,
children: rendered.children,
},
],
})
}
export { addPageBackgroundFloat, createDocument, partitionIr, renderSection }
@@ -0,0 +1,54 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
const DEFAULT_PAGE_WIDTH_PX = 794
const DEFAULT_PAGE_HEIGHT_PX = 1123
const MARGIN_DXA = 1134
function createRenderContext(docSettings: any = {}) {
const marginsPx = docSettings.marginsPx || {}
const pageWidthDxa = Math.max(
1440,
Math.round((docSettings.pageSizePx?.width || DEFAULT_PAGE_WIDTH_PX) * 15),
)
const pageHeightDxa = Math.max(
1440,
Math.round((docSettings.pageSizePx?.height || DEFAULT_PAGE_HEIGHT_PX) * 15),
)
const baseScale = docSettings.viewportWidthPx
? Math.min(1, pageWidthDxa / 15 / docSettings.viewportWidthPx)
: 1
// Extractor-provided whole-document squeeze for flow docs slightly taller
// than one page: shrinks geometry and fonts together a few percent so a
// two-line tail does not strand on its own page.
const squeeze = docSettings.pageFitSqueeze || 1
const measurementScale = baseScale * squeeze
// Arial is narrower than the browser's common Inter/Roboto fonts. Scaling
// it as aggressively as box geometry removes authored line wraps, so retain
// part of the original font size while still fitting the page.
const fontScale = Math.min(1, baseScale * 1.04) * squeeze
const pxToTwips = (px) => Math.round(px * 15 * measurementScale)
const pageMargins = {
top: pxToTwips(marginsPx.top ?? MARGIN_DXA / 15),
bottom: pxToTwips(marginsPx.bottom ?? MARGIN_DXA / 15),
left: pxToTwips(marginsPx.left ?? MARGIN_DXA / 15),
right: pxToTwips(marginsPx.right ?? MARGIN_DXA / 15),
header: docSettings.composed ? 0 : undefined,
footer: docSettings.composed ? 0 : undefined,
}
return {
pageWidthDxa,
pageHeightDxa,
pageMargins,
contentDxa: pageWidthDxa - pageMargins.left - pageMargins.right,
measurementScale,
fontScale,
marginDxa: MARGIN_DXA,
pxToHalfPoints: (px) => Math.round(px * 1.5 * fontScale),
pxToTwips,
pxToBorderEighths: (px) => Math.max(4, Math.round(px * 6 * measurementScale)),
}
}
export { createRenderContext }
+706
View File
@@ -0,0 +1,706 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import {
AlignmentType,
BorderStyle,
ExternalHyperlink,
HeightRule,
ImageRun,
LineRuleType,
PageBreak,
Paragraph,
ShadingType,
Table,
TableCell,
TableLayoutType,
TableRow,
TextRun,
TextWrappingType,
VerticalPositionAlign,
WidthType,
} from 'docx'
import { withBookmarks } from './bookmarks'
import { createContentControlFactory } from './content-controls'
import { orderedReference } from './numbering'
import { renderCard, renderColorBar, renderKpiRow, renderTable } from './table-renderers'
import {
HEADING_LEVELS,
NO_BORDERS,
NO_TABLE_BORDERS,
makeNodeRuns,
paraOptions,
spacerParagraph,
tabStopsFor,
wordBorder,
} from './word-utils'
function splitVerticalBorderSpacing(style: any = {}) {
if (!style.borderLeft && !style.borderRight) {
return { paragraphStyle: style, spacingAfterPx: 0, spacingBeforePx: 0 }
}
const spacingBeforePx = style.spacingBeforePx || 0
const spacingAfterPx = style.spacingAfterPx || 0
return {
paragraphStyle: {
...style,
spacingBeforePx: 0,
spacingAfterPx: 0,
},
spacingAfterPx,
spacingBeforePx,
}
}
function withExternalBorderSpacing(
context,
paragraph,
spacingBeforePx,
spacingAfterPx,
shading = null,
) {
const output = []
if (spacingBeforePx) output.push(spacerParagraph(context, spacingBeforePx, { shading }))
output.push(paragraph)
if (spacingAfterPx) output.push(spacerParagraph(context, spacingAfterPx, { shading }))
return output
}
class Generator {
[key: string]: any
constructor(images, context) {
this.images = images // shotId -> { buffer, width, height }
this.context = context
this.contentControl = createContentControlFactory()
// width (dxa) available to the node being rendered; shrinks inside table cells
this.avail = context.contentDxa
// page-anchored floating images, attached to the first paragraph
this.floats = []
// Repeated from the header so printed pages retain the authored backdrop.
this.pageBackgroundFloat = null
this.olInstance = 0
// Word promotes keepNext on in-cell paragraphs to row-level
// keep-with-next: rows chain into one unsplittable block that jumps to a
// fresh page whole. Set while rendering table-cell content.
this.suppressKeepNext = false
// Inverse of the above, set by cellChildren({keepWithNext}) for the
// non-last rows of a fits-on-one-page table: every paragraph rendered
// while true carries keepNext so the whole table stays together.
this.forceKeepNext = false
}
render(nodes, depth = 0) {
const out = []
// Word binds keepNext paragraph-to-paragraph only: a heading followed by
// a plain spacer is "kept" with just the spacer, and the section body
// still breaks to the next page leaving the heading orphaned. Extend the
// keep chain from a heading through its section head — spacers and at
// most one lede/subtitle paragraph — into the first substantive block.
// Trailing spacers must stay unbound or sections fuse into one
// document-wide keep chain and Word breaks pages far too early.
let chainActive = false
let ledeAllowance = 0
for (let index = 0; index < nodes.length; index++) {
const node = nodes[index]
let rendered
if (
!this.suppressKeepNext &&
node.type === 'para' &&
nodes[index + 1]?.type === 'spacer' &&
nodes[index + 1].bindsNeighbors
) {
// Paragraph before an authored in-flow gap (signature space): bind
// it through the gap to the following paragraph.
rendered = this.renderNode({ ...node, style: { ...node.style, keepNext: true } }, depth)
chainActive = false
} else if (
node.type === 'spacer' &&
nodes[index + 1]?.type === 'card' &&
(nodes[index + 1].heightPx || 0) > 700
) {
// A near-page-height unsplittable card cannot share its page with
// the authored gap before it — the card slides to the next page and
// the invisible gap strands a blank page. Collapse the gap; the
// page break itself provides the separation.
rendered = [
spacerParagraph(this.context, Math.min(node.px, 8), {
keepNext: chainActive,
shading: node.shading,
}),
]
} else if (
(chainActive || (node.bindsNeighbors && !this.suppressKeepNext)) &&
node.type === 'spacer'
) {
rendered = [
spacerParagraph(this.context, node.px, { keepNext: true, shading: node.shading }),
]
} else if (chainActive && node.type === 'para' && ledeAllowance > 0) {
// Only a real lede continues the chain: the next substantive node
// must be more section content. When it is another heading (or the
// end), this para IS the section body — it must terminate the chain,
// or trailing spacers bind section after section into one
// document-wide keep block that Word shoves onto a fresh page.
let next = index + 1
while (next < nodes.length && nodes[next].type === 'spacer') next += 1
if (next < nodes.length && nodes[next].type !== 'heading') {
ledeAllowance -= 1
rendered = this.renderNode({ ...node, style: { ...node.style, keepNext: true } }, depth)
} else {
rendered = this.renderNode(node, depth)
chainActive = false
}
} else {
rendered = this.renderNode(node, depth)
if (node.type === 'heading' && !this.suppressKeepNext) {
// A heading's trailing spacing also sits between it and the body.
const last = rendered.length - 1
if (rendered[last]?.__h2dSpacerPx) {
rendered[last] = spacerParagraph(this.context, rendered[last].__h2dSpacerPx, {
keepNext: true,
shading: rendered[last].__h2dSpacerShading,
borderLeft: rendered[last].__h2dSpacerBorderLeft,
})
}
} else if (chainActive && rendered[0]?.__h2dSpacerPx) {
// First substantive block: bind its own leading margin spacer.
rendered[0] = spacerParagraph(this.context, rendered[0].__h2dSpacerPx, {
keepNext: true,
shading: rendered[0].__h2dSpacerShading,
borderLeft: rendered[0].__h2dSpacerBorderLeft,
})
}
if (node.type === 'heading') {
chainActive = !this.suppressKeepNext
ledeAllowance = 1
} else {
chainActive = false
}
}
// A near-page-height unsplittable card cannot share a page with the
// gap that precedes it (the card slides on; the invisible gap strands
// a blank page) — collapse the previous block's trailing spacer.
if (
nodes[index + 1]?.type === 'card' &&
(nodes[index + 1].heightPx || 0) > 700 &&
!nodes[index + 1].allowSplit
) {
const last = rendered.length - 1
if ((rendered[last]?.__h2dSpacerPx || 0) > 8) {
rendered[last] = spacerParagraph(this.context, 8, {
shading: rendered[last].__h2dSpacerShading,
})
}
}
out.push(...rendered)
}
return out
}
renderNode(node, depth) {
const context = this.context
switch (node.type) {
case 'pagebreak':
return [
new Paragraph({
children: [new PageBreak()],
spacing: { before: 0, after: 0, line: 1, lineRule: LineRuleType.EXACT },
}),
]
case 'spacer':
return [
spacerParagraph(context, node.px, {
keepNext: this.forceKeepNext,
shading: node.shading,
borderLeft: node.borderLeft,
}),
]
case 'heading': {
// shaded single-line section header bar (h2 with background +
// padding): same treatment as shaded paras, otherwise the text sits
// baseline-left in the bar with no inset or vertical centering
if (node.style?.shading && node.style?.colorBar) {
return renderColorBar(this, node)
}
node = this.fitOneLineRuns(node)
const { paragraphStyle, spacingAfterPx, spacingBeforePx } = splitVerticalBorderSpacing(
node.style,
)
const opts = paraOptions(context, paragraphStyle)
// Built-in Word heading styles add their own top/bottom spacing.
// Override both sides explicitly so CSS margin: 0 remains zero.
opts.spacing = {
...opts.spacing,
before: opts.spacing?.before ?? 0,
after: opts.spacing?.after ?? 0,
}
const stops = tabStopsFor(context, node.runs)
if (stops.length) opts.tabStops = stops
return withExternalBorderSpacing(
context,
new Paragraph({
heading: HEADING_LEVELS[Math.min(node.level, 6) - 1],
children: withBookmarks(makeNodeRuns(context, node, this.images), node.bookmarks),
keepNext: this.forceKeepNext
? true
: node.style?.keepNext === false || this.suppressKeepNext
? undefined
: true,
keepLines: true,
...opts,
}),
spacingBeforePx,
spacingAfterPx,
paragraphStyle.shading,
)
}
case 'para': {
if (!node.runs.length) return []
if (node.style?.shading && node.style?.colorBar) {
return renderColorBar(this, node)
}
node = this.fitFillInRuns(node)
node = this.fitOneLineRuns(node)
const { paragraphStyle, spacingAfterPx, spacingBeforePx } = splitVerticalBorderSpacing(
node.style,
)
const opts = paraOptions(context, paragraphStyle)
const stops = tabStopsFor(context, node.runs)
if (stops.length) opts.tabStops = stops
if (node.style?.bullet) {
opts.numbering = { reference: 'h2d-ul', level: 0 }
}
if (this.forceKeepNext || (node.style?.keepNext && !this.suppressKeepNext)) {
opts.keepNext = true
}
if (node.style?.keepLines) opts.keepLines = true
return withExternalBorderSpacing(
context,
new Paragraph({
children: withBookmarks(makeNodeRuns(context, node, this.images), node.bookmarks),
...opts,
}),
spacingBeforePx,
spacingAfterPx,
paragraphStyle.shading,
)
}
case 'list': {
// One numbering instance per sublist, emitted at level 0: docx's
// startOverride only restarts level 0, so real multi-level lists
// would inherit a document-wide running counter (nested a-e lists
// continuing f-j, r-bb...). Level 0 per instance restarts like the
// browser restarts each <ol>; visual nesting comes from indentLeftPx.
const instanceByLevel = []
return node.items.map((entry) => {
// Older IR snapshots stored runs directly; accept both shapes so
// callers that persist/debug IR remain compatible.
const item = Array.isArray(entry) ? { runs: entry, style: {} } : entry
const opts = paraOptions(context, item.style)
const markerWidthPx = Math.max(10, Math.min(16, (item.runs[0]?.sizePx || 14) * 0.8))
opts.indent = {
left: context.pxToTwips(item.indentLeftPx || node.indentLeftPx || 22),
hanging: context.pxToTwips(markerWidthPx),
}
if (node.rtl) opts.bidirectional = true
if (this.forceKeepNext) opts.keepNext = true
const ordered = item.ordered ?? node.ordered
const level = Math.max(0, Math.min(8, item.level || 0))
if (level < instanceByLevel.length - 1) instanceByLevel.length = level + 1
if (instanceByLevel[level] == null) instanceByLevel[level] = this.olInstance++
const bulletReference =
item.markerType === 'square'
? 'h2d-ul-square'
: item.markerType === 'circle'
? 'h2d-ul-circle'
: 'h2d-ul'
if (item.continuation) {
opts.indent = { left: context.pxToTwips(item.indentLeftPx || node.indentLeftPx || 22) }
} else {
opts.numbering = ordered
? {
reference: orderedReference(item.markerType),
level: 0,
instance: instanceByLevel[level],
}
: { reference: bulletReference, level }
}
return new Paragraph({
children: withBookmarks(
makeNodeRuns(context, { runs: item.runs, style: item.style }, this.images),
item.bookmarks,
),
...opts,
})
})
}
case 'code':
return node.lines.map(
(line) =>
new Paragraph({
children: [
new TextRun({
text: line || ' ',
font: 'Consolas',
size: node.sizePx ? context.pxToHalfPoints(node.sizePx) : 18,
color: node.color && node.color !== '000000' ? node.color : undefined,
noProof: true,
}),
],
shading: { type: ShadingType.CLEAR, fill: node.shading },
}),
)
case 'hr': {
const widthFrac = Math.max(0.05, Math.min(1, node.widthFrac || 1))
if (node.short) {
const width = Math.max(120, Math.round(this.avail * widthFrac))
const output = []
if (node.spacingBeforePx) {
output.push(
spacerParagraph(context, node.spacingBeforePx, { shading: node.ambientShading }),
)
}
output.push(
new Table({
borders: NO_TABLE_BORDERS,
rows: [
new TableRow({
height: {
value: context.pxToTwips(node.heightPx || 2),
rule: HeightRule.EXACT,
},
children: [
new TableCell({
children: [new Paragraph({ spacing: { before: 0, after: 0 } })],
shading: { type: ShadingType.CLEAR, fill: node.color || 'CCCCCC' },
borders: NO_BORDERS,
margins: { top: 0, bottom: 0, left: 0, right: 0 },
}),
],
}),
],
width: { size: width, type: WidthType.DXA },
columnWidths: [width],
layout: TableLayoutType.FIXED,
}),
spacerParagraph(context, node.spacingAfterPx || 2, { shading: node.ambientShading }),
)
return output
}
const spare = Math.round(this.avail * (1 - widthFrac))
const left = node.align === 'center' ? Math.round(spare / 2) : 0
const right = node.align === 'center' ? spare - left : spare
return [
new Paragraph({
indent: { left, right },
shading: node.ambientShading
? { type: ShadingType.CLEAR, fill: node.ambientShading }
: undefined,
// collapse the carrier paragraph to (almost) just the border line;
// a default-height empty line reads as a stray blank row
children: [new TextRun({ text: '', size: 2, noProof: true })],
spacing: {
before: context.pxToTwips(node.spacingBeforePx || 0),
after: context.pxToTwips(node.spacingAfterPx || 2),
line: context.pxToTwips(Math.max(2, node.heightPx || 2)),
lineRule: LineRuleType.EXACT,
},
border: {
bottom: {
style: BorderStyle.SINGLE,
size: node.heightPx ? Math.max(6, Math.round(node.heightPx * 8)) : 6,
color: node.color || 'CCCCCC',
},
},
}),
]
}
case 'formfield': {
if (node.controlType === 'checkbox' || node.controlType === 'radio') {
return [
new Paragraph({
children: [this.contentControl(node)],
spacing: { before: 0, after: 0 },
...paraOptions(context, node.style),
}),
]
}
if (node.mode === 'line') {
return [
new Paragraph({
children: [this.contentControl(node)],
border: { bottom: wordBorder(context, node.borders?.bottom) },
spacing: { before: 0, after: 0, line: 240 },
}),
]
}
const width = Math.min(this.avail, Math.max(300, context.pxToTwips(node.width || 100)))
const borders: any = {}
for (const side of ['top', 'bottom', 'left', 'right']) {
borders[side] = wordBorder(context, node.borders?.[side])
}
const pad = node.padPx || {}
return [
new Table({
borders: NO_TABLE_BORDERS,
rows: [
new TableRow({
cantSplit: true,
height: node.height
? { value: context.pxToTwips(node.height), rule: HeightRule.ATLEAST }
: undefined,
children: [
new TableCell({
children: [
new Paragraph({
children: [this.contentControl(node)],
spacing: { before: 0, after: 0 },
}),
],
borders,
shading: node.shading
? { type: ShadingType.CLEAR, fill: node.shading }
: undefined,
margins: {
top: context.pxToTwips(pad.top || 4),
bottom: context.pxToTwips(pad.bottom || 4),
left: context.pxToTwips(pad.left || 6),
right: context.pxToTwips(pad.right || 6),
},
}),
],
}),
],
width: { size: width, type: WidthType.DXA },
columnWidths: [width],
}),
spacerParagraph(context, 2),
]
}
case 'image':
return this.renderImage(node)
case 'floatimg':
return this.collectFloatingImage(node)
case 'table':
return renderTable(this, node, depth)
case 'card':
return renderCard(this, node, depth)
case 'kpirow':
return renderKpiRow(this, node, depth)
default:
return []
}
}
// Display text measured as one browser line but wider than the cell it
// landed in: Word would wrap it mid-word ("INVOIC/E"). Shrink the font
// proportionally so it stays on one line. Display sizes only — body text
// in narrow columns should wrap naturally, not shrink.
// A fill-in blank is an unbreakable nbsp run sized to its browser width.
// Inside a narrow table cell it overflows and blows up Word's fixed
// layout (the whole table widens past the page and clips) — shrink the
// blank to the width the cell actually has left.
fitFillInRuns(node) {
const runs = node.runs || []
const isBlank = (run) =>
run.underline && run.preserveWhitespace && /^\u00a0+$/.test(run.text || '')
if (!runs.some(isBlank)) return node
const availPx = this.avail / 15 / this.context.measurementScale
const spaceWidth = (run) => Math.max(3, (run.sizePx || 14) * 0.45)
const textPx = runs.reduce(
(sum, run) => (isBlank(run) ? sum : sum + (run.text || '').length * (run.sizePx || 14) * 0.6),
0,
)
const blankPx = runs.reduce(
(sum, run) => (isBlank(run) ? sum + run.text.length * spaceWidth(run) : sum),
0,
)
if (textPx + blankPx <= availPx * 0.92) return node
const budget = Math.max(0, availPx * 0.92 - textPx)
const scale = blankPx > 0 ? Math.min(1, budget / blankPx) : 1
return {
...node,
runs: runs.map((run) =>
isBlank(run)
? { ...run, text: '\u00a0'.repeat(Math.max(3, Math.floor(run.text.length * scale))) }
: run,
),
}
}
fitOneLineRuns(node) {
if (!node.style?.oneLineWidthPx) return node
// Headings never letter-wrap regardless of size; body text only when it
// is display-scale (small body copy should wrap naturally).
const sizeFloor = node.type === 'heading' || node.style?.keepLines ? 14 : 24
if (!node.runs.some((run) => (run.sizePx || 0) >= sizeFloor)) return node
const availPx = this.avail / 15 / this.context.measurementScale
if (node.style.oneLineWidthPx <= availPx * 0.94) return node
// 6% safety: Word's Arial runs slightly wider than browser fonts.
const fit = Math.max(0.55, (availPx * 0.94) / node.style.oneLineWidthPx)
return {
...node,
runs: node.runs.map((run) => (run.sizePx ? { ...run, sizePx: run.sizePx * fit } : run)),
}
}
renderImage(node) {
const img = this.images[node.shotId]
if (!img) {
const fallbackRun = new TextRun({
text: node.fallbackText || node.href || 'Unavailable embedded content',
color: node.href ? '0563C1' : '666666',
underline: node.href ? {} : undefined,
noProof: true,
})
return [
new Paragraph({
children: node.href
? [new ExternalHyperlink({ children: [fallbackRun], link: node.href })]
: [fallbackRun],
}),
]
}
const bleedLeftPx = node.bleedLeftPx || 0
const bleedRightPx = node.bleedRightPx || 0
const maxPx = Math.floor((this.avail + this.context.pxToTwips(bleedLeftPx + bleedRightPx)) / 15)
const pageContentHeightPx =
(this.context.pageHeightDxa -
this.context.pageMargins.top -
this.context.pageMargins.bottom) /
15
// Word (Mac) starts the first line ~26px below the page top even at zero
// margins, and the image line adds baseline descent below. A slice scaled
// to (content height - 4) therefore clipped its bottom ~25px at the page
// edge (lost resume contact rows). 45px absorbs the inset plus variance.
const pageScale = node.pageComposition
? Math.max(0.01, pageContentHeightPx - 45) / node.height
: Infinity
const scale = Math.min(this.context.measurementScale, maxPx / node.width, pageScale)
const output = []
// Full-page composition slides: the page margins already carry the
// authored offset — an extra spacer overflows the page and strands the
// slide image on a blank-page boundary.
if (node.spacingBeforePx > 2 && !node.pageComposition) {
output.push(spacerParagraph(this.context, node.spacingBeforePx))
}
const renderedWidthPx = Math.round(node.width * scale)
const renderedHeightPx = Math.round(node.height * scale)
const imageRun = new ImageRun({
type: 'png',
data: img,
transformation: {
width: renderedWidthPx,
height: renderedHeightPx,
},
})
output.push(
new Paragraph({
children: node.href
? [new ExternalHyperlink({ children: [imageRun], link: node.href })]
: [imageRun],
// wide short strips are section banners — never strand one at a
// page bottom with its section content on the next page
keepNext:
!this.suppressKeepNext &&
!node.pageComposition &&
renderedWidthPx >= (this.avail / 15) * 0.85 &&
renderedHeightPx <= 220
? true
: undefined,
alignment:
// Full-page slides: headroom scaling leaves a margin — split it
// symmetrically instead of piling white space on one side.
node.pageComposition || node.align === 'center'
? AlignmentType.CENTER
: node.align === 'right'
? AlignmentType.RIGHT
: undefined,
indent:
bleedLeftPx || bleedRightPx
? {
left: -this.context.pxToTwips(bleedLeftPx),
right: -this.context.pxToTwips(bleedRightPx),
}
: undefined,
spacing: {
before: 0,
after: 0,
line: Math.max(1, renderedHeightPx * 15),
// Word positions inline images relative to the text baseline.
// An exact line box equal to the image height clips the image's top
// and may push it to the next page. "At least" keeps the authored
// image height while allowing Word to include the full ascent.
lineRule: LineRuleType.AT_LEAST,
},
border: node.topEdgeFill
? {
top: {
style: BorderStyle.SINGLE,
size: 48,
color: node.topEdgeFill,
space: 0,
},
}
: undefined,
}),
)
if (node.spacingAfterPx > 2 && !node.pageComposition) {
output.push(spacerParagraph(this.context, node.spacingAfterPx))
}
return output
}
collectFloatingImage(node) {
const img = this.images[node.shotId]
if (!img) return []
// in-parent decorations beyond the first page reach here only when no
// card consumed them — page-anchoring would pin them to page 1
if (node.inParent && node.yPx + node.height > (node.pageHpx || 1123)) return []
const EMU = 9525 // per px @96dpi
// rescale browser coordinates: the DOCX content area is usually
// narrower/shorter than the HTML content box
const contentHeightDxa = this.context.pageHeightDxa - 2 * this.context.marginDxa
const sx = node.pageWpx ? this.context.contentDxa / 15 / node.pageWpx : 1
const sy = node.pageHpx ? contentHeightDxa / 15 / node.pageHpx : 1
this.floats.push(
new ImageRun({
type: 'png',
data: img,
transformation: {
width: Math.round(node.width * sx),
height: Math.round(node.height * sx),
},
floating: {
// margin origin = start of the content area, matching the
// body-content-box coordinates measured in the browser
horizontalPosition: { relative: 'margin', offset: Math.round(node.xPx * sx * EMU) },
verticalPosition: node.atPageBottom
? { relative: 'page', align: VerticalPositionAlign.BOTTOM }
: { relative: 'margin', offset: Math.round(node.yPx * Math.min(sy, 1) * EMU) },
// decorations painted under the HTML content layer (z<=0) go
// behind text; explicit z>0 art stays in front (table-cell shading
// would paint over a behind-text image, so only when needed)
behindDocument: Boolean(node.behindText),
wrap: { type: TextWrappingType.NONE },
},
}),
)
return []
}
}
export { Generator }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,359 @@
// @ts-nocheck — generation layer ported verbatim from untyped JS; it is typed
// file by file without logic changes, and until then strict consumers
// (apps/html, apps/shell) must not fail on it.
import {
AlignmentType,
BorderStyle,
CheckBox,
ExternalHyperlink,
HeadingLevel,
ImageRun,
InternalHyperlink,
PageNumber,
LineRuleType,
Paragraph,
ShadingType,
Tab,
TabStopType,
TextRun,
UnderlineType,
} from 'docx'
import { bookmarkName } from './bookmarks'
import { mapFont } from './fonts'
function makeRuns(context, runs, images: any = {}) {
const out = []
for (const r of runs) {
if (r.pageNumberField) {
out.push(
new TextRun({
children: [r.pageNumberField === 'total' ? PageNumber.TOTAL_PAGES : PageNumber.CURRENT],
bold: r.bold || undefined,
italics: r.italic || undefined,
color: r.color || undefined,
size: r.sizePx ? context.pxToHalfPoints(r.sizePx) : undefined,
font: mapFont(r.fontFamily, r.mono, r.text),
}),
)
continue
}
if (r.contentControl === 'checkbox') {
out.push(new CheckBox({ checked: Boolean(r.checked), alias: r.alias || 'Checkbox' }))
continue
}
if (r.inlineImage) {
const image = images[r.shotId]
if (image) {
out.push(
new ImageRun({
type: 'png',
data: image,
transformation: { width: r.width, height: r.height },
}),
)
}
continue
}
const underlineType =
r.underlineStyle === 'dotted'
? UnderlineType.DOTTED
: r.underlineStyle === 'dashed'
? (UnderlineType as any).DASHED
: UnderlineType.SINGLE
const style = {
bold: r.bold || undefined,
italics: r.italic || undefined,
underline: r.underline
? { type: underlineType, color: r.underlineColor || undefined }
: undefined,
strike: r.strike || undefined,
// always explicit: inherited styles (Heading1..6 theme blue) must not win
color: r.color || undefined,
size: r.sizePx ? context.pxToHalfPoints(r.sizePx) : undefined,
// Emoji: leave the font unset so Word's built-in emoji fallback picks the
// platform color-emoji font. Forcing 'Segoe UI Emoji' renders tofu boxes
// (and flags as "GB") on Mac Word, which lacks that font.
font: r.emoji
? undefined
: r.symbol
? 'Arial Unicode MS'
: mapFont(r.fontFamily, r.mono, r.text),
characterSpacing: r.letterSpacing > 0.5 ? context.pxToTwips(r.letterSpacing) : undefined,
superScript: r.superscript || undefined,
subScript: r.subscript || undefined,
allCaps: r.uppercase || undefined,
// w:rtl on the run so Arabic/Hebrew glyphs shape and order correctly
// (docx mirrors size/bold/italics into their complex-script twins)
rightToLeft: r.rtl || undefined,
// arbitrary hex needs character shading (w:highlight only takes named colors)
shading: r.highlight ? { type: ShadingType.CLEAR, fill: r.highlight } : undefined,
// inline boxed chip -> character border (w:bdr); space:1 keeps a hair of
// padding between glyph and frame like the authored chip padding
border: r.charBorder
? {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(r.charBorder.widthPx),
color: r.charBorder.color,
space: 1,
}
: undefined,
noProof: true,
}
const lines = (r.text || '').split('\n')
lines.forEach((line, i) => {
const segments = line.split('\t')
segments.forEach((segment, j) => {
const needsBreak = i > 0 && j === 0
const children = []
if (j > 0) children.push(new Tab())
if (segment) children.push(segment)
// standalone <br> produces an empty segment that must still emit the break
if (!children.length && !needsBreak) return
const run = new TextRun({ ...style, children, break: needsBreak ? 1 : undefined })
if (r.anchor) {
out.push(new InternalHyperlink({ children: [run], anchor: bookmarkName(r.anchor) }))
} else if (r.href) {
out.push(new ExternalHyperlink({ children: [run], link: r.href }))
} else {
out.push(run)
}
})
})
}
return out
}
function makeNodeRuns(context, node, images: any = {}) {
const runs = makeRuns(context, node.runs, images)
const insetPx = node.style?.borderLeftSpacePx || 0
if (insetPx > 0) {
const sample = node.runs.find((run) => run.text) || {}
const fontSizePx = sample.sizePx || 16
const count = Math.max(1, Math.ceil(insetPx / (fontSizePx * 0.65)))
runs.unshift(
new TextRun({
text: '\u00A0'.repeat(count),
size: context.pxToHalfPoints(fontSizePx),
font: mapFont(sample.fontFamily, sample.mono, sample.text),
noProof: true,
}),
)
}
return runs
}
// Rebuild tab stops from measured positions: a separator whose following
// content starts far right becomes a right-aligned stop at the margin
// (dates), otherwise a left stop at the measured column position.
function tabStopsFor(context, runs) {
const tabs = runs.filter((r) => r.text.includes('\t'))
if (!tabs.length) return []
const stops = []
const seen = new Set()
for (const r of tabs) {
// Column starting past 75% of the line is a right-aligned tail (dates);
// otherwise reproduce the measured column position with a left stop.
const stop =
r.tabFrac != null && r.tabFrac < 0.75
? { type: TabStopType.LEFT, position: Math.round(r.tabFrac * context.contentDxa) }
: { type: TabStopType.RIGHT, position: context.contentDxa }
const key = `${stop.type}:${stop.position}`
if (!seen.has(key)) {
seen.add(key)
stops.push(stop)
}
}
return stops
}
function paraOptions(context, style: any = {}) {
const opts: any = {}
// w:bidi: paragraph flows right-to-left (default alignment becomes right)
if (style.rtl) opts.bidirectional = true
if (style.align === 'center') opts.alignment = AlignmentType.CENTER
if (style.align === 'right') opts.alignment = AlignmentType.RIGHT
// explicit physical left (an RTL paragraph author-aligned to the left edge)
if (style.align === 'left' && style.rtl) opts.alignment = AlignmentType.LEFT
if (style.align === 'justify') opts.alignment = AlignmentType.JUSTIFIED
if (style.indentLeftPx || style.indentHangingPx) {
// hanging: first line carries the literal bullet/number prefix at
// indentLeftPx, wrapped lines align under the text after the prefix
const hang = style.indentHangingPx ? context.pxToTwips(style.indentHangingPx) : 0
opts.indent = {
left: context.pxToTwips(style.indentLeftPx || 0) + hang,
...(hang ? { hanging: hang } : {}),
}
} else if (style.firstLineIndentPx) {
// CSS text-indent (CJK-style opening indent) -> w:ind firstLine
opts.indent = { firstLine: context.pxToTwips(style.firstLineIndentPx) }
}
opts.spacing = {}
if (style.spacingAfterPx) opts.spacing.after = context.pxToTwips(style.spacingAfterPx)
if (style.spacingBeforePx) opts.spacing.before = context.pxToTwips(style.spacingBeforePx)
if (style.lineRatio) {
// Word's intrinsic leading is larger for CJK fonts than Latin fonts.
const effective = Math.max(1, style.lineRatio / (style.cjk ? 1.3 : 1.15))
opts.spacing.line = Math.round(effective * 240)
}
if (style.exactLineHeightPx) {
// Shaded single-line bars: force the browser-rendered height, otherwise
// Word's CJK leading makes the colored strip visibly taller.
// Bordered paragraphs (left accent bars) must not use EXACT: Word drops
// the text to the line bottom while the border hugs the paragraph box,
// so the accent bar floats visibly above the heading text.
opts.spacing.line = context.pxToTwips(style.exactLineHeightPx)
opts.spacing.lineRule =
style.borderLeft || style.borderRight ? LineRuleType.AT_LEAST : LineRuleType.EXACT
}
if (style.shading) opts.shading = { type: ShadingType.CLEAR, fill: style.shading }
if (style.borderLeft || style.borderRight || style.borderTop || style.borderBottom) {
opts.border = {}
if (style.borderLeft) {
opts.border.left = {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(style.borderLeft.widthPx),
color: style.borderLeft.color,
// w:space pushes the border left, away from the text (in points,
// capped at 31 by Word)
space: style.borderLeftOutsetPx
? Math.min(
31,
Math.max(1, Math.round(style.borderLeftOutsetPx * 0.75 * context.measurementScale)),
)
: undefined,
}
}
if (style.borderBottom) {
opts.border.bottom = {
style:
style.borderBottom.style === 'dotted'
? BorderStyle.DOTTED
: style.borderBottom.style === 'dashed'
? BorderStyle.DASHED
: BorderStyle.SINGLE,
size: context.pxToBorderEighths(style.borderBottom.widthPx),
color: style.borderBottom.color,
space: 4,
}
}
if (style.borderRight) {
opts.border.right = {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(style.borderRight.widthPx),
color: style.borderRight.color,
space: style.borderRightSpacePx
? Math.max(1, Math.round(style.borderRightSpacePx * 0.75 * context.measurementScale))
: undefined,
}
}
if (style.borderTop) {
opts.border.top = {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(style.borderTop.widthPx),
color: style.borderTop.color,
space: 4,
}
}
}
return opts
}
// Empty paragraph occupying an exact pixel height (spacing around tables,
// which can't carry before/after spacing themselves).
// keepNext binds the spacer to the following block: needed between a heading
// and its section body (else the heading's own keepNext only reaches the
// spacer and Word orphans the heading at a page bottom), but must NOT be on
// trailing spacers \u2014 a document-wide spacer chain would fuse sections and
// force Word to break pages far too early.
function spacerParagraph(
context,
px,
{ keepNext = false, shading = null, borderLeft = null } = {},
) {
const paragraph = new Paragraph({
// Word tables already contribute a few pixels of leading. Force only
// authored block gaps large enough to be visually meaningful.
children: [new TextRun({ text: px >= 24 ? '\u200B' : '', size: 2, noProof: true })],
...(keepNext ? { keepNext: true } : {}),
...(shading ? { shading: { type: ShadingType.CLEAR, fill: shading } } : {}),
// continues a flattened card's left rail through spacing gaps
...(borderLeft
? {
border: {
left: {
style: BorderStyle.SINGLE,
size: context.pxToBorderEighths(borderLeft.widthPx),
color: borderLeft.color,
},
},
}
: {}),
spacing: {
before: 0,
after: 0,
line: context.pxToTwips(Math.max(px, 2)),
lineRule: LineRuleType.EXACT,
},
})
// Marker so Generator.render can swap a rendered block's leading spacer
// for a keepNext one when it directly follows a heading.
const marked = paragraph as any
marked.__h2dSpacerPx = px
marked.__h2dSpacerShading = shading
marked.__h2dSpacerBorderLeft = borderLeft
return paragraph
}
const NO_BORDER = { style: BorderStyle.NONE, size: 0, color: 'FFFFFF' }
const NO_BORDERS = {
top: NO_BORDER,
bottom: NO_BORDER,
left: NO_BORDER,
right: NO_BORDER,
}
// Table-level: without it the docx library emits default single borders,
// and Word (Mac) paints them even where cells say val="none" — visible as
// a gray frame around dark panels.
const NO_TABLE_BORDERS = {
...NO_BORDERS,
insideHorizontal: NO_BORDER,
insideVertical: NO_BORDER,
}
function wordBorder(context, border) {
if (!border) return NO_BORDER
const styles = {
dotted: BorderStyle.DOTTED,
dashed: BorderStyle.DASHED,
double: BorderStyle.DOUBLE,
}
return {
style: styles[border.style] || BorderStyle.SINGLE,
// Floor at 0.75pt: a scaled 1px CSS border falls to 0.5pt and turns
// nearly invisible in Word at common zoom levels (same floor as cards).
size: Math.max(6, context.pxToBorderEighths(border.widthPx)),
color: border.color,
}
}
const HEADING_LEVELS = [
HeadingLevel.HEADING_1,
HeadingLevel.HEADING_2,
HeadingLevel.HEADING_3,
HeadingLevel.HEADING_4,
HeadingLevel.HEADING_5,
HeadingLevel.HEADING_6,
]
export {
HEADING_LEVELS,
NO_BORDER,
NO_BORDERS,
NO_TABLE_BORDERS,
makeNodeRuns,
makeRuns,
paraOptions,
spacerParagraph,
tabStopsFor,
wordBorder,
}
+6
View File
@@ -0,0 +1,6 @@
export { convertHtmlToDocx } from './convert'
export type { ConvertOptions, ConvertResult, ConvertStage } from './convert'
export type { BrowserDriver, ClipRect, ScreenshotOptions, Viewport } from './driver'
export { BROWSER_HELPER_SCRIPTS, EXTRACTOR_CALL, EXTRACTOR_SOURCE } from './extract'
export { generateDocx } from './generate'
export { FONT_RULES, mapFont } from './generate/fonts'
+4
View File
@@ -0,0 +1,4 @@
declare module '*?raw' {
const source: string
export default source
}
File diff suppressed because it is too large Load Diff
+81
View File
@@ -0,0 +1,81 @@
/**
* html2docx <input.html> <output.docx> [--verbose]
*
* Runs through Vite's SSR loader so the extractor's `?raw` fragment imports
* resolve the same way they do in the app bundle and in vitest:
* npx tsx packages/html2docx/tools/cli.ts in.html out.docx
*
* Debug env: H2D_SHOT_TEXT_PATH (write rasterized text), H2D_IR_PATH (dump
* IR + trace), H2D_TRACE_SELECTOR (in-page probes).
*/
import { writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { createServer } from 'vite'
import type { ConvertOptions, ConvertResult } from '../src'
import type { PlaywrightDriver as PlaywrightDriverType } from '../src/drivers/playwright'
const A4 = { width: 794, height: 1123, deviceScaleFactor: 2 }
async function main(): Promise<void> {
const verbose = process.argv.includes('--verbose') || process.argv.includes('-v')
const args = process.argv.slice(2).filter((a) => a !== '--verbose' && a !== '-v')
if (args.length < 2) {
console.error('Usage: html2docx <input.html> <output.docx> [--verbose]')
process.exit(1)
}
const [input, output] = args
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const vite = await createServer({
root,
configFile: false,
logLevel: 'error',
server: { middlewareMode: true, hmr: false },
optimizeDeps: { noDiscovery: true },
})
try {
const lib = (await vite.ssrLoadModule('/src/index.ts')) as {
convertHtmlToDocx: (
input: { url: string },
driver: PlaywrightDriverType,
options: ConvertOptions,
) => Promise<ConvertResult>
}
const { PlaywrightDriver, launchChrome } = (await vite.ssrLoadModule(
'/src/drivers/playwright.ts',
)) as typeof import('../src/drivers/playwright')
const browser = await launchChrome()
try {
const driver = await PlaywrightDriver.create(browser, A4)
const url = input.startsWith('http') ? input : pathToFileURL(resolve(input)).href
const result = await lib.convertHtmlToDocx({ url }, driver, {
log: verbose ? (m) => console.error(m) : undefined,
traceSelector: process.env.H2D_TRACE_SELECTOR,
onIr: process.env.H2D_IR_PATH
? (ir, trace) => {
writeFileSync(`${process.env.H2D_IR_PATH}.trace`, JSON.stringify(trace, null, 1))
writeFileSync(
process.env.H2D_IR_PATH!,
JSON.stringify(ir, (key, value) => (key === 'buffer' ? undefined : value), 1),
)
}
: undefined,
})
await driver.close()
writeFileSync(output, result.docx)
if (process.env.H2D_SHOT_TEXT_PATH) {
writeFileSync(process.env.H2D_SHOT_TEXT_PATH, result.screenshotText, 'utf8')
}
console.log(output)
} finally {
await browser.close()
}
} finally {
await vite.close()
}
}
main().catch((e) => {
console.error(e)
process.exit(1)
})
+12
View File
@@ -0,0 +1,12 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"],
// DOM for the functions convert.ts serializes into the page
"lib": ["ES2022", "DOM", "DOM.Iterable"],
// ported from untyped JS; tightened file by file, no logic changes
"strict": false,
"noImplicitAny": false
},
"include": ["src", "tests", "tools"]
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['tests/**/*.test.ts'],
// every case renders in a real Chromium
testTimeout: 90000,
hookTimeout: 60000,
},
})
+1 -1
View File
@@ -15,6 +15,6 @@
},
"devDependencies": {
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
}
}
+3
View File
@@ -13,6 +13,7 @@ export type Lang =
| 'pt'
| 'it'
| 'pl'
| 'cs'
| 'nl'
| 'ms'
| 'he'
@@ -34,6 +35,7 @@ export const LANGS: readonly Lang[] = [
'pt',
'it',
'pl',
'cs',
'nl',
'ms',
'he',
@@ -76,6 +78,7 @@ const HTML_LANGS: Record<Lang, string> = {
pt: 'pt-BR',
it: 'it-IT',
pl: 'pl-PL',
cs: 'cs-CZ',
nl: 'nl-NL',
ms: 'ms-MY',
he: 'he-IL',
+4
View File
@@ -46,6 +46,7 @@ describe('normalizeLang', () => {
expect(normalizeLang('pt-PT')).toBe('pt')
expect(normalizeLang('it-IT')).toBe('it')
expect(normalizeLang('pl-PL')).toBe('pl')
expect(normalizeLang('cs-CZ')).toBe('cs')
expect(normalizeLang('nl-NL')).toBe('nl')
expect(normalizeLang('ms-MY')).toBe('ms')
expect(normalizeLang('he-IL')).toBe('he')
@@ -78,6 +79,7 @@ describe('isLang', () => {
expect(isLang('pt')).toBe(true)
expect(isLang('it')).toBe(true)
expect(isLang('pl')).toBe(true)
expect(isLang('cs')).toBe(true)
expect(isLang('nl')).toBe(true)
expect(isLang('ms')).toBe(true)
expect(isLang('he')).toBe(true)
@@ -173,6 +175,7 @@ describe('createI18n', () => {
pt: { hello: 'Olá {name}', plain: 'Arquivos' },
it: { hello: 'Ciao {name}', plain: 'File' },
pl: { hello: 'Cześć {name}', plain: 'Pliki' },
cs: { hello: 'Ahoj {name}', plain: 'Soubory' },
nl: { hello: 'Hallo {name}', plain: 'Bestanden' },
ms: { hello: 'Helo {name}', plain: 'Fail' },
he: { hello: 'שלום {name}', plain: 'קבצים' },
@@ -191,6 +194,7 @@ describe('createI18n', () => {
expect(t('ar', 'plain')).toBe('الملفات')
expect(t('pt', 'hello', { name: 'mundo' })).toBe('Olá mundo')
expect(t('he', 'plain')).toBe('קבצים')
expect(t('cs', 'plain')).toBe('Soubory')
expect(t('zh-TW', 'plain')).toBe('檔案')
})
})
+1 -1
View File
@@ -24,6 +24,6 @@
"devDependencies": {
"@types/node": "^24.10.1",
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
}
}
+7
View File
@@ -147,6 +147,13 @@ export function classifyFloatImages(
const bodyRight = units.length > 0 ? Math.max(...units.map((u) => u.box.x1)) : 0
for (const img of images) {
// a rasterized pattern fill (P35) is a drawn shape, never inline content:
// flowed, a title-only gradient card would add its full height to the text
if (img.synthetic) {
img.float = { wrap: 'behind', xOffsetPt: Math.max(0, img.box.x0 - bodyLeft) }
floats.push(img)
continue
}
const over = units.filter((u) => overlapRatio(u.box, img.box) >= 0.8)
const beside = units.filter(
(u) =>
+8 -1
View File
@@ -432,7 +432,12 @@ export function analyzePage(extracted: ExtractedPage): IrPage {
// a fill covering ~the whole page is the page wash, not content — record it
// for the document background and keep it out of the shape pool so it never
// reads as cell shading / highlight / vector art
const bg = extractPageBackground(shapes.fills, extracted.widthPt, extracted.heightPt)
const bg = extractPageBackground(
shapes.fills,
extracted.widthPt,
extracted.heightPt,
extracted.contentBox,
)
if (bg !== undefined && !isNearWhite(bg)) base.bgColor = bg
// full-bleed tile group (P22 B): a text-free page painted edge-to-edge by a
@@ -460,6 +465,7 @@ export function analyzePage(extracted: ExtractedPage): IrPage {
extracted.chars.map((c) => c.box),
extracted.widthPt,
extracted.heightPt,
extracted.contentBox,
)
if (panels.length > 0) {
base.bgPanels = panels.map((p) => solidPanelImage(p.box, p.color, p.alpha, p.z))
@@ -616,6 +622,7 @@ export function analyzePage(extracted: ExtractedPage): IrPage {
pixelWidth: img.pixelWidth,
pixelHeight: img.pixelHeight,
...(img.z !== undefined ? { z: img.z } : {}),
...(img.synthetic ? { synthetic: true as const } : {}),
}))
const { floats, inline } = classifyFloatImages(
suppressTextShadowImages(imageBlocks, remainingUnits),
+50 -6
View File
@@ -6,7 +6,7 @@
* P4. Pure geometry, fully unit-testable.
*/
import type { Rect } from '../geometry'
import { approxEq, intersectArea, rectArea } from '../geometry'
import { approxEq, coversBox, intersectArea, rectArea } from '../geometry'
import type { Fill, PageShapes, RawPath, RawSubpath, Stroke } from '../ir'
/** points this close are the same coordinate when detecting rectangles/axis lines */
@@ -494,11 +494,17 @@ export function extractPageBackground(
fills: Fill[],
widthPt: number,
heightPt: number,
/** print content box (uniform margins): a fill covering it is the wash too */
contentBox?: Rect | null,
): string | undefined {
let color: string | undefined
const pageBox = { x0: 0, y0: 0, x1: widthPt, y1: heightPt }
for (let i = fills.length - 1; i >= 0; i--) {
const b = fills[i]!.box
if (b.x1 - b.x0 >= widthPt * BG_COVER_RATIO && b.y1 - b.y0 >= heightPt * BG_COVER_RATIO) {
if (
coversBox(b, pageBox, BG_COVER_RATIO) ||
(contentBox != null && coversBox(b, contentBox, BG_COVER_RATIO))
) {
if (color === undefined) color = fills[i]!.color
fills.splice(i, 1)
}
@@ -535,9 +541,14 @@ export function extractBackgroundPanels(
charBoxes: readonly Rect[],
widthPt: number,
heightPt: number,
/** print content box: spines/banners are flush with ITS edges, not the paper's */
contentBox?: Rect | null,
): Fill[] {
const pageArea = widthPt * heightPt
if (pageArea <= 0) return []
const edge = contentBox ?? { x0: 0, y0: 0, x1: widthPt, y1: heightPt }
const edgeW = edge.x1 - edge.x0
const edgeH = edge.y1 - edge.y0
const panels: Fill[] = []
const isPanel = (b: Rect, color: string): boolean => {
if (isNearWhite(color)) return false
@@ -545,11 +556,11 @@ export function extractBackgroundPanels(
const share = area / pageArea
if (share < PANEL_MIN_AREA_RATIO || share > PANEL_MAX_AREA_RATIO) return false
const fullHeight =
b.y1 - b.y0 >= heightPt * PANEL_FULL_DIM_RATIO &&
(b.x0 <= PANEL_EDGE_TOL_PT || b.x1 >= widthPt - PANEL_EDGE_TOL_PT)
b.y1 - b.y0 >= edgeH * PANEL_FULL_DIM_RATIO &&
(b.x0 <= edge.x0 + PANEL_EDGE_TOL_PT || b.x1 >= edge.x1 - PANEL_EDGE_TOL_PT)
const fullWidth =
b.x1 - b.x0 >= widthPt * PANEL_FULL_DIM_RATIO &&
(b.y0 <= PANEL_EDGE_TOL_PT || b.y1 >= heightPt - PANEL_EDGE_TOL_PT)
b.x1 - b.x0 >= edgeW * PANEL_FULL_DIM_RATIO &&
(b.y0 <= edge.y0 + PANEL_EDGE_TOL_PT || b.y1 >= edge.y1 - PANEL_EDGE_TOL_PT)
if (!fullHeight && !fullWidth) return false
let chars = 0
for (const c of charBoxes) {
@@ -609,6 +620,14 @@ const CAPSULE_MIN_ASPECT = 2
/** …and mostly occupied by its text, not a decorative swoosh with a stray label */
const CAPSULE_MIN_TEXT_WIDTH_SHARE = 0.3
// ── plates hosting lighter cards (P35) ──
/** a hosted card must be at least this much lighter than its plate */
const PLATE_MIN_CARD_CONTRAST = 0.3
/** … and a real card, not a bullet (pt²) */
const PLATE_CARD_MIN_AREA_PT2 = 600
/** … while leaving the plate visible around it */
const PLATE_CARD_MAX_SHARE = 0.85
/** relative luminance of a RRGGBB hex, 0 (black) – 1 (white) */
export function hexLuminance(hex: string): number {
if (!/^[0-9a-fA-F]{6}$/.test(hex)) return 0
@@ -642,6 +661,14 @@ export function extractTextBackdrops(
const cy = (b.y0 + b.y1) / 2
return cx >= r.x0 && cx <= r.x1 && cy >= r.y0 && cy <= r.y1
}
// the pool as it was before any backdrop left it: hosted-card lookups must
// see cards that were themselves claimed earlier in the scan
const pool = [...fills, ...curvedFills]
const containsRect = (outer: Rect, inner: Rect): boolean =>
inner.x0 >= outer.x0 - 1 &&
inner.x1 <= outer.x1 + 1 &&
inner.y0 >= outer.y0 - 1 &&
inner.y1 <= outer.y1 + 1
const qualifies = (fill: Fill, rounded = false): boolean => {
const area = (fill.box.x1 - fill.box.x0) * (fill.box.y1 - fill.box.y0)
// the pool paths need a real card; the capsule path (rounded only) sizes
@@ -685,6 +712,23 @@ export function extractTextBackdrops(
const medianLuma = lumas[Math.floor(lumas.length / 2)]!
if (Math.abs(medianLuma - fillLuma) >= BACKDROP_CARD_MIN_CONTRAST) return true
}
// plate hosting lighter cards (P35): a dark UI mockup / feature plate
// whose text sits on lighter sub-cards — the text alone never contrasts
// with the plate, but without it those cards vanish on the white paper
if (
fillLuma <= BACKDROP_MAX_FILL_LUMA &&
area >= BACKDROP_CARD_MIN_PAGE_RATIO * pageArea &&
pool.some(
(other) =>
other !== fill &&
rectArea(other.box) >= PLATE_CARD_MIN_AREA_PT2 &&
rectArea(other.box) <= PLATE_CARD_MAX_SHARE * area &&
containsRect(fill.box, other.box) &&
hexLuminance(other.color) - fillLuma >= PLATE_MIN_CARD_CONTRAST,
)
) {
return true
}
// label plate (P16 I): a mid-size flat plate far taller than the short
// label it carries (a grey "payment method" caption block) — highlight bars and
// zebra rows hug their text line and never reach the height gate
+11 -5
View File
@@ -151,11 +151,17 @@ function findCandidates(
for (const row of rows) {
const prev = run[run.length - 1]
const rowH = row.box.y1 - row.box.y0
// a strong run is unmistakably tabular — its typical row splits into many
// units. Only such runs earn the relaxed continuation rules; a run seeded
// by 2-3-unit prose fragments must never glue itself into a table below
// (health.pdf: title rows + absorbed prose poisoned the whole candidate)
const runStrong = run.length > 0 && median(run.map((r) => r.units.length)) >= SPARSE_MIN_UNITS
// a strong run is unmistakably tabular — its typical ANCHOR row splits
// into many units. Only such runs earn the relaxed continuation rules; a
// run seeded by 2-3-unit prose fragments must never glue itself into a
// table below (health.pdf: title rows + absorbed prose poisoned the whole
// candidate). Judged over the anchor rows only: absorbed 1-unit label
// continuations must not dilute the median, or a statement whose every
// transaction wraps its description over several lines (bank statements'
// reference-number stacks) collapses the run after two absorptions.
const anchorRows = run.filter((r) => r.units.length >= STREAM_MIN_COLS)
const runStrong =
anchorRows.length > 0 && median(anchorRows.map((r) => r.units.length)) >= SPARSE_MIN_UNITS
let gapOk = false
if (prev !== undefined) {
const gap = prev.box.y0 - row.box.y1
+286 -10
View File
@@ -5,7 +5,7 @@
*/
import { detectVectorRegions } from '../analyze/vector'
import type { Rect } from '../geometry'
import { intersectArea, overlapRatio, rectArea } from '../geometry'
import { coversBox, intersectArea, overlapRatio, printContentBox, rectArea } from '../geometry'
import type { PdfChar, PageRender, RawPath, RawSubpath } from '../ir'
import { scriptOf } from '../script'
import type { PdfiumModule } from './pdfium'
@@ -44,6 +44,8 @@ export interface ExtractedImage {
pixelHeight: number
/** source paint order (top-level page-object index, P16 A) */
z?: number
/** rasterized pattern fill (P35), not a picture the author placed */
synthetic?: true
}
export interface ExtractedPage {
@@ -80,6 +82,12 @@ export interface ExtractedPage {
* as a full-page behindDoc float. Absent on plain (white / flat-fill) pages.
*/
bgRender?: PageRender
/**
* print content box (P35): all ink sits inside uniform page margins
* (browser/driver prints). Background rules measure page-covering fills
* against it — a body wash never reaches the paper edge on such pages.
*/
contentBox?: Rect
/**
* non-page-covering gradient shadings rasterized transparent (P19): slide
* title bars / accent strips. Consumed ONLY by the canvas rebuild path —
@@ -1304,6 +1312,7 @@ function detectBackgroundStack(
page: number,
widthPt: number,
heightPt: number,
contentBox: Rect | null,
): {
count: number
rasterIndices: number[]
@@ -1312,6 +1321,7 @@ function detectBackgroundStack(
suspectOnly: boolean
} {
const total = m._FPDFPage_CountObjects(page)
const pageBox: Rect = { x0: 0, y0: 0, x1: widthPt, y1: heightPt }
const rasterIndices: number[] = []
const formTextHandles = new Set<number>()
let count = 0
@@ -1339,14 +1349,19 @@ function detectBackgroundStack(
inPrefix = false
continue
}
const x0 = m.HEAPF32[f4 >> 2]!
const y0 = m.HEAPF32[(f4 >> 2) + 1]!
const x1 = m.HEAPF32[(f4 >> 2) + 2]!
const y1 = m.HEAPF32[(f4 >> 2) + 3]!
const coveredW = Math.min(x1, widthPt) - Math.max(x0, 0)
const coveredH = Math.min(y1, heightPt) - Math.max(y0, 0)
const bounds: Rect = {
x0: m.HEAPF32[f4 >> 2]!,
y0: m.HEAPF32[(f4 >> 2) + 1]!,
x1: m.HEAPF32[(f4 >> 2) + 2]!,
y1: m.HEAPF32[(f4 >> 2) + 3]!,
}
const cover = inPrefix ? BG_LAYER_DIM_COVER : BG_EXT_DIM_COVER
if (coveredW < widthPt * cover || coveredH < heightPt * cover) {
// a fill covering the print content box occludes everything on such a
// page just like a full-bleed wash does (the margins carry no ink)
if (
!coversBox(bounds, pageBox, cover) &&
!(contentBox !== null && coversBox(bounds, contentBox, cover))
) {
inPrefix = false
continue
}
@@ -1383,6 +1398,234 @@ function detectBackgroundStack(
return { count, rasterIndices, formTextHandles, suspectOnly: sureCount === 0 }
}
/**
* Print content box (P35): the bottom-most opaque fill whose bounds frame the
* page's ink inside uniform margins. Alpha-0 page-covering rects (Skia
* bounding artifacts) lay no ink and neither widen the ink nor qualify.
*/
function pageContentBox(
m: PdfiumModule,
page: number,
widthPt: number,
heightPt: number,
): Rect | null {
const total = m._FPDFPage_CountObjects(page)
const boxes: Rect[] = []
const fills: Rect[] = []
withAlloc(m, 4 * 4, (f4) => {
for (let i = 0; i < total; i++) {
const obj = m._FPDFPage_GetObject(page, i)
if (!obj) continue
const type = m._FPDFPageObj_GetType(obj)
const isPath = type === FPDF_PAGEOBJ_PATH
if (isPath && !pathPaintsInk(m, obj, f4)) continue
if (!m._FPDFPageObj_GetBounds(obj, f4, f4 + 4, f4 + 8, f4 + 12)) continue
const box: Rect = {
x0: m.HEAPF32[f4 >> 2]!,
y0: m.HEAPF32[(f4 >> 2) + 1]!,
x1: m.HEAPF32[(f4 >> 2) + 2]!,
y1: m.HEAPF32[(f4 >> 2) + 3]!,
}
if (box.x1 <= box.x0 || box.y1 <= box.y0) continue
boxes.push(box)
if (isPath && pathIsOpaqueFill(m, obj, f4)) fills.push(box)
}
})
// the wash is drawn early: the first (bottom-z) opaque fill that frames the ink wins
for (const f of fills) {
const box = printContentBox(f, boxes, widthPt, heightPt)
if (box) return box
}
return null
}
// ── pattern-filled paths (P35) ──
// CSS gradients print as PATHS filled with a shading/tiling PATTERN. PDFium's
// color API cannot voice a pattern: CPDF_ColorState::SetPattern reports a
// shading pattern as white and a colored tiling pattern as 0xBFBFBF, so the
// gradient cover/card reached the fill pool as a plain white/grey rectangle
// and was dropped (or shaded flat grey). Paths reporting exactly those
// fallback colors are probed with a tiny render of the object alone; the ones
// whose pixels disagree with the reported color rasterize transparent into
// the image stream and leave the path stream.
/** PDFium's pattern fallback colors (channel value, all three equal) */
const PATTERN_FALLBACK_CHANNELS = new Set([0xff, 0xbf])
/** smaller fills are bullets/rules — never gradients worth a bitmap */
const PATTERN_MIN_AREA_PT2 = 400
/** thinner strips are text-line highlights/underlines — a flow-breaking image buys nothing */
const PATTERN_MIN_DIM_PT = 12
/** probe render longest side (px) — enough to tell a gradient from a flat fill */
const PATTERN_PROBE_PX = 24
/** a probe pixel this far from the reported color (any channel) is not that color */
const PATTERN_COLOR_TOL = 24
/** probe pixels below this alpha are unpainted */
const PATTERN_PROBE_MIN_ALPHA = 8
/** the object must actually paint this share of its own bounds to be judged */
const PATTERN_PROBE_MIN_COVER = 0.05
/** per page, largest candidates first */
const PATTERN_MAX_PROBES = 48
const PATTERN_RENDER_SCALE = 1.5
const PATTERN_RENDER_MAX_PX = 4_000_000
/** render one top-level object alone, transparent, cropped to `region` at `scale` */
function renderObjectAloneRgba(
m: PdfiumModule,
doc: number,
pageIndex: number,
index: number,
region: Rect,
scale: number,
): { rgba: Uint8Array; width: number; height: number } | null {
const page = m._FPDF_LoadPage(doc, pageIndex)
if (!page) return null
try {
const total = m._FPDFPage_CountObjects(page)
for (let i = total - 1; i >= 0; i--) {
if (i === index) continue
const obj = m._FPDFPage_GetObject(page, i)
if (obj && m._FPDFPage_RemoveObject(page, obj)) m._FPDFPageObj_Destroy(obj)
}
const pageWidthPt = m._FPDF_GetPageWidthF(page)
const pageHeightPt = m._FPDF_GetPageHeightF(page)
const width = Math.max(1, Math.round((region.x1 - region.x0) * scale))
const height = Math.max(1, Math.round((region.y1 - region.y0) * scale))
const bitmap = m._FPDFBitmap_Create(width, height, 1)
if (!bitmap) return null
try {
m._FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0x00000000)
m._FPDF_RenderPageBitmap(
bitmap,
page,
Math.round(-region.x0 * scale),
Math.round(-(pageHeightPt - region.y1) * scale),
Math.round(pageWidthPt * scale),
Math.round(pageHeightPt * scale),
0,
0,
)
return bitmapToRgba(m, bitmap)
} finally {
m._FPDFBitmap_Destroy(bitmap)
}
} finally {
m._FPDF_ClosePage(page)
}
}
/**
* Probe verdict: 'flat' = the object really is the reported color (a plain
* white card — stays a path); 'pattern' = its pixels disagree (gradient /
* tile art — rasterize); 'invisible' = it paints next to nothing (a fully
* soft-masked layer — drop, it must not survive as a grey rectangle).
*/
function probeVerdict(px: { rgba: Uint8Array }, channel: number): 'flat' | 'pattern' | 'invisible' {
let covered = 0
let sampled = 0
let off = false
for (let i = 0; i < px.rgba.length; i += 4) {
sampled++
// any paint counts: a translucent white plate (alpha 0.15) is a real flat
// fill, only a fully masked-out layer is invisible
if (px.rgba[i + 3]! < PATTERN_PROBE_MIN_ALPHA) continue
covered++
if (
Math.abs(px.rgba[i]! - channel) > PATTERN_COLOR_TOL ||
Math.abs(px.rgba[i + 1]! - channel) > PATTERN_COLOR_TOL ||
Math.abs(px.rgba[i + 2]! - channel) > PATTERN_COLOR_TOL
) {
off = true
}
}
if (sampled === 0 || covered / sampled < PATTERN_PROBE_MIN_COVER) return 'invisible'
return off ? 'pattern' : 'flat'
}
/**
* Pattern-filled paths → transparent bitmaps in the image stream (P35).
* Returns the images plus the top-level indices readPaths must skip.
*/
function readPatternFills(
m: PdfiumModule,
doc: number,
pageIndex: number,
page: number,
widthPt: number,
heightPt: number,
skipBelowIndex: number,
): { images: ExtractedImage[]; consumed: Set<number> } {
const images: ExtractedImage[] = []
const consumed = new Set<number>()
const total = m._FPDFPage_CountObjects(page)
const candidates: { index: number; box: Rect; channel: number }[] = []
withAlloc(m, 4 * 4, (u4) => {
for (let i = skipBelowIndex; i < total; i++) {
const obj = m._FPDFPage_GetObject(page, i)
if (!obj || m._FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_PATH) continue
if (!m._FPDFPath_GetDrawMode(obj, u4, u4 + 4) || (m.HEAPU32[u4 >> 2]! | 0) === 0) continue
if (!m._FPDFPageObj_GetFillColor(obj, u4, u4 + 4, u4 + 8, u4 + 12)) continue
const r = m.HEAPU32[u4 >> 2]!
const g = m.HEAPU32[(u4 >> 2) + 1]!
const b = m.HEAPU32[(u4 >> 2) + 2]!
const a = m.HEAPU32[(u4 >> 2) + 3]!
if (r !== g || g !== b || !PATTERN_FALLBACK_CHANNELS.has(r) || a <= IMAGE_MIN_ALPHA) continue
if (!m._FPDFPageObj_GetBounds(obj, u4, u4 + 4, u4 + 8, u4 + 12)) continue
const box: Rect = {
x0: Math.max(0, m.HEAPF32[u4 >> 2]!),
y0: Math.max(0, m.HEAPF32[(u4 >> 2) + 1]!),
x1: Math.min(widthPt, m.HEAPF32[(u4 >> 2) + 2]!),
y1: Math.min(heightPt, m.HEAPF32[(u4 >> 2) + 3]!),
}
const w = box.x1 - box.x0
const h = box.y1 - box.y0
if (w < PATTERN_MIN_DIM_PT || h < PATTERN_MIN_DIM_PT || w * h < PATTERN_MIN_AREA_PT2) continue
candidates.push({ index: i, box, channel: r })
}
})
if (candidates.length === 0) return { images, consumed }
candidates.sort((p, q) => rectArea(q.box) - rectArea(p.box))
for (const c of candidates.slice(0, PATTERN_MAX_PROBES)) {
const w = c.box.x1 - c.box.x0
const h = c.box.y1 - c.box.y0
const probe = renderObjectAloneRgba(
m,
doc,
pageIndex,
c.index,
c.box,
PATTERN_PROBE_PX / Math.max(w, h),
)
if (!probe) continue
const verdict = probeVerdict(probe, c.channel)
if (process.env['PDF2DOCX_DEBUG_PATTERN'] !== undefined) {
console.error(
`[pattern] page ${pageIndex + 1} obj ${c.index} box ${JSON.stringify(c.box)} ch ${c.channel} → ${verdict}`,
)
}
if (verdict === 'invisible') {
consumed.add(c.index)
continue
}
// 0xBFBFBF is only ever the colored-tiling placeholder — a flat probe
// means a uniform tile, still not grey
if (verdict === 'flat' && c.channel !== 0xbf) continue
const scale = Math.min(PATTERN_RENDER_SCALE, Math.sqrt(PATTERN_RENDER_MAX_PX / (w * h)))
const px = renderObjectAloneRgba(m, doc, pageIndex, c.index, c.box, scale)
if (!px) continue
consumed.add(c.index)
images.push({
box: c.box,
data: encodeRgbaPng(px.rgba, px.width, px.height),
mime: 'image/png',
pixelWidth: px.width,
pixelHeight: px.height,
z: c.index,
synthetic: true,
})
}
return { images, consumed }
}
/** handles of text objects buried under the background stack (P16 B) */
function buriedTextObjects(m: PdfiumModule, page: number, stackCount: number): Set<number> {
const handles = new Set<number>()
@@ -2092,7 +2335,8 @@ export function extractPage(
// shadings / wallpaper images) becomes one behindDoc bitmap. Text-less
// pages stay out — the scanned/degraded fallback serves them better, and
// excluding a scan's own image here would break scanned detection.
const bgStack = detectBackgroundStack(m, doc, page, widthPt, heightPt)
const contentBox = pageContentBox(m, page, widthPt, heightPt)
const bgStack = detectBackgroundStack(m, doc, page, widthPt, heightPt, contentBox)
const hasRealText =
chars.filter((c) => !c.isGenerated && !isWhitespaceCode(c.code)).length > SCANNED_MAX_CHARS
// P29 B: a graphics-dominant scan's tile stack must NOT bake — the bake
@@ -2139,8 +2383,25 @@ export function extractPage(
OCR_SCAN_IMAGE_COVER
const ocrSkip = ocrTextRecovered ? coversPage : undefined
let images = readImages(m, doc, page, bgActive ? bgStack.count : 0, ocrSkip)
const patternFills = readPatternFills(
m,
doc,
pageIndex,
page,
widthPt,
heightPt,
bgActive ? bgStack.count : 0,
)
if (patternFills.images.length > 0) {
images = [...images, ...patternFills.images].sort((p, q) => (p.z ?? 0) - (q.z ?? 0))
}
// the consumed pattern paths stay in `paths` through vector-region
// detection (a gradient blob is part of the illustration it sits in) and
// leave the stream afterwards — the region bitmap or the pattern image
// carries them
let paths = readPaths(m, page, bgActive ? bgStack.count : 0)
if (shifted) {
if (contentBox) shiftRect(contentBox, dx, dy)
for (const img of images) shiftRect(img.box, dx, dy)
for (const p of paths) {
if (p.clipBox) shiftRect(p.clipBox, dx, dy)
@@ -2156,6 +2417,7 @@ export function extractPage(
if (rotation === 1 || rotation === 2 || rotation === 3) {
const t = rotateToDisplay(rotation, widthPt, heightPt)
for (const img of images) t.rect(img.box)
if (contentBox) t.rect(contentBox)
for (const p of paths) {
if (p.clipBox) t.rect(p.clipBox)
for (const sub of p.subpaths) {
@@ -2217,7 +2479,13 @@ export function extractPage(
}
// quality verdicts judge the page as authored (before vector-art rewriting)
const quality = assessQuality(chars, images, pageRect, rotation)
// rasterized pattern fills are vector art, never a scan's page image
const quality = assessQuality(
chars,
images.filter((img) => !img.synthetic),
pageRect,
rotation,
)
if (ocrImageDominant) quality.scanned = true
let rotatedDropped = 0
let quarterTurned = false
@@ -2249,6 +2517,7 @@ export function extractPage(
c.angle = normalizeAngle(c.angle + t.angleDelta)
}
for (const img of images) t.rect(img.box)
if (contentBox) t.rect(contentBox)
for (const p of paths) {
if (p.clipBox) t.rect(p.clipBox)
for (const sub of p.subpaths) {
@@ -2332,6 +2601,12 @@ export function extractPage(
}
}
if (patternFills.consumed.size > 0) {
outPaths = outPaths.filter(
(p) => p.fromForm || p.z === undefined || !patternFills.consumed.has(p.z),
)
}
// P27 guard input: extraction kept NONE of the page's visible body text
// and nothing visible (bake/region render) carries it either — the
// pipeline degrades such a page instead of shipping it silently empty
@@ -2376,6 +2651,7 @@ export function extractPage(
...(rotatedDropped > 0 ? { rotatedDropped } : {}),
...(options.cellData ? { cellData: true } : {}),
...(bgRender !== undefined ? { bgRender } : {}),
...(contentBox !== null ? { contentBox } : {}),
...(decorImages.length > 0 ? { decorImages } : {}),
}
} finally {
+63
View File
@@ -149,3 +149,66 @@ export function coverageRatio(boxes: readonly Rect[], widthPt: number, heightPt:
for (const cell of grid) covered += cell
return covered / (n * n)
}
/** a print content box must sit at least this far inside every page edge (pt) */
const CONTENT_BOX_MIN_MARGIN_PT = 8
/** … opposite margins agree within this (printers center the content box) */
const CONTENT_BOX_MARGIN_TOL_PT = 4
/** … and no margin eats more than this share of its page dimension */
const CONTENT_BOX_MAX_MARGIN_RATIO = 0.2
/** share of the page's ink objects that must sit inside the candidate box */
const CONTENT_BOX_MIN_INK_SHARE = 0.97
const CONTENT_BOX_INK_TOL_PT = 2
/**
* Print content box (P35): browsers/print drivers lay the page out inside
* uniform margins, so the ink sits in a box centered on the page (Chromium's
* default A4 print: 0.6in margins). A fill whose bounds ARE that box is the
* page wash even though it never reaches the paper edge. `candidate` is such
* a fill's bounds; it qualifies when its margins are matching and modest and
* essentially every ink box on the page lies inside it (a drop shadow or a
* bleed decoration outside is tolerated).
*/
export function printContentBox(
candidate: Rect,
inkBoxes: readonly Rect[],
widthPt: number,
heightPt: number,
): Rect | null {
if (inkBoxes.length === 0 || widthPt <= 0 || heightPt <= 0) return null
const box = {
x0: Math.max(0, candidate.x0),
y0: Math.max(0, candidate.y0),
x1: Math.min(widthPt, candidate.x1),
y1: Math.min(heightPt, candidate.y1),
}
if (box.x1 <= box.x0 || box.y1 <= box.y0) return null
const left = box.x0
const right = widthPt - box.x1
const bottom = box.y0
const top = heightPt - box.y1
if ([left, right, top, bottom].some((mg) => mg < CONTENT_BOX_MIN_MARGIN_PT)) return null
if (Math.max(left, right) > widthPt * CONTENT_BOX_MAX_MARGIN_RATIO) return null
if (Math.max(top, bottom) > heightPt * CONTENT_BOX_MAX_MARGIN_RATIO) return null
if (Math.abs(left - right) > CONTENT_BOX_MARGIN_TOL_PT) return null
if (Math.abs(top - bottom) > CONTENT_BOX_MARGIN_TOL_PT) return null
let inside = 0
for (const r of inkBoxes) {
if (
r.x0 >= box.x0 - CONTENT_BOX_INK_TOL_PT &&
r.x1 <= box.x1 + CONTENT_BOX_INK_TOL_PT &&
r.y0 >= box.y0 - CONTENT_BOX_INK_TOL_PT &&
r.y1 <= box.y1 + CONTENT_BOX_INK_TOL_PT
) {
inside++
}
}
return inside / inkBoxes.length >= CONTENT_BOX_MIN_INK_SHARE ? box : null
}
/** `inner` spans at least `ratio` of `outer` in both dimensions (clipped to `outer`) */
export function coversBox(inner: Rect, outer: Rect, ratio: number): boolean {
const w = Math.min(inner.x1, outer.x1) - Math.max(inner.x0, outer.x0)
const h = Math.min(inner.y1, outer.y1) - Math.max(inner.y0, outer.y0)
return w >= (outer.x1 - outer.x0) * ratio && h >= (outer.y1 - outer.y0) * ratio
}
+2
View File
@@ -231,6 +231,8 @@ export interface ImageBlock {
* wallpaper drawn first stays under card panels drawn later.
*/
z?: number
/** rasterized pattern fill (P35) — authored as a path, not a placed picture */
synthetic?: true
/**
* this panel is a card plate (P20): index into IrPage.cards. The flow
* rebuild skips its behindDoc pin (the anchored text box paints the plate);
+11 -2
View File
@@ -110,7 +110,9 @@ function authoredInkBoxes(extracted: ExtractedPage): Rect[] {
for (const c of extracted.chars) {
if (!c.isGenerated && !c.invisible && c.text.trim() !== '') boxes.push(c.box)
}
for (const img of extracted.images) boxes.push(img.box)
// rasterized pattern fills (P35) are neutral: authored as a path, emitted
// as an image — counting them page-wide would hide dropped foreground art
for (const img of extracted.images) if (!img.synthetic) boxes.push(img.box)
for (const p of extracted.paths) {
if (!p.filled || (p.fillAlpha ?? 255) < 128 || isNearWhiteHex(p.fillColor)) continue
for (const sub of p.subpaths) {
@@ -136,7 +138,10 @@ function authoredInkBoxes(extracted: ExtractedPage): Rect[] {
function emittedInkBoxes(page: IrPage): Rect[] {
if (page.render) return [{ x0: 0, y0: 0, x1: page.widthPt, y1: page.heightPt }]
const boxes: Rect[] = []
for (const b of page.blocks) boxes.push(b.box)
for (const b of page.blocks) {
if (b.kind === 'image' && b.synthetic) continue
boxes.push(b.box)
}
for (const panel of page.bgPanels ?? []) boxes.push(panel.box)
return boxes
}
@@ -201,6 +206,10 @@ export function stitchCrossPageParagraphs(pages: IrPage[]): void {
const cur = pages[i]!
if (prev.scanned || prev.degraded || prev.canvas) continue
if (cur.scanned || cur.degraded || cur.canvas) continue
// page-pinned art (background render / panels) anchors on the page's first
// paragraph: stitched, that anchor flows onto the PREVIOUS page and the
// art lands there (a dark page turns white) — such boundaries stay hard
if (prev.bgRender || cur.bgRender || prev.bgPanels?.length || cur.bgPanels?.length) continue
// multi-column pages paginate per column — boundary evidence is ambiguous
if ((prev.sections?.length ?? 0) > 1 || (cur.sections?.length ?? 0) > 1) continue
if (prev.sections?.some((s) => s.columns.length > 1)) continue
@@ -0,0 +1,70 @@
/**
* Borderless bank-statement layout (alpha feedback): every transaction
* prints one value row (dates, description, amounts) followed by several
* 1-unit description continuation lines (reference-number stacks). The
* run-strength gate used to take its median over ALL run rows, so two
* absorbed continuations collapsed it, absorption stopped, and the whole
* region fell back to scrambled flow text. Strength is judged over the
* anchor rows only.
*/
import { describe, expect, it } from 'vitest'
import { clusterCombiningMarks, groupIntoLines } from '../src/analyze/lines'
import { detectStreamTables } from '../src/analyze/stream'
import { splitIntoUnits } from '../src/analyze/units'
import type { PageShapes, PdfChar, TableBlock } from '../src/ir'
import { mkText } from './helpers/chars'
const shapesOf = (): PageShapes => ({ strokes: [], fills: [], ignoredPaths: 0 })
const unitsOf = (chars: PdfChar[]) => splitIntoUnits(groupIntoLines(clusterCombiningMarks(chars)))
const cellText = (table: TableBlock, r: number, c: number): string =>
table.rows[r]![c]!.blocks.map((b) =>
b.lines.map((l) => l.spans.map((s) => s.text).join('')).join(' '),
).join(' ')
/** right-aligned text: place so it ends at x1 (0.5 em per Latin glyph) */
function rightText(text: string, x1: number, y: number): PdfChar[] {
return mkText(text, x1 - text.length * 5, { y }).chars
}
/** two transactions, each a 5-unit value row plus three continuation lines */
function statement(): PdfChar[] {
const chars: PdfChar[] = []
chars.push(...mkText('03 AUG', 40, { y: 730 }).chars)
chars.push(...mkText('03 AUG', 95, { y: 730 }).chars)
chars.push(...mkText('COMM/COMM IN LIEU', 150, { y: 730 }).chars)
chars.push(...rightText('23.63', 430, 730))
chars.push(...rightText('6,717,284.65', 610, 730))
chars.push(...mkText('CT0039810817M001', 150, { y: 715 }).chars)
chars.push(...mkText('SGTT260731808027', 150, { y: 700 }).chars)
chars.push(...mkText('*MDSUSER 000003045', 150, { y: 685 }).chars)
chars.push(...mkText('03 AUG', 40, { y: 670 }).chars)
chars.push(...mkText('03 AUG', 95, { y: 670 }).chars)
chars.push(...mkText('CALL A/C WDL', 150, { y: 670 }).chars)
chars.push(...rightText('2,251,200.18', 430, 670))
chars.push(...rightText('4,466,084.47', 610, 670))
return chars
}
describe('detectStreamTables: bank statement with wrapped description stacks', () => {
it('keeps the run alive across several absorbed continuation rows', () => {
const { tables } = detectStreamTables(unitsOf(statement()), shapesOf())
expect(tables).toHaveLength(1)
const table = tables[0]!
expect(table.confidence).toBeGreaterThanOrEqual(0.5)
expect(table.rows).toHaveLength(5)
expect(table.rows[0]).toHaveLength(5)
// value rows land in their columns…
expect(cellText(table, 0, 0)).toBe('03 AUG')
expect(cellText(table, 0, 2)).toBe('COMM/COMM IN LIEU')
expect(cellText(table, 0, 3)).toBe('23.63')
expect(cellText(table, 0, 4)).toBe('6,717,284.65')
expect(cellText(table, 4, 3)).toBe('2,251,200.18')
// …and the reference stack stays inside the description column
expect(cellText(table, 1, 2)).toBe('CT0039810817M001')
expect(cellText(table, 2, 2)).toBe('SGTT260731808027')
expect(cellText(table, 3, 2)).toBe('*MDSUSER 000003045')
expect(cellText(table, 1, 0)).toBe('')
expect(cellText(table, 1, 3)).toBe('')
})
})
@@ -559,3 +559,97 @@ export async function buildLateBlankingWashPdf(): Promise<Uint8Array> {
page.drawText('Real title above the late wash', { x: 72, y: 700, size: 18, font })
return doc.save()
}
/**
* Chromium-print gradient card (P35): a PATH filled with an axial SHADING
* PATTERN under white display text — PDFium's color API reports the fill as
* plain white. A genuinely white card sits below it and must stay a path.
*/
export async function buildGradientCardPdf(): Promise<Uint8Array> {
const { PDFDocument, PDFName, PDFNumber, PDFOperator, PDFOperatorNames, StandardFonts, rgb } =
await import('pdf-lib')
const doc = await PDFDocument.create()
const page = doc.addPage([612, 792])
const shading = doc.context.obj({
ShadingType: 2,
ColorSpace: 'DeviceRGB',
Coords: [100, 0, 400, 0],
Extend: [true, true],
Function: doc.context.obj({
FunctionType: 2,
Domain: [0, 1],
C0: [0.1, 0.2, 0.6],
C1: [0.55, 0.1, 0.7],
N: 1,
}),
})
const pattern = doc.context.register(
doc.context.obj({ Type: 'Pattern', PatternType: 2, Shading: shading }),
)
page.node
.normalizedEntries()
.Resources.set(PDFName.of('Pattern'), doc.context.obj({ P1: pattern }))
page.pushOperators(
PDFOperator.of(PDFOperatorNames.NonStrokingColorspace, [PDFName.of('Pattern')]),
PDFOperator.of(PDFOperatorNames.NonStrokingColorN, [PDFName.of('P1')]),
PDFOperator.of(
PDFOperatorNames.AppendRectangle,
[100, 400, 300, 200].map((v) => PDFNumber.of(v)),
),
PDFOperator.of(PDFOperatorNames.FillNonZero),
)
page.drawRectangle({ x: 100, y: 150, width: 300, height: 100, color: rgb(1, 1, 1) })
const bold = await doc.embedFont(StandardFonts.HelveticaBold)
const font = await doc.embedFont(StandardFonts.Helvetica)
page.drawText('Gradient cover title', {
x: 120,
y: 500,
size: 20,
font: bold,
color: rgb(1, 1, 1),
})
const body = [
'Body text below the card keeps this a text page,',
'so the background machinery treats it as a document.',
]
body.forEach((t, i) => page.drawText(t, { x: 72, y: 110 - i * 14, size: 12, font }))
return doc.save()
}
/**
* Browser print with uniform 43pt margins (P35): the body wash is a dark fill
* covering the CONTENT box, never the paper edge; light text and a light card
* sit on it. `unequal` widens the right margin so the box is not centered.
*/
export async function buildPrintMarginWashPdf(unequal = false): Promise<Uint8Array> {
const { PDFDocument, StandardFonts, rgb } = await import('pdf-lib')
const doc = await PDFDocument.create()
const page = doc.addPage([595, 842])
const width = unequal ? 430 : 509
page.drawRectangle({ x: 43, y: 43, width, height: 756, color: rgb(0.04, 0.04, 0.04) })
page.drawRectangle({ x: 80, y: 420, width: 300, height: 120, color: rgb(0.94, 0.9, 0.82) })
const font = await doc.embedFont(StandardFonts.Helvetica)
page.drawText('Light heading on a dark printed page', {
x: 70,
y: 720,
size: 16,
font,
color: rgb(1, 1, 1),
})
const lines = [
'Paragraph text that flows across the dark body wash of the page,',
'long enough for the extractor to treat this as a real text page.',
'A parchment card below carries dark text of its own.',
]
lines.forEach((t, i) =>
page.drawText(t, { x: 70, y: 680 - i * 14, size: 11, font, color: rgb(0.9, 0.9, 0.9) }),
)
page.drawText('Card text stays dark on the light card.', {
x: 95,
y: 480,
size: 11,
font,
color: rgb(0.1, 0.1, 0.1),
})
return doc.save()
}
@@ -0,0 +1,206 @@
/**
* P35: browser prints (Chromium printToPDF with margins) — the body wash
* covers the print content box instead of the paper, and CSS gradients arrive
* as pattern-filled paths whose color PDFium cannot voice.
*/
import { describe, expect, it } from 'vitest'
import {
extractBackgroundPanels,
extractPageBackground,
extractTextBackdrops,
normalizeShapes,
} from '../src/analyze'
import { classifyFloatImages } from '../src/analyze/floats'
import { extractPage, withPdfDocument } from '../src/extract'
import { coversBox, printContentBox } from '../src/geometry'
import type { RawPath, RawSubpath } from '../src/ir'
import { buildGradientCardPdf, buildPrintMarginWashPdf } from './helpers/fixtures'
import { loadPdfium } from './helpers/wasm'
const rect = (x0: number, y0: number, x1: number, y1: number): RawSubpath => ({
points: [
{ x: x0, y: y0 },
{ x: x1, y: y0 },
{ x: x1, y: y1 },
{ x: x0, y: y1 },
],
closed: true,
hasCurves: false,
})
const fill = (x0: number, y0: number, x1: number, y1: number, fillColor: string): RawPath => ({
subpaths: [rect(x0, y0, x1, y1)],
filled: true,
stroked: false,
fillColor,
strokeColor: '000000',
strokeWidth: 1,
})
describe('printContentBox', () => {
const W = 595
const H = 842
const box = { x0: 43, y0: 43, x1: 552, y1: 799 }
const ink = [box, { x0: 70, y0: 600, x1: 400, y1: 720 }, { x0: 80, y0: 420, x1: 380, y1: 540 }]
it('accepts a centered inset fill that frames the page ink', () => {
expect(printContentBox(box, ink, W, H)).toEqual(box)
})
it('tolerates a stray decoration outside the box', () => {
const many = [
...ink,
...Array.from({ length: 40 }, (_, i) => ({
x0: 60,
y0: 100 + i * 10,
x1: 300,
y1: 105 + i * 10,
})),
]
expect(printContentBox(box, [...many, { x0: 0, y0: 0, x1: 20, y1: 20 }], W, H)).toEqual(box)
})
it('rejects unequal margins, full-bleed fills and boxes that leave ink outside', () => {
expect(printContentBox({ x0: 43, y0: 43, x1: 473, y1: 799 }, ink, W, H)).toBeNull()
expect(printContentBox({ x0: 0, y0: 0, x1: W, y1: H }, ink, W, H)).toBeNull()
expect(printContentBox(box, [...ink, { x0: 10, y0: 10, x1: 590, y1: 30 }], W, H)).toBeNull()
})
it('coversBox measures against the given box', () => {
expect(coversBox({ x0: 43, y0: 43, x1: 552, y1: 799 }, box, 0.94)).toBe(true)
expect(
coversBox({ x0: 43, y0: 43, x1: 552, y1: 799 }, { x0: 0, y0: 0, x1: W, y1: H }, 0.94),
).toBe(false)
})
})
describe('analyze: content-box washes and panels', () => {
const W = 595
const H = 842
const content = { x0: 43, y0: 43, x1: 552, y1: 799 }
it('extractPageBackground pulls a content-box wash out of the pool', () => {
const shapes = normalizeShapes([
fill(43, 43, 552, 799, '0A0A0A'),
fill(88, 43, 508, 677, 'E8E0C8'),
])
expect(extractPageBackground(shapes.fills, W, H)).toBeUndefined()
expect(shapes.fills).toHaveLength(2)
expect(extractPageBackground(shapes.fills, W, H, content)).toBe('0A0A0A')
expect(shapes.fills.map((f) => f.color)).toEqual(['E8E0C8'])
})
it('extractBackgroundPanels takes a spine flush with the content-box edge', () => {
const shapes = normalizeShapes([fill(43, 43, 221, 799, '4A5578')])
const chars = Array.from({ length: 6 }, (_, i) => ({
x0: 60,
y0: 700 - i * 20,
x1: 200,
y1: 712 - i * 20,
}))
const kept = normalizeShapes([fill(43, 43, 221, 799, '4A5578')])
expect(extractBackgroundPanels(kept.fills, chars, W, H)).toHaveLength(0)
const panels = extractBackgroundPanels(shapes.fills, chars, W, H, content)
expect(panels).toHaveLength(1)
expect(shapes.fills).toHaveLength(0)
})
})
describe('analyze: plates hosting lighter cards (P35)', () => {
const W = 595
const H = 842
const chars = (x0: number, y0: number, n: number, color: string) =>
Array.from({ length: n }, (_, i) => ({
box: { x0: x0 + i * 6, y0, x1: x0 + i * 6 + 5, y1: y0 + 8 },
code: 0x41,
color,
}))
it('keeps a dark plate whose only text sits on a lighter sub-card', () => {
const shapes = normalizeShapes([
fill(64, 448, 533, 800, '161312'),
fill(322, 507, 486, 718, 'F7F3EC'),
])
// dark text lives on the light card: plate vs text contrast is nil
const dark = chars(340, 600, 9, '161312')
const backdrops = extractTextBackdrops(shapes.fills, dark, [], W, H)
expect(backdrops.map((f) => f.color).sort()).toEqual(['161312', 'F7F3EC'])
expect(shapes.fills).toHaveLength(0)
})
it('a dark plate with nothing lighter on it and dark text stays out', () => {
const shapes = normalizeShapes([fill(64, 448, 533, 800, '161312')])
const backdrops = extractTextBackdrops(shapes.fills, chars(100, 600, 9, '161312'), [], W, H)
expect(backdrops).toHaveLength(0)
expect(shapes.fills).toHaveLength(1)
})
})
describe('analyze: synthetic pattern images float behind (P35)', () => {
it('a title-only gradient card never flows inline', () => {
const card = {
kind: 'image' as const,
box: { x0: 100, y0: 400, x1: 400, y1: 600 },
data: new Uint8Array(0),
mime: 'image/png' as const,
pixelWidth: 300,
pixelHeight: 200,
synthetic: true as const,
}
const { floats, inline } = classifyFloatImages([card], [], 612 * 792, {
x0: 0,
y0: 0,
x1: 612,
y1: 792,
})
expect(inline).toHaveLength(0)
expect(floats).toHaveLength(1)
expect(floats[0]!.float?.wrap).toBe('behind')
})
})
describe('extract: print-margin pages (P35)', () => {
it('a dark content-box wash becomes the page background render', async () => {
const m = await loadPdfium()
const page = withPdfDocument(m, await buildPrintMarginWashPdf(), (doc) =>
extractPage(m, doc, 0),
)
expect(page.scanned).toBe(false)
expect(page.degraded).toBe(false)
expect(page.contentBox).toBeDefined()
expect(page.contentBox!.x0).toBeCloseTo(43, 0)
expect(page.contentBox!.x1).toBeCloseTo(552, 0)
expect(page.bgRender).toBeDefined()
// the wash rides the background bitmap, the light card stays a fill
const big = page.paths.filter((p) => p.filled && p.fillColor === '0A0A0A')
expect(big).toHaveLength(0)
expect(page.paths.some((p) => p.filled && p.fillColor === 'F0E6D1')).toBe(true)
expect(page.chars.length).toBeGreaterThan(20)
})
it('an off-center inset fill is a plate, not the page wash', async () => {
const m = await loadPdfium()
const page = withPdfDocument(m, await buildPrintMarginWashPdf(true), (doc) =>
extractPage(m, doc, 0),
)
expect(page.contentBox).toBeUndefined()
expect(page.bgRender).toBeUndefined()
expect(page.paths.some((p) => p.filled && p.fillColor === '0A0A0A')).toBe(true)
})
it('a pattern-filled path rasterizes into the image stream; a real white card stays a path', async () => {
const m = await loadPdfium()
const page = withPdfDocument(m, await buildGradientCardPdf(), (doc) => extractPage(m, doc, 0))
expect(page.images).toHaveLength(1)
const img = page.images[0]!
expect(img.box.x0).toBeCloseTo(100, 0)
expect(img.box.x1).toBeCloseTo(400, 0)
expect(img.box.y0).toBeCloseTo(400, 0)
expect(img.box.y1).toBeCloseTo(600, 0)
expect(img.mime).toBe('image/png')
expect(img.z).toBeDefined()
const whites = page.paths.filter((p) => p.filled && p.fillColor === 'FFFFFF')
expect(whites).toHaveLength(1)
const ys = whites[0]!.subpaths[0]!.points.map((pt) => pt.y)
expect(Math.max(...ys)).toBeCloseTo(250, 0)
})
})
+32
View File
@@ -51,6 +51,38 @@ const mkPage = (index: number, blocks: TextBlock[]): IrPage =>
const fullTail = () => mkBlock([mkLine(50, 550, 760), mkLine(50, 550, 100), mkLine(50, 548, 80)])
describe('stitchCrossPageParagraphs (P32)', () => {
it('keeps the boundary hard when either page pins art to the page (P35)', () => {
const panel = {
kind: 'image' as const,
box: { x0: 0, y0: 0, x1: 200, y1: H },
data: new Uint8Array(0),
mime: 'image/png' as const,
pixelWidth: 2,
pixelHeight: 2,
}
for (const decorate of [
(prev: IrPage) => (prev.bgPanels = [panel]),
(_prev: IrPage, cur: IrPage) => (cur.bgPanels = [panel]),
(_prev: IrPage, cur: IrPage) =>
(cur.bgRender = {
data: new Uint8Array(0),
mime: 'image/png',
pixelWidth: 2,
pixelHeight: 2,
}),
]) {
const prev = mkPage(0, [fullTail()])
const cur = mkPage(1, [
mkBlock([mkLine(50, 400, 760, 'cont')]),
mkBlock([mkLine(50, 300, 700)]),
])
decorate(prev, cur)
stitchCrossPageParagraphs([prev, cur])
expect(cur.flowsFromPrev).toBeUndefined()
expect(cur.blocks).toHaveLength(2)
}
})
it('stitches a mid-paragraph boundary and marks the page', () => {
const prev = mkPage(0, [fullTail()])
const cur = mkPage(1, [
+1 -1
View File
@@ -25,6 +25,6 @@
"@types/node": "^24.10.1",
"pptxgenjs": "^4.0.1",
"typescript": "^5.9.3",
"vitest": "^4.1.0"
"vitest": "^4.1.11"
}
}
+21 -1
View File
@@ -59,6 +59,10 @@ export interface ChartSeries {
marker?: boolean
/** Explicit per-point colors <c:dPt> (common for pies; render layer palette otherwise) */
pointColors?: Array<string | undefined>
/** Pie: <c:dPt><c:spPr><a:noFill/> — the wedge is outline-only */
pointNoFill?: Array<boolean | undefined>
/** Pie: per-point outline <c:dPt><c:spPr><a:ln> (color null = explicit no line) */
pointLines?: Array<{ color: string | null; widthPt?: number } | undefined>
/** Pie: slice offset from center as percent of diameter (series-level c:explosion → all slices) */
explosionPct?: number
/** Pie: per-point explosion overrides (c:dPt/c:explosion) */
@@ -424,16 +428,32 @@ export function parseChartXml(
const dPts: any[] = ser['c:dPt'] ?? []
if (dPts.length) {
const pointColors: Array<string | undefined> = []
const pointNoFill: Array<boolean | undefined> = []
const pointLines: Array<{ color: string | null; widthPt?: number } | undefined> = []
const pointExpl: Array<number | undefined> = []
for (const dPt of dPts) {
const idx = parseInt(dPt['c:idx']?.['@_val'], 10)
if (Number.isNaN(idx)) continue
const c = resolveColorNode(dPt['c:spPr']?.['a:solidFill'], theme)
const dSp = dPt['c:spPr']
const c = resolveColorNode(dSp?.['a:solidFill'], theme)
if (c != null) pointColors[idx] = c
if (dSp && 'a:noFill' in dSp) pointNoFill[idx] = true
const dLn = dSp?.['a:ln']
if (dLn && typeof dLn === 'object') {
const lnColor = 'a:noFill' in dLn ? null : resolveColorNode(dLn['a:solidFill'], theme)
const lnW = parseInt(dLn['@_w'], 10)
if (lnColor !== undefined)
pointLines[idx] = {
color: lnColor,
...(Number.isFinite(lnW) && lnW > 0 ? { widthPt: lnW / 12700 } : {}),
}
}
const pe = parseInt(dPt['c:explosion']?.['@_val'], 10)
if (Number.isFinite(pe)) pointExpl[idx] = pe
}
if (pointColors.length) s.pointColors = pointColors
if (pointNoFill.length) s.pointNoFill = pointNoFill
if (pointLines.length) s.pointLines = pointLines
if (pointExpl.length) s.pointExplosionPct = pointExpl
}
series.push(s)
+26 -13
View File
@@ -9,7 +9,14 @@ import { XMLParser } from 'fast-xml-parser'
import { layoutHierTree, parseHierConstraints } from './dgm-hier'
import { scanSlide, type SpElement } from './scan'
import { tableRowGridCols } from './table-grid'
import { type Theme, resolveFontRef, resolveSchemeColor, themeWithOverride } from './theme'
import {
type EaScript,
type Theme,
eaScriptOfLang,
resolveFontRef,
resolveSchemeColor,
themeWithOverride,
} from './theme'
import { resolveColorNode as resolveColorNodeShared } from './color'
import {
resolvePlaceholderPresetGeom,
@@ -3438,10 +3445,25 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
// Text highlight <a:highlight> (PowerPoint draws it as a background behind the run)
const highlightNode = rPr['a:highlight']
const highlight = highlightNode ? resolveColorNode(highlightNode, ctx) : undefined
const langScript = eaScriptOfLang
const runLangScript = langScript(rPr['@_altLang']) ?? langScript(rPr['@_lang'])
// An ea theme ref on a theme with an empty <a:ea/>: the run's East Asian language (altLang
// first), else the text's own kana/hangul, else the placeholder level's lang, else — for
// bare ideographs — the theme's single Han script, picks the fontScheme per-script entry
const eaScript: EaScript | undefined =
runLangScript ??
(/[\u3040-\u30ff\u31f0-\u31ff]/.test(text)
? 'ja'
: /[\uac00-\ud7af\u1100-\u11ff]/.test(text)
? 'ko'
: undefined) ??
dflt?.eaScript ??
(/[\u3400-\u9fff\uf900-\ufaff]/.test(text) ? 'han' : undefined)
// Font: run explicit (incl. +mj/+mn theme refs) → inherited default → theme font
const latin = resolveFontRef(rPr['a:latin']?.['@_typeface'], ctx.theme) ?? dflt?.latinFont
const ea = resolveFontRef(rPr['a:ea']?.['@_typeface'], ctx.theme) ?? dflt?.eaFont
const cs = resolveFontRef(rPr['a:cs']?.['@_typeface'], ctx.theme) ?? dflt?.csFont
const latin =
resolveFontRef(rPr['a:latin']?.['@_typeface'], ctx.theme, eaScript) ?? dflt?.latinFont
const ea = resolveFontRef(rPr['a:ea']?.['@_typeface'], ctx.theme, eaScript) ?? dflt?.eaFont
const cs = resolveFontRef(rPr['a:cs']?.['@_typeface'], ctx.theme, eaScript) ?? dflt?.csFont
const sym = resolveFontRef(rPr['a:sym']?.['@_typeface'], ctx.theme)
// Symbol-slot characters (Wingdings dots/checkmarks stored as U+F0xx PUA) draw with a:sym,
// not the latin font; applied when the run is entirely PUA (the common single-glyph case)
@@ -3456,15 +3478,6 @@ function parseRun(r: any, ctx: ParseContext, dflt?: LevelTextStyle): TextRun {
134: 'sc', // GB2312
136: 'tc', // CHINESEBIG5
}
const langScript = (tag: unknown): 'ja' | 'ko' | 'sc' | 'tc' | undefined => {
const t = String(tag ?? '').toLowerCase()
if (t.startsWith('ja')) return 'ja'
if (t.startsWith('ko')) return 'ko'
if (/^zh(-(tw|hk|mo|hant))/.test(t)) return 'tc'
if (t.startsWith('zh')) return 'sc'
return undefined
}
const runLangScript = langScript(rPr['@_altLang']) ?? langScript(rPr['@_lang'])
const charsetOf = (bucket: string): ('ja' | 'ko' | 'sc' | 'tc') | undefined => {
if (runLangScript) return runLangScript
if (rPr[bucket]?.['@_typeface'] == null) return undefined
+9 -4
View File
@@ -17,7 +17,7 @@
*/
import { XMLParser } from 'fast-xml-parser'
import type { Transform, TextAlign } from './types'
import { type Theme, resolveFontRef } from './theme'
import { type EaScript, type Theme, eaScriptOfLang, resolveFontRef } from './theme'
import { resolveColorNode } from './color'
import { asXmlNode, xmlArray, type XmlNode } from './xml-utils'
@@ -41,6 +41,8 @@ export interface LevelTextStyle {
latinFont?: string
eaFont?: string
csFont?: string
/** East Asian script of the level's defRPr lang/altLang (steers empty-ea theme refs on runs without a lang of their own) */
eaScript?: EaScript
align?: TextAlign
/** Bullet default (master bodyStyle levels commonly use buChar '•') */
bullet?: {
@@ -320,11 +322,13 @@ export function parseDefRPrStyle(
dirDeg: num('@_dir') / 60000,
}
}
const latin = resolveFontRef(typefaceAttr(defRPr['a:latin']), theme)
const eaScript = eaScriptOfLang(defRPr['@_altLang']) ?? eaScriptOfLang(defRPr['@_lang'])
if (eaScript) out.eaScript = eaScript
const latin = resolveFontRef(typefaceAttr(defRPr['a:latin']), theme, eaScript)
if (latin) out.latinFont = latin
const ea = resolveFontRef(typefaceAttr(defRPr['a:ea']), theme)
const ea = resolveFontRef(typefaceAttr(defRPr['a:ea']), theme, eaScript)
if (ea) out.eaFont = ea
const cs = resolveFontRef(typefaceAttr(defRPr['a:cs']), theme)
const cs = resolveFontRef(typefaceAttr(defRPr['a:cs']), theme, eaScript)
if (cs) out.csFont = cs
return Object.keys(out).length ? out : undefined
}
@@ -536,6 +540,7 @@ export function mergeTextStyleChain(
if (out.latinFont == null && lvl.latinFont != null) out.latinFont = lvl.latinFont
if (out.eaFont == null && lvl.eaFont != null) out.eaFont = lvl.eaFont
if (out.csFont == null && lvl.csFont != null) out.csFont = lvl.csFont
if (out.eaScript == null && lvl.eaScript != null) out.eaScript = lvl.eaScript
if (out.align == null && lvl.align != null) out.align = lvl.align
if (out.bullet == null && lvl.bullet != null) out.bullet = lvl.bullet
if (out.marL == null && lvl.marL != null) out.marL = lvl.marL
+50 -3
View File
@@ -4,7 +4,7 @@
* schemeClr / theme fonts into final values.
*/
import { XMLParser } from 'fast-xml-parser'
import { asXmlNode, type XmlNode } from './xml-utils'
import { asXmlNode, xmlArray, type XmlNode } from './xml-utils'
const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@_' })
@@ -22,6 +22,9 @@ export interface Theme {
/** fontScheme: major / minor East Asian fonts */
majorEaFont?: string
minorEaFont?: string
/** fontScheme per-script fonts (<a:font script="Jpan" typeface=…/>), keyed by script tag */
majorScriptFonts?: Record<string, string>
minorScriptFonts?: Record<string, string>
/** fontScheme: major / minor Complex Script fonts (Arabic/Hebrew/Thai/Hindi etc.) */
majorCsFont?: string
minorCsFont?: string
@@ -84,6 +87,17 @@ function typeface(scheme: XmlNode, font: string, script: string): string | undef
return typeof v === 'string' && v ? v : undefined
}
function scriptFonts(scheme: XmlNode, font: string): Record<string, string> | undefined {
const out: Record<string, string> = {}
for (const f of xmlArray(asXmlNode(scheme[font])['a:font'])) {
const n = asXmlNode(f)
const script = n['@_script']
const face = n['@_typeface']
if (typeof script === 'string' && typeof face === 'string' && face) out[script] = face
}
return Object.keys(out).length ? out : undefined
}
export function parseTheme(themeXml: string): Theme {
const doc = asXmlNode(parser.parse(themeXml))
const themeEl = asXmlNode(doc['a:theme'] ?? doc.theme)
@@ -114,6 +128,8 @@ export function parseTheme(themeXml: string): Theme {
const minorEaFont = typeface(fontScheme, 'a:minorFont', 'a:ea')
const majorCsFont = typeface(fontScheme, 'a:majorFont', 'a:cs')
const minorCsFont = typeface(fontScheme, 'a:minorFont', 'a:cs')
const majorScriptFonts = scriptFonts(fontScheme, 'a:majorFont')
const minorScriptFonts = scriptFonts(fontScheme, 'a:minorFont')
// fmtScheme templates are parsed in order from raw-text slices (fillStyleLst children mix element types; regular parsing would lose the idx order)
const fmtM = /<a:fmtScheme\b[^>]*>[\s\S]*?<\/a:fmtScheme>/.exec(themeXml)
const fmt = fmtM?.[0] ?? ''
@@ -129,6 +145,8 @@ export function parseTheme(themeXml: string): Theme {
minorEaFont,
majorCsFont,
minorCsFont,
...(majorScriptFonts ? { majorScriptFonts } : {}),
...(minorScriptFonts ? { minorScriptFonts } : {}),
...(fillStyles ? { fillStyles } : {}),
...(lnStyles ? { lnStyles } : {}),
...(effectStyles ? { effectStyles } : {}),
@@ -163,21 +181,50 @@ export function themeWithOverride(base: Theme | undefined, overrideXml: string):
* Theme font reference ("+mj-lt" / "+mn-ea" etc.) → final font name.
* Values not starting with "+" are returned as-is; returns undefined when the theme has no match.
*/
/** 'han': ideographs without a language — resolves only when the theme names a single Han script */
export type EaScript = 'ja' | 'ko' | 'sc' | 'tc' | 'han'
const EA_SCRIPT_TAG: Record<Exclude<EaScript, 'han'>, string> = {
ja: 'Jpan',
ko: 'Hang',
sc: 'Hans',
tc: 'Hant',
}
const HAN_SCRIPT_TAGS = ['Jpan', 'Hans', 'Hant']
/** East Asian script of a BCP-47 lang/altLang tag (ja-JP → ja, zh-TW → tc, zh-CN → sc). */
export function eaScriptOfLang(tag: unknown): Exclude<EaScript, 'han'> | undefined {
const t = String(tag ?? '').toLowerCase()
if (t.startsWith('ja')) return 'ja'
if (t.startsWith('ko')) return 'ko'
if (/^zh(-(tw|hk|mo|hant))/.test(t)) return 'tc'
if (t.startsWith('zh')) return 'sc'
return undefined
}
export function resolveFontRef(
typeface: string | undefined,
theme: Theme | undefined,
/** Script of the text using an ea theme ref: with an empty <a:ea typeface=""/> PowerPoint
* takes the fontScheme's per-script entry (Jpan/Hang/Hans/Hant) before the Latin font. */
eaScript?: EaScript,
): string | undefined {
if (!typeface) return undefined
if (!typeface.startsWith('+')) return typeface
const scriptFont = (fonts: Record<string, string> | undefined): string | undefined => {
if (!eaScript || !fonts) return undefined
if (eaScript !== 'han') return fonts[EA_SCRIPT_TAG[eaScript]]
const han = HAN_SCRIPT_TAGS.filter((t) => fonts[t])
return han.length === 1 ? fonts[han[0]!] : undefined
}
switch (typeface) {
case '+mj-lt':
return theme?.majorFont
case '+mn-lt':
return theme?.minorFont
case '+mj-ea':
return theme?.majorEaFont ?? theme?.majorFont
return theme?.majorEaFont ?? scriptFont(theme?.majorScriptFonts) ?? theme?.majorFont
case '+mn-ea':
return theme?.minorEaFont ?? theme?.minorFont
return theme?.minorEaFont ?? scriptFont(theme?.minorScriptFonts) ?? theme?.minorFont
case '+mj-cs':
return theme?.majorCsFont ?? theme?.majorFont
case '+mn-cs':
+46 -1
View File
@@ -124,7 +124,11 @@ export class PackageArchive {
}
/** Resolve a slide's layout / master part paths (via the rels chain). */
resolveSlideChain(slidePath: string): { layoutPath?: string; masterPath?: string; themePath?: string } {
resolveSlideChain(slidePath: string): {
layoutPath?: string
masterPath?: string
themePath?: string
} {
const slideRels = this.readRels(slidePath)
let layoutPath: string | undefined
for (const rel of slideRels.values()) {
@@ -133,6 +137,10 @@ export class PackageArchive {
break
}
}
// Damaged decks ship slides without a rels part (or without the mandatory slideLayout
// relationship). PowerPoint refuses such files; LibreOffice renders them on the first
// layout of the first master, which keeps the deck's background/decorations — do the same.
if (!layoutPath) layoutPath = this.fallbackLayoutPath(slidePath)
let masterPath: string | undefined
let themePath: string | undefined
if (layoutPath) {
@@ -155,6 +163,43 @@ export class PackageArchive {
}
return { layoutPath, masterPath, themePath }
}
/**
* Layout for a slide that lost its slideLayout relationship: the first master's layouts in
* sldLayoutIdLst order, preferring the title layout for a slide carrying a ctrTitle placeholder
* (what the deck's own title page would have referenced), else the first layout.
*/
private fallbackLayoutPath(slidePath: string): string | undefined {
const presXml = this.readText('ppt/presentation.xml')
if (!presXml) return undefined
const presRels = this.readRels('ppt/presentation.xml')
const masterRid = /<p:sldMasterId\b[^>]*\br:id="([^"]+)"/.exec(presXml)?.[1]
const masterRel = masterRid
? presRels.get(masterRid)
: [...presRels.values()].find((r) => r.type.endsWith('/slideMaster'))
if (!masterRel) return undefined
const masterPath = resolveTarget('ppt/presentation.xml', masterRel.target)
const masterXml = this.readText(masterPath)
if (!masterXml) return undefined
const masterRels = this.readRels(masterPath)
const layouts: string[] = []
for (const m of masterXml.matchAll(/<p:sldLayoutId\b[^>]*\br:id="([^"]+)"/g)) {
const rel = masterRels.get(m[1]!)
if (rel) layouts.push(resolveTarget(masterPath, rel.target))
}
if (!layouts.length)
for (const rel of masterRels.values())
if (rel.type.endsWith('/slideLayout')) layouts.push(resolveTarget(masterPath, rel.target))
if (!layouts.length) return undefined
const wantsTitle = /<p:ph\b[^>]*\btype="ctrTitle"/.test(this.readText(slidePath) ?? '')
if (wantsTitle) {
const title = layouts.find((p) =>
/<p:sldLayout\b[^>]*\btype="title"/.test(this.readText(p) ?? ''),
)
if (title) return title
}
return layouts[0]
}
}
/** 'ppt/slides/slide1.xml' → 'ppt/slides/_rels/slide1.xml.rels' */
+16
View File
@@ -108,6 +108,22 @@ describe('parseChartXml', () => {
expect(m.series[0]!.pointColors?.[2]).toBe('#0000AA')
})
it('parses outline-only pie points: c:dPt noFill + per-point a:ln', () => {
const PIE = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
<c:pieChart><c:varyColors val="1"/><c:ser><c:idx val="0"/>
<c:dPt><c:idx val="0"/><c:spPr><a:noFill/><a:ln w="19050"><a:solidFill><a:srgbClr val="AA0000"/></a:solidFill></a:ln></c:spPr></c:dPt>
<c:dPt><c:idx val="1"/><c:spPr><a:solidFill><a:srgbClr val="0000AA"/></a:solidFill><a:ln><a:noFill/></a:ln></c:spPr></c:dPt>
<c:val><c:numRef><c:f>y</c:f><c:numCache><c:ptCount val="3"/><c:pt idx="0"><c:v>1</c:v></c:pt><c:pt idx="1"><c:v>2</c:v></c:pt><c:pt idx="2"><c:v>3</c:v></c:pt></c:numCache></c:numRef></c:val>
</c:ser></c:pieChart></c:plotArea></c:chart></c:chartSpace>`
const s = parseChartXml(PIE)!.series[0]!
expect(s.pointNoFill).toEqual([true])
expect(s.pointLines?.[0]).toEqual({ color: '#AA0000', widthPt: 1.5 })
expect(s.pointColors?.[1]).toBe('#0000AA')
expect(s.pointLines?.[1]).toEqual({ color: null })
expect(s.pointNoFill?.[1]).toBeUndefined()
expect(s.pointLines?.[2]).toBeUndefined()
})
it('parses pie explosion: series-level c:explosion and per-point c:dPt overrides', () => {
const PIE = `<c:chartSpace xmlns:c="c" xmlns:a="a"><c:chart><c:plotArea>
<c:pie3DChart><c:ser><c:idx val="0"/>
@@ -0,0 +1,72 @@
import { describe, expect, it } from 'vitest'
import { createBlankPptx, openPptx } from '../src/index'
describe('resolveSlideChain', () => {
it('follows the slide rels when present', async () => {
const { archive } = await openPptx(await createBlankPptx())
const chain = archive.resolveSlideChain('ppt/slides/slide1.xml')
expect(chain.layoutPath).toBe('ppt/slideLayouts/slideLayout1.xml')
expect(chain.masterPath).toBe('ppt/slideMasters/slideMaster1.xml')
expect(chain.themePath).toBe('ppt/theme/theme1.xml')
})
it('a slide with a ctrTitle placeholder falls back to the title layout', async () => {
const { archive } = await openPptx(await createBlankPptx())
archive.entries.delete('ppt/slides/_rels/slide1.xml.rels')
// Add a second layout typed "title" behind the existing one
const master = archive.readText('ppt/slideMasters/slideMaster1.xml')!
archive.entries.set(
'ppt/slideMasters/slideMaster1.xml',
Buffer.from(
master.replace(
'</p:sldLayoutIdLst>',
'<p:sldLayoutId id="2147483650" r:id="rIdT"/></p:sldLayoutIdLst>',
),
'utf8',
),
)
const rels = archive.readText('ppt/slideMasters/_rels/slideMaster1.xml.rels')!
archive.entries.set(
'ppt/slideMasters/_rels/slideMaster1.xml.rels',
Buffer.from(
rels.replace(
'</Relationships>',
'<Relationship Id="rIdT" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayoutT.xml"/></Relationships>',
),
'utf8',
),
)
archive.entries.set(
'ppt/slideLayouts/slideLayoutT.xml',
Buffer.from('<p:sldLayout type="title" xmlns:p="p"><p:cSld/></p:sldLayout>', 'utf8'),
)
const slide = archive.readText('ppt/slides/slide1.xml')!
archive.entries.set(
'ppt/slides/slide1.xml',
Buffer.from(
slide.replace(
'</p:spTree>',
'<p:sp><p:nvSpPr><p:cNvPr id="9" name="t"/><p:cNvSpPr/><p:nvPr><p:ph type="ctrTitle"/></p:nvPr></p:nvSpPr><p:spPr/></p:sp></p:spTree>',
),
'utf8',
),
)
expect(archive.resolveSlideChain('ppt/slides/slide1.xml').layoutPath).toBe(
'ppt/slideLayouts/slideLayoutT.xml',
)
// Without the ctrTitle placeholder the first layout wins
archive.entries.set('ppt/slides/slide1.xml', Buffer.from(slide, 'utf8'))
expect(archive.resolveSlideChain('ppt/slides/slide1.xml').layoutPath).toBe(
'ppt/slideLayouts/slideLayout1.xml',
)
})
it('falls back to the first layout of the first master when the slide has no rels part', async () => {
const { archive } = await openPptx(await createBlankPptx())
archive.entries.delete('ppt/slides/_rels/slide1.xml.rels')
const chain = archive.resolveSlideChain('ppt/slides/slide1.xml')
expect(chain.layoutPath).toBe('ppt/slideLayouts/slideLayout1.xml')
expect(chain.masterPath).toBe('ppt/slideMasters/slideMaster1.xml')
expect(chain.themePath).toBe('ppt/theme/theme1.xml')
})
})
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import { eaScriptOfLang, parseTheme, resolveFontRef } from '../src/theme'
const THEME = (ea: string) => `<?xml version="1.0"?><a:theme xmlns:a="a"><a:themeElements>
<a:clrScheme name="x"><a:dk1><a:srgbClr val="000000"/></a:dk1></a:clrScheme>
<a:fontScheme name="x">
<a:majorFont><a:latin typeface="Arial"/><a:ea typeface=""/><a:cs typeface=""/><a:font script="Jpan" typeface="MS Pゴシック"/><a:font script="Hang" typeface="굴림"/></a:majorFont>
<a:minorFont><a:latin typeface="Arial"/><a:ea typeface="${ea}"/><a:cs typeface=""/><a:font script="Jpan" typeface="MS Pゴシック"/><a:font script="Hans" typeface="\u9ed1\u4f53"/></a:minorFont>
</a:fontScheme><a:fmtScheme name="x"/></a:themeElements></a:theme>`
describe('theme per-script fonts', () => {
it('parses <a:font script=…> entries per major/minor font', () => {
const t = parseTheme(THEME(''))
expect(t.minorEaFont).toBeUndefined()
expect(t.minorScriptFonts).toEqual({ Jpan: 'MS Pゴシック', Hans: '\u9ed1\u4f53' })
expect(t.majorScriptFonts).toEqual({ Jpan: 'MS Pゴシック', Hang: '굴림' })
})
it('+mn-ea with an empty ea slot takes the script font for the text language, else Latin', () => {
const t = parseTheme(THEME(''))
expect(resolveFontRef('+mn-ea', t, 'ja')).toBe('MS Pゴシック')
expect(resolveFontRef('+mn-ea', t, 'sc')).toBe('\u9ed1\u4f53')
expect(resolveFontRef('+mn-ea', t, 'ko')).toBe('Arial')
expect(resolveFontRef('+mn-ea', t)).toBe('Arial')
expect(resolveFontRef('+mj-ea', t, 'ko')).toBe('굴림')
})
it("'han' (ideographs without a language) resolves only when the theme names a single Han script", () => {
const t = parseTheme(THEME(''))
// minor: Jpan + Hans → ambiguous → Latin; major: Jpan only → Jpan
expect(resolveFontRef('+mn-ea', t, 'han')).toBe('Arial')
expect(resolveFontRef('+mj-ea', t, 'han')).toBe('MS Pゴシック')
})
it('an explicit ea typeface still wins over the script entry', () => {
const t = parseTheme(THEME('Meiryo'))
expect(resolveFontRef('+mn-ea', t, 'ja')).toBe('Meiryo')
})
it('maps lang tags to East Asian scripts', () => {
expect(eaScriptOfLang('ja-JP')).toBe('ja')
expect(eaScriptOfLang('zh-TW')).toBe('tc')
expect(eaScriptOfLang('zh-CN')).toBe('sc')
expect(eaScriptOfLang('en-US')).toBeUndefined()
})
})

Some files were not shown because too many files have changed in this diff Show More