@rohal12/twee-ts 1.18.0 → 1.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paths-BuTAg2av.js","names":["_exhaustive","_exhaustive","VERSION","parsePath","_exhaustive","isInside","_exhaustive","CharCodes","isTag","Text","Comment","CDATA","isTagRaw","CREATOR_NAME","CREATOR_NAME","_exhaustive","_exhaustive"],"sources":["../src/ifid.ts","../src/escape.ts","../src/passage.ts","../src/story.ts","../src/media-types.ts","../src/filesystem.ts","../src/relaxed-json.ts","../src/semver.ts","../src/source-text.ts","../src/util.ts","../src/formats.ts","../src/atomic-write.ts","../src/remote-formats.ts","../src/format-resolution.ts","../src/types.ts","../src/lexer.ts","../src/twee2-compat.ts","../src/parser.ts","../node_modules/.pnpm/entities@8.1.0/node_modules/entities/dist/decode-codepoint.js","../node_modules/.pnpm/entities@8.1.0/node_modules/entities/dist/internal/decode-shared.js","../node_modules/.pnpm/entities@8.1.0/node_modules/entities/dist/generated/decode-data-html.js","../node_modules/.pnpm/entities@8.1.0/node_modules/entities/dist/generated/decode-data-xml.js","../node_modules/.pnpm/entities@8.1.0/node_modules/entities/dist/internal/bin-trie-flags.js","../node_modules/.pnpm/entities@8.1.0/node_modules/entities/dist/decode.js","../node_modules/.pnpm/htmlparser2@12.0.0/node_modules/htmlparser2/dist/Tokenizer.js","../node_modules/.pnpm/htmlparser2@12.0.0/node_modules/htmlparser2/dist/Parser.js","../node_modules/.pnpm/domelementtype@3.0.0/node_modules/domelementtype/dist/index.js","../node_modules/.pnpm/domhandler@6.0.1/node_modules/domhandler/dist/node.js","../node_modules/.pnpm/domhandler@6.0.1/node_modules/domhandler/dist/index.js","../node_modules/.pnpm/htmlparser2@12.0.0/node_modules/htmlparser2/dist/index.js","../src/html-parser.ts","../src/loader.ts","../src/template.ts","../src/modules.ts","../src/version.ts","../src/output-twine2.ts","../src/output-twine1.ts","../src/output-twee.ts","../src/passage-omission.ts","../src/start-passage.ts","../src/compiler.ts","../src/plugins/diagnostics.ts","../src/plugins/paths.ts"],"sourcesContent":["/**\n * IFID (Interactive Fiction IDentifier) generation and validation.\n * Ported from ifid.go.\n */\nimport { randomUUID } from 'node:crypto';\nimport type { IFID } from './types.js';\n\n/** Generate a new IFID (UUID v4, uppercase). */\nexport function generateIFID(): IFID {\n return randomUUID().toUpperCase() as IFID;\n}\n\n/**\n * Validate and brand an IFID string. Throws on invalid input.\n * Returns the IFID in its stored form (see `normalizeIFID`).\n */\nexport function createIFID(value: string): IFID {\n const err = validateIFID(value);\n if (err) throw new Error(`Invalid IFID: ${err}`);\n return normalizeIFID(value);\n}\n\n/** Length of the `UUID://...//` wrapper around a 36-character UUID. */\nconst WRAPPED_LENGTH = 45;\n\n/**\n * Bring an IFID into the form the story model stores and every output writes: the uppercase\n * bare UUID. A valid `UUID://...//` wrapped IFID loses its wrapper; outputs that need the wrapper\n * (the Treaty of Babel comment) add exactly one. Twine 2 IFIDs use only capital letters, so the\n * value is uppercased, as Tweego does. An invalid value is only uppercased, so that validation\n * reports it as written.\n */\nexport function normalizeIFID(value: string): IFID {\n const upper = value.toUpperCase();\n const bare = upper.length === WRAPPED_LENGTH && validateIFID(upper) === null ? upper.slice(7, 43) : upper;\n return bare as IFID;\n}\n\n/**\n * Validate an IFID string.\n * Accepts both bare UUIDs and UUID://...// wrapped format.\n * Returns null if valid, or an error message string.\n */\nexport function validateIFID(ifid: string): string | null {\n let uuid = ifid;\n\n switch (ifid.length) {\n case 36:\n break;\n case 45: {\n if (ifid.slice(0, 7).toUpperCase() !== 'UUID://' || ifid.slice(43) !== '//') {\n return 'invalid IFID UUID://...// format';\n }\n uuid = ifid.slice(7, 43);\n break;\n }\n default:\n return `invalid IFID length: ${ifid.length}`;\n }\n\n for (let i = 0; i < uuid.length; i++) {\n const ch = uuid[i]!;\n switch (i) {\n case 8:\n case 13:\n case 18:\n case 23:\n if (ch !== '-') {\n return `invalid IFID character '${ch}' at position ${i + 1}`;\n }\n break;\n case 14:\n if (ch < '1' || ch > '5') {\n return `invalid version '${ch}' at position ${i + 1}`;\n }\n break;\n case 19:\n if (!['8', '9', 'a', 'A', 'b', 'B'].includes(ch)) {\n return `invalid variant '${ch}' at position ${i + 1}`;\n }\n break;\n default:\n if (!/^[0-9a-fA-F]$/.test(ch)) {\n return `invalid IFID hex value '${ch}' at position ${i + 1}`;\n }\n break;\n }\n }\n\n return null;\n}\n","/**\n * HTML, attribute, tiddler, and twee escaping/unescaping utilities.\n * Ported from escaping.go.\n */\n\n/** Escape the minimum characters required for HTML attribute values. */\nexport function attrEscape(s: string): string {\n if (s.length === 0) return s;\n return s.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\n}\n\n/** Escape for HTML attribute values including < and > (for spec-compliant output). */\nexport function fullAttrEscape(s: string): string {\n if (s.length === 0) return s;\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/** Escape the minimum characters required for general HTML content. */\nexport function htmlEscape(s: string): string {\n if (s.length === 0) return s;\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/** Escape for Twine 1 tiddler format. */\nexport function tiddlerEscape(s: string): string {\n if (s.length === 0) return s;\n return s\n .replace(/\\\\/g, '\\\\s')\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n');\n}\n\n/** Unescape from Twine 1 tiddler format. */\nexport function tiddlerUnescape(s: string): string {\n if (s.length === 0) return s;\n return s.replace(/\\\\n/g, '\\n').replace(/\\\\t/g, '\\t').replace(/\\\\s/g, '\\\\');\n}\n\n/** Escape characters that are special in Twee passage names/tags. */\nexport function tweeEscape(s: string): string {\n if (s.length === 0) return s;\n return s.replace(/[\\\\[\\]{}]/g, (ch) => '\\\\' + ch);\n}\n\nconst JS_STRING_ESCAPES: Readonly<Record<string, string>> = {\n '\\\\': '\\\\\\\\',\n '\"': '\\\\\"',\n \"'\": \"\\\\'\",\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '<': '\\\\x3C',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n};\n\n/**\n * Escape a string for the inside of a single- or double-quoted JavaScript string literal, including one written\n * into an HTML `<script>` element. Besides backslashes, quotes and line breaks (with U+2028 and U+2029, which end\n * a string literal in JavaScript before ES2019), every `<` becomes `\\x3C`, so the literal holds no `</script`\n * that would end the element and no `<!--` or `<script` that would change where it ends. The string's value is\n * unchanged.\n */\nexport function jsStringEscape(s: string): string {\n if (s.length === 0) return s;\n return s.replace(/[\\\\\"'\\n\\r\\t<\\u2028\\u2029]/g, (ch) => JS_STRING_ESCAPES[ch] ?? ch);\n}\n\n/**\n * Escape a string for the inside of a double-quoted CSS string (such as a `font-family` name): `\\` and `\"` get\n * a backslash, and line breaks and other control characters become hex escapes followed by a space (`\\a ` for a\n * line feed), since a raw line break ends a CSS string and a backslash before one is a line continuation.\n */\nexport function cssStringEscape(s: string): string {\n if (s.length === 0) return s;\n return s.replace(/[\\\\\"\\u0000-\\u001f\\u007f]/g, (ch) =>\n ch === '\\\\' || ch === '\"' ? `\\\\${ch}` : `\\\\${ch.charCodeAt(0).toString(16)} `,\n );\n}\n\n/** Sanitize a string for safe inclusion in a CSS or JS block comment. */\nexport function commentSanitize(s: string): string {\n return s.replace(/\\*\\//g, '* /');\n}\n\n/** Sanitize a string for safe inclusion in an HTML comment: break up `-->` and `--!>`, which both end one. */\nexport function htmlCommentSanitize(s: string): string {\n return s.replace(/--(!?)>/g, '--$1 >');\n}\n\n/**\n * Escape JavaScript for the content of an HTML `<script>` element, so that the HTML parser reads all of it as\n * the element's text and ends the element at the end tag written after it.\n *\n * - Every `</script` (in any letter case) becomes `<\\/script`. HTML ends a script element at the first\n * `</script` followed by whitespace, `/` or `>`, wherever it is in the JavaScript, even inside a string.\n * - Every `<!--` becomes `<\\!--`, but only if the text would otherwise end in the HTML tokenizer's \"script\n * data double escaped\" state: after a `<!--` and then a `<script` start tag with no `-->` between them, the\n * end tag after the text would not end the element.\n *\n * Inserting a backslash after `<` keeps the value of every string, template, and regular expression literal\n * and every comment where these sequences can be written (`\\/` and `\\!` are identity escapes; a backslash\n * already before the `<` escapes the `<`, as it did before); `<\\/script` is also how minifiers such as Terser\n * write inline scripts. It only changes code that uses them outside literals (`a </script/ b`, an HTML-like `<!--`\n * comment that is escaped because of a later `<script`), the raw text of a tagged template, and a `<!--` in a\n * regular expression with the `u` or `v` flag. The result is unchanged by escaping it again.\n */\nexport function scriptContentEscape(s: string): string {\n const escaped = s.replace(/<(?=\\/script)/gi, '<\\\\');\n return endsDoubleEscaped(escaped) ? escaped.replace(/<(?=!--)/g, '<\\\\') : escaped;\n}\n\n/**\n * Whether the HTML tokenizer, reading `s` as script element content with no `</script` in it, ends in the\n * \"script data double escaped\" state, where an end tag after `s` would not end the element.\n * See https://html.spec.whatwg.org/multipage/parsing.html#script-data-escaped-state.\n */\nfunction endsDoubleEscaped(s: string): boolean {\n const scriptStartTag = /<script[\\t\\n\\f\\r />]/gi;\n let pos = 0;\n for (;;) {\n // Script data: a `<!--` enters the escaped state.\n const open = s.indexOf('<!--', pos);\n if (open === -1) return false;\n // Escaped: a `-->` leaves it (the dashes of `<!--` count, so `<!-->` leaves at once); a `<script` start\n // tag enters the double escaped state.\n const escapedFrom = open + 2;\n const close = s.indexOf('-->', escapedFrom);\n scriptStartTag.lastIndex = escapedFrom;\n const start = scriptStartTag.exec(s);\n if (start === null || (close !== -1 && close < start.index)) {\n if (close === -1) return false;\n pos = close + 3;\n continue;\n }\n // Double escaped: only a `</script` (none are left) or a `-->` leaves it.\n const end = s.indexOf('-->', start.index + start[0].length);\n if (end === -1) return true;\n pos = end + 3;\n }\n}\n\n/**\n * Escape CSS for the content of an HTML `<style>` element: every `</style` (in any letter case) becomes\n * `<\\/style`, since HTML ends a style element at the first `</style` followed by whitespace, `/` or `>`.\n * `\\/` stands for `/` in CSS strings and URLs, and comments don't matter; `</style` anywhere else isn't valid\n * CSS anyway.\n */\nexport function styleContentEscape(s: string): string {\n return s.replace(/<(?=\\/style)/gi, '<\\\\');\n}\n\n/** Apply ROT13 encoding to a string (only affects [A-Za-z]). */\nexport function rot13(s: string): string {\n if (s.length === 0) return s;\n return s.replace(/[A-Za-z]/g, (ch) => {\n const base = ch <= 'Z' ? 65 : 97;\n return String.fromCharCode(((ch.charCodeAt(0) - base + 13) % 26) + base);\n });\n}\n\n/** Unescape backslash-escaped Twee characters. */\nexport function tweeUnescape(s: string): string {\n if (s.length === 0) return s;\n let result = '';\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '\\\\') {\n i++;\n if (i >= s.length) {\n result += '\\\\';\n break;\n }\n }\n result += s[i];\n }\n return result;\n}\n","/**\n * Passage helpers and output methods.\n * Ported from passage.go / passagedata.go.\n */\nimport type { Passage, ReadonlyPassage, PassageMetadata, OutputMode, WordCountMethod } from './types.js';\nimport { attrEscape, fullAttrEscape, htmlEscape, tiddlerEscape, tweeEscape, rot13 } from './escape.js';\n\n// Info passages contain structural data, metadata, and code rather than story content.\nconst INFO_PASSAGE_NAMES = new Set([\n 'StoryAuthor',\n 'StoryInit',\n 'StoryMenu',\n 'StorySubtitle',\n 'StoryTitle',\n 'PassageReady',\n 'PassageDone',\n 'PassageHeader',\n 'PassageFooter',\n 'StoryBanner',\n 'StoryCaption',\n 'MenuOptions',\n 'MenuShare',\n 'MenuStory',\n 'StoryInterface',\n 'StoryShare',\n 'StorySettings',\n 'StoryData',\n 'StoryIncludes',\n]);\n\nconst INFO_TAGS = ['annotation', 'script', 'stylesheet', 'widget'];\n\nexport function hasTag(p: ReadonlyPassage, tag: string): boolean {\n return p.tags.includes(tag);\n}\n\nexport function hasAnyTag(p: ReadonlyPassage, ...tags: string[]): boolean {\n return p.tags.some((t) => tags.includes(t));\n}\n\nexport function hasTagStartingWith(p: ReadonlyPassage, prefix: string): boolean {\n return p.tags.some((t) => t.startsWith(prefix));\n}\n\nexport function hasInfoTags(p: ReadonlyPassage): boolean {\n return hasAnyTag(p, ...INFO_TAGS) || hasTagStartingWith(p, 'Twine.');\n}\n\nexport function hasInfoName(p: ReadonlyPassage): boolean {\n return INFO_PASSAGE_NAMES.has(p.name);\n}\n\nexport function isInfoPassage(p: ReadonlyPassage): boolean {\n return hasInfoName(p) || hasInfoTags(p);\n}\n\nexport function isStoryPassage(p: ReadonlyPassage): boolean {\n return !hasInfoName(p) && !hasInfoTags(p);\n}\n\nexport function hasMetadataPosition(p: ReadonlyPassage): boolean {\n return p.metadata != null && p.metadata.position != null && p.metadata.position !== '';\n}\n\nexport function hasMetadataSize(p: ReadonlyPassage): boolean {\n return p.metadata != null && p.metadata.size != null && p.metadata.size !== '';\n}\n\nexport function hasAnyMetadata(p: ReadonlyPassage): boolean {\n if (!p.metadata) return false;\n return Object.values(p.metadata).some((v) => v != null && v !== '');\n}\n\nexport function marshalMetadata(meta: PassageMetadata): string {\n const obj: Record<string, string> = {};\n for (const [key, value] of Object.entries(meta)) {\n if (typeof value === 'string' && value) obj[key] = value;\n }\n return JSON.stringify(obj);\n}\n\nexport function unmarshalMetadata(json: string): PassageMetadata {\n const raw: unknown = JSON.parse(json);\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return {};\n }\n const parsed = raw as Record<string, unknown>;\n const meta: PassageMetadata = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (typeof value === 'string') meta[key] = value;\n }\n return meta;\n}\n\n/** Convert passage to Twee source. */\nexport function passageToTwee(p: ReadonlyPassage, outMode: OutputMode): string {\n let output: string;\n if (outMode === 'twee3') {\n output = ':: ' + tweeEscape(p.name);\n if (p.tags.length > 0) {\n output += ' [' + tweeEscape(p.tags.join(' ')) + ']';\n }\n if (hasAnyMetadata(p) && p.metadata) {\n output += ' ' + marshalMetadata(p.metadata);\n }\n } else {\n output = ':: ' + p.name;\n if (p.tags.length > 0) {\n output += ' [' + p.tags.join(' ') + ']';\n }\n }\n output += '\\n';\n if (p.text.length > 0) {\n output += p.text + '\\n';\n }\n output += '\\n\\n';\n return output;\n}\n\n/** Generate `<tw-passagedata>` HTML for Twine 2. */\nexport function passageToPassagedata(\n p: ReadonlyPassage,\n pid: number,\n options?: { readonly sourceInfo?: boolean },\n): string {\n let position: string;\n let size: string;\n\n if (hasMetadataPosition(p)) {\n position = p.metadata?.position ?? '';\n } else {\n const x = pid % 10;\n const y = Math.floor(pid / 10);\n const xp = x === 0 ? 10 : x;\n const yp = x === 0 ? y : y + 1;\n position = `${xp * 125 - 25},${yp * 125 - 25}`;\n }\n\n if (hasMetadataSize(p)) {\n size = p.metadata?.size ?? '';\n } else {\n size = '100,100';\n }\n\n let attrs = `<tw-passagedata pid=\"${pid}\" name=${quote(fullAttrEscape(p.name))} tags=${quote(attrEscape(p.tags.join(' ')))} position=${quote(attrEscape(position))} size=${quote(attrEscape(size))}`;\n if (options?.sourceInfo && p.source) {\n attrs += ` data-source-file=${quote(attrEscape(p.source.file))} data-source-line=\"${p.source.line}\"`;\n }\n return `${attrs}>${htmlEscape(p.text)}</tw-passagedata>`;\n}\n\n/**\n * Whether Twine 1 `obfuscate:rot13` encodes a tiddler: every one but `StorySettings` and those tagged `Twine.image`\n * (Twine 1.4 `Tiddler.isObfuscateable()`). Its engine tests the stored name and tags, which these tiddlers keep\n * unencoded, so the decompiler tests them the same way.\n */\nexport function isObfuscatable(p: Pick<ReadonlyPassage, 'name' | 'tags'>): boolean {\n return p.name !== 'StorySettings' && !p.tags.includes('Twine.image');\n}\n\n/**\n * Generate `<div tiddler>` HTML for Twine 1. With `obfuscateRot13`, an obfuscatable tiddler (see\n * `isObfuscatable()`) has its name, each tag and its text ROT13-encoded, as Twine 1.4 writes it\n * (`Tiddler.toHtml()`), and as its engine.js decodes it.\n */\nexport function passageToTiddler(p: ReadonlyPassage, pid: number, obfuscateRot13 = false): string {\n let position: string;\n\n if (hasMetadataPosition(p)) {\n position = p.metadata?.position ?? '';\n } else {\n const x = pid % 10;\n const y = Math.floor(pid / 10);\n const xp = x === 0 ? 10 : x;\n const yp = x === 0 ? y : y + 1;\n position = `${xp * 140 - 130},${yp * 140 - 130}`;\n }\n\n const created = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 12);\n const encode = obfuscateRot13 && isObfuscatable(p) ? rot13 : (s: string) => s;\n const name = attrEscape(encode(p.name));\n const tags = attrEscape(p.tags.map(encode).join(' '));\n return `<div tiddler=${quote(name)} tags=${quote(tags)} created=${quote(created)} modifier=${quote('twee')} twine-position=${quote(attrEscape(position))}>${tiddlerEscape(encode(p.text))}</div>`;\n}\n\n/**\n * Count words in a passage.\n *\n * - `'tweego'` (default): Strip newlines, strip comments, count NFKD-normalized characters, divide by 5.\n * - `'whitespace'`: Strip comments and markup, split on whitespace, count tokens.\n */\nexport function countWords(p: ReadonlyPassage, method: WordCountMethod = 'tweego'): number {\n switch (method) {\n case 'tweego': {\n let text = p.text;\n text = text.replace(/\\n/g, '');\n text = text.replace(/(?:\\/%.+?%\\/|\\/\\*.+?\\*\\/|<!--.+?-->)/gs, '');\n const normalized = text.normalize('NFKD');\n const count = [...normalized].length;\n if (count === 0) return 0;\n const words = Math.floor(count / 5);\n return count % 5 > 0 ? words + 1 : words;\n }\n case 'whitespace': {\n let text = p.text;\n // Strip comments\n text = text.replace(/(?:\\/%.+?%\\/|\\/\\*.+?\\*\\/|<!--.+?-->)/gs, '');\n // Strip Twine macros <<...>>\n text = text.replace(/<<[^>]*>>/g, '');\n // Strip Twine links [[...]] — keep display text\n text = text.replace(/\\[\\[([^\\]|]*?)(?:\\|[^\\]]*?)?\\]\\]/g, '$1');\n // Strip HTML tags\n text = text.replace(/<[^>]+>/g, '');\n const tokens = text.split(/\\s+/).filter((t) => t.length > 0);\n return tokens.length;\n }\n default: {\n const _exhaustive: never = method;\n throw new Error(`Unhandled word count method: ${_exhaustive as string}`);\n }\n }\n}\n\n/**\n * Apply tag aliases: for each passage carrying an alias tag, add the canonical\n * tag if not already present. Returns new passage objects where tags changed;\n * unchanged passages are returned as-is. Idempotent — safe to call multiple times.\n */\nexport function applyTagAliases(passages: readonly Passage[], aliases: Record<string, string>): Passage[] {\n const entries = Object.entries(aliases);\n if (entries.length === 0) return [...passages];\n return passages.map((p) => {\n const original = p.tags;\n const added: string[] = [];\n for (const [alias, canonical] of entries) {\n if (original.includes(alias) && !original.includes(canonical) && !added.includes(canonical)) {\n added.push(canonical);\n }\n }\n return added.length > 0 ? { ...p, tags: [...original, ...added] } : p;\n });\n}\n\nfunction quote(s: string): string {\n return `\"${s}\"`;\n}\n","/**\n * Story model + StoryData JSON marshal/unmarshal.\n * Ported from story.go + storydata.go.\n */\nimport type { Story, ReadonlyStory, Passage, Diagnostic, WordCountMethod, IFID } from './types.js';\nimport { normalizeIFID, validateIFID } from './ifid.js';\nimport { isStoryPassage, countWords } from './passage.js';\n\n// --- Passage name index ---\n\n/**\n * A story's passage positions by name, for O(1) lookups. `story.passages` is a plain mutable\n * array that code outside this module may change (StoryBuilder documents it), so the index\n * records what it was built from and is rebuilt when that no longer matches.\n */\ninterface NameIndex {\n /** The array the index describes; assigning `story.passages` gives a different one. */\n readonly passages: readonly Passage[];\n /** The name at each position when the index was last updated. */\n readonly names: string[];\n /** Position by name; with duplicate names in the array, the last position. */\n readonly positions: Map<string, number>;\n}\n\nconst passageIndex = new WeakMap<Story, NameIndex>();\n\nfunction buildIndex(story: Story): NameIndex {\n const names = story.passages.map((p) => p.name);\n const index: NameIndex = { passages: story.passages, names, positions: new Map(names.map((name, i) => [name, i])) };\n passageIndex.set(story, index);\n return index;\n}\n\n/**\n * The index, rebuilt if `story.passages` was reassigned or changed length. O(1); `position()`\n * also checks every hit. A change that keeps the length, such as replacing an element, can still\n * hide a passage from a lookup, so `storyVerifyIndex()` checks every position.\n */\nfunction currentIndex(story: Story): NameIndex {\n const index = passageIndex.get(story);\n return index !== undefined && index.passages === story.passages && index.names.length === story.passages.length\n ? index\n : buildIndex(story);\n}\n\n/**\n * Rebuild the index unless it matches `story.passages` at every position. O(n): for entry points\n * that run after code outside the compiler may have changed the passages, such as StoryBuilder.\n */\nfunction storyVerifyIndex(story: Story): void {\n const index = currentIndex(story);\n if (!story.passages.every((p, i) => p.name === index.names[i])) buildIndex(story);\n}\n\n/** The position of the passage named `name`, or -1. */\nfunction position(story: Story, name: string): number {\n const i = currentIndex(story).positions.get(name);\n if (i === undefined) return -1;\n if (story.passages[i]?.name === name) return i;\n return buildIndex(story).positions.get(name) ?? -1;\n}\n\n/** Add a passage whose name no passage has yet at the end. */\nfunction push(story: Story, p: Passage): void {\n const index = currentIndex(story);\n index.positions.set(p.name, story.passages.length);\n index.names.push(p.name);\n story.passages.push(p);\n}\n\n/** Put a passage at position `i`, in place of the passage there. */\nfunction replaceAt(story: Story, i: number, p: Passage): void {\n const renamed = story.passages[i]?.name !== p.name;\n story.passages[i] = p;\n // Only moving a generated name aside renames a position; that is rare, so rebuild then.\n if (renamed) buildIndex(story);\n}\n\n// --- Generated passage names ---\n\n/** Names of compiler special passages, which storyAdd() reads into the story model. */\nconst SPECIAL_PASSAGE_NAMES: ReadonlySet<string> = new Set([\n 'StoryData',\n 'StoryIncludes',\n 'StorySettings',\n 'StoryTitle',\n]);\n\n/**\n * Where a passage name that the compiler made up came from. Generated names yield to every other\n * name in the story: see `storyAdd()`.\n * - `code`: a stylesheet or script (a `.css`, `.js` or font file, or an imported Twine 2 story's\n * stylesheet or script). Output finds these by tag, so a new name is not reported.\n * - `media`: an image, audio, video or text track file. Stories refer to these by passage name,\n * so a new name is reported.\n */\nexport type GeneratedName =\n | { readonly kind: 'code'; readonly base: string }\n | { readonly kind: 'media'; readonly base: string; readonly file: string };\n\n/** Passages whose names were generated, kept by identity so that cached passages keep the mark. */\nconst generatedNames = new WeakMap<Passage, GeneratedName>();\n\n/**\n * Mark a passage's name as generated (from a file name, or for imported story code) and return\n * the passage. `origin.base` is the name that free names are numbered from: `base`, `base 2`, ….\n */\nexport function withGeneratedName(p: Passage, origin: GeneratedName): Passage {\n generatedNames.set(p, origin);\n return p;\n}\n\n/** The first of `base`, `base 2`, `base 3`, … that `isFree` accepts. */\nexport function freeName(base: string, isFree: (name: string) => boolean): string {\n if (isFree(base)) return base;\n for (let n = 2; ; n++) {\n const candidate = `${base} ${n}`;\n if (isFree(candidate)) return candidate;\n }\n}\n\n/** Whether a generated name may take `name`: no passage has it and it is no special name. */\nfunction isFreeForGenerated(story: Story, name: string): boolean {\n return !SPECIAL_PASSAGE_NAMES.has(name) && position(story, name) === -1;\n}\n\nfunction reportRename(origin: GeneratedName, from: string, to: string, diagnostics: Diagnostic[]): void {\n switch (origin.kind) {\n case 'code':\n return;\n case 'media': {\n const reason = SPECIAL_PASSAGE_NAMES.has(from)\n ? `\"${from}\" is a compiler special passage name`\n : `another passage has the name \"${from}\"`;\n diagnostics.push({\n level: 'warning',\n message: `Passage \"${from}\" from \"${origin.file}\" renamed to \"${to}\"; ${reason}.`,\n });\n return;\n }\n default: {\n const _exhaustive: never = origin;\n throw new Error(`unhandled generated name: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\n/** Add a passage with a generated name, under the first free name if its own is taken. */\nfunction addGenerated(story: Story, p: Passage, origin: GeneratedName, diagnostics: Diagnostic[]): void {\n if (isFreeForGenerated(story, p.name)) {\n push(story, p);\n return;\n }\n const name = freeName(origin.base, (n) => isFreeForGenerated(story, n));\n reportRename(origin, p.name, name, diagnostics);\n push(story, withGeneratedName({ ...p, name }, origin));\n}\n\n/**\n * If a passage with a generated name has `name`, give it the first free name, in its place in the\n * passage list, so that a passage from the sources can take the name.\n */\nfunction moveGeneratedAside(story: Story, name: string, diagnostics: Diagnostic[]): void {\n const i = position(story, name);\n const existing = i === -1 ? undefined : story.passages[i];\n const origin = existing === undefined ? undefined : generatedNames.get(existing);\n if (existing === undefined || origin === undefined) return;\n const free = freeName(origin.base, (n) => isFreeForGenerated(story, n));\n reportRename(origin, name, free, diagnostics);\n replaceAt(story, i, withGeneratedName({ ...existing, name: free }, origin));\n}\n\n// --- Story ---\n\nfunction defaultTwine2Metadata(): Story['twine2'] {\n return {\n format: '',\n formatVersion: '',\n options: new Map(),\n start: '',\n tags: '',\n tagColors: new Map(),\n zoom: 1,\n };\n}\n\nexport function createStory(): Story {\n const story: Story = {\n name: '',\n ifid: '' as IFID,\n passages: [],\n legacyIFID: '' as IFID,\n twine1: { settings: new Map() },\n twine2: defaultTwine2Metadata(),\n };\n buildIndex(story);\n return story;\n}\n\nexport function storyHas(story: Story, name: string): boolean {\n return position(story, name) !== -1;\n}\n\nexport function storyIndex(story: Story, name: string): number {\n return position(story, name);\n}\n\nexport function storyGet(story: Story, name: string): Passage | undefined {\n const i = position(story, name);\n return i === -1 ? undefined : story.passages[i];\n}\n\nexport function storyAppend(story: Story, p: Passage, diagnostics: Diagnostic[]): void {\n const i = position(story, p.name);\n if (i === -1) {\n push(story, p);\n } else {\n diagnostics.push({\n level: 'warning',\n message: `Replacing existing passage \"${p.name}\" with duplicate.`,\n });\n replaceAt(story, i, p);\n }\n}\n\nexport function storyPrepend(story: Story, p: Passage, diagnostics: Diagnostic[]): void {\n moveGeneratedAside(story, p.name, diagnostics);\n const i = position(story, p.name);\n if (i === -1) {\n story.passages.unshift(p);\n // Every position moves up by one.\n buildIndex(story);\n } else {\n diagnostics.push({\n level: 'warning',\n message: `Replacing existing passage \"${p.name}\" with duplicate.`,\n });\n replaceAt(story, i, p);\n }\n}\n\n// --- StoryData JSON ---\n\ninterface StoryDataJSON {\n ifid?: string;\n format?: string;\n 'format-version'?: string;\n options?: string[];\n start?: string;\n tags?: string;\n 'tag-colors'?: Record<string, string>;\n zoom?: number;\n}\n\nexport function marshalStoryData(story: ReadonlyStory): string {\n const data: StoryDataJSON = {};\n if (story.ifid) data.ifid = story.ifid;\n if (story.twine2.format) data.format = story.twine2.format;\n if (story.twine2.formatVersion) data['format-version'] = story.twine2.formatVersion;\n\n const options: string[] = [];\n for (const [opt, val] of story.twine2.options) {\n if (val) options.push(opt);\n }\n if (options.length > 0) data.options = options;\n\n if (story.twine2.start) data.start = story.twine2.start;\n if (story.twine2.tags) data.tags = story.twine2.tags;\n\n if (story.twine2.tagColors.size > 0) {\n data['tag-colors'] = Object.fromEntries(story.twine2.tagColors);\n }\n if (story.twine2.zoom !== 1) data.zoom = story.twine2.zoom;\n\n return JSON.stringify(data, null, '\\t');\n}\n\nexport function unmarshalStoryData(story: Story, json: string): string | null {\n let raw: unknown;\n try {\n raw = JSON.parse(json) as unknown;\n } catch (e) {\n return `Cannot unmarshal \"StoryData\"; ${e instanceof Error ? e.message : String(e)}`;\n }\n\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return 'Cannot unmarshal \"StoryData\"; expected a JSON object';\n }\n const data = raw as StoryDataJSON;\n\n // StoryData holds all of this metadata, so a field it leaves out gets its default, not the\n // value of an earlier StoryData passage. The StorySettings IFID is kept apart (legacyIFID).\n const twine2 = defaultTwine2Metadata();\n story.ifid = typeof data.ifid === 'string' ? normalizeIFID(data.ifid) : ('' as IFID);\n if (typeof data.format === 'string') twine2.format = data.format;\n if (typeof data['format-version'] === 'string') twine2.formatVersion = data['format-version'];\n if (Array.isArray(data.options)) {\n for (const opt of data.options) {\n if (typeof opt === 'string') twine2.options.set(opt, true);\n }\n }\n if (typeof data.start === 'string') twine2.start = data.start;\n if (typeof data.tags === 'string') twine2.tags = data.tags;\n if (typeof data['tag-colors'] === 'object' && data['tag-colors'] !== null && !Array.isArray(data['tag-colors'])) {\n for (const [tag, color] of Object.entries(data['tag-colors'])) {\n if (typeof color === 'string') twine2.tagColors.set(tag, color);\n }\n }\n if (typeof data.zoom === 'number' && data.zoom !== 0) twine2.zoom = data.zoom;\n story.twine2 = twine2;\n\n return null;\n}\n\n// --- StorySettings (legacy) ---\n\nexport function unmarshalStorySettings(story: Story, text: string, diagnostics: Diagnostic[]): void {\n const obsolete: string[] = [];\n\n for (const rawLine of text.split('\\n')) {\n const line = rawLine.trim();\n if (line.length === 0) continue;\n\n const colonIdx = line.indexOf(':');\n if (colonIdx === -1) {\n diagnostics.push({\n level: 'warning',\n message: `Malformed \"StorySettings\" entry; skipping \"${line}\".`,\n });\n continue;\n }\n\n const key = line.slice(0, colonIdx).trim().toLowerCase();\n const val = line\n .slice(colonIdx + 1)\n .trim()\n .toLowerCase();\n\n switch (key) {\n case 'ifid': {\n const err = validateIFID(val);\n if (err === null) {\n story.legacyIFID = normalizeIFID(val);\n }\n obsolete.push('\"ifid\"');\n continue;\n }\n case 'zoom':\n obsolete.push('\"zoom\"');\n continue;\n }\n\n story.twine1.settings.set(key, val);\n }\n\n if (obsolete.length > 0) {\n const entries = obsolete.length === 1 ? 'entry' : 'entries';\n const pronoun = obsolete.length === 1 ? 'it' : 'them';\n diagnostics.push({\n level: 'warning',\n message:\n `Detected obsolete \"StorySettings\" ${entries}: ${obsolete.join(', ')}. ` +\n `Please remove ${pronoun} from the \"StorySettings\" special passage.`,\n });\n }\n}\n\n/**\n * Process a passage and add it to the story, handling special passages.\n * Creates new passage objects where text is modified rather than mutating the input.\n *\n * A passage replaces an earlier one with the same name, except where either name was generated\n * (see `withGeneratedName()`): a generated name never replaces a passage and is never replaced.\n * A passage with a generated name takes the first free name of `base`, `base 2`, … when its own\n * is taken or is a compiler special name. A passage with a name from the sources that a generated\n * name holds takes it over, and the generated one moves to the first free name in its place.\n */\nexport function storyAdd(story: Story, p: Passage, diagnostics: Diagnostic[]): void {\n const origin = generatedNames.get(p);\n if (origin !== undefined) {\n addGenerated(story, p, origin, diagnostics);\n return;\n }\n moveGeneratedAside(story, p.name, diagnostics);\n\n let processed = p;\n\n switch (p.name) {\n case 'StoryIncludes':\n diagnostics.push({\n level: 'warning',\n message:\n 'Ignoring \"StoryIncludes\" compiler special passage; twee-ts allows you to specify project files and/or directories to recursively search.',\n });\n break;\n\n case 'StoryData': {\n const err = unmarshalStoryData(story, p.text);\n if (err === null) {\n // Validate the IFID if present.\n if (story.ifid.length > 0) {\n const vErr = validateIFID(story.ifid);\n if (vErr !== null) {\n diagnostics.push({\n level: 'error',\n message: `Cannot validate IFID; ${vErr}.`,\n });\n }\n }\n // Rebuild passage contents to normalize.\n processed = { ...p, text: marshalStoryData(story) };\n } else {\n diagnostics.push({\n level: 'warning',\n message: `Cannot unmarshal \"StoryData\" compiler special passage; ${err}.`,\n });\n }\n break;\n }\n\n case 'StorySettings':\n unmarshalStorySettings(story, p.text, diagnostics);\n break;\n\n case 'StoryTitle': {\n const trimmed = p.text.trim();\n processed = { ...p, text: trimmed };\n story.name = trimmed;\n break;\n }\n }\n\n storyAppend(story, processed, diagnostics);\n}\n\n/** Get story passage count and word count stats. */\nexport function getStoryStats(\n story: Story,\n wordCountMethod: WordCountMethod = 'tweego',\n): { passages: number; storyPassages: number; words: number } {\n let storyPassages = 0;\n let words = 0;\n for (const p of story.passages) {\n if (isStoryPassage(p)) {\n storyPassages++;\n words += countWords(p, wordCountMethod);\n }\n }\n return { passages: story.passages.length, storyPassages, words };\n}\n\n/**\n * Builder that separates the mutable construction phase from the immutable consumption phase.\n * During construction, the internal `Story` is mutable via `add()` and direct access: you may\n * push, splice, sort, rename or reassign `story.passages` between calls, and `add()` and `has()`\n * see the passages as they are then.\n * After `build()`, the story is returned as `ReadonlyStory`.\n */\nexport class StoryBuilder {\n /** The mutable story, accessible during construction for loader functions. */\n readonly story: Story;\n\n constructor() {\n this.story = createStory();\n }\n\n /** Add a passage, handling special passages (StoryData, StoryTitle, etc.). */\n add(passage: Passage, diagnostics: Diagnostic[]): void {\n // A found name is checked at its position, so it is current. Only a new name (or a generated\n // one, which looks up other names) needs every position checked first.\n if (generatedNames.has(passage) || !storyHas(this.story, passage.name)) storyVerifyIndex(this.story);\n storyAdd(this.story, passage, diagnostics);\n }\n\n /** Check if a passage name exists. */\n has(name: string): boolean {\n // A found name is checked at its position; only \"not found\" needs every position checked.\n if (storyHas(this.story, name)) return true;\n storyVerifyIndex(this.story);\n return storyHas(this.story, name);\n }\n\n /** Finalize and return the story as read-only. */\n build(): ReadonlyStory {\n return this.story;\n }\n}\n","/**\n * Extension → MIME type mapping.\n * Ported from util.go:mediaTypeFromExt().\n */\n\nimport { extname } from 'node:path';\n\nconst MEDIA_TYPE_MAP: Record<string, string> = {\n // Audio\n aac: 'audio/aac',\n flac: 'audio/flac',\n ogg: 'audio/ogg',\n wav: 'audio/wav',\n mp3: 'audio/mpeg',\n m4a: 'audio/mp4',\n oga: 'audio/ogg',\n opus: 'audio/ogg',\n wave: 'audio/wav',\n weba: 'audio/webm',\n\n // Fonts\n otf: 'font/otf',\n ttf: 'font/ttf',\n woff: 'font/woff',\n woff2: 'font/woff2',\n\n // Images\n gif: 'image/gif',\n jpeg: 'image/jpeg',\n jpg: 'image/jpeg',\n png: 'image/png',\n svg: 'image/svg+xml',\n tif: 'image/tiff',\n tiff: 'image/tiff',\n webp: 'image/webp',\n\n // Metadata\n vtt: 'text/vtt',\n\n // Video\n mp4: 'video/mp4',\n ogv: 'video/ogg',\n webm: 'video/webm',\n};\n\nexport function mediaTypeFromExt(ext: string): string {\n return MEDIA_TYPE_MAP[ext] ?? 'application/octet-stream';\n}\n\nexport function mediaTypeFromFilename(filename: string): string {\n return mediaTypeFromExt(normalizedFileExt(filename));\n}\n\nexport function normalizedFileExt(filename: string): string {\n const ext = extname(filename);\n if (!ext) return '';\n return ext.slice(1).toLowerCase();\n}\n\n/** Slugify a string for safe use as a DOM ID. */\nexport function slugify(original: string): string {\n return original.replace(/[\\x00-\\x20!-/:-@[-^`{-\\x9f]+/g, '_');\n}\n\n/** Check if a file has a known type that should be processed. */\nexport function isKnownFileType(filename: string): boolean {\n const ext = normalizedFileExt(filename);\n return KNOWN_EXTENSIONS.has(ext);\n}\n\nconst KNOWN_EXTENSIONS = new Set([\n 'tw',\n 'twee',\n 'tw2',\n 'twee2',\n 'htm',\n 'html',\n 'css',\n 'js',\n 'otf',\n 'ttf',\n 'woff',\n 'woff2',\n 'gif',\n 'jpeg',\n 'jpg',\n 'png',\n 'svg',\n 'tif',\n 'tiff',\n 'webp',\n 'aac',\n 'flac',\n 'm4a',\n 'mp3',\n 'oga',\n 'ogg',\n 'opus',\n 'wav',\n 'wave',\n 'weba',\n 'mp4',\n 'ogv',\n 'webm',\n 'vtt',\n]);\n\n/** Font format hint for @font-face. */\nexport function fontFormatHint(ext: string): string {\n switch (ext) {\n case 'ttf':\n return 'truetype';\n case 'otf':\n return 'opentype';\n default:\n return ext;\n }\n}\n","/**\n * File system utilities: path walking, file type detection, watch mode.\n * Ported from filesystem.go.\n */\nimport {\n accessSync,\n constants as fsConstants,\n lstatSync,\n readdirSync,\n realpathSync,\n statSync,\n watch as fsWatch,\n} from 'node:fs';\nimport type { FSWatcher, Stats } from 'node:fs';\nimport * as nodePath from 'node:path';\nimport { basename, dirname, resolve, relative, join, sep } from 'node:path';\nimport { isKnownFileType } from './media-types.js';\nimport type { Diagnostic } from './types.js';\n\n/**\n * Whether `filename` matches one of the `exclude` globs. The globs are matched\n * against the file's path relative to the working directory, the path\n * getFilenames reports; an absolute `filename` is made relative first. A leading\n * `./` in a glob is dropped. Matching is Node's `path.matchesGlob`.\n */\nexport function isExcluded(filename: string, exclude: readonly string[]): boolean {\n if (exclude.length === 0) return false;\n // Read from the namespace, not imported by name: path.matchesGlob arrived in\n // Node 22.5, and a named import would stop this module loading on 22.0-22.4.\n const { matchesGlob } = nodePath;\n if (typeof matchesGlob !== 'function') {\n throw new Error(`The exclude option needs Node.js 22.5 or newer (found ${process.version}).`);\n }\n const rel = relative(process.cwd(), resolve(filename)) || filename;\n return exclude.some((pattern) => matchesGlob(rel, pattern.replace(/^\\.\\//, '')));\n}\n\n/**\n * The paths a build writes. Source discovery never reads them back as sources,\n * and the watchers don't rebuild for them.\n */\nexport interface BuildOutputs {\n /**\n * Files the build writes: the story, and for a bundler also its chunks, its\n * assets and the public files it copies.\n */\n readonly files: readonly string[];\n /**\n * Folders the build writes into, which hold nothing but its output. One found\n * while walking a source folder is skipped whole, files from earlier builds\n * included (old hashed chunks, say). A folder named as a source, or one that\n * holds a source folder, is still walked, and only `files` are left out of it.\n */\n readonly dirs: readonly string[];\n}\n\n/** A build that writes nothing: `compile()`, or output to stdout. */\nexport const NO_BUILD_OUTPUTS: BuildOutputs = { files: [], dirs: [] };\n\n/** The outputs of a build that writes the one file `outFile`, or none without it. */\nexport function toBuildOutputs(outputs: BuildOutputs | string | undefined): BuildOutputs {\n if (outputs === undefined) return NO_BUILD_OUTPUTS;\n return typeof outputs === 'string' ? { files: [outputs], dirs: [] } : outputs;\n}\n\n/**\n * The path outputs are compared by: absolute, with every symbolic link in it\n * resolved, so two paths that reach the same file through different links (a\n * symlinked project folder, an alias of the output folder) compare equal. A\n * path that doesn't exist yet, such as the output before the first build, is\n * its nearest existing folder's real path joined with the rest.\n */\nexport function realPathOf(path: string): string {\n const abs = resolve(path);\n try {\n return realpathSync.native(abs);\n } catch {\n // Missing or unreadable: resolve the folder it would be in instead.\n }\n const parent = dirname(abs);\n return parent === abs ? abs : join(realPathOf(parent), basename(abs));\n}\n\n/** Whether the path `inner` is `outer` or inside it. */\nfunction isSameOrInside(inner: string, outer: string): boolean {\n return inner === outer || inner.startsWith(outer.endsWith(sep) ? outer : outer + sep);\n}\n\n/** A build's outputs as real paths (see realPathOf), with the checks discovery and the watchers make. */\nexport interface OutputPaths {\n /** Whether the real path `real` is a file the build writes. */\n isFile(real: string): boolean;\n /** Whether the real path `real` is a folder the build owns (see BuildOutputs.dirs). */\n isDir(real: string): boolean;\n /** Whether the folder at the real path `real` is an owned folder or holds an output, at any depth. */\n holds(real: string): boolean;\n /**\n * Whether source discovery, walking the folders `roots`, leaves the path out\n * as output: an output file, or a path it only reaches through an owned folder.\n */\n isOutput(path: string, roots: readonly string[]): boolean;\n}\n\nexport function outputPaths(outputs: BuildOutputs): OutputPaths {\n const files = new Set(outputs.files.map(realPathOf));\n const dirs = new Set(outputs.dirs.map(realPathOf));\n const all = [...files, ...dirs];\n return {\n isFile: (real) => files.has(real),\n isDir: (real) => dirs.has(real),\n holds: (real) => dirs.has(real) || all.some((output) => output !== real && isSameOrInside(output, real)),\n isOutput(path, roots) {\n const real = realPathOf(path);\n if (files.has(real)) return true;\n const owners = [...dirs].filter((dir) => isSameOrInside(real, dir));\n if (owners.length === 0) return false;\n // A root walks into the path unless an owned folder below the root holds it.\n const reaching = roots.map(realPathOf).filter((root) => isSameOrInside(real, root));\n return reaching.every((root) => owners.some((dir) => dir !== root && isSameOrInside(dir, root)));\n },\n };\n}\n\n/**\n * A folder entry as source discovery walks it, found at `pathname` with the real\n * path `real` when it is no link: a link to a file counts as that file, and a\n * link to anything else (a folder above all) as nothing, undefined. Throws when\n * the entry or a link's target can't be read.\n */\nexport function walkedEntry(\n pathname: string,\n real: string,\n): { readonly stat: Stats; readonly real: string } | undefined {\n const stat = lstatSync(pathname);\n if (!stat.isSymbolicLink()) return { stat, real };\n const target = statSync(pathname);\n return target.isFile() ? { stat: target, real: realPathOf(pathname) } : undefined;\n}\n\nexport interface FilenamesResult {\n readonly filenames: string[];\n /** One warning per path that could not be read. */\n readonly diagnostics: Diagnostic[];\n /**\n * The paths given that are themselves an output file. A build reading one would\n * overwrite its own source; the compiler refuses it, as Tweego does.\n */\n readonly outputSources: string[];\n}\n\n/**\n * Recursively walk directories, collecting regular file paths.\n *\n * Leaves out what the build writes (`outputs`, compared by real path, see\n * realPathOf) so its last output is never read back, and the files that match an\n * `exclude` glob (see isExcluded). A path given that is itself an output file is\n * not walked but listed in `outputSources`.\n *\n * Symbolic links: a path given is followed wherever it leads. Inside a folder, a\n * link to a file is read, but a link to a folder is not followed, as Tweego's walk\n * doesn't follow one. A link back to its own folder or a parent would otherwise\n * walk the same files again at every depth.\n *\n * Like Tweego, a path that cannot be read is reported as a warning and skipped.\n */\nexport function getFilenames(\n pathnames: readonly string[],\n outputs?: BuildOutputs | string,\n exclude: readonly string[] = [],\n): FilenamesResult {\n const filenames: string[] = [];\n const diagnostics: Diagnostic[] = [];\n const outputSources: string[] = [];\n const output = outputPaths(toBuildOutputs(outputs));\n\n function warn(pathname: string, e: unknown): void {\n diagnostics.push({ level: 'warning', message: `path ${pathname}: ${e instanceof Error ? e.message : String(e)}` });\n }\n\n function addFile(pathname: string): void {\n const abs = resolve(pathname);\n const rel = relative(process.cwd(), abs);\n if (isExcluded(rel || abs, exclude)) return;\n filenames.push(rel || abs);\n }\n\n // A folder's entries. `real` is the folder's real path; an entry that is no link\n // has the real path `real/entry`, so no entry needs resolving.\n function walkDir(pathname: string, real: string): void {\n let entries;\n try {\n entries = readdirSync(pathname);\n } catch (e) {\n warn(pathname, e);\n return;\n }\n for (const entry of entries) walkEntry(join(pathname, entry), join(real, entry));\n }\n\n function walkEntry(pathname: string, real: string): void {\n let entry;\n try {\n entry = walkedEntry(pathname, real);\n } catch (e) {\n warn(pathname, e);\n return;\n }\n if (entry === undefined) return;\n if (entry.stat.isFile()) {\n if (!output.isFile(entry.real)) addFile(pathname);\n } else if (entry.stat.isDirectory() && !output.isDir(entry.real)) {\n walkDir(pathname, entry.real);\n }\n }\n\n for (const pathname of pathnames) {\n let stat;\n try {\n stat = statSync(pathname);\n } catch (e) {\n warn(pathname, e);\n continue;\n }\n const real = realPathOf(pathname);\n if (stat.isFile()) {\n if (output.isFile(real)) outputSources.push(pathname);\n else addFile(pathname);\n } else if (stat.isDirectory()) {\n walkDir(pathname, real);\n }\n }\n\n return { filenames, diagnostics, outputSources };\n}\n\nexport interface WatchHandle {\n close(): void;\n}\n\n/**\n * A watched path that can't be watched: fs.watch failed on it, or on the folder it is\n * watched through. watchFilesystem passes it to its `onError` and keeps watching the rest.\n */\nexport class WatchPathError extends Error {\n constructor(\n readonly path: string,\n cause: unknown,\n ) {\n super(`Cannot watch ${path}: ${cause instanceof Error ? cause.message : String(cause)}`);\n this.name = 'WatchPathError';\n }\n}\n\n/** What a stat finds at a path: a folder (with its identity) or something else. */\ntype PathKind =\n { readonly kind: 'dir'; readonly id: string } | { readonly kind: 'file' } | { readonly kind: 'missing' };\n\nfunction pathKind(path: string): PathKind {\n try {\n const stats = statSync(path);\n return stats.isDirectory() ? { kind: 'dir', id: `${stats.dev}:${stats.ino}` } : { kind: 'file' };\n } catch {\n // Missing, or unreadable: either way, wait for it to change.\n return { kind: 'missing' };\n }\n}\n\n/**\n * Where a watched path stands, and so which folders its watches must be on. A watch follows the\n * folder it was started on, not its path, so the watches are set up again whenever this changes.\n */\ninterface RootState {\n /**\n * The folder the path is watched through, which sees it created, deleted or replaced: its\n * parent folder, or while that is missing, the nearest folder above it that exists.\n */\n readonly anchor: { readonly path: string; readonly id: string } | undefined;\n /** The path itself: a folder is watched recursively; a file is watched through `anchor`. */\n readonly self: PathKind;\n}\n\nfunction rootState(abs: string): RootState {\n return { anchor: nearestFolderAbove(abs), self: pathKind(abs) };\n}\n\nfunction nearestFolderAbove(abs: string): RootState['anchor'] {\n for (let dir = dirname(abs), below = abs; dir !== below; below = dir, dir = dirname(dir)) {\n const kind = pathKind(dir);\n if (kind.kind === 'dir') return { path: dir, id: kind.id };\n }\n return undefined;\n}\n\n/** Whether two states need the same watches: the same anchor folder, and the same watched folder if any. */\nfunction sameWatches(a: RootState, b: RootState): boolean {\n const selfId = (s: RootState): string | undefined => (s.self.kind === 'dir' ? s.self.id : undefined);\n return a.anchor?.path === b.anchor?.path && a.anchor?.id === b.anchor?.id && selfId(a) === selfId(b);\n}\n\n/** One watched path (a source, module or head file), as given and as an absolute path. */\ninterface Root {\n readonly path: string;\n readonly abs: string;\n state: RootState;\n watchers: FSWatcher[];\n /** A watch could not be started, or broke: it is tried again on the next event in its anchor folder. */\n failed: boolean;\n /** The last failure reported, so that one that persists is reported once. */\n lastReport: string | undefined;\n}\n\n/**\n * Watch paths for changes, calling the build callback on known file type changes.\n * A folder is watched recursively; a file is watched on its own and counts\n * whatever its type (a head file, say). A change to a file `ignore` returns true\n * for (given the path relative to the working directory) schedules no build.\n * Uses debouncing to avoid rapid rebuilds.\n *\n * A watched path that doesn't exist yet is waited for, and one that is deleted, or renamed\n * away and replaced, is followed to the new folder or file at its path: each path is also\n * watched through the folder above it. When that sets up a path's watches again, the next\n * build is a full one (`changedFiles` undefined), since changes made in between went unseen.\n * A path that can't be watched is passed to `onError` as a WatchPathError, once while the\n * failure persists; the other paths are still watched.\n */\nexport function watchFilesystem(\n pathnames: string[],\n outFilename: string,\n callback: (changedFiles?: ReadonlySet<string>) => void,\n ignore: (filename: string) => boolean = () => false,\n onError: (error: WatchPathError) => void = () => {},\n): WatchHandle {\n const output = outputPaths(toBuildOutputs(outFilename));\n let buildTimer: ReturnType<typeof setTimeout> | null = null;\n const BUILD_DEBOUNCE = 500;\n const pendingFiles = new Set<string>();\n let pendingFullBuild = false;\n let closed = false;\n\n // `changedFile` undefined: a full build, which wins over the changed files pending with it.\n function scheduleBuild(changedFile?: string): void {\n if (changedFile === undefined) pendingFullBuild = true;\n else pendingFiles.add(changedFile);\n if (buildTimer) clearTimeout(buildTimer);\n buildTimer = setTimeout(() => {\n buildTimer = null;\n const files = pendingFullBuild || pendingFiles.size === 0 ? undefined : new Set(pendingFiles);\n pendingFiles.clear();\n pendingFullBuild = false;\n callback(files);\n }, BUILD_DEBOUNCE);\n }\n\n const roots: Root[] = pathnames.map((path) => {\n const abs = resolve(path);\n return { path, abs, state: rootState(abs), watchers: [], failed: false, lastReport: undefined };\n });\n\n // A watched path that is a file counts whatever its type.\n const isNamedFile = (abs: string): boolean => roots.some((r) => r.abs === abs && r.state.self.kind === 'file');\n\n // A changed file, as an absolute path. `named`: it is one of the watched paths\n // itself, so it counts whatever its type. Reported relative to the working\n // directory, the form getFilenames gives and the incremental cache is keyed by.\n function fileChanged(abs: string, named: boolean): void {\n if (!named && !isKnownFileType(abs)) return;\n // Compared by real path: the output may be reached through a link.\n if (output.isFile(realPathOf(abs))) return;\n const rel = relative(process.cwd(), abs);\n if (!ignore(rel || abs)) scheduleBuild(rel || abs);\n }\n\n function report(root: Root, cause: unknown): void {\n const error = new WatchPathError(root.path, cause);\n if (error.message === root.lastReport) return;\n root.lastReport = error.message;\n onError(error);\n }\n\n function startWatch(root: Root, path: string, recursive: boolean, listener: (filename: string) => void): void {\n try {\n // A recursive watch on a folder it can't read starts without an error on Linux, and\n // then never reports anything: check first.\n if (recursive) accessSync(path, fsConstants.R_OK | fsConstants.X_OK);\n const watcher = fsWatch(path, { recursive }, (_event, filename) => {\n if (!closed) listener(filename ?? '');\n });\n watcher.on('error', (e) => {\n watcher.close();\n root.watchers = root.watchers.filter((w) => w !== watcher);\n root.failed = true;\n if (!closed && !recheck(root, false)) report(root, e);\n });\n root.watchers.push(watcher);\n } catch (e) {\n root.failed = true;\n report(root, e);\n }\n }\n\n // Starts the watches `root.state` calls for, closing any earlier ones.\n function arm(root: Root): void {\n for (const w of root.watchers) w.close();\n root.watchers = [];\n root.failed = false;\n const { anchor, self } = root.state;\n if (anchor) {\n startWatch(root, anchor.path, false, (filename) => {\n // A file is watched through its folder, not on its own: the OS reports only the file's\n // name for a watch on the file, and an editor that saves by replacing the file would\n // leave such a watch on the old one.\n const before = root.state.self.kind;\n recheck(root, true);\n const isFile = before === 'file' || isNamedFile(root.abs);\n if (isFile && filename !== '' && resolve(anchor.path, filename) === root.abs) fileChanged(root.abs, true);\n });\n }\n if (self.kind === 'dir') {\n startWatch(root, root.path, true, (filename) => {\n // No name: an event on the folder itself, such as its deletion.\n if (filename === '') recheck(root, true);\n else {\n const abs = resolve(root.abs, filename);\n fileChanged(abs, isNamedFile(abs));\n }\n });\n }\n if (!root.failed) root.lastReport = undefined;\n }\n\n /**\n * Sets up `root`'s watches again when its path, or the folder above it, is no longer the\n * one they were started on (or, with `retry`, when one of them failed), and then schedules a\n * full build. Returns whether its state changed.\n */\n function recheck(root: Root, retry: boolean): boolean {\n const before = root.state;\n const after = rootState(root.abs);\n const changed = !sameWatches(before, after);\n const wasFailed = root.failed;\n if (!changed && !(retry && wasFailed)) {\n root.state = after;\n return false;\n }\n root.state = after;\n arm(root);\n const recovered = wasFailed && !root.failed;\n if ((changed || recovered) && (before.self.kind !== 'missing' || after.self.kind !== 'missing')) scheduleBuild();\n return changed;\n }\n\n for (const root of roots) arm(root);\n\n // Build once initially (no changedFiles = full build).\n callback();\n\n return {\n close() {\n closed = true;\n if (buildTimer) clearTimeout(buildTimer);\n for (const root of roots) for (const w of root.watchers) w.close();\n },\n };\n}\n","/**\n * A parser for the object literal a Twine 2 `format.js` passes to `window.storyFormat()`.\n *\n * The story formats spec does not require that object to be strict JSON, and Twine 2 runs\n * `format.js` as JavaScript. This parser accepts JSON plus the JavaScript literal syntax formats\n * use in practice: single-quoted strings, unquoted (identifier) and numeric keys, trailing commas,\n * comments, JavaScript string escapes, and hexadecimal, octal and binary numbers.\n *\n * It reads string literals token by token, so their contents come back exactly as JavaScript\n * evaluation gives them: text that only looks like structure (`a, }`, `word:`, an apostrophe) is\n * never touched. Anything outside that subset, such as a function or a variable, is a syntax error.\n */\n\nconst IDENTIFIER = /[A-Za-z_$][\\w$]*/y;\nconst NUMBER = /[+-]?(?:0[xX][0-9a-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)/y;\nconst IDENTIFIER_PART = /[\\w$]/;\nconst WHITESPACE = /[\\s]/;\nconst HEX = /^[0-9a-fA-F]+$/;\n\n/** Simple single-character escapes and the characters they stand for. */\nconst SIMPLE_ESCAPES: Readonly<Record<string, string>> = {\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n v: '\\v',\n};\n\n/**\n * Parse a JavaScript object, array or primitive literal: all of `text`, or the part from `start` to\n * `end`. Error positions count from the start of `text`, so they point into the file it came from.\n *\n * @throws SyntaxError naming the line and column of the first thing it cannot parse.\n */\nexport function parseRelaxedJSON(text: string, start = 0, end = text.length): unknown {\n let pos = start;\n\n function fail(message: string, at = pos): never {\n const before = text.slice(0, at);\n const line = before.split('\\n').length;\n const column = at - before.lastIndexOf('\\n');\n throw new SyntaxError(`${message} at line ${line}, column ${column}`);\n }\n\n /** The character at `pos`, or '' at the end of the input. */\n const peek = (): string => (pos < end ? (text[pos] ?? '') : '');\n\n const describeChar = (at: number): string => (at >= end ? 'end of input' : JSON.stringify(text[at]));\n\n /** Skip whitespace and comments. */\n const skipTrivia = (): void => {\n while (pos < end) {\n const ch = peek();\n if (WHITESPACE.test(ch)) {\n pos++;\n } else if (text.startsWith('//', pos)) {\n const lineEnd = text.slice(pos, end).search(/[\\n\\r\\u2028\\u2029]/);\n pos = lineEnd === -1 ? end : pos + lineEnd;\n } else if (text.startsWith('/*', pos)) {\n const commentEnd = text.indexOf('*/', pos + 2);\n if (commentEnd === -1 || commentEnd + 2 > end) fail('Unterminated comment');\n pos = commentEnd + 2;\n } else {\n return;\n }\n }\n };\n\n const consume = (ch: string): void => {\n skipTrivia();\n if (peek() !== ch) fail(`Expected ${JSON.stringify(ch)} but found ${describeChar(pos)}`);\n pos++;\n };\n\n /** Read exactly `count` hex digits and return their value. */\n const readHex = (count: number): number => {\n const digits = text.slice(pos, Math.min(pos + count, end));\n if (digits.length !== count || !HEX.test(digits)) fail('Invalid hexadecimal escape sequence');\n pos += count;\n return parseInt(digits, 16);\n };\n\n /** Decode the escape sequence after a backslash; `pos` is just past the backslash. */\n const readEscape = (): string => {\n const ch = peek();\n const simple = SIMPLE_ESCAPES[ch];\n if (simple !== undefined) {\n pos++;\n return simple;\n }\n switch (ch) {\n case '':\n return fail('Unterminated string');\n case 'x':\n pos++;\n return String.fromCharCode(readHex(2));\n case 'u': {\n pos++;\n if (peek() !== '{') return String.fromCharCode(readHex(4));\n const close = text.indexOf('}', pos);\n if (close === -1 || close >= end) fail('Invalid Unicode escape sequence');\n pos++;\n const codePoint = readHex(close - pos);\n if (codePoint > 0x10ffff) fail('Undefined Unicode code-point');\n pos = close + 1;\n return String.fromCodePoint(codePoint);\n }\n case '\\r':\n // A line continuation: the escaped line break is dropped.\n pos += text[pos + 1] === '\\n' ? 2 : 1;\n return '';\n case '\\n':\n case '\\u2028':\n case '\\u2029':\n pos++;\n return '';\n case '0':\n if (/[0-9]/.test(text[pos + 1] ?? '')) fail('Octal escape sequences are not supported');\n pos++;\n return '\\0';\n default:\n if (/[1-9]/.test(ch)) fail('Octal escape sequences are not supported');\n // Any other escaped character stands for itself (\\' \\\" \\\\ \\/ …).\n pos++;\n return ch;\n }\n };\n\n const readString = (): string => {\n const quote = peek();\n pos++;\n let out = '';\n let chunkStart = pos;\n for (;;) {\n if (pos >= end) fail('Unterminated string');\n const ch = peek();\n if (ch === quote) {\n out += text.slice(chunkStart, pos);\n pos++;\n return out;\n }\n if (ch === '\\n' || ch === '\\r') fail('Unterminated string');\n if (ch === '\\\\') {\n out += text.slice(chunkStart, pos);\n pos++;\n out += readEscape();\n chunkStart = pos;\n } else {\n pos++;\n }\n }\n };\n\n /** Read a match of a sticky regular expression at `pos`, or return undefined. */\n const readToken = (pattern: RegExp): string | undefined => {\n pattern.lastIndex = pos;\n const m = pattern.exec(text);\n if (!m || pattern.lastIndex > end) return undefined;\n pos = pattern.lastIndex;\n return m[0];\n };\n\n const readNumber = (): number | undefined => {\n const tokenStart = pos;\n const token = readToken(NUMBER);\n if (token === undefined) return undefined;\n if (IDENTIFIER_PART.test(peek())) fail('Invalid number', tokenStart);\n const sign = token.startsWith('-') ? -1 : 1;\n return sign * Number(/^[+-]/.test(token) ? token.slice(1) : token);\n };\n\n const readKey = (): string => {\n skipTrivia();\n const ch = peek();\n if (ch === '\"' || ch === \"'\") return readString();\n const identifier = readToken(IDENTIFIER);\n if (identifier !== undefined) return identifier;\n const number = readNumber();\n if (number !== undefined) return String(number);\n return fail(`Expected a property name but found ${describeChar(pos)}`);\n };\n\n const readObject = (): Record<string, unknown> => {\n pos++; // {\n // Properties are defined, not assigned, so a \"__proto__\" key stays an ordinary property.\n const out: Record<string, unknown> = {};\n for (;;) {\n skipTrivia();\n if (peek() === '}') {\n pos++;\n return out;\n }\n const key = readKey();\n consume(':');\n Object.defineProperty(out, key, { value: readValue(), enumerable: true, writable: true, configurable: true });\n skipTrivia();\n if (peek() === ',') pos++;\n else if (peek() !== '}') fail(`Expected \",\" or \"}\" but found ${describeChar(pos)}`);\n }\n };\n\n const readArray = (): unknown[] => {\n pos++; // [\n const out: unknown[] = [];\n for (;;) {\n skipTrivia();\n if (peek() === ']') {\n pos++;\n return out;\n }\n out.push(readValue());\n skipTrivia();\n if (peek() === ',') pos++;\n else if (peek() !== ']') fail(`Expected \",\" or \"]\" but found ${describeChar(pos)}`);\n }\n };\n\n function readValue(): unknown {\n skipTrivia();\n const ch = peek();\n if (ch === '{') return readObject();\n if (ch === '[') return readArray();\n if (ch === '\"' || ch === \"'\") return readString();\n const tokenStart = pos;\n const identifier = readToken(IDENTIFIER);\n if (identifier !== undefined) {\n if (identifier === 'true') return true;\n if (identifier === 'false') return false;\n if (identifier === 'null') return null;\n return fail(`Unexpected identifier ${JSON.stringify(identifier)}`, tokenStart);\n }\n const number = readNumber();\n if (number !== undefined) return number;\n return fail(`Unexpected ${describeChar(pos)}`);\n }\n\n const value = readValue();\n skipTrivia();\n if (pos < end) fail(`Unexpected ${describeChar(pos)} after the value`);\n return value;\n}\n","/**\n * SemVer parsing and precedence, shared by every story format lookup (local folders, the download\n * cache and remote indices).\n *\n * Parsing follows Tweego's `semver.NewVersion` (Masterminds/semver): a leading `v` is allowed, and\n * `x` or `x.y` stand for `x.0.0` and `x.y.0`. Comparison follows SemVer 2.0.0 §11: a prerelease\n * ranks below its release, prerelease identifiers compare field by field, and build metadata is\n * ignored.\n */\nimport type { SemVer } from './types.js';\n\nconst IDENTIFIERS = String.raw`[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*`;\nconst VERSION = new RegExp(String.raw`^[vV]?(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:-(${IDENTIFIERS}))?(?:\\+${IDENTIFIERS})?$`);\nconst NUMERIC = /^\\d+$/;\n\n/** Parse a version string, or return null when it is not a version. */\nexport function parseVersion(text: string): SemVer | null {\n const m = VERSION.exec(text);\n if (!m) return null;\n return {\n major: Number(m[1]),\n minor: Number(m[2] ?? 0),\n patch: Number(m[3] ?? 0),\n prerelease: m[4] === undefined ? [] : m[4].split('.'),\n };\n}\n\n/** Compare two prerelease identifiers: numeric ones numerically and below alphanumeric ones, which compare as ASCII. */\nfunction compareIdentifiers(a: string, b: string): number {\n const aNumeric = NUMERIC.test(a);\n const bNumeric = NUMERIC.test(b);\n if (aNumeric && bNumeric) return Math.sign(Number(a) - Number(b));\n if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Compare prerelease identifier lists. An empty list (a release) ranks above any prerelease. */\nfunction comparePrerelease(a: readonly string[], b: readonly string[]): number {\n if (a.length === 0 || b.length === 0) return Math.sign(b.length - a.length);\n const shared = Math.min(a.length, b.length);\n for (let i = 0; i < shared; i++) {\n const order = compareIdentifiers(a[i] ?? '', b[i] ?? '');\n if (order !== 0) return order;\n }\n return Math.sign(a.length - b.length);\n}\n\n/** Compare two versions by SemVer precedence: negative when `a` ranks lower, 0 when equal, positive when higher. */\nexport function compareVersions(a: SemVer, b: SemVer): number {\n return (\n Math.sign(a.major - b.major) ||\n Math.sign(a.minor - b.minor) ||\n Math.sign(a.patch - b.patch) ||\n comparePrerelease(a.prerelease, b.prerelease)\n );\n}\n\n/** Whether two version strings name the same version (prerelease included, build metadata ignored). */\nexport function sameVersion(a: string, b: string): boolean {\n const left = parseVersion(a);\n const right = parseVersion(b);\n return left !== null && right !== null && compareVersions(left, right) === 0;\n}\n","/**\n * Source text normalization shared by every input path (files, in-memory sources, `parseTwee`).\n */\n\n/**\n * Strip a leading UTF-8 byte order mark and convert CRLF and bare CR line endings to LF.\n * Idempotent, so text that is already normalized passes through unchanged.\n */\nexport function normalizeSourceText(text: string): string {\n const withoutBOM = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n return withoutBOM.replace(/\\r\\n?/g, '\\n');\n}\n\n/** Byte order marks at the start of a line, directly before a passage header's `::`. */\nconst BOMS_BEFORE_HEADER = /(?<=^|\\n)\\uFEFF+(?=::)/g;\n\n/**\n * Normalize Twee source text: {@link normalizeSourceText}, and also remove byte order marks at the start of\n * a line that are directly followed by `::`. Concatenating files (`cat a.tw b.tw`) leaves the BOM of every\n * later file in front of its first passage header, which would otherwise not be recognised as a header.\n * A U+FEFF anywhere else is passage text and kept. Idempotent.\n */\nexport function normalizeTweeSourceText(text: string): string {\n return normalizeSourceText(text).replace(BOMS_BEFORE_HEADER, '');\n}\n","/**\n * Shared file I/O utilities.\n */\nimport { readFileSync } from 'node:fs';\nimport { parse as parsePath } from 'node:path';\nimport type { Diagnostic } from './types.js';\nimport { normalizeSourceText } from './source-text.js';\n\n/** Text decoded from bytes, with the warning when the bytes were not valid UTF-8. */\nexport interface DecodedText {\n readonly text: string;\n readonly diagnostics: readonly Diagnostic[];\n}\n\n/** The charset assumed for text that is not valid UTF-8, as Tweego assumes it. */\nconst FALLBACK_CHARSET = 'windows-1252';\n\n/**\n * Throws on invalid UTF-8 instead of replacing bytes with U+FFFD. `ignoreBOM` keeps a leading BOM in the\n * text, as `readFileSync(file, 'utf-8')` did, so {@link normalizeSourceText} strips exactly one.\n */\nconst utf8Decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });\n\n/**\n * The code points of the Windows-1252 bytes 0x80 to 0x9F, from the WHATWG Encoding Standard. The five bytes\n * Windows-1252 leaves undefined map to the C1 control with the same number, as the standard and Go's charmap\n * do. Every other byte is the code point with the same number.\n *\n * Decoded by hand, because Node's `TextDecoder('windows-1252')` decodes as ISO-8859-1 in some releases\n * (Node 22.18 turns 0x80 into U+0080 instead of €), and builds without ICU lack it.\n */\nconst WINDOWS_1252_C1 = [\n 0x20ac, 0x81, 0x201a, 0x192, 0x201e, 0x2026, 0x2020, 0x2021, 0x2c6, 0x2030, 0x160, 0x2039, 0x152, 0x8d, 0x17d, 0x8f,\n 0x90, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x2dc, 0x2122, 0x161, 0x203a, 0x153, 0x9d, 0x17e, 0x178,\n] as const;\n\nfunction decodeWindows1252(bytes: Uint8Array): string {\n const chunks: string[] = [];\n // Chunked, so String.fromCharCode never gets more arguments than the engine allows.\n for (let start = 0; start < bytes.length; start += 0x2000) {\n const codes = Array.from(bytes.subarray(start, start + 0x2000), (b) =>\n b >= 0x80 && b <= 0x9f ? (WINDOWS_1252_C1[b - 0x80] ?? b) : b,\n );\n chunks.push(String.fromCharCode(...codes));\n }\n return chunks.join('');\n}\n\n/**\n * Decode bytes read from `filename` as UTF-8. Bytes that are not valid UTF-8 are decoded as Windows-1252\n * instead, with a warning naming the file, as Tweego does (`fileReadAllWithEncoding` in io.go), so a legacy\n * file keeps its non-ASCII characters instead of losing them to U+FFFD.\n *\n * The text is returned as decoded: a leading BOM and CR line endings are kept (see {@link normalizeSourceText}).\n */\nexport function decodeText(bytes: Uint8Array, filename: string): DecodedText {\n try {\n return { text: utf8Decoder.decode(bytes), diagnostics: [] };\n } catch {\n return {\n text: decodeWindows1252(bytes),\n diagnostics: [\n {\n level: 'warning',\n message: `read ${filename}: Invalid UTF-8; assuming charset is ${FALLBACK_CHARSET}.`,\n file: filename,\n },\n ],\n };\n }\n}\n\n/**\n * Read a text file: decode it with {@link decodeText} (UTF-8, or Windows-1252 when it is not valid UTF-8),\n * strip a leading BOM and convert CRLF and bare CR line endings to LF. This is the one path every file read\n * as text goes through: sources, modules, the head file, story formats and the config file.\n *\n * @param diagnostics Receives the warning when the file is not valid UTF-8. Without it, the file is decoded\n * the same way and the warning is dropped.\n * @throws When the file cannot be read.\n */\nexport function readUTF8(filename: string, diagnostics?: Diagnostic[]): string {\n const decoded = decodeText(readFileSync(filename), filename);\n diagnostics?.push(...decoded.diagnostics);\n return normalizeSourceText(decoded.text);\n}\n\n/** Read a file as base64. */\nexport function readBase64(filename: string): string {\n return readFileSync(filename).toString('base64');\n}\n\n/** Get the filename without extension, a dotfile keeps its whole name. */\nexport function baseNameWithoutExt(filename: string): string {\n return parsePath(filename).name;\n}\n","/**\n * Story format discovery, loading, and SemVer matching.\n * Ported from formats.go + config.go.\n *\n * Every lookup (local folders here, the download cache and remote indices in remote-formats.ts)\n * goes through the same version parsing ({@link parseVersion}) and the same matching rules\n * ({@link selectFormatCandidate}).\n */\nimport { readdirSync, statSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { homedir } from 'node:os';\nimport type {\n Diagnostic,\n FormatDecodeResult,\n FormatRequest,\n SemVer,\n StoryFormatInfo,\n Twine2FormatJSON,\n} from './types.js';\nimport { parseRelaxedJSON } from './relaxed-json.js';\nimport { compareVersions, parseVersion } from './semver.js';\nimport { readUTF8 } from './util.js';\n\n/** A `\"setup\": function` property, which Harlowe appends to its otherwise-JSON format object. */\nconst SETUP_FUNCTION_PROPERTY = /,\\s*\"setup\"\\s*:\\s*function\\b/g;\n\n/** Drop a trailing `\"setup\": function(){…}` property from a format object, if it has one. */\nfunction stripSetupFunction(chunk: string): string | undefined {\n let lastIndex = -1;\n for (const match of chunk.matchAll(SETUP_FUNCTION_PROPERTY)) lastIndex = match.index;\n return lastIndex === -1 ? undefined : chunk.slice(0, lastIndex) + '}';\n}\n\n/** Index after the whitespace and `//` or block comments starting at `i`. */\nfunction skipTrivia(text: string, i: number): number {\n let pos = i;\n for (;;) {\n const ch = text[pos];\n if (ch !== undefined && /\\s/.test(ch)) {\n pos++;\n } else if (text.startsWith('//', pos)) {\n const newline = text.indexOf('\\n', pos);\n pos = newline === -1 ? text.length : newline + 1;\n } else if (text.startsWith('/*', pos)) {\n const close = text.indexOf('*/', pos + 2);\n pos = close === -1 ? text.length : close + 2;\n } else {\n return pos;\n }\n }\n}\n\n/** Index after the quoted string starting at `i` (a quote character); template literals nest `${…}`. */\nfunction skipString(text: string, i: number): number {\n const quote = text[i];\n let pos = i + 1;\n while (pos < text.length) {\n const ch = text[pos];\n if (ch === '\\\\') {\n pos += 2;\n } else if (ch === quote) {\n return pos + 1;\n } else if (quote === '`' && ch === '$' && text[pos + 1] === '{') {\n const close = findClosingBrace(text, pos + 1);\n if (close === -1) return text.length;\n pos = close + 1;\n } else {\n pos++;\n }\n }\n return text.length;\n}\n\nfunction startsComment(text: string, pos: number): boolean {\n return text[pos] === '/' && (text[pos + 1] === '/' || text[pos + 1] === '*');\n}\n\nfunction startsString(text: string, pos: number): boolean {\n const ch = text[pos];\n return ch === '\"' || ch === \"'\" || ch === '`';\n}\n\n/** Index of the `}` matching the `{` at `open`, skipping comments and strings; -1 when unbalanced. */\nfunction findClosingBrace(text: string, open: number): number {\n let depth = 0;\n let pos = open;\n while (pos < text.length) {\n if (startsComment(text, pos)) {\n pos = skipTrivia(text, pos);\n } else if (startsString(text, pos)) {\n pos = skipString(text, pos);\n } else {\n if (text[pos] === '{') depth++;\n else if (text[pos] === '}' && --depth === 0) return pos;\n pos++;\n }\n }\n return -1;\n}\n\nconst STORY_FORMAT = 'storyFormat';\nconst IDENTIFIER_CHAR = /[\\w$]/;\n\n/**\n * Locate the object literal passed to `storyFormat(` as `[start, end)` offsets, ignoring comments and\n * strings outside it and never evaluating anything. Without such a call, the first `{` outside comments\n * and strings starts the object. When its closing brace cannot be matched (a Harlowe setup function can\n * hold regular expression literals), the last `}` of the file ends it.\n */\nfunction locateFormatObject(text: string): { readonly start: number; readonly end: number } | undefined {\n let start = -1;\n let firstBrace = -1;\n let pos = 0;\n while (pos < text.length && start === -1) {\n if (startsComment(text, pos)) {\n pos = skipTrivia(text, pos);\n } else if (startsString(text, pos)) {\n pos = skipString(text, pos);\n } else if (text[pos] === '{') {\n if (firstBrace === -1) firstBrace = pos;\n pos++;\n } else if (text.startsWith(STORY_FORMAT, pos) && !IDENTIFIER_CHAR.test(text[pos - 1] ?? '')) {\n const paren = skipTrivia(text, pos + STORY_FORMAT.length);\n const brace = text[paren] === '(' ? skipTrivia(text, paren + 1) : -1;\n if (text[brace] === '{') start = brace;\n pos += STORY_FORMAT.length;\n } else {\n pos++;\n }\n }\n if (start === -1) start = firstBrace;\n if (start === -1) return undefined;\n const close = findClosingBrace(text, start);\n const end = close === -1 ? text.lastIndexOf('}') : close;\n return end < start ? undefined : { start, end: end + 1 };\n}\n\ntype ObjectParse = { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly error: string };\n\n/**\n * Parse the format object at `start`–`end` of `text`: strict JSON first (fast), then the\n * JavaScript literal subset formats use. Error positions point into `text`.\n */\nfunction parseFormatObject(text: string, start: number, end: number): ObjectParse {\n try {\n return { ok: true, value: JSON.parse(text.slice(start, end)) };\n } catch {\n // Not strict JSON; the spec does not require it to be.\n }\n try {\n return { ok: true, value: parseRelaxedJSON(text, start, end) };\n } catch (e) {\n return { ok: false, error: e instanceof Error ? e.message : String(e) };\n }\n}\n\n/** Check a parsed format object's fields. Per spec, `name` is optional; `version` and `source` are required. */\n/** The name given to a format.js that names no format. */\nexport const UNNAMED_FORMAT_NAME = 'Untitled Story Format';\n\nfunction toFormatJSON(raw: unknown): FormatDecodeResult {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return { ok: false, reason: 'Story format JSON chunk is not an object.' };\n }\n const obj = raw as Record<string, unknown>;\n if (typeof obj.version !== 'string') return { ok: false, reason: 'Story format has no \"version\" string.' };\n if (typeof obj.source !== 'string') return { ok: false, reason: 'Story format has no \"source\" string.' };\n if (!parseVersion(obj.version)) {\n return { ok: false, reason: `Story format version ${JSON.stringify(obj.version)} is not a SemVer version.` };\n }\n const data: Twine2FormatJSON = {\n name: typeof obj.name === 'string' ? obj.name : UNNAMED_FORMAT_NAME,\n version: obj.version,\n source: obj.source,\n proofing: obj.proofing === true,\n };\n if (typeof obj.author === 'string') data.author = obj.author;\n if (typeof obj.description === 'string') data.description = obj.description;\n if (typeof obj.image === 'string') data.image = obj.image;\n if (typeof obj.url === 'string') data.url = obj.url;\n if (typeof obj.license === 'string') data.license = obj.license;\n return { ok: true, data };\n}\n\n/**\n * Read the metadata of a Twine 2 format.js, or say why it cannot be used.\n *\n * The object passed to `window.storyFormat()` may be strict JSON or a JavaScript object literal\n * (single quotes, unquoted keys, trailing commas, comments). String values come back exactly as\n * JavaScript evaluation gives them. Harlowe's function-valued `setup` property is dropped; the\n * workaround keys on the property itself, so the same bytes parse whether they come from a\n * `harlowe-3` directory or a direct download.\n */\nexport function decodeFormatJSON(source: string): FormatDecodeResult {\n const located = locateFormatObject(source);\n if (located === undefined) {\n return { ok: false, reason: 'Could not find Twine 2 style story format JSON chunk.' };\n }\n\n const parsed = parseFormatObject(source, located.start, located.end);\n if (parsed.ok) return toFormatJSON(parsed.value);\n\n // Harlowe workaround: strip the \"setup\" function property.\n const stripped = stripSetupFunction(source.slice(located.start, located.end));\n const retried = stripped === undefined ? undefined : parseFormatObject(stripped, 0, stripped.length);\n if (retried?.ok) return toFormatJSON(retried.value);\n return { ok: false, reason: `Could not decode story format JSON chunk: ${parsed.error}` };\n}\n\n/**\n * Parse the Twine 2 format.js JSON chunk; null when it cannot be used ({@link decodeFormatJSON}\n * gives the reason).\n *\n * @param _formatId No longer used; kept so existing callers keep compiling.\n */\nexport function parseFormatJSON(source: string, _formatId?: string): Twine2FormatJSON | null {\n const result = decodeFormatJSON(source);\n return result.ok ? result.data : null;\n}\n\n/** A directory's entries in a stable order, or none when it cannot be read. */\nfunction listDirectory(dir: string): string[] {\n try {\n return readdirSync(dir).sort();\n } catch {\n return [];\n }\n}\n\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n\nfunction isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * Load the format in one folder: its format.js (Twine 2), else its header.html (Twine 1).\n * A format.js that cannot be used is reported as a warning, as Tweego does.\n */\nfunction loadFormatDir(\n searchDir: string,\n id: string,\n diagnostics: Diagnostic[] | undefined,\n): StoryFormatInfo | undefined {\n const formatDir = join(searchDir, id);\n if (!isDirectory(formatDir)) return undefined;\n\n for (const baseFilename of ['format.js', 'header.html']) {\n const filename = join(formatDir, baseFilename);\n if (!isFile(filename)) continue;\n\n if (baseFilename === 'header.html') {\n // Twine 1 format: the folder name is its name.\n return { id, filename, isTwine2: false, name: id, version: '', proofing: false };\n }\n\n // An encoding warning explains a skipped format; for a usable one, readFormatSource() reports it when used.\n const encoding: Diagnostic[] = [];\n let decoded: FormatDecodeResult;\n try {\n decoded = decodeFormatJSON(readUTF8(filename, encoding));\n } catch (e) {\n decoded = { ok: false, reason: `Could not read ${filename}: ${e instanceof Error ? e.message : String(e)}` };\n }\n if (!decoded.ok) {\n diagnostics?.push(...encoding);\n diagnostics?.push({\n level: 'warning',\n message: `format ${id}: Skipping format; ${decoded.reason} (${filename})`,\n });\n continue;\n }\n const { data } = decoded;\n const format: StoryFormatInfo = {\n id,\n filename,\n isTwine2: true,\n name: data.name,\n version: data.version,\n proofing: data.proofing ?? false,\n };\n if (data.author) format.author = data.author;\n if (data.description) format.description = data.description;\n if (data.image) format.image = data.image;\n if (data.url) format.url = data.url;\n if (data.license) format.license = data.license;\n return format;\n }\n return undefined;\n}\n\n/**\n * Discover every story format in the search directories, keyed by folder name (the format ID),\n * without version pruning.\n *\n * Directories are searched in order, and a later directory outranks an earlier one: when two hold\n * the same folder name, the later one's format is kept. The map iterates in that order too, lowest\n * rank first. Formats that cannot be used are left out, with a warning in `diagnostics`.\n */\nexport function discoverAllFormats(\n searchDirs: readonly string[],\n diagnostics?: Diagnostic[],\n): Map<string, StoryFormatInfo> {\n const formats = new Map<string, StoryFormatInfo>();\n for (const searchDir of searchDirs) {\n for (const entry of listDirectory(searchDir)) {\n const format = loadFormatDir(searchDir, entry, diagnostics);\n if (!format) continue;\n // Re-insert, so the map's order follows the directories' rank.\n formats.delete(entry);\n formats.set(entry, format);\n }\n }\n return formats;\n}\n\n/** The version a format is pruned and selected by, or null for one outside SemVer pruning. */\nfunction prunableVersion(format: StoryFormatInfo): SemVer | null {\n return format.isTwine2 && format.name ? parseVersion(format.version) : null;\n}\n\n/** The search directory a discovered format was found in. */\nfunction searchDirOf(format: StoryFormatInfo): string {\n return dirname(dirname(format.filename));\n}\n\n/**\n * Prune formats by SemVer: within each (name, major) group, keep only the version with the highest\n * precedence (a release outranks its prereleases). Between equal versions, the folder in the\n * higher-ranked search directory wins, and within one directory the first folder name in sort\n * order. Returns a new map in the same order.\n *\n * Pruning serves name-based selection and listings. An explicit format ID is looked up in the\n * unpruned map, so a pinned folder is used even when another folder holds a newer version.\n */\nexport function pruneFormats(formats: ReadonlyMap<string, StoryFormatInfo>): Map<string, StoryFormatInfo> {\n // Search directories first appear in the map in rank order (see discoverAllFormats).\n const dirRank = new Map<string, number>();\n for (const format of formats.values()) {\n const dir = searchDirOf(format);\n if (!dirRank.has(dir)) dirRank.set(dir, dirRank.size);\n }\n const rankOf = (format: StoryFormatInfo): number => dirRank.get(searchDirOf(format)) ?? 0;\n\n const best = new Map<string, { readonly format: StoryFormatInfo; readonly version: SemVer }>();\n for (const format of formats.values()) {\n const version = prunableVersion(format);\n if (!version) continue;\n const group = `${format.name}@${version.major}`;\n const current = best.get(group);\n const order = current ? compareVersions(version, current.version) : 1;\n if (order > 0 || (order === 0 && current && rankOf(format) > rankOf(current.format))) {\n best.set(group, { format, version });\n }\n }\n return new Map(\n [...formats].filter(([id, format]) => {\n const version = prunableVersion(format);\n return version === null || best.get(`${format.name}@${version.major}`)?.format.id === id;\n }),\n );\n}\n\n/**\n * Discover all story formats in the given search directories, pruned by SemVer: within each\n * (name, major) group only the highest version survives. See {@link discoverAllFormats} for the\n * directory ranking and {@link pruneFormats} for pruning.\n */\nexport function discoverFormats(searchDirs: readonly string[]): Map<string, StoryFormatInfo> {\n return pruneFormats(discoverAllFormats(searchDirs));\n}\n\n/**\n * Get the format search directories, lowest rank first: the story format subdirectories of the\n * home directory, then of the working directory, then each `TWEEGO_PATH` entry, then `extraPaths`\n * (`formatPaths`). A later directory outranks an earlier one for the same format folder name, so\n * `formatPaths` override `TWEEGO_PATH`, which overrides the home and working directories, as in\n * Tweego.\n */\nexport function getFormatSearchDirs(extraPaths: readonly string[] = [], useTweegoPath = true): string[] {\n const subdirNames = ['storyformats', '.storyformats', 'story-formats', 'storyFormats', 'targets'];\n const basePaths = new Set<string>();\n\n // Home directory\n try {\n basePaths.add(homedir());\n } catch {\n // ignore\n }\n\n // Working directory\n basePaths.add(process.cwd());\n\n const dirs = [...basePaths].flatMap((base) => subdirNames.map((sub) => join(base, sub))).filter(isDirectory);\n\n // TWEEGO_PATH environment variable\n const tweegoPath = useTweegoPath ? process.env.TWEEGO_PATH : undefined;\n if (tweegoPath) dirs.push(...tweegoPath.split(process.platform === 'win32' ? ';' : ':'));\n\n // Extra user-provided paths outrank everything else.\n dirs.push(...extraPaths);\n\n return dirs;\n}\n\n/**\n * Parse a version string into [major, minor, patch]. Accepts what {@link parseVersion} accepts\n * (`v1.2.3`, `1.2`, `2.0.0-beta.1`); the prerelease and build metadata are dropped.\n */\nexport function parseSemver(v: string): [number, number, number] | null {\n const parsed = parseVersion(v);\n return parsed ? [parsed.major, parsed.minor, parsed.patch] : null;\n}\n\n/** Compare [major, minor, patch] tuples. Use {@link compareVersions} to take prereleases into account. */\nexport function semverCompare(a: [number, number, number], b: [number, number, number]): number {\n const [aMajor, aMinor, aPatch] = a;\n const [bMajor, bMinor, bPatch] = b;\n if (aMajor !== bMajor) return aMajor - bMajor;\n if (aMinor !== bMinor) return aMinor - bMinor;\n if (aPatch !== bPatch) return aPatch - bPatch;\n return 0;\n}\n\n/** Build a directory-style format ID from a name and version, e.g. ('SugarCube', '2.37.3') → 'sugarcube-2'. */\nexport function makeFormatId(name: string, version: string): string {\n const major = parseVersion(version)?.major ?? 0;\n return `${name.toLowerCase().replace(/\\s+/g, '-')}-${major}`;\n}\n\n/** Describe a format request for diagnostics. */\nexport function describeFormatRequest(request: FormatRequest): string {\n switch (request.kind) {\n case 'id':\n return `\"${request.id}\"`;\n case 'name':\n return request.version ? `\"${request.name}\" at version \"${request.version}\"` : `\"${request.name}\"`;\n default: {\n const _exhaustive: never = request;\n throw new Error(`unhandled format request: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\n/** Options for {@link selectFormatCandidate}. */\nexport interface SelectFormatOptions {\n /** For a name request, also accept a version older than the one asked for (same major only). */\n readonly allowOlder?: boolean;\n}\n\n/** {@link selectFormatCandidate} over one set of candidates, matching names without regard to case. */\nfunction pickFormatCandidate<T>(\n request: FormatRequest,\n candidates: readonly T[],\n describe: (candidate: T) => { readonly name: string; readonly version: string },\n allowOlder: boolean,\n): T | undefined {\n const wanted = request.kind === 'name' ? parseVersion(request.version) : null;\n let best: { readonly candidate: T; readonly version: SemVer } | undefined;\n\n for (const candidate of candidates) {\n const { name, version } = describe(candidate);\n const have = parseVersion(version);\n if (!have) continue;\n\n if (request.kind === 'id') {\n if (makeFormatId(name, version) !== request.id.toLowerCase()) continue;\n } else {\n if (name.toLowerCase() !== request.name.toLowerCase()) continue;\n if (wanted) {\n const order = compareVersions(have, wanted);\n if (order === 0) return candidate;\n if (have.major !== wanted.major) continue;\n if (!allowOlder && order < 0) continue;\n }\n }\n\n if (!best || compareVersions(have, best.version) > 0) best = { candidate, version: have };\n }\n\n return best?.candidate;\n}\n\n/**\n * Pick the candidate that best answers a format request. Local folders, the download cache and\n * remote indices all select through this one function.\n *\n * - An ID request ('sugarcube-2') matches, without regard to case, a candidate whose name and\n * major version build that ID, and takes the greatest such version.\n * - A name request matches the name without regard to case, but a candidate whose name matches in\n * case too is preferred when one answers the request. An exact version (prerelease included)\n * wins outright; otherwise the greatest version with the same major that is not older than the\n * one asked for (or, with `allowOlder`, the greatest same-major version). An unparseable\n * requested version takes the greatest version of any major.\n *\n * Versions compare by SemVer precedence ({@link compareVersions}), so a release outranks its\n * prereleases. Between equal versions, the earlier candidate wins.\n */\nexport function selectFormatCandidate<T>(\n request: FormatRequest,\n candidates: readonly T[],\n describe: (candidate: T) => { readonly name: string; readonly version: string },\n options: SelectFormatOptions = {},\n): T | undefined {\n const allowOlder = options.allowOlder ?? false;\n if (request.kind === 'name') {\n const exactCase = candidates.filter((c) => describe(c).name === request.name);\n const preferred = pickFormatCandidate(request, exactCase, describe, allowOlder);\n if (preferred !== undefined) return preferred;\n }\n return pickFormatCandidate(request, candidates, describe, allowOlder);\n}\n\n/** The Twine 2 formats of a discovered map, those from higher-ranked search directories first. */\nexport function rankedTwine2Formats(formats: ReadonlyMap<string, StoryFormatInfo>): StoryFormatInfo[] {\n return [...formats.values()].filter((f) => f.isTwine2).reverse();\n}\n\n/**\n * Look a format ID up among discovered folders. The ID matches a folder name without regard to\n * case; an exact-case folder is preferred, then the highest-ranked one.\n */\nexport function findFormatById(formats: ReadonlyMap<string, StoryFormatInfo>, id: string): StoryFormatInfo | undefined {\n const exact = formats.get(id);\n if (exact) return exact;\n const wanted = id.toLowerCase();\n return [...formats.values()].reverse().find((f) => f.id.toLowerCase() === wanted);\n}\n\n/**\n * Get format ID from Twine 2 name and version, as a compile selects a local format by StoryData:\n * {@link selectFormatCandidate} over the pruned formats, so the greatest version with the same\n * major that is not older than `version` (any major when `version` is unparseable).\n */\nexport function getFormatIdByNameAndVersion(\n formats: ReadonlyMap<string, StoryFormatInfo>,\n name: string,\n version: string,\n): string | undefined {\n const request: FormatRequest = { kind: 'name', name, version };\n return selectFormatCandidate(request, rankedTwine2Formats(pruneFormats(formats)), (f) => f)?.id;\n}\n\n/** Get format ID from Twine 2 name, picking the greatest version. */\nexport function getFormatIdByName(formats: ReadonlyMap<string, StoryFormatInfo>, name: string): string | undefined {\n return getFormatIdByNameAndVersion(formats, name, '');\n}\n\n/**\n * Read the story format source (for Twine 2, extract the `source` property from JSON).\n * `diagnostics` receives a warning when the format file is not valid UTF-8 (it is read as Windows-1252).\n */\nexport function readFormatSource(format: StoryFormatInfo, diagnostics?: Diagnostic[]): string {\n const source = readUTF8(format.filename, diagnostics);\n if (!format.isTwine2) return source;\n const decoded = decodeFormatJSON(source);\n if (!decoded.ok) throw new Error(`Cannot parse format ${format.id} JSON: ${decoded.reason}`);\n return decoded.data.source;\n}\n\n/** Read a file as UTF-8 (re-exported for loader use). */\nexport { readUTF8 as readFileUTF8 } from './util.js';\n","/**\n * Atomic file replacement, for every file twee-ts writes that something else may read\n * meanwhile: build output (which live-reload servers read on each change) and downloaded\n * story formats (which other twee-ts processes share).\n */\nimport { randomBytes } from 'node:crypto';\nimport { chmodSync, lstatSync, readlinkSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { basename, dirname, join, resolve } from 'node:path';\n\n/**\n * Writes `data` to `path` so that a reader sees either the previous file or the complete new\n * one, never a partly written file. The data goes to a temporary file in the same folder,\n * which is then renamed over `path`. When `path` is a symlink (even a dangling one, or a chain of links), the file it\n * finally points to is replaced or created and the link stays, and an existing file keeps its permissions.\n *\n * On failure (a full disk, a missing folder) the temporary file is removed, `path` is left\n * as it was, and the error is thrown with `path` in its message and its original `code`.\n */\nexport function writeFileAtomic(path: string, data: string): void {\n let temp: string | undefined;\n try {\n const target = resolveWriteTarget(path);\n temp = join(dirname(target), `.${basename(target)}.${process.pid}-${randomBytes(6).toString('hex')}.tmp`);\n writeFileSync(temp, data, { encoding: 'utf-8', flag: 'wx' });\n keepPermissions(target, temp);\n renameSync(temp, target);\n } catch (e) {\n if (temp !== undefined) rmSync(temp, { force: true });\n throw writeError(path, e);\n }\n}\n\n/** Links followed before a path counts as a cycle (Linux stops at 40 as well). */\nconst MAX_LINK_DEPTH = 40;\n\n/**\n * The file a symlink at `path` finally points to, or `path` itself when it is no link. Links are\n * followed one by one, so a link whose target does not exist yet (absolute, relative, or a chain\n * of them) still resolves to the file that should be created. A cycle or an unreadable link throws.\n */\nfunction resolveWriteTarget(path: string): string {\n let current = path;\n for (let depth = 0; depth <= MAX_LINK_DEPTH; depth++) {\n const stat = lstatSync(current, { throwIfNoEntry: false });\n if (stat === undefined || !stat.isSymbolicLink()) return current;\n current = resolve(dirname(current), readlinkSync(current));\n }\n throw Object.assign(new Error(`ELOOP: too many levels of symbolic links, ${path}`), { code: 'ELOOP' });\n}\n\n/**\n * Gives `temp` the permission bits of `target`, when `target` exists. Best effort: on a file\n * system without Unix permissions chmod can fail, and writing in place never kept them there either.\n */\nfunction keepPermissions(target: string, temp: string): void {\n const existing = statSync(target, { throwIfNoEntry: false });\n if (existing === undefined) return;\n try {\n chmodSync(temp, existing.mode & 0o7777);\n } catch {\n // The new file keeps the default permissions.\n }\n}\n\n/** `cause` as an error that names `path` and keeps the original error code. */\nfunction writeError(path: string, cause: unknown): Error {\n const message = cause instanceof Error ? cause.message : String(cause);\n const error: Error & { code?: unknown } = new Error(`Cannot write ${path}: ${message}`, { cause });\n if (cause instanceof Error && 'code' in cause) error.code = cause.code;\n return error;\n}\n","/**\n * Remote story format fetching, caching, and checksum verification.\n * Uses the Story Formats Archive (SFA) as the default source.\n *\n * Two caches hold downloads. Formats found through an index are shared by name and version\n * (`<cache>/<name>/<version>/format.js`). A format downloaded from a direct URL is kept under\n * that URL instead, so one project's copy never answers another project's request.\n * Cache files are replaced atomically, so another process never reads a partly written one.\n */\nimport { createHash } from 'node:crypto';\nimport { mkdirSync, existsSync, readdirSync, statSync, rmSync, lstatSync } from 'node:fs';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { homedir } from 'node:os';\nimport type {\n FormatRequest,\n RemoteFetchOptions,\n SFAIndex,\n SFAIndexEntry,\n StoryFormatInfo,\n Twine2FormatJSON,\n} from './types.js';\nimport { parseSemver, parseFormatJSON, makeFormatId, selectFormatCandidate, UNNAMED_FORMAT_NAME } from './formats.js';\nimport type { SelectFormatOptions } from './formats.js';\nimport { sameVersion } from './semver.js';\nimport { decodeText, readUTF8 } from './util.js';\nimport { writeFileAtomic } from './atomic-write.js';\n\nconst DEFAULT_SFA_INDICES = [\n 'https://videlais.github.io/story-formats-archive/official/index.json',\n 'https://videlais.github.io/story-formats-archive/unofficial/index.json',\n];\n\n/** How long one story format request (an index or a format.js) may take by default, in milliseconds. */\nexport const DEFAULT_FORMAT_FETCH_TIMEOUT = 30_000;\n\n/** The longest delay a timer accepts; a longer timeout means no limit. */\nconst MAX_TIMER_DELAY = 2_147_483_647;\n\n/** Get the cache directory for downloaded story formats. */\nexport function getCacheDir(): string {\n const xdg = process.env['XDG_CACHE_HOME'];\n const base = xdg || join(homedir(), '.cache');\n return join(base, 'twee-ts', 'storyformats');\n}\n\n/** The cache directory for formats downloaded from direct URLs, beside {@link getCacheDir}. */\nfunction getUrlCacheDir(): string {\n return join(dirname(getCacheDir()), 'storyformat-urls');\n}\n\n/** The name of one direct URL's cache entry: a hash of the URL, so each URL has its own. */\nfunction urlCacheKey(url: string): string {\n return createHash('sha256').update(url).digest('hex');\n}\n\n/**\n * Whether a string can serve as one directory name inside the cache: not empty, not `.` or `..`,\n * and free of path separators. Format names and versions come from downloaded metadata, so they\n * are untrusted path input.\n */\nfunction isSafeSegment(segment: string): boolean {\n return segment !== '' && segment !== '.' && segment !== '..' && !/[/\\\\\\0]/.test(segment);\n}\n\n/** Whether absolute path `target` lies strictly inside absolute path `root`. */\nfunction isInside(root: string, target: string): boolean {\n const rel = relative(root, target);\n return rel !== '' && !isAbsolute(rel) && rel.split(sep)[0] !== '..';\n}\n\n/** The cache directory for one format version. Throws when the name or version could leave the cache. */\nfunction cachedFormatDir(name: string, version: string): string {\n if (!isSafeSegment(name)) {\n throw new Error(`Refusing to cache a story format with an unsafe name: ${JSON.stringify(name)}`);\n }\n if (!isSafeSegment(version) || !parseSemver(version)) {\n throw new Error(`Refusing to cache story format \"${name}\" with an unsafe version: ${JSON.stringify(version)}`);\n }\n const root = resolve(getCacheDir());\n const dir = resolve(root, name, version);\n if (!isInside(root, dir)) {\n throw new Error(`Refusing to cache a story format outside the cache directory ${root}: ${dir}`);\n }\n return dir;\n}\n\n/** Whether `e` is a Node.js system error with the given code. */\nfunction hasErrorCode(e: unknown, code: string): boolean {\n return e instanceof Error && 'code' in e && e.code === code;\n}\n\n/**\n * Create `dir` as a plain directory, or check that it already is one (a symlink could lead out of the cache).\n * A directory another process creates between the check and the mkdir is fine.\n */\nfunction ensurePlainDirectory(dir: string): void {\n if (lstatSync(dir, { throwIfNoEntry: false }) === undefined) {\n try {\n mkdirSync(dir);\n return;\n } catch (e) {\n if (!hasErrorCode(e, 'EEXIST')) throw e;\n }\n }\n const stat = lstatSync(dir, { throwIfNoEntry: false });\n if (stat === undefined || stat.isSymbolicLink() || !stat.isDirectory()) {\n throw new Error(`Refusing to write a story format outside the cache directory: ${dir} is not a plain directory`);\n }\n}\n\n/**\n * Write a downloaded format.js to `<root>/<...segments>/format.js`, replacing any earlier copy\n * atomically, and return its path. Every directory below `root` must be a plain one.\n */\nfunction writeCacheEntry(root: string, segments: readonly string[], text: string): string {\n mkdirSync(root, { recursive: true });\n const dir = segments.reduce((parent, segment) => {\n const child = join(parent, segment);\n ensurePlainDirectory(child);\n return child;\n }, root);\n\n const formatPath = join(dir, 'format.js');\n if (lstatSync(formatPath, { throwIfNoEntry: false })?.isSymbolicLink()) {\n throw new Error(`Refusing to write a story format outside the cache directory: ${formatPath} is a symlink`);\n }\n writeFileAtomic(formatPath, text);\n return formatPath;\n}\n\n/** In-memory index cache, keyed by URL. Cleared each compile. */\nconst indexCache = new Map<string, SFAIndex>();\n\n/** Clear the in-memory index cache. */\nexport function clearIndexCache(): void {\n indexCache.clear();\n}\n\n/** One network request with everyone in this process who waits on its result. */\ninterface SharedRequest<T> {\n readonly promise: Promise<T>;\n readonly controller: AbortController;\n waiters: number;\n}\n\n/** Requests in progress, by what they fetch, so concurrent compiles make each request once. */\nconst sharedRequests = new Map<string, SharedRequest<unknown>>();\n\n/** How one caller waits on a shared request. */\ninterface WaitOptions {\n /** Stops this caller's wait at once, rejecting with the signal's reason. */\n readonly signal: AbortSignal | undefined;\n /** How long this caller waits, in milliseconds (0: no limit). */\n readonly timeout: number;\n /** The error this caller's wait ends with when its timeout passes. */\n readonly timedOut: () => Error;\n}\n\n/**\n * Runs `start` once for all callers that ask for `key` while it is in progress. Each caller waits\n * under its own limits: a caller whose `signal` aborts, or whose `timeout` passes, stops waiting\n * at once and rejects, while the others keep waiting. The request itself is aborted (through\n * the signal `start` receives) once no caller waits on it. `start` must not depend on any one\n * caller: what differs between callers belongs after the shared result.\n */\nfunction shareRequest<T>(\n key: string,\n { signal, timeout, timedOut }: WaitOptions,\n start: (signal: AbortSignal) => Promise<T>,\n): Promise<T> {\n if (signal?.aborted) return Promise.reject(signal.reason);\n const request = (sharedRequests.get(key) as SharedRequest<T> | undefined) ?? startSharedRequest(key, start);\n request.waiters++;\n\n return new Promise<T>((resolve, reject) => {\n let waiting = true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const stopWaiting = (): void => {\n if (!waiting) return;\n waiting = false;\n signal?.removeEventListener('abort', onAbort);\n clearTimeout(timer);\n request.waiters--;\n };\n const giveUp = (reason: unknown): void => {\n stopWaiting();\n if (request.waiters === 0) {\n if (sharedRequests.get(key) === request) sharedRequests.delete(key);\n request.controller.abort(reason);\n }\n reject(reason);\n };\n const onAbort = (): void => giveUp(signal?.reason);\n signal?.addEventListener('abort', onAbort, { once: true });\n if (timeout > 0 && timeout <= MAX_TIMER_DELAY) timer = setTimeout(() => giveUp(timedOut()), timeout);\n request.promise.then(\n (value) => {\n stopWaiting();\n resolve(value);\n },\n (e: unknown) => {\n stopWaiting();\n reject(e);\n },\n );\n });\n}\n\nfunction startSharedRequest<T>(key: string, start: (signal: AbortSignal) => Promise<T>): SharedRequest<T> {\n const controller = new AbortController();\n const request: SharedRequest<T> = { promise: start(controller.signal), controller, waiters: 0 };\n sharedRequests.set(key, request);\n const forget = (): void => {\n if (sharedRequests.get(key) === request) sharedRequests.delete(key);\n };\n request.promise.then(forget, forget);\n return request;\n}\n\n/** The time limit for each request, from the caller's options. */\nfunction requestTimeout(options: RemoteFetchOptions): number {\n const timeout = options.timeout ?? DEFAULT_FORMAT_FETCH_TIMEOUT;\n if (!(timeout >= 0)) {\n throw new RangeError(`A story format request timeout must be 0 or more milliseconds, not ${timeout}`);\n }\n return timeout;\n}\n\n/** How one caller waits for `url`: under its own signal and timeout. `what` names the request in errors. */\nfunction waitOptions(options: RemoteFetchOptions, what: string, url: string): WaitOptions {\n const timeout = requestTimeout(options);\n return {\n signal: options.signal,\n timeout,\n timedOut: () => new Error(`Failed to ${what} from ${url}: timed out after ${timeout} ms`),\n };\n}\n\n/**\n * Fetch `url` as bytes, aborting when `signal` does. `what` names the request in errors, as in\n * \"Failed to <what> from <url>\". The bytes are returned undecoded, so checksums cover what was served.\n */\nasync function fetchBytes(url: string, what: string, signal: AbortSignal): Promise<Uint8Array<ArrayBuffer>> {\n const res = await fetch(url, { signal });\n if (!res.ok) {\n throw new Error(`Failed to ${what} from ${url}: ${res.status} ${res.statusText}`);\n }\n return new Uint8Array(await res.arrayBuffer());\n}\n\n/** Download a format.js once for every caller in this process that asks for `url` meanwhile. */\nfunction shareDownload(url: string, options: RemoteFetchOptions): Promise<Uint8Array<ArrayBuffer>> {\n return shareRequest(`download\\0${url}`, waitOptions(options, 'download format', url), (signal) =>\n fetchBytes(url, 'download format', signal),\n );\n}\n\n/** Decode a downloaded format.js as local ones are (UTF-8, else Windows-1252), without a leading BOM. */\nfunction decodeDownload(bytes: Uint8Array, url: string): string {\n const { text } = decodeText(bytes, url);\n return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n}\n\n/** Validate that a JSON value is a valid SFAIndexEntry. */\nfunction isValidEntry(val: unknown): val is SFAIndexEntry {\n if (typeof val !== 'object' || val === null || Array.isArray(val)) return false;\n const obj = val as Record<string, unknown>;\n return (\n typeof obj.name === 'string' &&\n typeof obj.version === 'string' &&\n typeof obj.checksums === 'object' &&\n obj.checksums !== null &&\n !Array.isArray(obj.checksums)\n );\n}\n\n/** Validate that a JSON value conforms to the SFAIndex shape. */\nfunction validateSFAIndex(json: unknown): SFAIndex {\n if (typeof json !== 'object' || json === null) {\n throw new Error('SFA index is not an object');\n }\n const obj = json as Record<string, unknown>;\n const twine1 = Array.isArray(obj['twine1']) ? (obj['twine1'] as unknown[]).filter(isValidEntry) : [];\n const twine2 = Array.isArray(obj['twine2']) ? (obj['twine2'] as unknown[]).filter(isValidEntry) : [];\n return { twine1, twine2 };\n}\n\n/** Fetch and parse an SFA index.json, with in-memory caching. Concurrent calls for one URL share a request. */\nexport async function fetchIndex(url: string, options: RemoteFetchOptions = {}): Promise<SFAIndex> {\n options.signal?.throwIfAborted();\n const cached = indexCache.get(url);\n if (cached) return cached;\n\n return shareRequest(`index\\0${url}`, waitOptions(options, 'fetch format index', url), async (signal) => {\n const text = decodeDownload(await fetchBytes(url, 'fetch format index', signal), url);\n const data = validateSFAIndex(JSON.parse(text));\n indexCache.set(url, data);\n return data;\n });\n}\n\ninterface FindEntryResult {\n entry: SFAIndexEntry;\n formatType: 'twine1' | 'twine2';\n}\n\n/**\n * Find the best matching entry in an SFA index.\n * Exact version preferred, then highest version with same major.\n */\nexport function findEntry(index: SFAIndex, name: string, version: string): FindEntryResult | undefined {\n return findEntryForRequest(index, { kind: 'name', name, version });\n}\n\n/** Find the best matching entry in an SFA index for a name or ID request (twine2 entries first). */\nfunction findEntryForRequest(index: SFAIndex, request: FormatRequest): FindEntryResult | undefined {\n const candidates: FindEntryResult[] = [\n ...(index.twine2 ?? []).map((entry) => ({ entry, formatType: 'twine2' as const })),\n ...(index.twine1 ?? []).map((entry) => ({ entry, formatType: 'twine1' as const })),\n ];\n return selectFormatCandidate(request, candidates, (c) => c.entry);\n}\n\n/** Verify SHA-256 checksum using Web Crypto API (Node 22 built-in). */\nexport async function verifySHA256(content: Uint8Array<ArrayBuffer>, expectedHex: string): Promise<boolean> {\n const digest = await crypto.subtle.digest('SHA-256', content);\n const hex = Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n return hex === expectedHex.toLowerCase();\n}\n\n/** Derive the download URL for a format.js from the index URL and entry. */\nfunction getDownloadUrl(indexUrl: string, entry: SFAIndexEntry, formatType: 'twine1' | 'twine2'): string {\n const base = indexUrl.replace(/\\/index\\.json$/, '');\n return `${base}/${formatType}/${entry.name}/${entry.version}/format.js`;\n}\n\n/** The StoryFormatInfo of a Twine 2 format.js cached at `filename`. */\nfunction cachedFormatInfo(\n id: string,\n filename: string,\n data: { readonly name: string; readonly version: string; readonly proofing?: boolean },\n): StoryFormatInfo {\n return { id, filename, isTwine2: true, name: data.name, version: data.version, proofing: data.proofing ?? false };\n}\n\n/**\n * Check that a downloaded format is the one the index entry promised. The name matches without\n * regard to case, as format requests do, and the version by SemVer precedence, so \"1.0\" and \"v1.0.0\"\n * agree. A format.js that names no format ({@link UNNAMED_FORMAT_NAME}) is allowed: such formats\n * exist, and the index entry then supplies the name it is cached under.\n */\nfunction checkFormatIdentity(entry: SFAIndexEntry, data: Twine2FormatJSON, downloadUrl: string): void {\n const nameMatches = data.name === UNNAMED_FORMAT_NAME || data.name.toLowerCase() === entry.name.toLowerCase();\n if (nameMatches && sameVersion(data.version, entry.version)) return;\n throw new Error(\n `Story format mismatch for ${downloadUrl}: the index lists ${entry.name} ${entry.version}, ` +\n `but the download is ${data.name} ${data.version}`,\n );\n}\n\n/**\n * Download a format, verify its checksum, check that it is the format the entry names, write it to\n * the cache shared by name and version, and return its StoryFormatInfo. Concurrent calls for one\n * download URL share one request for the bytes; each call then verifies them against its own\n * entry, within its own timeout.\n */\nexport async function fetchAndCacheFormat(\n entry: SFAIndexEntry,\n downloadUrl: string,\n options: RemoteFetchOptions = {},\n): Promise<StoryFormatInfo> {\n // Index metadata is untrusted: reject a name or version that would leave the cache before downloading.\n cachedFormatDir(entry.name, entry.version);\n const bytes = await shareDownload(downloadUrl, options);\n\n // Verify the checksum against the bytes as served, if the entry has one.\n const checksumKey = Object.keys(entry.checksums ?? {}).find((k) => k.endsWith('format.js'));\n if (checksumKey) {\n const expected = entry.checksums[checksumKey];\n if (!expected) throw new Error(`Missing checksum value for key \"${checksumKey}\"`);\n if (!(await verifySHA256(bytes, expected))) {\n throw new Error(`Checksum verification failed for ${entry.name} ${entry.version}`);\n }\n }\n\n // Parse format JSON to extract name/version/source\n const text = decodeDownload(bytes, downloadUrl);\n const id = makeFormatId(entry.name, entry.version);\n const data = parseFormatJSON(text, id);\n if (!data) {\n throw new Error(`Failed to parse format JSON from ${downloadUrl}`);\n }\n checkFormatIdentity(entry, data, downloadUrl);\n\n // This caller gave up meanwhile: leave the cache as it was.\n options.signal?.throwIfAborted();\n const formatPath = writeCacheEntry(resolve(getCacheDir()), [entry.name, entry.version], text);\n return cachedFormatInfo(id, formatPath, data);\n}\n\n/**\n * Download a direct format.js URL, parse its JSON, cache it under that URL (apart from the\n * downloads shared by name and version), and return its StoryFormatInfo. Concurrent calls for\n * one URL share one request.\n */\nexport async function fetchDirectFormat(url: string, options: RemoteFetchOptions = {}): Promise<StoryFormatInfo> {\n const bytes = await shareDownload(url, options);\n const text = decodeDownload(bytes, url);\n\n const data = parseFormatJSON(text);\n if (!data) {\n throw new Error(`Failed to parse format JSON from ${url}`);\n }\n // The metadata is untrusted: refuse what could not be cached by name and version either.\n cachedFormatDir(data.name, data.version);\n\n // This caller gave up meanwhile: leave the cache as it was.\n options.signal?.throwIfAborted();\n const formatPath = writeCacheEntry(getUrlCacheDir(), [urlCacheKey(url)], text);\n return cachedFormatInfo(makeFormatId(data.name, data.version), formatPath, data);\n}\n\n/** The copy of a direct format URL in the download cache, if it has been downloaded before. */\nfunction getCachedDirectFormat(url: string): StoryFormatInfo | undefined {\n const formatPath = join(getUrlCacheDir(), urlCacheKey(url), 'format.js');\n try {\n if (!existsSync(formatPath)) return undefined;\n const data = parseFormatJSON(readUTF8(formatPath));\n if (!data) return undefined;\n return cachedFormatInfo(makeFormatId(data.name, data.version), formatPath, data);\n } catch {\n return undefined;\n }\n}\n\n/** Options for {@link resolveFormatUrls}. */\nexport interface ResolveFormatUrlsOptions extends RemoteFetchOptions {\n /** Use only the URLs downloaded before; fetch nothing. */\n readonly offline?: boolean;\n}\n\n/**\n * Look a request up among direct format URLs, in order, and return the first format that\n * answers it. A URL downloaded before is answered by its cached copy without the network;\n * any other is downloaded (unless `offline`). When none answers and a download failed, the\n * last failure is thrown. An aborted signal rejects with its reason and tries no further URL.\n *\n * Internal, for format resolution; not part of the public API.\n */\nexport async function resolveFormatUrls(\n request: FormatRequest,\n urls: readonly string[],\n options: ResolveFormatUrlsOptions = {},\n): Promise<StoryFormatInfo | undefined> {\n let lastError: Error | undefined;\n for (const url of urls) {\n const cached = getCachedDirectFormat(url);\n if (cached) {\n if (answers(request, cached)) return cached;\n continue;\n }\n if (options.offline) continue;\n try {\n const info = await fetchDirectFormat(url, options);\n if (answers(request, info)) return info;\n } catch (e) {\n if (options.signal?.aborted) throw options.signal.reason;\n lastError = toError(e);\n }\n }\n if (lastError) throw lastError;\n return undefined;\n}\n\n/**\n * Find the best format among the cached copies of direct format URLs, without network access.\n * Matching follows {@link selectFormatCandidate}, so `allowOlder` admits a same-major older version.\n * Each URL keeps its own copy; the shared name and version downloads are never consulted.\n *\n * Internal, for format resolution; not part of the public API.\n */\nexport function findCachedUrlFormat(\n request: FormatRequest,\n urls: readonly string[],\n options: SelectFormatOptions = {},\n): StoryFormatInfo | undefined {\n const cached = urls.flatMap((url) => getCachedDirectFormat(url) ?? []);\n return selectFormatCandidate(request, cached, (f) => f, options);\n}\n\n/** Whether `info` is a format the request accepts. */\nfunction answers(request: FormatRequest, info: StoryFormatInfo): boolean {\n return selectFormatCandidate(request, [info], (f) => f) !== undefined;\n}\n\nfunction toError(e: unknown): Error {\n return e instanceof Error ? e : new Error(String(e));\n}\n\n/**\n * Try to resolve a remote story format by name and version.\n * 1. Try direct format URLs (each one's cached copy, else a download)\n * 2. Use an exactly matching download from the shared cache, without touching the network\n * 3. Try custom index URLs, then the default SFA indices\n * 4. Fall back to a compatible download from the shared cache (e.g. when offline)\n *\n * `options.signal` aborts the lookup, which then rejects with the signal's reason;\n * `options.timeout` limits each request (default {@link DEFAULT_FORMAT_FETCH_TIMEOUT} ms).\n */\nexport async function resolveRemoteFormat(\n name: string,\n version: string,\n indices?: readonly string[],\n urls?: readonly string[],\n options: RemoteFetchOptions = {},\n): Promise<StoryFormatInfo | undefined> {\n return resolveRemoteFormatRequest({ kind: 'name', name, version }, indices, urls, options);\n}\n\n/**\n * Resolve a story format request remotely, in the same order as {@link resolveRemoteFormat}.\n * An ID request such as 'sugarcube-2' matches the format whose name and major version build that ID\n * (SugarCube 2.x), taking the greatest version available.\n */\nexport async function resolveRemoteFormatRequest(\n request: FormatRequest,\n indices?: readonly string[],\n urls?: readonly string[],\n options: RemoteFetchOptions = {},\n): Promise<StoryFormatInfo | undefined> {\n options.signal?.throwIfAborted();\n let lastError: Error | undefined;\n\n // 1. The caller's own format URLs come before anything shared by name and version.\n try {\n const direct = await resolveFormatUrls(request, urls ?? [], options);\n if (direct) return direct;\n } catch (e) {\n if (options.signal?.aborted) throw options.signal.reason;\n lastError = toError(e);\n }\n\n // 2. An exact version already downloaded needs no network access.\n const cached = findCachedFormat(request);\n if (cached && request.kind === 'name' && sameVersion(cached.version, request.version)) return cached;\n\n // 3. Try custom indices, then default SFA indices\n const allIndices = [...(indices ?? []), ...DEFAULT_SFA_INDICES];\n for (const indexUrl of allIndices) {\n try {\n const index = await fetchIndex(indexUrl, options);\n const result = findEntryForRequest(index, request);\n if (result) {\n // Check cache first\n const hit = getCachedFormat(result.entry.name, result.entry.version);\n if (hit) return hit;\n\n const downloadUrl = getDownloadUrl(indexUrl, result.entry, result.formatType);\n return await fetchAndCacheFormat(result.entry, downloadUrl, options);\n }\n } catch (e) {\n if (options.signal?.aborted) throw options.signal.reason;\n lastError = toError(e);\n }\n }\n\n // 4. No source had it (or none could be reached): a compatible cached download still answers the request.\n if (cached) return cached;\n\n // If all sources failed with errors, propagate the last one\n if (lastError) throw lastError;\n return undefined;\n}\n\n/**\n * Find the cached download that best answers a format request, without network access.\n * Only the downloads shared by name and version are searched, not those from direct URLs.\n * Matching follows {@link selectFormatCandidate}.\n */\nexport function findCachedFormat(\n request: FormatRequest,\n options: SelectFormatOptions = {},\n): StoryFormatInfo | undefined {\n return selectFormatCandidate(request, [...discoverCachedFormats().values()], (f) => f, options);\n}\n\n/** Check if a format is already in the local cache. */\nfunction getCachedFormat(name: string, version: string): StoryFormatInfo | undefined {\n if (!isSafeSegment(name) || !isSafeSegment(version)) return undefined;\n const formatPath = join(getCacheDir(), name, version, 'format.js');\n try {\n if (!existsSync(formatPath)) return undefined;\n const source = readUTF8(formatPath);\n const id = makeFormatId(name, version);\n const data = parseFormatJSON(source, id);\n if (!data) return undefined;\n return cachedFormatInfo(id, formatPath, data);\n } catch {\n return undefined;\n }\n}\n\n/** Discover all cached remote formats. Returns a Map like discoverFormats(). */\nexport function discoverCachedFormats(): Map<string, StoryFormatInfo> {\n const formats = new Map<string, StoryFormatInfo>();\n const cacheDir = getCacheDir();\n\n try {\n if (!existsSync(cacheDir)) return formats;\n } catch {\n return formats;\n }\n\n let names: string[];\n try {\n names = readdirSync(cacheDir);\n } catch {\n return formats;\n }\n\n for (const name of names) {\n const nameDir = join(cacheDir, name);\n try {\n if (!statSync(nameDir).isDirectory()) continue;\n } catch {\n continue;\n }\n\n let versions: string[];\n try {\n versions = readdirSync(nameDir);\n } catch {\n continue;\n }\n\n for (const version of versions) {\n const info = getCachedFormat(name, version);\n if (info) {\n formats.set(`${info.id}-${version}`, info);\n }\n }\n }\n\n return formats;\n}\n\n/** Info about a cached format entry with size and modification date. */\nexport interface CachedFormatEntry {\n readonly name: string;\n readonly version: string;\n readonly sizeBytes: number;\n readonly modifiedAt: Date;\n}\n\n/** List all cached formats with size and modification date. */\nexport function listCachedFormats(): readonly CachedFormatEntry[] {\n const cacheDir = getCacheDir();\n const entries: CachedFormatEntry[] = [];\n\n try {\n if (!existsSync(cacheDir)) return entries;\n } catch {\n return entries;\n }\n\n let names: string[];\n try {\n names = readdirSync(cacheDir);\n } catch {\n return entries;\n }\n\n for (const name of names) {\n const nameDir = join(cacheDir, name);\n try {\n if (!statSync(nameDir).isDirectory()) continue;\n } catch {\n continue;\n }\n\n let versions: string[];\n try {\n versions = readdirSync(nameDir);\n } catch {\n continue;\n }\n\n for (const version of versions) {\n const formatPath = join(nameDir, version, 'format.js');\n try {\n const stat = statSync(formatPath);\n entries.push({\n name,\n version,\n sizeBytes: stat.size,\n modifiedAt: stat.mtime,\n });\n } catch {\n // Skip entries without a valid format.js\n }\n }\n }\n\n return entries;\n}\n\n/**\n * Clear all cached formats, or only those matching a given name. Returns the number of entries removed.\n * Clearing all also removes the downloads from direct format URLs; a name clears only the\n * downloads shared by name and version.\n * A name must be a single cache entry name (as `listCachedFormats()` reports it); anything with a\n * path separator or `.`/`..` throws instead of deleting outside the format's own directory.\n */\nexport function clearCachedFormats(name?: string): number {\n if (name && !isSafeSegment(name)) {\n throw new Error(\n `Refusing to clear ${JSON.stringify(name)}: it is not a cached format name. Use a name as \"cache list\" shows it.`,\n );\n }\n\n const cacheDir = getCacheDir();\n\n if (!name) {\n const count = listCachedFormats().length + countUrlCacheEntries();\n rmSync(cacheDir, { recursive: true, force: true });\n rmSync(getUrlCacheDir(), { recursive: true, force: true });\n return count;\n }\n\n if (!existsSync(cacheDir)) return 0;\n\n const root = resolve(cacheDir);\n const nameDir = resolve(root, name);\n if (!isInside(root, nameDir)) {\n throw new Error(`Refusing to clear ${JSON.stringify(name)}: it is not a cached format name.`);\n }\n // lstat, so a symlinked entry is never followed out of the cache: only plain directories are entries.\n if (!lstatSync(nameDir, { throwIfNoEntry: false })?.isDirectory()) return 0;\n\n let versions: string[];\n try {\n versions = readdirSync(nameDir);\n } catch {\n return 0;\n }\n const count = versions.length;\n rmSync(nameDir, { recursive: true, force: true });\n return count;\n}\n\n/** The number of direct format URLs with a download in the cache. */\nfunction countUrlCacheEntries(): number {\n const dir = getUrlCacheDir();\n try {\n return readdirSync(dir).filter((key) => existsSync(join(dir, key, 'format.js'))).length;\n } catch {\n return 0;\n }\n}\n\n/** Get total cache size in bytes and format count. */\nexport function getCacheSize(): { totalBytes: number; count: number } {\n const entries = listCachedFormats();\n const totalBytes = entries.reduce((sum, e) => sum + e.sizeBytes, 0);\n return { totalBytes, count: entries.length };\n}\n","/**\n * Story format selection for a compile.\n *\n * The request comes from the explicit `formatId` option, else the StoryData format name and\n * version, else the default ID. That one request is then looked up in the local format\n * directories, the download cache, and (unless disabled) remote sources. A request that none of\n * them can answer is reported as an error rather than swapped for a different story format.\n */\nimport type { Diagnostic, FormatRequest, RemoteFetchOptions, StoryFormatInfo } from './types.js';\nimport {\n describeFormatRequest,\n discoverAllFormats,\n findFormatById,\n getFormatSearchDirs,\n pruneFormats,\n rankedTwine2Formats,\n selectFormatCandidate,\n} from './formats.js';\nimport {\n findCachedFormat,\n findCachedUrlFormat,\n resolveFormatUrls,\n resolveRemoteFormatRequest,\n} from './remote-formats.js';\n\n/** Where to look for story formats. */\nexport interface FormatResolutionOptions {\n readonly formatPaths?: readonly string[];\n readonly useTweegoPath?: boolean;\n readonly noRemote?: boolean;\n readonly formatIndices?: readonly string[];\n readonly formatUrls?: readonly string[];\n /** Aborts the format requests; resolution then rejects with the signal's reason. */\n readonly signal?: AbortSignal;\n /** Milliseconds each format request may take. */\n readonly formatFetchTimeout?: number;\n}\n\n/** Choose the format request: explicit format ID > StoryData format > default ID. */\nexport function formatRequestFor(\n formatId: string | undefined,\n storyFormat: string,\n storyFormatVersion: string,\n defaultId: string,\n): FormatRequest {\n if (formatId) return { kind: 'id', id: formatId };\n if (storyFormat) return { kind: 'name', name: storyFormat, version: storyFormatVersion };\n return { kind: 'id', id: defaultId };\n}\n\n/**\n * Look a request up among the formats found in local format directories. An ID names a folder, so\n * it is looked up among all of them; a name request selects by SemVer among the pruned formats.\n */\nfunction findLocalFormat(\n all: ReadonlyMap<string, StoryFormatInfo>,\n pruned: ReadonlyMap<string, StoryFormatInfo>,\n request: FormatRequest,\n): StoryFormatInfo | undefined {\n switch (request.kind) {\n case 'id':\n return findFormatById(all, request.id);\n case 'name':\n return selectFormatCandidate(request, rankedTwine2Formats(pruned), (f) => f);\n default: {\n const _exhaustive: never = request;\n throw new Error(`unhandled format request: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Resolve a format request to a story format.\n *\n * Order: local format directories, then the project's direct format URLs (each one's cached\n * copy, else a download unless `noRemote`), then the download cache shared by name and version,\n * then format indices (unless `noRemote`). Names and IDs match the same way in each (see\n * `selectFormatCandidate`), so a request that a local format answers never reaches the cache or the\n * network. Local formats that cannot be used are reported as warnings. When a StoryData request\n * names a version that none of them has, an older version of the same format and major version\n * is used with a warning, from local formats, the project's cached format URLs, or the shared cache. Anything else is an error diagnostic,\n * and the result is `undefined`.\n */\nexport async function resolveStoryFormat(\n request: FormatRequest,\n options: FormatResolutionOptions,\n diagnostics: Diagnostic[],\n): Promise<StoryFormatInfo | undefined> {\n const noRemote = options.noRemote ?? false;\n const searchDirs = getFormatSearchDirs(options.formatPaths, options.useTweegoPath ?? true);\n const all = discoverAllFormats(searchDirs, diagnostics);\n const pruned = pruneFormats(all);\n const wanted = describeFormatRequest(request);\n\n const local = findLocalFormat(all, pruned, request);\n if (local) return local;\n\n const fetchOptions: RemoteFetchOptions = { signal: options.signal, timeout: options.formatFetchTimeout };\n const warnOnFailure = async (\n lookup: () => Promise<StoryFormatInfo | undefined>,\n ): Promise<StoryFormatInfo | undefined> => {\n try {\n return await lookup();\n } catch (e) {\n if (options.signal?.aborted) throw options.signal.reason;\n diagnostics.push({\n level: 'warning',\n message: `Remote format fetch failed for ${wanted}: ${e instanceof Error ? e.message : String(e)}`,\n });\n return undefined;\n }\n };\n\n // The project's own format URLs come before the downloads shared by name and version, so\n // another project's download of the same name and version never stands in for them.\n const direct = await warnOnFailure(() =>\n resolveFormatUrls(request, options.formatUrls ?? [], { ...fetchOptions, offline: noRemote }),\n );\n if (direct) return direct;\n\n const cached = findCachedFormat(request);\n if (cached) return cached;\n\n if (!noRemote) {\n const remote = await warnOnFailure(() =>\n resolveRemoteFormatRequest(request, options.formatIndices, [], fetchOptions),\n );\n if (remote) return remote;\n }\n\n // A same-major older version keeps the story in its own format; it never crosses majors.\n if (request.kind === 'name') {\n const older =\n selectFormatCandidate(request, rankedTwine2Formats(pruned), (f) => f, { allowOlder: true }) ??\n // Every configured URL was downloaded above unless remote fetching is off or it failed, so\n // its cached copy is the whole answer here.\n findCachedUrlFormat(request, options.formatUrls ?? [], { allowOlder: true }) ??\n findCachedFormat(request, { allowOlder: true });\n if (older) {\n diagnostics.push({\n level: 'warning',\n message: `Story format ${wanted} is not available; using ${older.name} ${older.version} instead.`,\n });\n return older;\n }\n }\n\n const reason = noRemote ? ' (remote fetching disabled)' : '';\n diagnostics.push({\n level: 'error',\n message: `Story format ${wanted} is not available${reason}. Found: ${[...all.keys()].join(', ') || 'none'}`,\n });\n return undefined;\n}\n","/**\n * All public interfaces for twee-ts.\n */\n\n// --- Output modes ---\n\nexport type OutputMode = 'html' | 'twee3' | 'twee1' | 'twine2-archive' | 'twine1-archive' | 'json';\n\n// --- Word count ---\n\nexport type WordCountMethod = 'tweego' | 'whitespace';\n\n// --- Source input ---\n\nexport type InlineSource = { filename: string; content: string | Buffer };\nexport type SourceInput = string | InlineSource;\n\n// --- Compile options ---\n\nexport interface CompileOptions {\n /**\n * Files, directories, or inline sources to compile. Directories are walked\n * recursively; inside one, a symbolic link to a file is read, but a link to a\n * directory is not followed (as in Tweego).\n */\n sources: readonly SourceInput[];\n /**\n * Glob patterns for files to leave out of `sources`, matched against each file's\n * path relative to the working directory (as `stats.files` lists it). Modules are not affected.\n */\n exclude?: readonly string[];\n /** Output mode. Default: 'html'. */\n outputMode?: OutputMode;\n /** Story format directory ID (e.g. 'sugarcube-2'). */\n formatId?: string;\n /** Name of the starting passage. Default: 'Start'. */\n startPassage?: string;\n /** Extra directories to search for story formats. */\n formatPaths?: readonly string[];\n /** Also search TWEEGO_PATH env for formats. Default: true. */\n useTweegoPath?: boolean;\n /** Module files to inject into <head>. */\n modules?: readonly string[];\n /** Raw HTML file to append to <head>. */\n headFile?: string;\n /** Trim passage whitespace. Default: true. */\n trim?: boolean;\n /** Twee2 compatibility mode. Default: false. */\n twee2Compat?: boolean;\n /** Enable debug/test mode option. Default: false. */\n testMode?: boolean;\n /** URLs to SFA-compatible index.json files for remote format lookup. */\n formatIndices?: readonly string[];\n /**\n * Direct URLs to format.js files. Each URL's download is cached under that URL, and is\n * looked up before the downloads shared by name and version.\n */\n formatUrls?: readonly string[];\n /** Disable remote format fetching. Default: false. */\n noRemote?: boolean;\n /**\n * Cancels the compile. Story format requests still in progress are aborted, and the compile\n * rejects with the signal's reason. `watch()` aborts its builds, and stops watching, when it aborts.\n */\n signal?: AbortSignal;\n /**\n * Milliseconds each story format request (an index or a format.js) may take before it fails\n * with a warning and the next source is tried. 0 turns the limit off. Default: 30000.\n */\n formatFetchTimeout?: number;\n /** Map alias tags to canonical special tags (e.g. { library: 'script' }). */\n tagAliases?: Record<string, string>;\n /** Emit source file and line as data- attributes on passage elements. Default: false. */\n sourceInfo?: boolean;\n /** Word counting method. Default: 'tweego'. */\n wordCountMethod?: WordCountMethod;\n}\n\nexport interface CompileToFileOptions extends CompileOptions {\n /**\n * Output file path. It is never read as a source, even inside a source folder or\n * reached through a symbolic link. Naming it as a source, a module or the head\n * file is a TweeTsError, and nothing is written.\n */\n outFile: string;\n}\n\nexport interface WatchOptions extends CompileToFileOptions {\n /**\n * Called after each build is written, including one whose diagnostics report errors. Builds\n * run one at a time and are reported in order, each as it finishes, also while changes keep\n * arriving: the changes made during a build go into one follow-up build after it.\n */\n onBuild?: (result: CompileResult) => void;\n /**\n * Called when a build fails with a fatal error (nothing is written), when `onBuild` throws,\n * and when a watched path can't be watched (the other paths are still watched). An exception\n * thrown here is reported to the console, and watching goes on.\n */\n onError?: (error: Error) => void;\n}\n\n// --- Compile result ---\n\nexport type Diagnostic =\n | { level: 'warning'; message: string; file?: string; line?: number }\n | { level: 'error'; message: string; file?: string; line?: number; fatal?: boolean };\n\nexport interface CompileResult {\n /** The compiled output string (HTML, Twee, JSON, etc.). */\n output: string;\n /** The parsed story model (read-only after compilation). */\n story: ReadonlyStory;\n /** The format used for compilation (undefined for non-HTML modes). */\n format?: StoryFormatInfo;\n /** Collected diagnostics. */\n diagnostics: Diagnostic[];\n /** Compilation statistics. */\n stats: CompileStats;\n}\n\nexport interface CompileStats {\n passages: number;\n storyPassages: number;\n words: number;\n files: string[];\n}\n\n// --- Passage ---\n\nexport interface SourceLocation {\n readonly file: string;\n readonly line: number;\n}\n\nexport interface PassageMetadata {\n position?: string;\n size?: string;\n [key: string]: string | undefined;\n}\n\nexport interface Passage {\n name: string;\n tags: string[];\n text: string;\n metadata?: PassageMetadata;\n source?: SourceLocation;\n}\n\n// --- Branded types ---\n\nexport type IFID = string & { readonly __brand: 'IFID' };\n\n// --- Story ---\n\nexport interface Twine1Metadata {\n settings: Map<string, string>;\n}\n\nexport interface Twine2Metadata {\n format: string;\n formatVersion: string;\n options: Map<string, boolean>;\n start: string;\n tags: string;\n tagColors: Map<string, string>;\n zoom: number;\n}\n\nexport interface Story {\n name: string;\n ifid: IFID;\n passages: Passage[];\n legacyIFID: IFID;\n twine1: Twine1Metadata;\n twine2: Twine2Metadata;\n}\n\n// --- Readonly story (post-construction) ---\n\nexport type ReadonlyPassage = Readonly<Omit<Passage, 'tags' | 'metadata'>> & {\n readonly tags: readonly string[];\n readonly metadata?: Readonly<PassageMetadata>;\n};\n\nexport type ReadonlyStory = Readonly<Omit<Story, 'passages' | 'twine1' | 'twine2'>> & {\n readonly passages: readonly ReadonlyPassage[];\n readonly twine1: Readonly<Omit<Twine1Metadata, 'settings'>> & {\n readonly settings: ReadonlyMap<string, string>;\n };\n readonly twine2: Readonly<Omit<Twine2Metadata, 'options' | 'tagColors'>> & {\n readonly options: ReadonlyMap<string, boolean>;\n readonly tagColors: ReadonlyMap<string, string>;\n };\n};\n\n// --- Passage omission (why an output leaves a passage out) ---\n\nexport type OmittingTag = 'Twine.private' | 'script' | 'stylesheet';\n\nexport type PassageOmission =\n | { readonly kind: 'special-name'; readonly name: 'StoryData' | 'StoryTitle' }\n | { readonly kind: 'tag'; readonly tag: OmittingTag }\n | { readonly kind: 'empty-story-settings' };\n\n/** The output whose rules decide which passages a story emits as passages. */\nexport type PassageOutputTarget = 'twine1' | 'twine2';\n\n// --- HTML decompile ---\n\nexport interface DecompileOptions {\n /**\n * Trim whitespace at both ends of passage text (and of the Twine 2 story stylesheet and script),\n * as the Twee lexer does. When false, the stored text is kept exactly. Default: true.\n */\n readonly trim?: boolean;\n}\n\n// --- Story inspection ---\n\nexport interface InspectOptions {\n /**\n * Check link destinations against this output's passage rules. A link to a passage that the\n * output leaves out (in Twine 2: `script`, `stylesheet` and `Twine.private` passages,\n * StoryData, StoryTitle and an empty StorySettings; in Twine 1: `Twine.private` passages) is\n * then a broken link, and says why. The passages it leaves out also give no links, as their\n * text never reaches the player, except script passages, which Twine 2 output runs. Without a\n * target, every source passage gives links, and a link is broken only when no passage has its\n * name.\n */\n readonly target?: PassageOutputTarget;\n}\n\n// --- Story format ---\n\nexport interface StoryFormatInfo {\n id: string;\n filename: string;\n isTwine2: boolean;\n name: string;\n version: string;\n proofing: boolean;\n author?: string;\n description?: string;\n image?: string;\n url?: string;\n license?: string;\n}\n\n/**\n * The story format a compile asks for: a directory-style ID (e.g. 'sugarcube-2', which names\n * a format and a major version) or a Twine 2 format name with a version (as StoryData has it).\n */\nexport type FormatRequest =\n | { readonly kind: 'id'; readonly id: string }\n | { readonly kind: 'name'; readonly name: string; readonly version: string };\n\nexport interface Twine2FormatJSON {\n name: string;\n version: string;\n proofing?: boolean;\n source: string;\n author?: string;\n description?: string;\n image?: string;\n url?: string;\n license?: string;\n}\n\n/** The result of reading a format.js: its metadata, or why it cannot be used. */\nexport type FormatDecodeResult =\n { readonly ok: true; readonly data: Twine2FormatJSON } | { readonly ok: false; readonly reason: string };\n\n/**\n * A parsed SemVer version. Build metadata is dropped, since it takes no part in precedence.\n * Each prerelease identifier is kept as written ('beta', '1').\n */\nexport interface SemVer {\n readonly major: number;\n readonly minor: number;\n readonly patch: number;\n readonly prerelease: readonly string[];\n}\n\n// --- Lexer ---\n\nexport const ItemType = {\n Error: 0,\n EOF: 1,\n Header: 2,\n Name: 3,\n Tags: 4,\n Metadata: 5,\n Content: 6,\n} as const;\nexport type ItemType = (typeof ItemType)[keyof typeof ItemType];\n\nexport interface LexerItem {\n type: ItemType;\n line: number;\n pos: number;\n val: string;\n}\n\n// --- Story Format Archive (SFA) ---\n\nexport interface SFAIndexEntry {\n name: string;\n version: string;\n proofing: boolean;\n files: string[];\n checksums: Record<string, string>;\n}\n\nexport interface SFAIndex {\n twine1: SFAIndexEntry[];\n twine2: SFAIndexEntry[];\n}\n\n/** Options for the network requests that fetch story formats and their indices. */\nexport interface RemoteFetchOptions {\n /** Aborts the requests; the call then rejects with the signal's reason. */\n readonly signal?: AbortSignal;\n /** Milliseconds each request may take before it fails. 0 turns the limit off. Default: 30000. */\n readonly timeout?: number;\n}\n\n// --- Incremental compilation cache ---\n\nexport interface FileCacheEntry {\n readonly mtimeMs: number;\n /**\n * Identity of the parse options (`trim`, `twee2Compat`) the entry was parsed with. An entry is\n * reused only when this matches the current options; an entry without it is treated as stale\n * and reparsed. The value is opaque: leave it to twee-ts to set.\n */\n readonly parseOptionsKey?: string;\n readonly passages: readonly Passage[];\n readonly diagnostics: readonly Diagnostic[];\n}\n\n// --- Config file ---\n\nexport interface TweeTsConfig {\n sources?: string[];\n exclude?: string[];\n output?: string;\n outputMode?: OutputMode;\n formatId?: string;\n startPassage?: string;\n formatPaths?: string[];\n formatIndices?: string[];\n formatUrls?: string[];\n useTweegoPath?: boolean;\n modules?: string[];\n headFile?: string;\n trim?: boolean;\n twee2Compat?: boolean;\n testMode?: boolean;\n noRemote?: boolean;\n /** Milliseconds each story format request may take. 0 turns the limit off. Default: 30000. */\n formatFetchTimeout?: number;\n tagAliases?: Record<string, string>;\n sourceInfo?: boolean;\n wordCountMethod?: WordCountMethod;\n}\n","/**\n * Twee 3 state-machine lexer implemented as a synchronous generator.\n * Ported from tweelexer.go — Go channels become `yield`.\n */\nimport type { LexerItem } from './types.js';\nimport { ItemType } from './types.js';\n\nconst EOF = -1;\nconst HEADER_DELIM = '::';\nconst NEWLINE_HEADER_DELIM = '\\n::';\n\ntype StateFn = ((ctx: LexerContext) => StateFn | null) | null;\n\nclass LexerContext {\n readonly input: string;\n line = 1;\n start = 0;\n pos = 0;\n private items: LexerItem[] = [];\n\n constructor(input: string) {\n this.input = input;\n }\n\n next(): number {\n if (this.pos >= this.input.length) return EOF;\n const ch = this.input.charCodeAt(this.pos);\n this.pos++;\n if (ch === 0x0a) this.line++;\n return ch;\n }\n\n peek(): number {\n if (this.pos >= this.input.length) return EOF;\n return this.input.charCodeAt(this.pos);\n }\n\n backup(): void {\n if (this.pos > this.start) {\n this.pos--;\n if (this.input.charCodeAt(this.pos) === 0x0a) this.line--;\n } else {\n throw new Error('backup would leave pos < start');\n }\n }\n\n // Line-counting invariant: next() increments this.line for each newline during\n // character-by-character scanning. However, Content items are produced by jumping\n // this.pos directly (e.g. via indexOf) without calling next(), so those newlines\n // haven't been counted yet. emit() re-counts newlines in [start, pos) for Content\n // items to compensate. This is safe because this.start is reset to this.pos after\n // every emit(), so no range is ever counted twice.\n emit(type: ItemType): void {\n const val = this.input.slice(this.start, this.pos);\n this.items.push({ type, line: this.line, pos: this.start, val });\n if (type === ItemType.Content) {\n for (let i = this.start; i < this.pos; i++) {\n if (this.input.charCodeAt(i) === 0x0a) this.line++;\n }\n }\n this.start = this.pos;\n }\n\n ignore(): void {\n for (let i = this.start; i < this.pos; i++) {\n if (this.input.charCodeAt(i) === 0x0a) this.line++;\n }\n this.start = this.pos;\n }\n\n acceptRun(valid: string): void {\n let ch: number;\n for (ch = this.next(); ch !== EOF && valid.includes(String.fromCharCode(ch)); ch = this.next()) {\n // consume\n }\n if (ch !== EOF) this.backup();\n }\n\n errorf(message: string): null {\n this.items.push({\n type: ItemType.Error,\n line: this.line,\n pos: this.start,\n val: message,\n });\n return null;\n }\n\n /** Drain all pending items and return them. */\n drainItems(): LexerItem[] {\n const result = this.items;\n this.items = [];\n return result;\n }\n}\n\nfunction acceptQuoted(ctx: LexerContext, quote: number): string | null {\n for (;;) {\n const ch = ctx.next();\n switch (ch) {\n case 0x5c: {\n // backslash\n const r = ctx.next();\n if (r !== 0x0a && r !== EOF) break;\n // fall through\n }\n // falls through\n case 0x0a:\n case EOF:\n return 'unterminated quoted string';\n default:\n if (ch === quote) return null;\n break;\n }\n }\n}\n\n// --- State functions ---\n\nfunction lexProlog(ctx: LexerContext): StateFn {\n if (ctx.input.startsWith(HEADER_DELIM, ctx.pos)) {\n return lexHeaderDelim;\n }\n const i = ctx.input.indexOf(NEWLINE_HEADER_DELIM, ctx.pos);\n if (i > -1) {\n ctx.pos = i + 1; // skip to the newline, then past it\n ctx.ignore();\n return lexHeaderDelim;\n }\n ctx.emit(ItemType.EOF);\n return null;\n}\n\nfunction lexContent(ctx: LexerContext): StateFn {\n if (ctx.input.startsWith(HEADER_DELIM, ctx.pos)) {\n return lexHeaderDelim;\n }\n const i = ctx.input.indexOf(NEWLINE_HEADER_DELIM, ctx.pos);\n if (i > -1) {\n ctx.pos = i + 1;\n ctx.emit(ItemType.Content);\n return lexHeaderDelim;\n }\n ctx.pos = ctx.input.length;\n if (ctx.pos > ctx.start) {\n ctx.emit(ItemType.Content);\n }\n ctx.emit(ItemType.EOF);\n return null;\n}\n\nfunction lexHeaderDelim(ctx: LexerContext): StateFn {\n ctx.pos += HEADER_DELIM.length;\n ctx.emit(ItemType.Header);\n return lexName;\n}\n\nfunction lexName(ctx: LexerContext): StateFn {\n let r: number;\n outer: for (;;) {\n r = ctx.next();\n switch (r) {\n case 0x5c: {\n // backslash\n const next = ctx.next();\n if (next !== 0x0a && next !== EOF) break;\n // fall through to terminators\n r = next;\n }\n // falls through\n case 0x5b: // [\n case 0x5d: // ]\n case 0x7b: // {\n case 0x7d: // }\n case 0x0a: // \\n\n case EOF:\n if (r !== EOF) ctx.backup();\n break outer;\n }\n }\n // Always emit a name item, even if empty.\n ctx.emit(ItemType.Name);\n\n switch (r) {\n case 0x5b:\n return lexTags; // [\n case 0x5d:\n return ctx.errorf(`unexpected right square bracket ']'`);\n case 0x7b:\n return lexMetadata; // {\n case 0x7d:\n return ctx.errorf(`unexpected right curly brace '}'`);\n case 0x0a: // newline\n ctx.pos++;\n ctx.ignore();\n return lexContent;\n }\n ctx.emit(ItemType.EOF);\n return null;\n}\n\nfunction lexNextOptionalBlock(ctx: LexerContext): StateFn {\n // Consume whitespace.\n ctx.acceptRun(' \\t');\n ctx.ignore();\n\n const r = ctx.peek();\n switch (r) {\n case 0x5b:\n return lexTags; // [\n case 0x5d:\n return ctx.errorf(`unexpected right square bracket ']'`);\n case 0x7b:\n return lexMetadata; // {\n case 0x7d:\n return ctx.errorf(`unexpected right curly brace '}'`);\n case 0x0a: // newline\n ctx.pos++;\n ctx.ignore();\n return lexContent;\n case EOF:\n ctx.emit(ItemType.EOF);\n return null;\n }\n return ctx.errorf(`illegal character '${String.fromCharCode(r)}' amid the optional blocks`);\n}\n\nfunction lexTags(ctx: LexerContext): StateFn {\n // Consume the left delimiter '['.\n ctx.pos++;\n\n for (;;) {\n const r = ctx.next();\n switch (r) {\n case 0x5c: {\n // backslash\n const next = ctx.next();\n if (next !== 0x0a && next !== EOF) break;\n // fall through\n }\n // falls through\n case 0x0a:\n case EOF:\n if (r === 0x0a) ctx.backup();\n return ctx.errorf('unterminated tag block');\n case 0x5d: // ]\n if (ctx.pos > ctx.start) ctx.emit(ItemType.Tags);\n return lexNextOptionalBlock;\n case 0x5b: // [\n return ctx.errorf(`unexpected left square bracket '['`);\n case 0x7b: // {\n return ctx.errorf(`unexpected left curly brace '{'`);\n case 0x7d: // }\n return ctx.errorf(`unexpected right curly brace '}'`);\n }\n }\n}\n\nfunction lexMetadata(ctx: LexerContext): StateFn {\n // Consume the left delimiter '{'.\n ctx.pos++;\n\n let depth = 1;\n for (;;) {\n const r = ctx.next();\n switch (r) {\n case 0x22: {\n // double quote\n const err = acceptQuoted(ctx, 0x22);\n if (err) return ctx.errorf(err);\n break;\n }\n case 0x0a: // newline\n ctx.backup();\n // falls through\n case EOF:\n return ctx.errorf('unterminated metadata block');\n case 0x7b: // {\n depth++;\n break;\n case 0x7d: // }\n depth--;\n if (depth === 0) {\n if (ctx.pos > ctx.start) ctx.emit(ItemType.Metadata);\n return lexNextOptionalBlock;\n }\n break;\n }\n }\n}\n\n/**\n * Twee 3 lexer — yields LexerItem tokens from Twee source text.\n *\n * In the Go reference, this uses goroutines and channels.\n * Here we use a synchronous generator that accumulates items per state step.\n */\nexport function* tweeLexer(input: string): Generator<LexerItem, void, undefined> {\n const ctx = new LexerContext(input);\n let state: StateFn = lexProlog;\n while (state !== null) {\n state = state(ctx);\n const items = ctx.drainItems();\n for (const item of items) {\n yield item;\n }\n }\n}\n\n/** Convenience class wrapper for the lexer generator. */\nexport class TweeLexer {\n private gen: Generator<LexerItem, void, undefined>;\n\n constructor(input: string) {\n this.gen = tweeLexer(input);\n }\n\n nextItem(): { item: LexerItem; done: boolean } {\n const result = this.gen.next();\n if (result.done) {\n return { item: { type: ItemType.EOF, line: 0, pos: 0, val: '' }, done: true };\n }\n return { item: result.value, done: false };\n }\n\n *[Symbol.iterator](): Generator<LexerItem, void, undefined> {\n yield* this.gen;\n }\n}\n","/**\n * Twee2 to Twee3 header syntax conversion.\n * Ported from twee2compat.go.\n */\n\nconst twee2DetectRe = /^:: *[^[]*?(?: *\\[.*?\\])? *<(.*?)> *$/m;\nconst twee2HeaderRe = /^(:: *[^[]*?)( *\\[.*?\\])?(?: *<(.*?)>)? *$/gm;\nconst twee2BadPosRe = /^(::.*?) *\\{\"position\":\" *\"\\}$/gm;\n\nfunction hasTwee2Syntax(s: string): boolean {\n return twee2DetectRe.test(s);\n}\n\n/**\n * Convert Twee2-style position blocks `<x,y>` to Twee3 metadata blocks `{\"position\":\"x,y\"}`.\n */\nexport function twee2ToV3(s: string): string {\n if (!hasTwee2Syntax(s)) return s;\n let result = s.replace(twee2HeaderRe, (_, p1: string, p2: string | undefined, p3: string | undefined) => {\n const tags = p2 ?? '';\n const pos = p3 ?? '';\n return `${p1}${tags} {\"position\":\"${pos}\"}`;\n });\n result = result.replace(twee2BadPosRe, '$1');\n return result;\n}\n","/**\n * Parse lexer items into Passage[].\n * Ported from storyload.go:loadTwee().\n */\nimport type { Passage, PassageMetadata, Diagnostic } from './types.js';\nimport { ItemType } from './types.js';\nimport { tweeLexer } from './lexer.js';\nimport { tweeUnescape } from './escape.js';\nimport { twee2ToV3 } from './twee2-compat.js';\nimport { normalizeTweeSourceText } from './source-text.js';\n\nexport interface ParseOptions {\n /** Filename for diagnostics. */\n filename?: string;\n /** Trim whitespace from passage content. Default: true. */\n trim?: boolean;\n /** Enable Twee2 compatibility. Default: false. */\n twee2Compat?: boolean;\n}\n\nexport interface ParseResult {\n passages: Passage[];\n diagnostics: Diagnostic[];\n}\n\n/**\n * Parse Twee source text into passages.\n *\n * The source is normalized first, as files are when they are read: a leading UTF-8 BOM is\n * removed and CRLF and bare CR line endings become LF. A BOM at the start of a later line,\n * directly before `::` (left there by concatenating files), is removed too, so that line\n * stays a passage header.\n */\nexport function parseTwee(source: string, options: ParseOptions = {}): ParseResult {\n const { filename = '<inline>', trim = true, twee2Compat = false } = options;\n const diagnostics: Diagnostic[] = [];\n\n const normalized = normalizeTweeSourceText(source);\n const tweeSource = twee2Compat ? twee2ToV3(normalized) : normalized;\n\n const passages: Passage[] = [];\n let current: Passage | null = null;\n let pCount = 0;\n let lastType: ItemType = ItemType.EOF;\n\n for (const item of tweeLexer(tweeSource)) {\n switch (item.type) {\n case ItemType.Error:\n diagnostics.push({\n level: 'error',\n message: `line ${item.line}: Malformed twee source; ${item.val}.`,\n file: filename,\n line: item.line,\n });\n // Fatal: return what we have\n return { passages, diagnostics };\n\n case ItemType.EOF:\n if (pCount > 0 && current) {\n passages.push(current);\n }\n return { passages, diagnostics };\n\n case ItemType.Header:\n pCount++;\n if (pCount > 1 && current) {\n passages.push(current);\n }\n current = { name: '', tags: [], text: '', source: { file: filename, line: item.line } };\n break;\n\n case ItemType.Name: {\n if (!current) break;\n const name = tweeUnescape(item.val).trim();\n if (name.length === 0) {\n diagnostics.push({\n level: 'error',\n message: `line ${item.line}: Malformed twee source; passage with no name.`,\n file: filename,\n line: item.line,\n });\n return { passages, diagnostics };\n }\n current.name = name;\n break;\n }\n\n case ItemType.Tags: {\n if (!current) break;\n if (lastType !== ItemType.Name) {\n diagnostics.push({\n level: 'error',\n message: `line ${item.line}: Malformed twee source; optional tags block must immediately follow the passage name.`,\n file: filename,\n line: item.line,\n });\n return { passages, diagnostics };\n }\n // Strip the surrounding [ and ]\n const inner = item.val.slice(1, -1);\n current.tags = tweeUnescape(inner).split(/\\s+/).filter(Boolean);\n break;\n }\n\n case ItemType.Metadata: {\n if (!current) break;\n if (lastType !== ItemType.Name && lastType !== ItemType.Tags) {\n diagnostics.push({\n level: 'error',\n message: `line ${item.line}: Malformed twee source; optional metadata block must immediately follow the passage name or tags block.`,\n file: filename,\n line: item.line,\n });\n return { passages, diagnostics };\n }\n try {\n // The lexer only emits a metadata item that starts with `{` and ends with its closing `}`,\n // so a successful parse is always an object.\n const parsed = JSON.parse(item.val) as Record<string, unknown>;\n const meta: PassageMetadata = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (typeof value === 'string') {\n meta[key] = value;\n }\n }\n current.metadata = meta;\n } catch (e) {\n diagnostics.push({\n level: 'warning',\n message: `load ${filename}: line ${item.line}: Malformed twee source; could not decode metadata (reason: ${e instanceof Error ? e.message : String(e)}).`,\n file: filename,\n line: item.line,\n });\n }\n break;\n }\n\n case ItemType.Content: {\n if (!current) break;\n if (trim) {\n current.text = item.val.trim();\n } else {\n // Per spec: trailing blank lines MUST be stripped regardless of trim option\n current.text = item.val.replace(/\\n\\s*$/, '');\n }\n break;\n }\n\n default: {\n const _exhaustive: never = item.type;\n diagnostics.push({\n level: 'error',\n message: `line ${item.line}: Unhandled lexer item type: ${_exhaustive}.`,\n file: filename,\n line: item.line,\n });\n return { passages, diagnostics };\n }\n }\n\n lastType = item.type;\n }\n\n // Shouldn't reach here (EOF is always emitted), but just in case:\n if (pCount > 0 && current) {\n passages.push(current);\n }\n return { passages, diagnostics };\n}\n","// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134\n/**\n * C1 Unicode control character reference replacements (code points 128–159).\n * Index i gives the replacement for code point 128+i; 0 means \"no replacement\".\n */\nconst c1 = [\n 8364, 0, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 0,\n 381, 0, 0, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250,\n 339, 0, 382, 376,\n];\n/**\n * True for NUL, UTF-16 surrogates, and values past U+10FFFF.\n * @param codePoint Unicode code point to check.\n */\nfunction isInvalidCodePoint(codePoint) {\n return (codePoint === 0 ||\n (codePoint >= 0xd8_00 && codePoint <= 0xdf_ff) ||\n codePoint > 0x10_ff_ff);\n}\n/**\n * Replace the given code point with U+FFFD if it is NUL (0), a surrogate, or\n * outside the valid Unicode range. Code points in the C1 controls range\n * (128–159) are remapped to their Windows-1252 equivalents, following the\n * HTML spec. All other code points are returned unchanged.\n * @param codePoint Unicode code point to convert.\n */\nexport function replaceCodePoint(codePoint) {\n if (isInvalidCodePoint(codePoint)) {\n return 0xff_fd;\n }\n if (codePoint >= 128 && codePoint <= 159) {\n return c1[codePoint - 128] || codePoint;\n }\n return codePoint;\n}\n/**\n * XML numeric character references are the referenced Unicode code point.\n * Invalid values still become U+FFFD; the HTML Windows-1252 C1 remap is not\n * applied.\n * @see https://www.w3.org/TR/xml/#NT-CharRef\n * @param codePoint Unicode code point to convert.\n */\nexport function replaceCodePointXML(codePoint) {\n return isInvalidCodePoint(codePoint) ? 0xff_fd : codePoint;\n}\n/**\n * Convert the code point of a decoded numeric entity to a string, replacing\n * invalid values.\n *\n * Fast path for plain BMP code points: [1..0x7F] and [0xA0..0xD7FF] pass\n * `replaceCodePoint` unchanged (no NUL, C1 remap, surrogate, or out-of-range\n * handling) and fit a single charCode. 0xd760 = 0xD800 (the first surrogate)\n * - 0xA0.\n * @param codePoint Unicode code point to convert.\n */\nexport function codePointToString(codePoint) {\n return (codePoint - 1) >>> 0 < 0x7f || (codePoint - 0xa0) >>> 0 < 0xd7_60\n ? String.fromCharCode(codePoint)\n : String.fromCodePoint(replaceCodePoint(codePoint));\n}\n//# sourceMappingURL=decode-codepoint.js.map","/*\n * Inverse of the encoder's SAFE alphabet (0x21..0x7E minus 0x22, 0x24, 0x5C),\n * precomputed once at module load. Entries for excluded chars stay 0 but\n * are never read.\n */\nconst BASE91_INVERSE = /* #__PURE__ */ (() => {\n const table = new Uint8Array(127);\n let code = 0;\n for (let char = 0x21; char <= 0x7e; char++) {\n if (char !== 0x22 && char !== 0x24 && char !== 0x5c) {\n table[char] = code++;\n }\n }\n return table;\n})();\n/**\n * Decode a dictionary-encoded trie string back into its Uint16Array.\n *\n * Stream layout (consumed in this order):\n * 1. dict1 atoms — `dict1AtomCount` uint16 values, delta+RLE encoded.\n * 2. dict2 atoms — `atomCount - dict1AtomCount` values, delta+RLE.\n * 3. dict2 ngrams — `ngramCount - (dictSize - dict1AtomCount)` entries,\n * each a pair of slot codes that resolve to earlier slots.\n * 4. dict1 ngrams — `dictSize - dict1AtomCount` entries, same shape.\n * 5. data — slot codes, each expanding to one or more uint16 values.\n *\n * Codes use a 91-char base (printable ASCII minus `\"`, `$`, `\\`):\n * - char1 < dictSize → 1-char code, slot = char1\n * - char1 ≥ dictSize → 2-char code, slot = dictSize + (char1 - dictSize)*91 + char2\n *\n * Slot index → token kind:\n * [0, A) dict1 atoms (1-char codes)\n * [A, dictSize) dict1 ngrams (1-char codes)\n * [dictSize, dictSize+D) dict2 atoms (2-char codes)\n * [dictSize+D, end) dict2 ngrams (2-char codes)\n *\n * Both atom dicts decode before any ngram, and dict2 ngrams decode before\n * dict1 ngrams. So every ngram entry references slots whose contents are\n * already filled — no forward references to handle.\n *\n * This runs on library import. Flat typed arrays store each slot as either\n * a plain value (`single`, covering every atom) or a range in a shared\n * `pool` (ngrams).\n * @param input Packed trie string.\n * @param resultLength Expected number of uint16 values in the output.\n * @param atomCount Total number of distinct uint16 values in the trie.\n * @param dict1AtomCount Atoms in the 1-char range (`A` above).\n * @param ngramCount Total number of ngram entries (dict1 + dict2).\n * @param dictSize Number of 1-char code slots; the rest of `BASE - dictSize`\n * first-byte values are 2-char codes.\n */\nexport function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCount, dictSize) {\n const base = 91;\n const inputLength = input.length;\n // For 2-char codes, slot = char1 * base - twoCharBias + char2.\n const twoCharBias = dictSize * (base - 1);\n let pos = 0;\n /** Read one slot code at `pos` and return its slot index, advancing pos. */\n const readSlotCode = () => {\n const c1 = BASE91_INVERSE[input.charCodeAt(pos++)];\n return c1 < dictSize\n ? c1\n : c1 * base - twoCharBias + BASE91_INVERSE[input.charCodeAt(pos++)];\n };\n const dict2AtomCount = atomCount - dict1AtomCount;\n const slotCount = atomCount + ngramCount;\n /*\n * Per-slot contents: atoms (always a single value) live directly in\n * `single`; ngram slots hold -1 there and expand to\n * `pool[start[slot] .. start[slot] + length[slot])`.\n */\n const single = new Int32Array(slotCount);\n single.fill(-1, dict1AtomCount, dictSize);\n single.fill(-1, dictSize + dict2AtomCount, slotCount);\n const start = new Int32Array(slotCount);\n const length = new Int32Array(slotCount);\n /**\n * Decode `count` ascending uint16 values from a delta+RLE stream into\n * `single[off..off+count)`.\n *\n * code < 89 → delta = code\n * code == 89 → run-length: next char encodes runLength-2; emit `runLength` consecutive +1 values\n * code == 90, next < 90 → escape: delta = 89 + next * BASE + after-next\n * code == 90, next == 90 → double-escape: extra char for very large deltas\n * @param count\n * @param off\n */\n function decodeDelta(count, off) {\n let previous = 0;\n let slot = off;\n const end = off + count;\n while (slot < end) {\n const code = BASE91_INVERSE[input.charCodeAt(pos++)];\n if (code < 89) {\n previous += code;\n single[slot++] = previous;\n }\n else if (code === 89) {\n let runLength = BASE91_INVERSE[input.charCodeAt(pos++)] + 2;\n while (runLength--)\n single[slot++] = ++previous;\n }\n else {\n const next = BASE91_INVERSE[input.charCodeAt(pos++)];\n previous +=\n 89 +\n // eslint-disable-next-line unicorn/prefer-minimal-ternary -- branches read a different number of side-effecting input bytes\n (next < 90\n ? next * base + BASE91_INVERSE[input.charCodeAt(pos++)]\n : BASE91_INVERSE[input.charCodeAt(pos++)] * 8281 +\n BASE91_INVERSE[input.charCodeAt(pos++)] * base +\n BASE91_INVERSE[input.charCodeAt(pos++)]);\n single[slot++] = previous;\n }\n }\n }\n // Streams 1 & 2: atoms decoded into their slot ranges.\n decodeDelta(dict1AtomCount, 0);\n decodeDelta(dict2AtomCount, dictSize);\n /*\n * Streams 3 & 4 are read in two passes: first collect every ngram's two\n * references and derive its expanded length (each ref resolves to an earlier\n * slot, so lengths are already known), which sizes the shared pool.\n * Pool ranges are handed out in decode order, so the second pass fills\n * the pool contiguously with a single write cursor.\n */\n const references = new Int32Array(ngramCount * 2);\n let poolSize = 0;\n let ngramIndex = 0;\n /**\n * Read `count` ngram entries (each = 2 slot-code references) for the slots\n * starting at `startSlot`, recording references and assigning pool ranges.\n * @param count\n * @param startSlot\n */\n function readNgramReferences(count, startSlot) {\n for (let index = 0; index < count; index++) {\n const slot = startSlot + index;\n const a = readSlotCode();\n const b = readSlotCode();\n references[ngramIndex * 2] = a;\n references[ngramIndex * 2 + 1] = b;\n ngramIndex += 1;\n start[slot] = poolSize;\n const entryLength = (single[a] < 0 ? length[a] : 1) +\n (single[b] < 0 ? length[b] : 1);\n length[slot] = entryLength;\n poolSize += entryLength;\n }\n }\n readNgramReferences(ngramCount - dictSize + dict1AtomCount, dictSize + dict2AtomCount);\n readNgramReferences(dictSize - dict1AtomCount, dict1AtomCount);\n // Second pass: concatenate each ngram's two halves into the pool.\n const pool = new Uint16Array(poolSize);\n let write = 0;\n for (let index = 0; index < ngramIndex; index++) {\n for (let half = 0; half < 2; half++) {\n const source = references[index * 2 + half];\n const value = single[source];\n if (value < 0) {\n let read = start[source];\n const readEnd = read + length[source];\n while (read < readEnd)\n pool[write++] = pool[read++];\n }\n else {\n pool[write++] = value;\n }\n }\n }\n // Stream 5: data. Each code expands to its slot's stored values.\n const out = new Uint16Array(resultLength);\n let outIndex = 0;\n while (pos < inputLength) {\n let slot = BASE91_INVERSE[input.charCodeAt(pos++)];\n if (slot >= dictSize) {\n slot =\n slot * base -\n twoCharBias +\n BASE91_INVERSE[input.charCodeAt(pos++)];\n }\n const value = single[slot];\n if (value < 0) {\n let read = start[slot];\n const readEnd = read + length[slot];\n while (read < readEnd)\n out[outIndex++] = pool[read++];\n }\n else {\n out[outIndex++] = value;\n }\n }\n return out;\n}\n//# sourceMappingURL=decode-shared.js.map","// Generated using scripts/write-decode-map.ts\nimport { decodeTrieDict } from \"../internal/decode-shared.js\";\n/** Packed HTML decode trie data. */\nexport const htmlDecodeTree = /* #__PURE__ */ decodeTrieDict(\"!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}&/N'(0(/*-%(%%}#'+&T%7.2}#&%&#%#36/5##%&%%#&#%%#))2%%##%&&'0~!#*+&'%1~!%).'3q?&%'1~!.##%6(~!+%%%(Gw'rT~!E#<nA%#jZ~!H%(~!42##~!*31&~!G%U~#)5~#`3~!J~!Z~%]~%Y~%C~!q~!u~#kz~%#~!6'~!D~!U~!?~#T~!c%~!G#'~%7|~!G~!J~!G&~#pb~(Df}#%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p@Ku+D#'!t7~GrP~?rNKvlaya7'!h+v-5qMg=t|cd,U#5AAaa5Abb{S@52B5@a[@52B5Gx[iXueu;d<#`a(!/549C;ag>23ExY5@Dah89b^~689Jv)!~2b[~1Lv'w(%*!a#bX|aPrmawRe]keu7uhv-q6rxu,q`xTo]/a5aU!bNaDXbi!b-!ao!b<bwA!#5@B932:aV2G|:d-)Y#hJrL>RhG<7@C5<H|_=Cau:5aj5@B932:bJ|ng>vIbs)#?C2F|9jPv0w.vISh-MKvUaz(.!9ABbb|[5;5<H|Eg>unwfh;9:4E|YjQsBt|vjx'hYq3!(?C2F|J:2<BaY?C2F|GOu!5x,g|p{ah!-(?C2F|c9:4E|OjXuvvNr}:Rh&i[w*t|cd+U#jJvsu)vsSn~Mkfrmu9p}u7vwv]So!McW#Xa!ax5@A5aY:5;5<H|>kJv~vYrquJu3x4ib#T)2@SmZM?C2F|Bj:rmu9@xPhI(a*a#U#`a3-5Abb|L~@:RhK9:4E|0@52B5G|#C::aY?C2F|-:2<BaY?C2F|.5Jvk!a)javYrquJu3x4ia#T)2@SmYM?C2F|HAxPhH(!a#U#`a*-5Abb|4~@:RhJ9:4E|R@52B5G|F:2<BaY?C2F|Sc^#Xa2j=Qq5CJvB!-g<v{z;hhM?C2F|Zi[vrv{z;hiM?C2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P\", 13_494, 2713, 49, 25, 61);\n//# sourceMappingURL=decode-data-html.js.map","// Generated using scripts/write-decode-map.ts\n/** Packed XML decode trie data. */\nexport const xmlDecodeTree = /* #__PURE__ */ new Uint16Array([\n 512, 26_465, 29_036, 7, 0, 2, 4, 116, 24_638, 116, 24_636, 8693, 29_807,\n 24_610, 621, 1, 0, 0, 3, 112, 24_614, 111, 115, 24_615,\n]);\n//# sourceMappingURL=decode-data-xml.js.map","/**\n * Bit flags & masks for the binary trie encoding used for entity decoding.\n *\n * The trie is a flat `Uint16Array`. Every node starts with one header word:\n *\n * 15..14 VALUE_LENGTH Number of words the value occupies, +1.\n * 0 = no value; 1 = value inline in bits 12..0;\n * 2/3 = value in the 1/2 words after the header.\n * 13 FLAG13 If VALUE_LENGTH > 0: semicolon required (\"strict\"\n * entity; `;` is never stored as a branch).\n * If VALUE_LENGTH == 0: this node is a compact run.\n * 12..7 BRANCH_LENGTH Number of branches (or run length for runs).\n * 6..0 JUMP_TABLE Jump-table offset / single-branch char / first\n * run char (see below).\n *\n * Branch data follows the header and any value words. Its shape is selected\n * by (JUMP_TABLE, BRANCH_LENGTH) in the header:\n *\n * Single branch JUMP_TABLE = the only child's char, BRANCH_LENGTH = 0.\n * No branch words; the child node follows immediately.\n * Jump table JUMP_TABLE = first covered char (> 0), BRANCH_LENGTH =\n * table length. One word per covered char: 0 = no branch,\n * otherwise the child's offset from the END of the table,\n * +1 (so 0 stays the no-branch sentinel).\n * Dictionary JUMP_TABLE = 0, BRANCH_LENGTH = number of branches.\n * ceil(n/2) words of sorted keys packed two per word\n * (low byte first), then n pointer words storing the\n * child's offset from the END of the branch data.\n * Compact run VALUE_LENGTH = 0, FLAG13 set. BRANCH_LENGTH = run\n * length (3..63), JUMP_TABLE = first char; remaining run\n * chars packed two per word after the header. The target\n * node follows the packed words immediately.\n *\n * Pointers are end-relative (rather than relative to the pointer's own\n * position) because that makes the common \"child encoded right after the\n * branch data\" case a small constant, which compresses far better. Offsets\n * to already-encoded (shared) nodes wrap via uint16 modulo arithmetic; the\n * decoder masks navigation results with `& 0xff_ff` to match.\n */\nexport var BinTrieFlags;\n(function (BinTrieFlags) {\n BinTrieFlags[BinTrieFlags[\"VALUE_LENGTH\"] = 49152] = \"VALUE_LENGTH\";\n BinTrieFlags[BinTrieFlags[\"FLAG13\"] = 8192] = \"FLAG13\";\n BinTrieFlags[BinTrieFlags[\"BRANCH_LENGTH\"] = 8064] = \"BRANCH_LENGTH\";\n BinTrieFlags[BinTrieFlags[\"JUMP_TABLE\"] = 127] = \"JUMP_TABLE\";\n /** Bits 12..0: the inline value of a VALUE_LENGTH = 1 header word. */\n BinTrieFlags[BinTrieFlags[\"VALUE_MASK\"] = 8191] = \"VALUE_MASK\";\n})(BinTrieFlags || (BinTrieFlags = {}));\n//# sourceMappingURL=bin-trie-flags.js.map","import { codePointToString, replaceCodePoint, replaceCodePointXML, } from \"./decode-codepoint.js\";\nimport { htmlDecodeTree } from \"./generated/decode-data-html.js\";\nimport { xmlDecodeTree } from \"./generated/decode-data-xml.js\";\nimport { BinTrieFlags } from \"./internal/bin-trie-flags.js\";\nvar CharCodes;\n(function (CharCodes) {\n CharCodes[CharCodes[\"AMP\"] = 38] = \"AMP\";\n CharCodes[CharCodes[\"NUM\"] = 35] = \"NUM\";\n CharCodes[CharCodes[\"SEMI\"] = 59] = \"SEMI\";\n CharCodes[CharCodes[\"EQUALS\"] = 61] = \"EQUALS\";\n CharCodes[CharCodes[\"ZERO\"] = 48] = \"ZERO\";\n CharCodes[CharCodes[\"NINE\"] = 57] = \"NINE\";\n CharCodes[CharCodes[\"LOWER_A\"] = 97] = \"LOWER_A\";\n CharCodes[CharCodes[\"LOWER_X\"] = 120] = \"LOWER_X\";\n})(CharCodes || (CharCodes = {}));\n/** Bit that needs to be set to convert an upper case ASCII character to lower case */\nconst TO_LOWER_BIT = 0b10_0000;\n/*\n * `parseNumericEntity` packs its two results into one 32-bit integer:\n * `(consumed << CONSUMED_SHIFT) | codePoint`. The 21-bit code point field\n * fits any valid Unicode value (max 0x10FFFF, clamped before packing); the\n * consumed count excludes `&` and gets the remaining 11 bits. Extract it\n * with `>>>` so the topmost bit isn't treated as a sign.\n *\n * Plain consts rather than a `const enum`: with `isolatedModules`, enum\n * member reads compile to runtime property loads.\n */\nconst CONSUMED_SHIFT = 21;\nconst CODE_POINT_MASK = 0x1f_ff_ff;\n/**\n * Reserved consumed field for counts of at least 2047 characters after `&`.\n * The true count is in `longNumericConsumed`.\n */\nconst CONSUMED_OVERFLOW = 0x7_ff;\n/**\n * Side channel for numeric entities of at least 2048 characters including\n * `&`. Set by `parseNumericEntity` when its consumed count reaches the\n * reserved value `CONSUMED_OVERFLOW`; callers read the true count from here.\n * A module-level slot avoids a tuple allocation on the hot path.\n */\nlet longNumericConsumed = 0;\n/**\n * Extract the consumed count from a `parseNumericEntity` packed result,\n * recovering the true length from `longNumericConsumed` when the packed\n * field contains the sentinel. Read it before the next `parseNumericEntity`\n * call, which may overwrite the side channel. This helper owns that protocol.\n * @param packed Packed result of `parseNumericEntity`.\n */\nfunction unpackConsumed(packed) {\n const consumed = packed >>> CONSUMED_SHIFT;\n return consumed === CONSUMED_OVERFLOW ? longNumericConsumed : consumed;\n}\n/**\n * Unsigned subtraction trick: (code - lo) >>> 0 wraps negatives to large\n * values, so a single `<=` covers the entire [lo..hi] range check.\n * @param code Code point to check.\n */\nfunction isNumber(code) {\n return (code - CharCodes.ZERO) >>> 0 <= 9;\n}\nfunction isHexadecimalCharacter(code) {\n return ((code | TO_LOWER_BIT) - CharCodes.LOWER_A) >>> 0 <= 5; // F - a\n}\nfunction isAlpha(code) {\n return ((code | TO_LOWER_BIT) - CharCodes.LOWER_A) >>> 0 <= 25; // Z - a\n}\n/**\n * Checks if the given character is a valid end character for an entity in an attribute.\n *\n * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.\n * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state\n * @param code Code point to check.\n */\nfunction isEntityInAttributeInvalidEnd(code) {\n return code === CharCodes.EQUALS || isAlpha(code) || isNumber(code);\n}\nvar EntityDecoderState;\n(function (EntityDecoderState) {\n EntityDecoderState[EntityDecoderState[\"EntityStart\"] = 0] = \"EntityStart\";\n EntityDecoderState[EntityDecoderState[\"NumericStart\"] = 1] = \"NumericStart\";\n EntityDecoderState[EntityDecoderState[\"NumericDecimal\"] = 2] = \"NumericDecimal\";\n EntityDecoderState[EntityDecoderState[\"NumericHex\"] = 3] = \"NumericHex\";\n EntityDecoderState[EntityDecoderState[\"NamedEntity\"] = 4] = \"NamedEntity\";\n})(EntityDecoderState || (EntityDecoderState = {}));\n/**\n * Decoding mode for named entities.\n */\nexport var DecodingMode;\n(function (DecodingMode) {\n /** Entities in text nodes that can end with any character. */\n DecodingMode[DecodingMode[\"Legacy\"] = 0] = \"Legacy\";\n /** Only allow entities terminated with a semicolon. */\n DecodingMode[DecodingMode[\"Strict\"] = 1] = \"Strict\";\n /** Entities in attributes have limitations on ending characters. */\n DecodingMode[DecodingMode[\"Attribute\"] = 2] = \"Attribute\";\n})(DecodingMode || (DecodingMode = {}));\n/**\n * Token decoder with support of writing partial entities.\n */\nexport class EntityDecoder {\n decodeTree;\n emitCodePoint;\n errors;\n /** The current state of the decoder. */\n state = EntityDecoderState.EntityStart;\n /** Characters that were consumed while parsing an entity. */\n consumed = 1;\n /**\n * The result of the entity.\n *\n * For named entities: the trie index of the best legacy match so far\n * (0 = none). For numeric entities: the accumulated code point.\n */\n result = 0;\n /** The current index in the decode tree. */\n treeIndex = 0;\n /**\n * Characters consumed since the last recorded legacy match, plus one.\n * Invariant at the top of the `stateNamedEntity` loop: `excess` equals\n * the number of unrecorded consumed characters + 1.\n */\n // biome-ignore lint/correctness/noUnusedPrivateClassMembers: False positive (read via destructuring)\n excess = 1;\n /** The mode in which the decoder is operating. */\n decodeMode = DecodingMode.Strict;\n /** The number of characters that have been consumed in the current run. */\n // biome-ignore lint/correctness/noUnusedPrivateClassMembers: False positive\n runConsumed = 0;\n constructor(\n /** The predefined HTML or XML decode tree. */\n decodeTree, \n /**\n * The function that is called when a codepoint is decoded.\n *\n * For named entities that decode to multiple code points, this will\n * be called multiple times, with the second codepoint, and the same\n * `consumed` value.\n * @param codepoint The decoded codepoint.\n * @param consumed The number of characters consumed by the decoder.\n */\n emitCodePoint, \n /** An object that is used to produce errors. */\n errors) {\n this.decodeTree = decodeTree;\n this.emitCodePoint = emitCodePoint;\n this.errors = errors;\n }\n /**\n * Resets the instance to make it reusable.\n * @param decodeMode Entity decoding mode to use.\n */\n startEntity(decodeMode) {\n this.decodeMode = decodeMode;\n this.state = EntityDecoderState.EntityStart;\n this.result = 0;\n this.treeIndex = 0;\n this.excess = 1;\n this.consumed = 1;\n this.runConsumed = 0;\n }\n /**\n * Write an entity to the decoder. This can be called multiple times with partial entities.\n * If the entity is incomplete, the decoder will return -1.\n *\n * Mirrors the non-streaming `decodeWithTrie`, but with the ability to stop decoding if the\n * entity is incomplete, and resume when the next string is written.\n * @param input The string containing the entity (or a continuation of the entity).\n * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.\n * @returns The number of characters that were consumed, or -1 if the entity is incomplete.\n */\n write(input, offset) {\n switch (this.state) {\n case EntityDecoderState.EntityStart: {\n if (input.charCodeAt(offset) === CharCodes.NUM) {\n this.state = EntityDecoderState.NumericStart;\n this.consumed += 1;\n return this.stateNumericStart(input, offset + 1);\n }\n this.state = EntityDecoderState.NamedEntity;\n return this.stateNamedEntity(input, offset);\n }\n case EntityDecoderState.NumericStart: {\n return this.stateNumericStart(input, offset);\n }\n case EntityDecoderState.NumericDecimal: {\n return this.stateNumericDecimal(input, offset);\n }\n case EntityDecoderState.NumericHex: {\n return this.stateNumericHex(input, offset);\n }\n default: {\n // NamedEntity — the only remaining state.\n return this.stateNamedEntity(input, offset);\n }\n }\n }\n /**\n * Switches between the numeric decimal and hexadecimal states.\n *\n * Equivalent to the `Numeric character reference state` in the HTML spec.\n * @param input The string containing the entity (or a continuation of the entity).\n * @param offset The current offset.\n * @returns The number of characters that were consumed, or -1 if the entity is incomplete.\n */\n // eslint-disable-next-line unicorn/consistent-class-member-order\n stateNumericStart(input, offset) {\n if (offset >= input.length) {\n return -1;\n }\n if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {\n this.state = EntityDecoderState.NumericHex;\n this.consumed += 1;\n return this.stateNumericHex(input, offset + 1);\n }\n this.state = EntityDecoderState.NumericDecimal;\n return this.stateNumericDecimal(input, offset);\n }\n /**\n * Parses a hexadecimal numeric entity.\n *\n * Equivalent to the `Hexademical character reference state` in the HTML\n * spec. Digit parsing matches the hex loop in `parseNumericEntity`.\n * The accumulated value is preserved for numeric validation callbacks.\n * @param input The string containing the entity (or a continuation of the entity).\n * @param offset The current offset.\n * @returns The number of characters that were consumed, or -1 if the entity is incomplete.\n */\n stateNumericHex(input, offset) {\n const inputLength = input.length;\n // Local accumulators; flushed before any exit (see stateNamedEntity).\n let { result } = this;\n let { consumed } = this;\n while (offset < inputLength) {\n const char = input.charCodeAt(offset);\n if (isNumber(char) || isHexadecimalCharacter(char)) {\n // Convert hex digit to value (0-15); 'a'/'A' -> 10.\n const digit = char <= CharCodes.NINE\n ? char - CharCodes.ZERO\n : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10;\n result = result * 16 + digit;\n consumed += 1;\n offset += 1;\n }\n else {\n this.result = result;\n this.consumed = consumed;\n return this.emitNumericEntity(char, 3);\n }\n }\n this.result = result;\n this.consumed = consumed;\n return -1; // Incomplete entity\n }\n /**\n * Parses a decimal numeric entity.\n *\n * Equivalent to the `Decimal character reference state` in the HTML\n * spec. Digit parsing matches the decimal loop in `parseNumericEntity`.\n * The accumulated value is preserved for numeric validation callbacks.\n * @param input The string containing the entity (or a continuation of the entity).\n * @param offset The current offset.\n * @returns The number of characters that were consumed, or -1 if the entity is incomplete.\n */\n stateNumericDecimal(input, offset) {\n const inputLength = input.length;\n // Local accumulators; flushed before any exit (see stateNamedEntity).\n let { result } = this;\n let { consumed } = this;\n while (offset < inputLength) {\n const digit = input.charCodeAt(offset) - CharCodes.ZERO;\n if (digit >>> 0 > 9) {\n this.result = result;\n this.consumed = consumed;\n return this.emitNumericEntity(digit + CharCodes.ZERO, 2);\n }\n result = result * 10 + digit;\n consumed += 1;\n offset += 1;\n }\n this.result = result;\n this.consumed = consumed;\n return -1; // Incomplete entity\n }\n /**\n * Validate and emit a numeric entity.\n *\n * Implements the logic from the `Hexademical character reference start\n * state` and `Numeric character reference end state` in the HTML spec.\n * @param lastCp The last code point of the entity. Used to see if the\n * entity was terminated with a semicolon.\n * @param expectedLength The minimum number of characters that should be\n * consumed. Used to validate that at least one digit\n * was consumed.\n * @returns The number of characters that were consumed.\n */\n emitNumericEntity(lastCp, expectedLength) {\n // Ensure we consumed at least one digit.\n if (this.consumed <= expectedLength) {\n this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed);\n return 0;\n }\n // Figure out if this is a legit end of the entity\n if (lastCp === CharCodes.SEMI) {\n this.consumed += 1;\n }\n else if (this.decodeMode === DecodingMode.Strict) {\n return 0;\n }\n this.emitCodePoint((this.decodeTree === xmlDecodeTree\n ? replaceCodePointXML\n : replaceCodePoint)(this.result), this.consumed);\n if (this.errors) {\n if (lastCp !== CharCodes.SEMI) {\n this.errors.missingSemicolonAfterCharacterReference();\n }\n this.errors.validateNumericCharacterReference(this.result);\n }\n return this.consumed;\n }\n /**\n * Flush locally-tracked walk state back to the fields, then emit the\n * recorded legacy match or reject (cold path — at most once per\n * entity). Called after failed navigation (leaf node, branch miss, or\n * compact-run mismatch). In attribute mode, reject if no legacy was\n * recorded at the current node, if we descended past it, or if the\n * pending input character is an invalid attribute terminator.\n * @param consumed Locally-tracked consumed count.\n * @param excess Locally-tracked excess count.\n * @param char Pending input character (may be the mismatching char).\n * @param valueLength Value length at the current trie node.\n */\n flushAndEmitLegacyOrReject(consumed, excess, char, valueLength) {\n this.consumed = consumed;\n this.excess = excess;\n return this.result === 0 ||\n (this.decodeMode === DecodingMode.Attribute &&\n (valueLength === 0 ||\n excess > 1 ||\n isEntityInAttributeInvalidEnd(char)))\n ? 0\n : this.emitNotTerminatedNamedEntity();\n }\n /**\n * Parses a named entity.\n *\n * Equivalent to the `Named character reference state` in the HTML spec.\n * @param input The string containing the entity (or a continuation of the entity).\n * @param offset The current offset.\n * @returns The number of characters that were consumed, or -1 if the entity is incomplete.\n */\n stateNamedEntity(input, offset) {\n const { decodeTree } = this;\n const inputLength = input.length;\n const isStrict = this.decodeMode === DecodingMode.Strict;\n /*\n * Local copies of the resumable walk state avoid per-character\n * field writes. They are flushed back to the fields\n * on every exit (chunk end, and before any emit helper that reads\n * them). `this.result` is only written at the (rare) record points,\n * so it stays a direct field write.\n *\n * Legacy-match recording happens in two idempotent places: at the\n * loop top when sitting on a value node, and in the chunk-end\n * epilogue (so `end()` sees matches that land exactly on a chunk\n * boundary). Recording applies `consumed += excess - 1; excess = 1`,\n * which is a no-op when repeated — the loop-top invariant is\n * `excess` = unrecorded consumed characters + 1.\n */\n let { treeIndex } = this;\n let { excess } = this;\n let { consumed } = this;\n let current = decodeTree[treeIndex];\n while (offset < inputLength) {\n /*\n * Descend through value-less jump-table nodes (including the\n * single-branch encoding) inline, mirroring `decodeWithTrie`:\n * this avoids a `determineBranch` call per level for the\n * dominant node shape — including the root on the first write.\n */\n while ((current &\n (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) ===\n 0 &&\n (current & BinTrieFlags.JUMP_TABLE) !== 0) {\n const char = input.charCodeAt(offset);\n const jumpOffset = current & BinTrieFlags.JUMP_TABLE;\n const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;\n if (branchCount === 0) {\n // Single branch encoded inline in the jump offset bits.\n if (char !== jumpOffset) {\n return this.flushAndEmitLegacyOrReject(consumed, excess, char, 0);\n }\n treeIndex += 1;\n }\n else {\n const slot = char - jumpOffset;\n if (slot >>> 0 >= branchCount) {\n return this.flushAndEmitLegacyOrReject(consumed, excess, char, 0);\n }\n const stored = decodeTree[treeIndex + 1 + slot];\n if (stored === 0) {\n return this.flushAndEmitLegacyOrReject(consumed, excess, char, 0);\n }\n // End-relative: branch data ends at treeIndex+1+branchCount.\n treeIndex = (treeIndex + branchCount + stored) & 0xff_ff;\n }\n current = decodeTree[treeIndex];\n offset += 1;\n excess += 1;\n /*\n * `charCodeAt` past the end returns NaN, which would alias\n * to slot 0 after `>>> 0` — bail out explicitly.\n */\n // eslint-disable-next-line unicorn/no-break-in-nested-loop\n if (offset >= inputLength)\n break;\n }\n if (offset >= inputLength)\n break;\n // Handle compact runs (resumable across chunks).\n if ((current &\n (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) ===\n BinTrieFlags.FLAG13) {\n const runLength = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; /* 3..63 */\n let { runConsumed } = this;\n // If we are starting a run, check the first char.\n if (runConsumed === 0) {\n const char = input.charCodeAt(offset);\n if (char !== (current & BinTrieFlags.JUMP_TABLE)) {\n return this.flushAndEmitLegacyOrReject(consumed, excess, char, 0);\n }\n offset += 1;\n excess += 1;\n runConsumed = 1;\n }\n // Check remaining characters in the run (packed two per uint16 word).\n while (runConsumed < runLength) {\n if (offset >= inputLength) {\n this.treeIndex = treeIndex;\n this.excess = excess;\n this.consumed = consumed;\n this.runConsumed = runConsumed;\n return -1;\n }\n const charIndexInPacked = runConsumed - 1;\n const packedWord = decodeTree[treeIndex + 1 + (charIndexInPacked >> 1)];\n const expectedChar = (packedWord >> ((charIndexInPacked & 1) << 3)) & 0xff;\n const char = input.charCodeAt(offset);\n if (char !== expectedChar) {\n this.runConsumed = 0;\n return this.flushAndEmitLegacyOrReject(consumed, excess, char, 0);\n }\n offset += 1;\n excess += 1;\n runConsumed += 1;\n }\n this.runConsumed = 0;\n treeIndex += 1 + (runLength >> 1);\n current = decodeTree[treeIndex];\n // Loop top handles the landed-on node (record/emit/branch).\n continue;\n }\n // Header plus out-of-line value words; 0 means no value.\n const valueLength = current >>> 14;\n const char = input.charCodeAt(offset);\n if (valueLength !== 0) {\n // Record a legacy match (FLAG13 clear = semicolon optional).\n if (!isStrict && (current & BinTrieFlags.FLAG13) === 0) {\n this.result = treeIndex;\n consumed += excess - 1;\n excess = 1;\n }\n /*\n * Implicit semicolon handling: emit immediately. Covers both\n * strict (FLAG13 set) and legacy entities — neither stores\n * an explicit `;` branch in the trie.\n */\n if (char === CharCodes.SEMI) {\n return this.emitNamedEntityData(treeIndex, valueLength, consumed + excess);\n }\n /*\n * `valueLength === 1` packs the codepoint into the header\n * word's low 13 bits, where branch metadata also lives. Skip\n * the branch lookup on leaves so those value bits aren't\n * reinterpreted as branch offsets.\n */\n if (valueLength === 1) {\n return this.flushAndEmitLegacyOrReject(consumed, excess, char, valueLength);\n }\n }\n // Value-bearing or dictionary node: dispatch through determineBranch.\n const next = determineBranch(decodeTree, current, treeIndex + (valueLength || 1), char);\n if (next < 0) {\n return this.flushAndEmitLegacyOrReject(consumed, excess, char, valueLength);\n }\n treeIndex = next;\n current = decodeTree[treeIndex];\n offset += 1;\n excess += 1;\n }\n /*\n * Chunk exhausted. Record a legacy match we may be sitting on, so a\n * subsequent `end()` emits it, then persist the walk state.\n */\n if (!isStrict &&\n current >>> 14 !== 0 &&\n (current & BinTrieFlags.FLAG13) === 0) {\n this.result = treeIndex;\n consumed += excess - 1;\n excess = 1;\n }\n this.treeIndex = treeIndex;\n this.excess = excess;\n this.consumed = consumed;\n return -1;\n }\n /**\n * Emit a named entity that was not terminated with a semicolon.\n * @returns The number of characters consumed.\n */\n emitNotTerminatedNamedEntity() {\n const { result, decodeTree } = this;\n const valueLength = decodeTree[result] >>> 14;\n this.emitNamedEntityData(result, valueLength, this.consumed);\n this.errors?.missingSemicolonAfterCharacterReference();\n return this.consumed;\n }\n /**\n * Emit a named entity.\n * @param result The index of the entity in the decode tree.\n * @param valueLength Encoded value length (header plus any value words).\n * @param consumed The number of characters consumed.\n * @returns The number of characters consumed.\n */\n emitNamedEntityData(result, valueLength, consumed) {\n const { decodeTree } = this;\n this.emitCodePoint(valueLength === 1\n ? decodeTree[result] & BinTrieFlags.VALUE_MASK\n : decodeTree[result + 1], consumed);\n if (valueLength === 3) {\n // Emit the second UTF-16 code unit.\n this.emitCodePoint(decodeTree[result + 2], consumed);\n }\n return consumed;\n }\n /**\n * Signal to the parser that the end of the input was reached.\n *\n * Remaining data will be emitted and relevant errors will be produced.\n * @returns The number of characters consumed.\n */\n end() {\n switch (this.state) {\n case EntityDecoderState.NamedEntity: {\n // Emit a named entity if we have one.\n return this.result !== 0 &&\n (this.decodeMode !== DecodingMode.Attribute ||\n this.result === this.treeIndex)\n ? this.emitNotTerminatedNamedEntity()\n : 0;\n }\n // Otherwise, emit a numeric entity if we have one.\n case EntityDecoderState.NumericDecimal: {\n return this.emitNumericEntity(0, 2);\n }\n case EntityDecoderState.NumericHex: {\n return this.emitNumericEntity(0, 3);\n }\n case EntityDecoderState.NumericStart: {\n this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed);\n return 0;\n }\n default: {\n // EntityStart or unknown — return 0.\n return 0;\n }\n }\n }\n}\n/**\n * Determines the branch of the current node that is taken given the current\n * character. This function is used to traverse the trie.\n *\n * See `BinTrieFlags` for the branch-data layouts handled here.\n * @param decodeTree The trie.\n * @param current The current node's header word.\n * @param nodeIndex Index of the node's first branch-data word (the header\n * plus any value words have been skipped by the caller).\n * @param char The current character.\n * @returns The index of the next node, or -1 if no branch is taken.\n */\nexport function determineBranch(decodeTree, current, nodeIndex, char) {\n const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;\n const jumpOffset = current & BinTrieFlags.JUMP_TABLE;\n // Case 1: Single branch or jump table (jumpOffset encodes the first/only char code).\n if (jumpOffset) {\n if (branchCount === 0) {\n // Single branch encoded inline in the jump offset bits.\n return char === jumpOffset ? nodeIndex : -1;\n }\n /*\n * Jump table: branchCount consecutive slots starting at jumpOffset.\n * Unsigned comparison handles both < 0 and >= branchCount in one check.\n */\n const slot = char - jumpOffset;\n if (slot >>> 0 >= branchCount)\n return -1;\n const stored = decodeTree[nodeIndex + slot];\n /*\n * 0 = empty slot (no branch); otherwise the child's offset from the\n * end of the branch array, +1 (end-relative pointers compress\n * better). `& 0xff_ff` mirrors the encoder's uint16 wrap for\n * backreferences to already-encoded nodes.\n */\n return stored === 0\n ? -1\n : (nodeIndex + branchCount + stored - 1) & 0xff_ff;\n }\n /*\n * Case 2: Packed dictionary. Linear scan — over 90% of dict nodes have\n * <= 4 branches in the HTML trie, where the constant-factor savings\n * dominate over binary search's asymptotic edge.\n */\n if (branchCount === 0)\n return -1;\n const packedKeySlots = (branchCount + 1) >> 1;\n const branchEnd = nodeIndex + packedKeySlots + branchCount;\n for (let index = 0; index < branchCount; index++) {\n const packed = decodeTree[nodeIndex + (index >> 1)];\n const key = (packed >> ((index & 1) << 3)) & 0xff;\n if (key === char) {\n const pointerIndex = nodeIndex + packedKeySlots + index;\n // Pointers are relative to the end of the branch data.\n return (branchEnd + decodeTree[pointerIndex]) & 0xff_ff;\n }\n // Keys are sorted; if we've passed `char`, no match is possible.\n if (key > char)\n return -1;\n }\n return -1;\n}\n/**\n * Read the decoded value from a trie node.\n * @param decodeTree The trie.\n * @param nodeIndex The index of the node.\n * @param valueLength The length of the value (1, 2, or 3).\n * @returns The decoded string.\n */\nfunction readTrieValue(decodeTree, nodeIndex, valueLength) {\n if (valueLength === 1) {\n return String.fromCharCode(decodeTree[nodeIndex] & BinTrieFlags.VALUE_MASK);\n }\n if (valueLength === 2) {\n return String.fromCharCode(decodeTree[nodeIndex + 1]);\n }\n return String.fromCharCode(decodeTree[nodeIndex + 1], decodeTree[nodeIndex + 2]);\n}\n/**\n * Parse a numeric entity (`&#DDD;` or `&#xHHH;`).\n *\n * Encodes the result as `(consumed << CONSUMED_SHIFT) | codepoint` (see\n * the packing comment at the top of the file; overlong entities spill\n * their length into `longNumericConsumed`). Returns 0 when no digits were\n * found.\n *\n * This is the sync counterpart of the streaming\n * `EntityDecoder#stateNumericDecimal` / `#stateNumericHex`. Digit parsing\n * matches those methods; only this packed result needs a value clamp.\n * @param input The input string.\n * @param numberStart Index of the `#` character.\n * @param inputLength Cached `input.length`.\n */\nfunction parseNumericEntity(input, numberStart, inputLength) {\n let offset = numberStart + 1; // Skip \"#\"\n let cp = 0;\n let digitStart = offset;\n /*\n * Separate decimal and hexadecimal loops: each multiplies by a constant\n * and runs a single digit test, instead of a per-character base check.\n */\n if (offset < inputLength &&\n (input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {\n offset += 1;\n digitStart = offset;\n while (offset < inputLength) {\n const char = input.charCodeAt(offset);\n if (isNumber(char)) {\n cp = cp * 16 + (char - CharCodes.ZERO);\n }\n else if (isHexadecimalCharacter(char)) {\n cp = cp * 16 + ((char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10);\n }\n else {\n break;\n }\n offset += 1;\n }\n }\n else {\n while (offset < inputLength) {\n const digit = input.charCodeAt(offset) - CharCodes.ZERO;\n if (digit >>> 0 > 9)\n break;\n cp = cp * 10 + digit;\n offset += 1;\n }\n }\n if (offset === digitStart)\n return 0;\n // Include the semicolon in consumed when present.\n if (offset < inputLength && input.charCodeAt(offset) === CharCodes.SEMI) {\n offset += 1;\n }\n /*\n * Clamp out-of-range values to 0x110000 so they fit the 21-bit field\n * and decode to U+FFFD. Lengths at or above CONSUMED_OVERFLOW use the\n * side channel described with the packing constants.\n */\n if (cp > 0x10_ff_ff)\n cp = 0x11_00_00;\n let consumed = offset - numberStart;\n if (consumed >= CONSUMED_OVERFLOW) {\n // eslint-disable-next-line unicorn/no-top-level-assignment-in-function -- deliberate side channel, see `longNumericConsumed`\n longNumericConsumed = consumed;\n consumed = CONSUMED_OVERFLOW;\n }\n return (consumed << CONSUMED_SHIFT) | cp;\n}\n/**\n * Decode all entities in `input` using the HTML trie.\n *\n * Hard-wired to `htmlDecodeTree`: the inline root navigation below assumes\n * the HTML root's jump-table shape, so this must not be generalized to\n * other tries (the XML trie's dictionary root would silently match no\n * entities — `decodeXML` has its own hand-coded fast path instead).\n * @param input The string to decode.\n * @param isStrict Only match semicolon-terminated entities.\n * @param isAttribute Whether to apply attribute-specific parsing rules (disallowing certain non-semicolon terminators).\n * @returns The decoded string.\n */\nfunction decodeWithTrie(input, isStrict, isAttribute) {\n const decodeTree = htmlDecodeTree;\n // Fast path: no entities at all — return input without any allocation.\n let offset = input.indexOf(\"&\");\n if (offset < 0)\n return input;\n const inputLength = input.length;\n /*\n * `chunkStart` marks the start of the next pending slice. Rejected\n * entities don't advance it, so consecutive rejections are stitched\n * into a single `slice` once a real match (or end of input) is hit.\n */\n let chunkStart = 0;\n let result = \"\";\n /*\n * Root navigation fields, hoisted out of the per-entity loop. The HTML\n * root is a multi-branch jump-table covering [A-Za-z]; see the inline\n * first-iteration comment below.\n */\n const root = decodeTree[0];\n const rootJumpOffset = root & BinTrieFlags.JUMP_TABLE;\n const rootBranchCount = (root & BinTrieFlags.BRANCH_LENGTH) >> 7;\n do {\n const entityStart = offset + 1;\n // Quick check: entity names must start with [A-Za-z], numeric with #.\n const firstChar = input.charCodeAt(entityStart);\n let consumed;\n let value;\n if (firstChar === CharCodes.NUM) {\n const packed = parseNumericEntity(input, entityStart, inputLength);\n consumed = unpackConsumed(packed);\n // In strict mode, require semicolon termination.\n if (isStrict &&\n consumed > 0 &&\n input.charCodeAt(entityStart + consumed - 1) !== CharCodes.SEMI) {\n consumed = 0;\n }\n value =\n consumed === 0\n ? \"\"\n : codePointToString(packed & CODE_POINT_MASK);\n }\n else if (isAlpha(firstChar)) {\n consumed = 0;\n value = \"\";\n /*\n * The generator guarantees a jump-table root. Consume the first\n * character directly, then walk from its child.\n */\n const rootSlotIndex = firstChar - rootJumpOffset;\n let nodeIndex;\n if (rootSlotIndex >>> 0 < rootBranchCount) {\n const stored = decodeTree[1 + rootSlotIndex];\n nodeIndex =\n stored === 0 ? -1 : (rootBranchCount + stored) & 0xff_ff;\n }\n else {\n nodeIndex = -1;\n }\n /*\n * Best legacy (no-semicolon) match so far, as trie coordinates.\n * Deferring `readTrieValue` to the end avoids allocating a\n * string for matches that longer matches supersede.\n */\n let bestNodeIndex = 0;\n let bestValueLength = 0;\n let current = nodeIndex < 0 ? 0 : decodeTree[nodeIndex];\n let index = entityStart + 1;\n /*\n * Walk the trie from the root child. The `trie` label lets the\n * inner descent and compact-run loops abandon the entity (and\n * fall through to the legacy/reject handling) directly.\n */\n trie: while (index < inputLength) {\n /*\n * Inline value-less jump tables and single branches. A miss\n * falls through to the recorded legacy match or rejection.\n */\n while (\n // Value-less, non-run node with a nonzero jump offset.\n (current &\n (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) ===\n 0 &&\n (current & BinTrieFlags.JUMP_TABLE) !== 0) {\n const jumpOffset = current & BinTrieFlags.JUMP_TABLE;\n const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;\n if (branchCount === 0) {\n // Single branch encoded inline in the jump offset bits.\n if (input.charCodeAt(index) !== jumpOffset)\n break trie;\n nodeIndex += 1;\n }\n else {\n const slot = input.charCodeAt(index) - jumpOffset;\n if (slot >>> 0 >= branchCount)\n break trie;\n const stored = decodeTree[nodeIndex + 1 + slot];\n if (stored === 0)\n break trie;\n // End-relative: branch data ends at nodeIndex+1+branchCount.\n nodeIndex =\n (nodeIndex + branchCount + stored) & 0xff_ff;\n }\n current = decodeTree[nodeIndex];\n index += 1;\n /*\n * `charCodeAt` past the end returns NaN, which would\n * alias to slot 0 after `>>> 0` — bail out explicitly.\n */\n if (index >= inputLength)\n break trie;\n }\n // FLAG13 without a value marks a compact run.\n if ((current &\n (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) ===\n BinTrieFlags.FLAG13) {\n const runLength = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;\n // Check first char (stored in JUMP_TABLE bits).\n if (input.charCodeAt(index) !==\n (current & BinTrieFlags.JUMP_TABLE)) {\n // eslint-disable-next-line unicorn/no-break-in-nested-loop\n break;\n }\n index += 1;\n // Check remaining characters (packed two per uint16 word).\n const remaining = runLength - 1;\n let wordIndex = nodeIndex + 1;\n let charIndexInPacked = 0;\n /*\n * Process pairs: read one packed word, compare low byte then high byte.\n * No explicit bounds check needed — charCodeAt returns NaN for OOB,\n * which never equals an integer, so the mismatch break fires naturally.\n */\n for (; charIndexInPacked + 1 < remaining; charIndexInPacked += 2) {\n const packed = decodeTree[wordIndex];\n if (input.charCodeAt(index) !== (packed & 0xff))\n break trie;\n index += 1;\n if (input.charCodeAt(index) !== ((packed >> 8) & 0xff))\n break trie;\n index += 1;\n wordIndex += 1;\n }\n // Handle odd trailing char.\n if (charIndexInPacked < remaining) {\n if (input.charCodeAt(index) !==\n (decodeTree[wordIndex] & 0xff))\n // eslint-disable-next-line unicorn/no-break-in-nested-loop\n break;\n index += 1;\n }\n nodeIndex += 1 + (runLength >> 1);\n current = decodeTree[nodeIndex];\n // eslint-disable-next-line unicorn/no-break-in-nested-loop\n continue;\n }\n // Header plus out-of-line value words; 0 means no value.\n const valueLength = current >>> 14;\n const char = input.charCodeAt(index);\n /*\n * Check current node for a value before navigating.\n * This handles both: (a) values reached via compact runs on the\n * previous iteration, and (b) values at regular branch targets.\n */\n if (valueLength !== 0) {\n // If char is `;`, emit immediately.\n if (char === CharCodes.SEMI) {\n consumed = index - entityStart + 1;\n // Inline leaves carry the value in the low 13 bits.\n value =\n valueLength === 1\n ? String.fromCharCode(current & BinTrieFlags.VALUE_MASK)\n : readTrieValue(decodeTree, nodeIndex, valueLength);\n // eslint-disable-next-line unicorn/no-break-in-nested-loop\n break;\n }\n // Record non-terminated (legacy) match (FLAG13 clear = semicolon optional).\n if (!isStrict && (current & BinTrieFlags.FLAG13) === 0) {\n consumed = index - entityStart;\n bestNodeIndex = nodeIndex;\n bestValueLength = valueLength;\n }\n /*\n * A valueLength of 1 means the value is packed inline in the header\n * word — these are always leaf nodes with no branches, so we can\n * stop walking the trie.\n */\n // eslint-disable-next-line unicorn/no-break-in-nested-loop\n if (valueLength === 1)\n break;\n }\n // Navigate to the next node (valueLength || 1: skip past value words, minimum 1 for header).\n const next = determineBranch(decodeTree, current, nodeIndex + (valueLength || 1), char);\n // eslint-disable-next-line unicorn/no-break-in-nested-loop\n if (next < 0)\n break;\n nodeIndex = next;\n current = decodeTree[nodeIndex];\n index += 1;\n }\n /*\n * Post-loop: if the semicolon path didn't set value,\n * check for a final legacy match. The last navigation may\n * have landed on a legacy node whose value hasn't been\n * recorded yet (loop exited before the top-of-loop check\n * could run).\n */\n if (value === \"\") {\n const finalVL = current >>> 14;\n if (finalVL !== 0 &&\n !isStrict &&\n (current & BinTrieFlags.FLAG13) === 0) {\n consumed = index - entityStart;\n bestNodeIndex = nodeIndex;\n bestValueLength = finalVL;\n }\n if (consumed > 0) {\n value = readTrieValue(decodeTree, bestNodeIndex, bestValueLength);\n }\n }\n }\n else {\n consumed = 0;\n value = \"\";\n }\n /*\n * The attribute end-char rule (HTML spec §13.2.5.73) only applies to\n * unterminated *named* references. Semicolon-terminated entities and\n * numeric entities are always accepted, matching EntityDecoder behavior.\n *\n * When `attribute` is false (the common case), short-circuit skips all\n * the unterminated-named checks entirely.\n */\n if (consumed === 0 ||\n (isAttribute &&\n firstChar !== CharCodes.NUM &&\n input.charCodeAt(entityStart + consumed - 1) !==\n CharCodes.SEMI &&\n entityStart + consumed < inputLength &&\n isEntityInAttributeInvalidEnd(input.charCodeAt(entityStart + consumed)))) {\n // Rejected: leave `&` in the pending chunk, scan past it.\n offset = entityStart;\n }\n else {\n if (chunkStart < offset) {\n result += input.slice(chunkStart, offset);\n }\n result += value;\n offset = chunkStart = entityStart + consumed;\n }\n /*\n * Adjacent entities (`&x;&y;`) are common in entity-dense input;\n * checking the single character at `offset` first skips the\n * `indexOf` call (and its per-call overhead) for that case.\n */\n if (input.charCodeAt(offset) !== CharCodes.AMP) {\n offset = input.indexOf(\"&\", offset);\n }\n } while (offset >= 0);\n return result + input.slice(chunkStart);\n}\n/**\n * Decodes an HTML string.\n * @param htmlString The string to decode.\n * @param mode The decoding mode.\n * @returns The decoded string.\n */\nexport function decodeHTML(htmlString, mode = DecodingMode.Legacy) {\n return decodeWithTrie(htmlString, mode === DecodingMode.Strict, mode === DecodingMode.Attribute);\n}\n/**\n * Decodes an HTML string in an attribute.\n * @param htmlAttribute The string to decode.\n * @returns The decoded string.\n */\nexport function decodeHTMLAttribute(htmlAttribute) {\n return decodeWithTrie(htmlAttribute, false, true);\n}\n/**\n * Decodes an HTML string, requiring all entities to be terminated by a semicolon.\n * @param htmlString The string to decode.\n * @returns The decoded string.\n */\nexport function decodeHTMLStrict(htmlString) {\n return decodeWithTrie(htmlString, true, false);\n}\n/**\n * Decodes an XML string, requiring all entities to be terminated by a semicolon.\n *\n * Uses a hand-coded fast path for the 5 XML named entities (amp, lt, gt,\n * quot, apos) plus numeric entities, bypassing the trie entirely.\n * @param xmlString The string to decode.\n * @returns The decoded string.\n */\nexport function decodeXML(xmlString) {\n let offset = xmlString.indexOf(\"&\");\n if (offset < 0)\n return xmlString;\n let lastIndex = 0;\n let result = \"\";\n do {\n const start = offset + 1;\n let consumed = 0;\n let value = \"\";\n const c1 = xmlString.charCodeAt(start);\n if (c1 === CharCodes.NUM) {\n const packed = parseNumericEntity(xmlString, start, xmlString.length);\n consumed = unpackConsumed(packed);\n // XML is always strict — require semicolon.\n if (consumed === 0 ||\n xmlString.charCodeAt(start + consumed - 1) !== CharCodes.SEMI) {\n consumed = 0;\n }\n else {\n const codePoint = packed & CODE_POINT_MASK;\n // Nonzero BMP values below the surrogate range need no replacement.\n value =\n (codePoint - 1) >>> 0 < 0xd7_ff\n ? String.fromCharCode(codePoint)\n : String.fromCodePoint(replaceCodePointXML(codePoint));\n }\n }\n else {\n /* eslint-disable unicorn/no-break-in-nested-loop -- Keep XML name dispatch inline with the decode loop. */\n switch (c1) {\n // &lt; / &gt;\n case 0x6c:\n case 0x67: {\n if (xmlString.charCodeAt(start + 1) === 0x74 &&\n xmlString.charCodeAt(start + 2) === CharCodes.SEMI) {\n consumed = 3;\n value = c1 === 0x6c ? \"<\" : \">\";\n }\n break;\n }\n // &amp; / &apos;\n case 0x61: {\n const c2 = xmlString.charCodeAt(start + 1);\n if (c2 === 0x6d &&\n xmlString.charCodeAt(start + 2) === 0x70 &&\n xmlString.charCodeAt(start + 3) === CharCodes.SEMI) {\n consumed = 4;\n value = \"&\";\n }\n else if (c2 === 0x70 &&\n xmlString.charCodeAt(start + 2) === 0x6f &&\n xmlString.charCodeAt(start + 3) === 0x73 &&\n xmlString.charCodeAt(start + 4) === CharCodes.SEMI) {\n consumed = 5;\n value = \"'\";\n }\n break;\n }\n // &quot;\n case 0x71: {\n if (xmlString.charCodeAt(start + 1) === 0x75 &&\n xmlString.charCodeAt(start + 2) === 0x6f &&\n xmlString.charCodeAt(start + 3) === 0x74 &&\n xmlString.charCodeAt(start + 4) === CharCodes.SEMI) {\n consumed = 5;\n value = '\"';\n }\n break;\n }\n }\n /* eslint-enable unicorn/no-break-in-nested-loop */\n }\n if (consumed > 0) {\n if (lastIndex < offset)\n result += xmlString.slice(lastIndex, offset);\n result += value;\n offset = lastIndex = start + consumed;\n }\n else {\n offset = start;\n }\n /*\n * Adjacent entities (`&x;&y;`) are common in entity-dense input;\n * checking the single character at `lastIndex` first skips the\n * `indexOf` call (and its per-call overhead) for that case.\n */\n offset =\n xmlString.charCodeAt(offset) === CharCodes.AMP\n ? offset\n : xmlString.indexOf(\"&\", offset);\n } while (offset >= 0);\n return result + xmlString.slice(lastIndex);\n}\nexport { replaceCodePoint, replaceCodePointXML, } from \"./decode-codepoint.js\";\n// Re-export for use by eg. htmlparser2\nexport { htmlDecodeTree } from \"./generated/decode-data-html.js\";\nexport { xmlDecodeTree } from \"./generated/decode-data-xml.js\";\n//# sourceMappingURL=decode.js.map","import { DecodingMode, EntityDecoder, htmlDecodeTree, xmlDecodeTree, } from \"entities/decode\";\nvar CharCodes;\n(function (CharCodes) {\n CharCodes[CharCodes[\"Tab\"] = 9] = \"Tab\";\n CharCodes[CharCodes[\"NewLine\"] = 10] = \"NewLine\";\n CharCodes[CharCodes[\"FormFeed\"] = 12] = \"FormFeed\";\n CharCodes[CharCodes[\"CarriageReturn\"] = 13] = \"CarriageReturn\";\n CharCodes[CharCodes[\"Space\"] = 32] = \"Space\";\n CharCodes[CharCodes[\"ExclamationMark\"] = 33] = \"ExclamationMark\";\n CharCodes[CharCodes[\"Number\"] = 35] = \"Number\";\n CharCodes[CharCodes[\"Amp\"] = 38] = \"Amp\";\n CharCodes[CharCodes[\"SingleQuote\"] = 39] = \"SingleQuote\";\n CharCodes[CharCodes[\"DoubleQuote\"] = 34] = \"DoubleQuote\";\n CharCodes[CharCodes[\"Dash\"] = 45] = \"Dash\";\n CharCodes[CharCodes[\"Slash\"] = 47] = \"Slash\";\n CharCodes[CharCodes[\"Zero\"] = 48] = \"Zero\";\n CharCodes[CharCodes[\"Nine\"] = 57] = \"Nine\";\n CharCodes[CharCodes[\"Semi\"] = 59] = \"Semi\";\n CharCodes[CharCodes[\"Lt\"] = 60] = \"Lt\";\n CharCodes[CharCodes[\"Eq\"] = 61] = \"Eq\";\n CharCodes[CharCodes[\"Gt\"] = 62] = \"Gt\";\n CharCodes[CharCodes[\"Questionmark\"] = 63] = \"Questionmark\";\n CharCodes[CharCodes[\"UpperA\"] = 65] = \"UpperA\";\n CharCodes[CharCodes[\"LowerA\"] = 97] = \"LowerA\";\n CharCodes[CharCodes[\"UpperF\"] = 70] = \"UpperF\";\n CharCodes[CharCodes[\"LowerF\"] = 102] = \"LowerF\";\n CharCodes[CharCodes[\"UpperZ\"] = 90] = \"UpperZ\";\n CharCodes[CharCodes[\"LowerZ\"] = 122] = \"LowerZ\";\n CharCodes[CharCodes[\"LowerX\"] = 120] = \"LowerX\";\n CharCodes[CharCodes[\"OpeningSquareBracket\"] = 91] = \"OpeningSquareBracket\";\n})(CharCodes || (CharCodes = {}));\n/** All the states the tokenizer can be in. */\nvar State;\n(function (State) {\n State[State[\"Text\"] = 1] = \"Text\";\n State[State[\"BeforeTagName\"] = 2] = \"BeforeTagName\";\n State[State[\"InTagName\"] = 3] = \"InTagName\";\n State[State[\"InSelfClosingTag\"] = 4] = \"InSelfClosingTag\";\n State[State[\"BeforeClosingTagName\"] = 5] = \"BeforeClosingTagName\";\n State[State[\"InClosingTagName\"] = 6] = \"InClosingTagName\";\n State[State[\"AfterClosingTagName\"] = 7] = \"AfterClosingTagName\";\n // Attributes\n State[State[\"BeforeAttributeName\"] = 8] = \"BeforeAttributeName\";\n State[State[\"InAttributeName\"] = 9] = \"InAttributeName\";\n State[State[\"AfterAttributeName\"] = 10] = \"AfterAttributeName\";\n State[State[\"BeforeAttributeValue\"] = 11] = \"BeforeAttributeValue\";\n State[State[\"InAttributeValueDq\"] = 12] = \"InAttributeValueDq\";\n State[State[\"InAttributeValueSq\"] = 13] = \"InAttributeValueSq\";\n State[State[\"InAttributeValueNq\"] = 14] = \"InAttributeValueNq\";\n // Declarations\n State[State[\"BeforeDeclaration\"] = 15] = \"BeforeDeclaration\";\n State[State[\"InDeclaration\"] = 16] = \"InDeclaration\";\n // Processing instructions\n State[State[\"InProcessingInstruction\"] = 17] = \"InProcessingInstruction\";\n // Comments & CDATA\n State[State[\"BeforeComment\"] = 18] = \"BeforeComment\";\n State[State[\"CDATASequence\"] = 19] = \"CDATASequence\";\n State[State[\"DeclarationSequence\"] = 20] = \"DeclarationSequence\";\n State[State[\"InSpecialComment\"] = 21] = \"InSpecialComment\";\n State[State[\"InCommentLike\"] = 22] = \"InCommentLike\";\n // Special tags\n State[State[\"SpecialStartSequence\"] = 23] = \"SpecialStartSequence\";\n State[State[\"InSpecialTag\"] = 24] = \"InSpecialTag\";\n State[State[\"InPlainText\"] = 25] = \"InPlainText\";\n State[State[\"InEntity\"] = 26] = \"InEntity\";\n})(State || (State = {}));\nfunction isWhitespace(c) {\n return (c === CharCodes.Space ||\n c === CharCodes.NewLine ||\n c === CharCodes.Tab ||\n c === CharCodes.FormFeed ||\n c === CharCodes.CarriageReturn);\n}\nfunction isEndOfTagSection(c) {\n return c === CharCodes.Slash || c === CharCodes.Gt || isWhitespace(c);\n}\nfunction isASCIIAlpha(c) {\n return ((c >= CharCodes.LowerA && c <= CharCodes.LowerZ) ||\n (c >= CharCodes.UpperA && c <= CharCodes.UpperZ));\n}\n/**\n * Quote style used for parsed attributes.\n */\nexport var QuoteType;\n(function (QuoteType) {\n QuoteType[QuoteType[\"NoValue\"] = 0] = \"NoValue\";\n QuoteType[QuoteType[\"Unquoted\"] = 1] = \"Unquoted\";\n QuoteType[QuoteType[\"Single\"] = 2] = \"Single\";\n QuoteType[QuoteType[\"Double\"] = 3] = \"Double\";\n})(QuoteType || (QuoteType = {}));\n/**\n * Sequences used to match longer strings.\n *\n * We don't have `Script`, `Style`, or `Title` here. Instead, we re-use the *End\n * sequences with an increased offset.\n */\nconst Sequences = {\n Empty: new Uint8Array(0),\n Cdata: new Uint8Array([0x43, 0x44, 0x41, 0x54, 0x41, 0x5b]), // CDATA[\n CdataEnd: new Uint8Array([0x5d, 0x5d, 0x3e]), // ]]>\n CommentEnd: new Uint8Array([0x2d, 0x2d, 0x21, 0x3e]), // `--!>`\n Doctype: new Uint8Array([0x64, 0x6f, 0x63, 0x74, 0x79, 0x70, 0x65]), // `doctype`\n IframeEnd: new Uint8Array([0x3c, 0x2f, 0x69, 0x66, 0x72, 0x61, 0x6d, 0x65]), // `</iframe`\n NoembedEnd: new Uint8Array([\n 0x3c, 0x2f, 0x6e, 0x6f, 0x65, 0x6d, 0x62, 0x65, 0x64,\n ]), // `</noembed`\n NoframesEnd: new Uint8Array([\n 0x3c, 0x2f, 0x6e, 0x6f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73,\n ]), // `</noframes`\n Plaintext: new Uint8Array([\n 0x3c, 0x2f, 0x70, 0x6c, 0x61, 0x69, 0x6e, 0x74, 0x65, 0x78, 0x74,\n ]), // `</plaintext`\n ScriptEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74]), // `</script`\n StyleEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x74, 0x79, 0x6c, 0x65]), // `</style`\n TitleEnd: new Uint8Array([0x3c, 0x2f, 0x74, 0x69, 0x74, 0x6c, 0x65]), // `</title`\n TextareaEnd: new Uint8Array([\n 0x3c, 0x2f, 0x74, 0x65, 0x78, 0x74, 0x61, 0x72, 0x65, 0x61,\n ]), // `</textarea`\n XmpEnd: new Uint8Array([0x3c, 0x2f, 0x78, 0x6d, 0x70]), // `</xmp`\n};\n/**\n * Maps the first lowercase character of an HTML tag name to the sequence\n * used for special-tag detection. All sequences share a common layout\n * where index 2 is the first tag-name character, so matching always\n * continues from offset 3.\n */\nconst specialStartSequences = new Map([\n [Sequences.IframeEnd[2], Sequences.IframeEnd],\n [Sequences.NoembedEnd[2], Sequences.NoembedEnd],\n [Sequences.Plaintext[2], Sequences.Plaintext],\n [Sequences.ScriptEnd[2], Sequences.ScriptEnd],\n [Sequences.TitleEnd[2], Sequences.TitleEnd],\n [Sequences.XmpEnd[2], Sequences.XmpEnd],\n]);\n/**\n * Tokenizer implementation used by `Parser`.\n */\nexport default class Tokenizer {\n cbs;\n /** The current state the tokenizer is in. */\n state = State.Text;\n /** The read buffer. */\n buffer = \"\";\n /** The beginning of the section that is currently being read. */\n sectionStart = 0;\n /** The index within the buffer that we are currently looking at. */\n index = 0;\n /** The start of the last entity. */\n entityStart = 0;\n /** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */\n baseState = State.Text;\n /** For special parsing behavior inside of script and style tags. */\n isSpecial = false;\n /** Indicates whether the tokenizer has been paused. */\n running = true;\n /** The offset of the current buffer. */\n offset = 0;\n xmlMode;\n decodeEntities;\n recognizeSelfClosing;\n entityDecoder;\n constructor({ xmlMode = false, decodeEntities = true, recognizeSelfClosing = xmlMode, }, cbs) {\n this.cbs = cbs;\n this.xmlMode = xmlMode;\n this.decodeEntities = decodeEntities;\n this.recognizeSelfClosing = recognizeSelfClosing;\n this.entityDecoder = new EntityDecoder(xmlMode ? xmlDecodeTree : htmlDecodeTree, (cp, consumed) => this.emitCodePoint(cp, consumed));\n }\n reset() {\n this.state = State.Text;\n this.buffer = \"\";\n this.sectionStart = 0;\n this.index = 0;\n this.baseState = State.Text;\n this.isSpecial = false;\n this.currentSequence = Sequences.Empty;\n this.sequenceIndex = 0;\n this.running = true;\n this.offset = 0;\n }\n write(chunk) {\n this.offset += this.buffer.length;\n this.buffer = chunk;\n this.parse();\n }\n end() {\n if (this.running)\n this.finish();\n }\n pause() {\n this.running = false;\n }\n resume() {\n this.running = true;\n if (this.index < this.buffer.length + this.offset) {\n this.parse();\n }\n }\n stateText(c) {\n if (c === CharCodes.Lt ||\n (!this.decodeEntities && this.fastForwardTo(CharCodes.Lt))) {\n if (this.index > this.sectionStart) {\n this.cbs.ontext(this.sectionStart, this.index);\n }\n this.state = State.BeforeTagName;\n this.sectionStart = this.index;\n }\n else if (this.decodeEntities && c === CharCodes.Amp) {\n this.startEntity();\n }\n }\n currentSequence = Sequences.Empty;\n sequenceIndex = 0;\n enterTagBody() {\n if (this.currentSequence === Sequences.Plaintext) {\n this.currentSequence = Sequences.Empty;\n this.state = State.InPlainText;\n }\n else if (this.isSpecial) {\n this.state = State.InSpecialTag;\n this.sequenceIndex = 0;\n }\n else {\n this.state = State.Text;\n }\n }\n /**\n * Match the opening tag name against an HTML text-only tag sequence.\n *\n * Some tags share an initial prefix (`script`/`style`, `title`/`textarea`,\n * `noembed`/`noframes`), so we may switch to an alternate sequence at the\n * first distinguishing byte. On a successful full match we fall back to\n * the normal tag-name state; a later `>` will enter raw-text, RCDATA, or\n * plaintext mode based on `currentSequence` / `isSpecial`.\n * @param c Current character code point.\n */\n stateSpecialStartSequence(c) {\n const lower = c | 0x20;\n // Still matching — check for an alternate sequence at branch points.\n if (this.sequenceIndex < this.currentSequence.length) {\n if (lower === this.currentSequence[this.sequenceIndex]) {\n this.sequenceIndex++;\n return;\n }\n if (this.sequenceIndex === 3) {\n if (this.currentSequence === Sequences.ScriptEnd &&\n lower === Sequences.StyleEnd[3]) {\n this.currentSequence = Sequences.StyleEnd;\n this.sequenceIndex = 4;\n return;\n }\n if (this.currentSequence === Sequences.TitleEnd &&\n lower === Sequences.TextareaEnd[3]) {\n this.currentSequence = Sequences.TextareaEnd;\n this.sequenceIndex = 4;\n return;\n }\n }\n else if (this.sequenceIndex === 4 &&\n this.currentSequence === Sequences.NoembedEnd &&\n lower === Sequences.NoframesEnd[4]) {\n this.currentSequence = Sequences.NoframesEnd;\n this.sequenceIndex = 5;\n return;\n }\n }\n else if (isEndOfTagSection(c)) {\n // Full match on a valid tag boundary — keep the sequence.\n this.sequenceIndex = 0;\n this.state = State.InTagName;\n this.stateInTagName(c);\n return;\n }\n // No match — abandon special-tag detection.\n this.isSpecial = false;\n this.currentSequence = Sequences.Empty;\n this.sequenceIndex = 0;\n this.state = State.InTagName;\n this.stateInTagName(c);\n }\n stateCDATASequence(c) {\n if (c === Sequences.Cdata[this.sequenceIndex]) {\n if (++this.sequenceIndex === Sequences.Cdata.length) {\n this.state = State.InCommentLike;\n this.currentSequence = Sequences.CdataEnd;\n this.sequenceIndex = 0;\n this.sectionStart = this.index + 1;\n }\n }\n else {\n this.sequenceIndex = 0;\n if (this.xmlMode) {\n this.state = State.InDeclaration;\n this.stateInDeclaration(c); // Reconsume the character\n }\n else {\n this.state = State.InSpecialComment;\n this.stateInSpecialComment(c); // Reconsume the character\n }\n }\n }\n /**\n * When we wait for one specific character, we can speed things up\n * by skipping through the buffer until we find it.\n * @param c Current character code point.\n * @returns Whether the character was found.\n */\n fastForwardTo(c) {\n while (++this.index < this.buffer.length + this.offset) {\n if (this.buffer.charCodeAt(this.index - this.offset) === c) {\n return true;\n }\n }\n /*\n * We increment the index at the end of the `parse` loop,\n * so set it to `buffer.length - 1` here.\n *\n * TODO: Refactor `parse` to increment index before calling states.\n */\n this.index = this.buffer.length + this.offset - 1;\n return false;\n }\n /**\n * Emit a comment token and return to the text state.\n * @param offset Number of characters in the end sequence that have already been matched.\n */\n emitComment(offset) {\n this.cbs.oncomment(this.sectionStart, this.index, offset);\n this.sequenceIndex = 0;\n this.sectionStart = this.index + 1;\n this.state = State.Text;\n }\n /**\n * Comments and CDATA end with `-->` and `]]>`.\n *\n * Their common qualities are:\n * - Their end sequences have a distinct character they start with.\n * - That character is then repeated, so we have to check multiple repeats.\n * - All characters but the start character of the sequence can be skipped.\n * @param c Current character code point.\n */\n stateInCommentLike(c) {\n if (!this.xmlMode &&\n this.currentSequence === Sequences.CommentEnd &&\n this.sequenceIndex <= 1 &&\n /*\n * We're still at the very start of the comment: the only\n * characters consumed since `<!--` are the dashes that\n * advanced sequenceIndex (0 for `<!-->`, 1 for `<!--->`).\n */\n this.index === this.sectionStart + this.sequenceIndex &&\n c === CharCodes.Gt) {\n // Abruptly closed empty HTML comment.\n this.emitComment(this.sequenceIndex);\n }\n else if (this.currentSequence === Sequences.CommentEnd &&\n this.sequenceIndex === 2 &&\n c === CharCodes.Gt) {\n // `!` is optional here, so the same sequence also accepts `-->`.\n this.emitComment(2);\n }\n else if (this.currentSequence === Sequences.CommentEnd &&\n this.sequenceIndex === this.currentSequence.length - 1 &&\n c !== CharCodes.Gt) {\n this.sequenceIndex = Number(c === CharCodes.Dash);\n }\n else if (c === this.currentSequence[this.sequenceIndex]) {\n if (++this.sequenceIndex === this.currentSequence.length) {\n if (this.currentSequence === Sequences.CdataEnd) {\n this.cbs.oncdata(this.sectionStart, this.index, 2);\n }\n else {\n this.cbs.oncomment(this.sectionStart, this.index, 3);\n }\n this.sequenceIndex = 0;\n this.sectionStart = this.index + 1;\n this.state = State.Text;\n }\n }\n else if (this.sequenceIndex === 0) {\n // Fast-forward to the first character of the sequence\n if (this.fastForwardTo(this.currentSequence[0])) {\n this.sequenceIndex = 1;\n }\n }\n else if (c !== this.currentSequence[this.sequenceIndex - 1]) {\n // Allow long sequences, eg. --->, ]]]>\n this.sequenceIndex = 0;\n }\n }\n /**\n * HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a tag name.\n *\n * XML allows a lot more characters here (@see https://www.w3.org/TR/REC-xml/#NT-NameStartChar).\n * We allow anything that wouldn't end the tag.\n * @param c Current character code point.\n */\n isTagStartChar(c) {\n return this.xmlMode ? !isEndOfTagSection(c) : isASCIIAlpha(c);\n }\n /**\n * Scan raw-text / RCDATA content for the matching end tag.\n *\n * For RCDATA tags (`<title>`, `<textarea>`) entities are decoded inline.\n * For raw-text tags (`<script>`, `<style>`, etc.) we fast-forward to `<`.\n * @param c Current character code point.\n */\n stateInSpecialTag(c) {\n if (this.sequenceIndex === this.currentSequence.length) {\n if (isEndOfTagSection(c)) {\n const endOfText = this.index - this.currentSequence.length;\n if (this.sectionStart < endOfText) {\n // Spoof the index so that reported locations match up.\n const actualIndex = this.index;\n this.index = endOfText;\n this.cbs.ontext(this.sectionStart, endOfText);\n this.index = actualIndex;\n }\n this.isSpecial = false;\n this.sectionStart = endOfText + 2; // Skip over the `</`\n this.stateInClosingTagName(c);\n return; // We are done; skip the rest of the function.\n }\n this.sequenceIndex = 0;\n }\n if ((c | 0x20) === this.currentSequence[this.sequenceIndex]) {\n this.sequenceIndex += 1;\n }\n else if (this.sequenceIndex === 0) {\n if (this.currentSequence === Sequences.TitleEnd ||\n this.currentSequence === Sequences.TextareaEnd) {\n // RCDATA tags have to parse entities while still looking for their end tag.\n if (this.decodeEntities && c === CharCodes.Amp) {\n this.startEntity();\n }\n }\n else if (this.fastForwardTo(CharCodes.Lt)) {\n // Outside of RCDATA tags, we can fast-forward.\n this.sequenceIndex = 1;\n }\n }\n else {\n // If we see a `<`, set the sequence index to 1; useful for eg. `<</script>`.\n this.sequenceIndex = Number(c === CharCodes.Lt);\n }\n }\n stateBeforeTagName(c) {\n if (c === CharCodes.ExclamationMark) {\n this.state = State.BeforeDeclaration;\n this.sectionStart = this.index + 1;\n }\n else if (c === CharCodes.Questionmark) {\n if (this.xmlMode) {\n this.state = State.InProcessingInstruction;\n this.sequenceIndex = 0;\n this.sectionStart = this.index + 1;\n }\n else {\n this.state = State.InSpecialComment;\n this.sectionStart = this.index;\n }\n }\n else if (this.isTagStartChar(c)) {\n this.sectionStart = this.index;\n const special = this.xmlMode || this.cbs.isInForeignContext?.()\n ? undefined\n : specialStartSequences.get(c | 0x20);\n if (special === undefined) {\n this.state = State.InTagName;\n }\n else {\n this.isSpecial = true;\n this.currentSequence = special;\n this.sequenceIndex = 3;\n this.state = State.SpecialStartSequence;\n }\n }\n else if (c === CharCodes.Slash) {\n this.state = State.BeforeClosingTagName;\n }\n else {\n this.state = State.Text;\n this.stateText(c);\n }\n }\n stateInTagName(c) {\n if (isEndOfTagSection(c)) {\n this.cbs.onopentagname(this.sectionStart, this.index);\n this.sectionStart = -1;\n this.state = State.BeforeAttributeName;\n this.stateBeforeAttributeName(c);\n }\n }\n stateBeforeClosingTagName(c) {\n if (isWhitespace(c)) {\n if (this.xmlMode) {\n // Ignore\n }\n else {\n this.state = State.InSpecialComment;\n this.sectionStart = this.index;\n }\n }\n else if (c === CharCodes.Gt) {\n this.state = State.Text;\n if (!this.xmlMode) {\n this.sectionStart = this.index + 1;\n }\n }\n else {\n this.state = this.isTagStartChar(c)\n ? State.InClosingTagName\n : State.InSpecialComment;\n this.sectionStart = this.index;\n }\n }\n stateInClosingTagName(c) {\n if (isEndOfTagSection(c)) {\n this.cbs.onclosetag(this.sectionStart, this.index);\n this.sectionStart = -1;\n this.state = State.AfterClosingTagName;\n this.stateAfterClosingTagName(c);\n }\n }\n stateAfterClosingTagName(c) {\n // Skip everything until \">\"\n if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {\n this.state = State.Text;\n this.sectionStart = this.index + 1;\n }\n }\n stateBeforeAttributeName(c) {\n if (c === CharCodes.Gt) {\n this.cbs.onopentagend(this.index);\n this.enterTagBody();\n this.sectionStart = this.index + 1;\n }\n else if (c === CharCodes.Slash) {\n this.state = State.InSelfClosingTag;\n }\n else if (!isWhitespace(c)) {\n this.state = State.InAttributeName;\n this.sectionStart = this.index;\n }\n }\n /**\n * Handle `/` before `>` in an opening tag.\n *\n * In HTML mode, text-only tags ignore the self-closing flag and still enter\n * their raw-text/RCDATA/plaintext state unless self-closing tags are being\n * recognized. In XML mode, or for ordinary tags, the tokenizer returns to\n * regular text parsing after emitting the self-closing callback.\n * @param c Current character code point.\n */\n stateInSelfClosingTag(c) {\n if (c === CharCodes.Gt) {\n this.cbs.onselfclosingtag(this.index);\n this.sectionStart = this.index + 1;\n if (!this.recognizeSelfClosing) {\n this.enterTagBody();\n return;\n }\n this.state = State.Text;\n this.isSpecial = false; // Reset special state, in case of self-closing special tags\n this.currentSequence = Sequences.Empty;\n }\n else if (!isWhitespace(c)) {\n this.state = State.BeforeAttributeName;\n this.stateBeforeAttributeName(c);\n }\n }\n stateInAttributeName(c) {\n if (c === CharCodes.Eq || isEndOfTagSection(c)) {\n this.cbs.onattribname(this.sectionStart, this.index);\n this.sectionStart = this.index;\n this.state = State.AfterAttributeName;\n this.stateAfterAttributeName(c);\n }\n }\n stateAfterAttributeName(c) {\n if (c === CharCodes.Eq) {\n this.state = State.BeforeAttributeValue;\n }\n else if (c === CharCodes.Slash || c === CharCodes.Gt) {\n this.cbs.onattribend(QuoteType.NoValue, this.sectionStart);\n this.sectionStart = -1;\n this.state = State.BeforeAttributeName;\n this.stateBeforeAttributeName(c);\n }\n else if (!isWhitespace(c)) {\n this.cbs.onattribend(QuoteType.NoValue, this.sectionStart);\n this.state = State.InAttributeName;\n this.sectionStart = this.index;\n }\n }\n stateBeforeAttributeValue(c) {\n if (c === CharCodes.DoubleQuote) {\n this.state = State.InAttributeValueDq;\n this.sectionStart = this.index + 1;\n }\n else if (c === CharCodes.SingleQuote) {\n this.state = State.InAttributeValueSq;\n this.sectionStart = this.index + 1;\n }\n else if (!isWhitespace(c)) {\n this.sectionStart = this.index;\n this.state = State.InAttributeValueNq;\n this.stateInAttributeValueNoQuotes(c); // Reconsume token\n }\n }\n handleInAttributeValue(c, quote) {\n if (c === quote ||\n (!this.decodeEntities && this.fastForwardTo(quote))) {\n this.cbs.onattribdata(this.sectionStart, this.index);\n this.sectionStart = -1;\n this.cbs.onattribend(quote === CharCodes.DoubleQuote\n ? QuoteType.Double\n : QuoteType.Single, this.index + 1);\n this.state = State.BeforeAttributeName;\n }\n else if (this.decodeEntities && c === CharCodes.Amp) {\n this.startEntity();\n }\n }\n stateInAttributeValueDoubleQuotes(c) {\n this.handleInAttributeValue(c, CharCodes.DoubleQuote);\n }\n stateInAttributeValueSingleQuotes(c) {\n this.handleInAttributeValue(c, CharCodes.SingleQuote);\n }\n stateInAttributeValueNoQuotes(c) {\n if (isWhitespace(c) || c === CharCodes.Gt) {\n this.cbs.onattribdata(this.sectionStart, this.index);\n this.sectionStart = -1;\n this.cbs.onattribend(QuoteType.Unquoted, this.index);\n this.state = State.BeforeAttributeName;\n this.stateBeforeAttributeName(c);\n }\n else if (this.decodeEntities && c === CharCodes.Amp) {\n this.startEntity();\n }\n }\n /**\n * Distinguish between CDATA, declarations, HTML comments, and HTML bogus\n * comments after `<!`.\n *\n * In HTML mode, only real comments and doctypes stay on declaration paths;\n * everything else becomes a bogus comment terminated by the next `>`.\n * @param c Current character code point.\n */\n stateBeforeDeclaration(c) {\n if (c === CharCodes.OpeningSquareBracket) {\n this.state = State.CDATASequence;\n this.sequenceIndex = 0;\n }\n else if (this.xmlMode) {\n this.state =\n c === CharCodes.Dash\n ? State.BeforeComment\n : State.InDeclaration;\n }\n else if ((c | 0x20) === Sequences.Doctype[0]) {\n this.state = State.DeclarationSequence;\n this.currentSequence = Sequences.Doctype;\n this.sequenceIndex = 1;\n }\n else if (c === CharCodes.Gt) {\n this.cbs.oncomment(this.sectionStart, this.index, 0);\n this.state = State.Text;\n this.sectionStart = this.index + 1;\n }\n else if (c === CharCodes.Dash) {\n this.state = State.BeforeComment;\n }\n else {\n this.state = State.InSpecialComment;\n }\n }\n /**\n * Continue matching `doctype` after `<!d`.\n *\n * A full `doctype` match stays on the declaration path; any other name falls\n * back to an HTML bogus comment, which matches browser behavior for\n * non-doctype `<!...>` constructs.\n * @param c Current character code point.\n */\n stateDeclarationSequence(c) {\n if (this.sequenceIndex === this.currentSequence.length) {\n this.state = State.InDeclaration;\n this.stateInDeclaration(c);\n }\n else if ((c | 0x20) === this.currentSequence[this.sequenceIndex]) {\n this.sequenceIndex += 1;\n }\n else if (c === CharCodes.Gt) {\n this.cbs.oncomment(this.sectionStart, this.index, 0);\n this.state = State.Text;\n this.sectionStart = this.index + 1;\n }\n else {\n this.state = State.InSpecialComment;\n }\n }\n stateInDeclaration(c) {\n if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {\n this.cbs.ondeclaration(this.sectionStart, this.index);\n this.state = State.Text;\n this.sectionStart = this.index + 1;\n }\n }\n /**\n * XML processing instructions (`<?...?>`).\n *\n * In HTML mode `<?` is routed to `InSpecialComment` instead, so this\n * state is only reachable in XML mode.\n * @param c Current character code point.\n */\n stateInProcessingInstruction(c) {\n if (c === CharCodes.Questionmark) {\n // Remember that we just consumed `?`, so the next `>` closes the PI.\n this.sequenceIndex = 1;\n }\n else if (c === CharCodes.Gt && this.sequenceIndex === 1) {\n this.cbs.onprocessinginstruction(this.sectionStart, this.index - 1);\n this.sequenceIndex = 0;\n this.state = State.Text;\n this.sectionStart = this.index + 1;\n }\n else {\n // Keep scanning for the next `?`, which can start a closing `?>`.\n this.sequenceIndex = Number(this.fastForwardTo(CharCodes.Questionmark));\n }\n }\n stateBeforeComment(c) {\n if (c === CharCodes.Dash) {\n this.state = State.InCommentLike;\n this.currentSequence = Sequences.CommentEnd;\n this.sequenceIndex = 0;\n this.sectionStart = this.index + 1;\n }\n else if (this.xmlMode) {\n this.state = State.InDeclaration;\n }\n else if (c === CharCodes.Gt) {\n this.cbs.oncomment(this.sectionStart, this.index, 0);\n this.state = State.Text;\n this.sectionStart = this.index + 1;\n }\n else {\n this.state = State.InSpecialComment;\n }\n }\n stateInSpecialComment(c) {\n if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {\n this.cbs.oncomment(this.sectionStart, this.index, 0);\n this.state = State.Text;\n this.sectionStart = this.index + 1;\n }\n }\n startEntity() {\n this.baseState = this.state;\n this.state = State.InEntity;\n this.entityStart = this.index;\n this.entityDecoder.startEntity(this.xmlMode\n ? DecodingMode.Strict\n : this.baseState === State.Text ||\n this.baseState === State.InSpecialTag\n ? DecodingMode.Legacy\n : DecodingMode.Attribute);\n }\n stateInEntity() {\n const indexInBuffer = this.index - this.offset;\n const length = this.entityDecoder.write(this.buffer, indexInBuffer);\n // If `length` is positive, we are done with the entity.\n if (length >= 0) {\n this.state = this.baseState;\n if (length === 0) {\n this.index -= 1;\n }\n }\n else {\n if (indexInBuffer < this.buffer.length &&\n this.buffer.charCodeAt(indexInBuffer) === CharCodes.Amp) {\n this.state = this.baseState;\n this.index -= 1;\n return;\n }\n // Mark buffer as consumed.\n this.index = this.offset + this.buffer.length - 1;\n }\n }\n /**\n * Remove data that has already been consumed from the buffer.\n */\n cleanup() {\n // If we are inside of text or attributes, emit what we already have.\n if (this.running && this.sectionStart !== this.index) {\n if (this.state === State.Text ||\n this.state === State.InPlainText ||\n (this.state === State.InSpecialTag && this.sequenceIndex === 0)) {\n this.cbs.ontext(this.sectionStart, this.index);\n this.sectionStart = this.index;\n }\n else if (this.state === State.InAttributeValueDq ||\n this.state === State.InAttributeValueSq ||\n this.state === State.InAttributeValueNq) {\n this.cbs.onattribdata(this.sectionStart, this.index);\n this.sectionStart = this.index;\n }\n }\n }\n shouldContinue() {\n return this.index < this.buffer.length + this.offset && this.running;\n }\n /**\n * Iterates through the buffer, calling the function corresponding to the current state.\n *\n * States that are more likely to be hit are higher up, as a performance improvement.\n */\n parse() {\n while (this.shouldContinue()) {\n const c = this.buffer.charCodeAt(this.index - this.offset);\n switch (this.state) {\n case State.Text: {\n this.stateText(c);\n break;\n }\n case State.InPlainText: {\n // Skip to end of buffer; cleanup() emits the text.\n this.index = this.buffer.length + this.offset - 1;\n break;\n }\n case State.SpecialStartSequence: {\n this.stateSpecialStartSequence(c);\n break;\n }\n case State.InSpecialTag: {\n this.stateInSpecialTag(c);\n break;\n }\n case State.CDATASequence: {\n this.stateCDATASequence(c);\n break;\n }\n case State.DeclarationSequence: {\n this.stateDeclarationSequence(c);\n break;\n }\n case State.InAttributeValueDq: {\n this.stateInAttributeValueDoubleQuotes(c);\n break;\n }\n case State.InAttributeName: {\n this.stateInAttributeName(c);\n break;\n }\n case State.InCommentLike: {\n this.stateInCommentLike(c);\n break;\n }\n case State.InSpecialComment: {\n this.stateInSpecialComment(c);\n break;\n }\n case State.BeforeAttributeName: {\n this.stateBeforeAttributeName(c);\n break;\n }\n case State.InTagName: {\n this.stateInTagName(c);\n break;\n }\n case State.InClosingTagName: {\n this.stateInClosingTagName(c);\n break;\n }\n case State.BeforeTagName: {\n this.stateBeforeTagName(c);\n break;\n }\n case State.AfterAttributeName: {\n this.stateAfterAttributeName(c);\n break;\n }\n case State.InAttributeValueSq: {\n this.stateInAttributeValueSingleQuotes(c);\n break;\n }\n case State.BeforeAttributeValue: {\n this.stateBeforeAttributeValue(c);\n break;\n }\n case State.BeforeClosingTagName: {\n this.stateBeforeClosingTagName(c);\n break;\n }\n case State.AfterClosingTagName: {\n this.stateAfterClosingTagName(c);\n break;\n }\n case State.InAttributeValueNq: {\n this.stateInAttributeValueNoQuotes(c);\n break;\n }\n case State.InSelfClosingTag: {\n this.stateInSelfClosingTag(c);\n break;\n }\n case State.InDeclaration: {\n this.stateInDeclaration(c);\n break;\n }\n case State.BeforeDeclaration: {\n this.stateBeforeDeclaration(c);\n break;\n }\n case State.BeforeComment: {\n this.stateBeforeComment(c);\n break;\n }\n case State.InProcessingInstruction: {\n this.stateInProcessingInstruction(c);\n break;\n }\n case State.InEntity: {\n this.stateInEntity();\n break;\n }\n }\n this.index++;\n }\n this.cleanup();\n }\n finish() {\n if (this.state === State.InEntity) {\n this.entityDecoder.end();\n this.state = this.baseState;\n }\n this.handleTrailingData();\n this.cbs.onend();\n }\n handleTrailingCommentLikeData(endIndex) {\n if (this.state !== State.InCommentLike) {\n return false;\n }\n if (this.currentSequence === Sequences.CdataEnd) {\n if (this.xmlMode) {\n if (this.sectionStart < endIndex) {\n this.cbs.oncdata(this.sectionStart, endIndex, 0);\n }\n }\n else {\n /* In HTML mode, unclosed CDATA is a bogus comment. */\n const cdataStart = this.sectionStart - Sequences.Cdata.length - 1;\n this.cbs.oncomment(cdataStart, endIndex, 0);\n }\n }\n else {\n const offset = this.xmlMode\n ? 0\n : Math.min(this.sequenceIndex, Sequences.CommentEnd.length - 1);\n this.cbs.oncomment(this.sectionStart, endIndex, offset);\n }\n return true;\n }\n handleTrailingMarkupDeclaration(endIndex) {\n if (this.xmlMode) {\n switch (this.state) {\n case State.InSpecialComment:\n case State.BeforeComment:\n case State.CDATASequence:\n case State.DeclarationSequence:\n case State.InDeclaration: {\n this.cbs.ontext(this.sectionStart, endIndex);\n return true;\n }\n default: {\n return false;\n }\n }\n }\n switch (this.state) {\n case State.BeforeDeclaration:\n case State.InSpecialComment:\n case State.BeforeComment:\n case State.CDATASequence: {\n this.cbs.oncomment(this.sectionStart, endIndex, 0);\n return true;\n }\n case State.DeclarationSequence: {\n if (this.sequenceIndex !== Sequences.Doctype.length) {\n this.cbs.oncomment(this.sectionStart, endIndex, 0);\n }\n return true;\n }\n case State.InDeclaration: {\n return true;\n }\n default: {\n return false;\n }\n }\n }\n /** Handle any trailing data. */\n handleTrailingData() {\n const endIndex = this.buffer.length + this.offset;\n if (this.handleTrailingCommentLikeData(endIndex) ||\n this.handleTrailingMarkupDeclaration(endIndex)) {\n return;\n }\n // If there is no remaining data, we are done.\n if (this.sectionStart >= endIndex) {\n return;\n }\n switch (this.state) {\n case State.InTagName:\n case State.BeforeAttributeName:\n case State.BeforeAttributeValue:\n case State.AfterAttributeName:\n case State.InAttributeName:\n case State.InAttributeValueSq:\n case State.InAttributeValueDq:\n case State.InAttributeValueNq:\n case State.InClosingTagName: {\n /*\n * If we are currently in an opening or closing tag, us not calling the\n * respective callback signals that the tag should be ignored.\n */\n break;\n }\n default: {\n this.cbs.ontext(this.sectionStart, endIndex);\n }\n }\n }\n emitCodePoint(cp, consumed) {\n if (this.baseState !== State.Text &&\n this.baseState !== State.InSpecialTag) {\n if (this.sectionStart < this.entityStart) {\n this.cbs.onattribdata(this.sectionStart, this.entityStart);\n }\n this.sectionStart = this.entityStart + consumed;\n this.index = this.sectionStart - 1;\n this.cbs.onattribentity(cp);\n }\n else {\n if (this.sectionStart < this.entityStart) {\n this.cbs.ontext(this.sectionStart, this.entityStart);\n }\n this.sectionStart = this.entityStart + consumed;\n this.index = this.sectionStart - 1;\n this.cbs.ontextentity(cp, this.sectionStart);\n }\n }\n}\n//# sourceMappingURL=Tokenizer.js.map","const { fromCodePoint } = String;\nimport Tokenizer, { QuoteType } from \"./Tokenizer.js\";\nconst formTags = new Set([\n \"input\",\n \"option\",\n \"optgroup\",\n \"select\",\n \"button\",\n \"datalist\",\n \"textarea\",\n]);\nconst pTag = new Set([\"p\"]);\nconst headingTags = new Set([\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"p\"]);\nconst tableSectionTags = new Set([\"thead\", \"tbody\"]);\nconst ddtTags = new Set([\"dd\", \"dt\"]);\nconst rtpTags = new Set([\"rt\", \"rp\"]);\nconst openImpliesClose = new Map([\n [\"tr\", new Set([\"tr\", \"th\", \"td\"])],\n [\"th\", new Set([\"th\"])],\n [\"td\", new Set([\"thead\", \"th\", \"td\"])],\n [\"body\", new Set([\"head\", \"link\", \"script\"])],\n [\"a\", new Set([\"a\"])],\n [\"li\", new Set([\"li\"])],\n [\"p\", pTag],\n [\"h1\", headingTags],\n [\"h2\", headingTags],\n [\"h3\", headingTags],\n [\"h4\", headingTags],\n [\"h5\", headingTags],\n [\"h6\", headingTags],\n [\"select\", formTags],\n [\"input\", formTags],\n [\"output\", formTags],\n [\"button\", formTags],\n [\"datalist\", formTags],\n [\"textarea\", formTags],\n [\"option\", new Set([\"option\"])],\n [\"optgroup\", new Set([\"optgroup\", \"option\"])],\n [\"dd\", ddtTags],\n [\"dt\", ddtTags],\n [\"address\", pTag],\n [\"article\", pTag],\n [\"aside\", pTag],\n [\"blockquote\", pTag],\n [\"details\", pTag],\n [\"div\", pTag],\n [\"dl\", pTag],\n [\"fieldset\", pTag],\n [\"figcaption\", pTag],\n [\"figure\", pTag],\n [\"footer\", pTag],\n [\"form\", pTag],\n [\"header\", pTag],\n [\"hr\", pTag],\n [\"main\", pTag],\n [\"nav\", pTag],\n [\"ol\", pTag],\n [\"pre\", pTag],\n [\"section\", pTag],\n [\"table\", pTag],\n [\"ul\", pTag],\n [\"rt\", rtpTags],\n [\"rp\", rtpTags],\n [\"tbody\", tableSectionTags],\n [\"tfoot\", tableSectionTags],\n]);\nconst DOCUMENT_TYPE = \"doctype\";\nconst voidElements = new Set([\n \"area\",\n \"base\",\n \"basefont\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"frame\",\n \"hr\",\n \"img\",\n \"input\",\n \"isindex\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\nconst foreignContextElements = new Set([\"math\", \"svg\"]);\n/**\n * Elements that can be used to integrate HTML content within foreign namespaces (e.g., SVG or MathML).\n *\n * Entries must use the SVG-adjusted casing (e.g. \"foreignObject\" not\n * \"foreignobject\") since they are compared against adjusted tag names.\n */\nconst htmlIntegrationElements = new Set([\n \"mi\",\n \"mo\",\n \"mn\",\n \"ms\",\n \"mtext\",\n \"annotation-xml\",\n \"foreignObject\",\n \"desc\",\n \"title\",\n]);\nconst svgTagNameAdjustments = new Map([\n [\"altglyph\", \"altGlyph\"],\n [\"altglyphdef\", \"altGlyphDef\"],\n [\"altglyphitem\", \"altGlyphItem\"],\n [\"animatecolor\", \"animateColor\"],\n [\"animatemotion\", \"animateMotion\"],\n [\"animatetransform\", \"animateTransform\"],\n [\"clippath\", \"clipPath\"],\n [\"feblend\", \"feBlend\"],\n [\"fecolormatrix\", \"feColorMatrix\"],\n [\"fecomponenttransfer\", \"feComponentTransfer\"],\n [\"fecomposite\", \"feComposite\"],\n [\"feconvolvematrix\", \"feConvolveMatrix\"],\n [\"fediffuselighting\", \"feDiffuseLighting\"],\n [\"fedisplacementmap\", \"feDisplacementMap\"],\n [\"fedistantlight\", \"feDistantLight\"],\n [\"fedropshadow\", \"feDropShadow\"],\n [\"feflood\", \"feFlood\"],\n [\"fefunca\", \"feFuncA\"],\n [\"fefuncb\", \"feFuncB\"],\n [\"fefuncg\", \"feFuncG\"],\n [\"fefuncr\", \"feFuncR\"],\n [\"fegaussianblur\", \"feGaussianBlur\"],\n [\"feimage\", \"feImage\"],\n [\"femerge\", \"feMerge\"],\n [\"femergenode\", \"feMergeNode\"],\n [\"femorphology\", \"feMorphology\"],\n [\"feoffset\", \"feOffset\"],\n [\"fepointlight\", \"fePointLight\"],\n [\"fespecularlighting\", \"feSpecularLighting\"],\n [\"fespotlight\", \"feSpotLight\"],\n [\"fetile\", \"feTile\"],\n [\"feturbulence\", \"feTurbulence\"],\n [\"foreignobject\", \"foreignObject\"],\n [\"glyphref\", \"glyphRef\"],\n [\"lineargradient\", \"linearGradient\"],\n [\"radialgradient\", \"radialGradient\"],\n [\"textpath\", \"textPath\"],\n]);\nvar ForeignContext;\n(function (ForeignContext) {\n ForeignContext[ForeignContext[\"None\"] = 0] = \"None\";\n ForeignContext[ForeignContext[\"Svg\"] = 1] = \"Svg\";\n ForeignContext[ForeignContext[\"MathML\"] = 2] = \"MathML\";\n})(ForeignContext || (ForeignContext = {}));\nconst reNameEnd = /\\s|\\//;\n/**\n * Incremental parser implementation.\n */\nexport class Parser {\n options;\n /** The start index of the last event. */\n startIndex = 0;\n /** The end index of the last event. */\n endIndex = 0;\n /**\n * Store the start index of the current open tag,\n * so we can update the start index for attributes.\n */\n openTagStart = 0;\n tagname = \"\";\n attribname = \"\";\n attribvalue = \"\";\n attribs = null;\n stack = [];\n foreignContext;\n cbs;\n lowerCaseTagNames;\n lowerCaseAttributeNames;\n recognizeSelfClosing;\n /** We are parsing HTML. Inverse of the `xmlMode` option. */\n htmlMode;\n tokenizer;\n buffers = [];\n bufferOffset = 0;\n /** The index of the last written buffer. Used when resuming after a `pause()`. */\n writeIndex = 0;\n /** Indicates whether the parser has finished running / `.end` has been called. */\n ended = false;\n constructor(cbs, options = {}) {\n this.options = options;\n this.cbs = cbs ?? {};\n this.htmlMode = !this.options.xmlMode;\n this.lowerCaseTagNames = options.lowerCaseTags ?? this.htmlMode;\n this.lowerCaseAttributeNames =\n options.lowerCaseAttributeNames ?? this.htmlMode;\n this.recognizeSelfClosing =\n options.recognizeSelfClosing ?? !this.htmlMode;\n this.tokenizer = new (options.Tokenizer ?? Tokenizer)(this.options, this);\n this.foreignContext = [ForeignContext.None];\n this.cbs.onparserinit?.(this);\n }\n // Tokenizer event handlers\n /**\n * @param start Start index for the current parser event.\n * @param endIndex End index for the current parser event.\n * @internal\n */\n ontext(start, endIndex) {\n const data = this.getSlice(start, endIndex);\n this.endIndex = endIndex - 1;\n this.cbs.ontext?.(data);\n this.startIndex = endIndex;\n }\n /**\n * @param cp Current Unicode code point.\n * @param endIndex End index for the current parser event.\n * @internal\n */\n ontextentity(cp, endIndex) {\n this.endIndex = endIndex - 1;\n this.cbs.ontext?.(fromCodePoint(cp));\n this.startIndex = endIndex;\n }\n /** @internal */\n isInForeignContext() {\n return this.foreignContext[0] !== ForeignContext.None;\n }\n /**\n * Checks if the current tag is a void element. Override this if you want\n * to specify your own additional void elements.\n * @param name Name of the pseudo selector.\n */\n isVoidElement(name) {\n return this.htmlMode && voidElements.has(name);\n }\n /**\n * Read a tag name from the buffer.\n *\n * When `lowerCaseTagNames` is enabled (the default in HTML mode), the name\n * is lowercased and may be adjusted for SVG casing or the `image` → `img`\n * alias.\n * @param start Start index of the tag name in the buffer.\n * @param endIndex End index of the tag name in the buffer.\n */\n readTagName(start, endIndex) {\n const name = this.lowerCaseTagNames\n ? this.getSlice(start, endIndex).toLowerCase()\n : this.getSlice(start, endIndex);\n if (!(this.lowerCaseTagNames && this.htmlMode)) {\n return name;\n }\n if (this.foreignContext[0] === ForeignContext.Svg) {\n return svgTagNameAdjustments.get(name) ?? name;\n }\n /*\n * Closing tags for SVG elements inside HTML integration points\n * (e.g. </foreignObject> while inside its own content) need case\n * adjustment so the name matches what was pushed to the stack.\n * `foreignContext.length > 1` means a foreign ancestor exists —\n * the base [None] entry plus at least one pushed context.\n */\n if (this.foreignContext.length > 1) {\n const adjusted = svgTagNameAdjustments.get(name);\n if (adjusted !== undefined && this.stack.includes(adjusted)) {\n return adjusted;\n }\n }\n if (!this.isInForeignContext()) {\n return name === \"image\" ? \"img\" : name;\n }\n return name;\n }\n /**\n * @param start Start index for the current parser event.\n * @param endIndex End index for the current parser event.\n * @internal\n */\n onopentagname(start, endIndex) {\n this.endIndex = endIndex;\n this.emitOpenTag(this.readTagName(start, endIndex));\n }\n emitOpenTag(name) {\n this.openTagStart = this.startIndex;\n this.tagname = name;\n /*\n * The spec ignores a second <form> when one is already open.\n * Setting tagname to \"\" suppresses all downstream effects: attribs\n * stays null so endOpenTag is a no-op, and closeCurrentTag can't\n * match \"\" on the stack.\n */\n if (this.htmlMode && name === \"form\" && this.stack.includes(\"form\")) {\n this.tagname = \"\";\n return;\n }\n const impliesClose = this.htmlMode && openImpliesClose.get(name);\n if (impliesClose) {\n while (this.stack.length > 0 && impliesClose.has(this.stack[0])) {\n this.popElement(true);\n }\n }\n if (!this.isVoidElement(name)) {\n this.stack.unshift(name);\n if (this.htmlMode) {\n if (name === \"svg\") {\n this.foreignContext.unshift(ForeignContext.Svg);\n }\n else if (name === \"math\") {\n this.foreignContext.unshift(ForeignContext.MathML);\n }\n else if (htmlIntegrationElements.has(name)) {\n this.foreignContext.unshift(ForeignContext.None);\n }\n }\n }\n this.cbs.onopentagname?.(name);\n if (this.cbs.onopentag)\n this.attribs = {};\n }\n endOpenTag(isImplied) {\n this.startIndex = this.openTagStart;\n if (this.attribs) {\n this.cbs.onopentag?.(this.tagname, this.attribs, isImplied);\n this.attribs = null;\n }\n if (this.cbs.onclosetag && this.isVoidElement(this.tagname)) {\n this.cbs.onclosetag(this.tagname, true);\n }\n this.tagname = \"\";\n }\n /**\n * @param endIndex End index for the current parser event.\n * @internal\n */\n onopentagend(endIndex) {\n this.endIndex = endIndex;\n this.endOpenTag(false);\n // Set `startIndex` for next node\n this.startIndex = endIndex + 1;\n }\n /**\n * @param start Start index for the current parser event.\n * @param endIndex End index for the current parser event.\n * @internal\n */\n onclosetag(start, endIndex) {\n this.endIndex = endIndex;\n const name = this.readTagName(start, endIndex);\n if (!this.isVoidElement(name)) {\n const pos = this.stack.indexOf(name);\n if (pos !== -1) {\n for (let index = 0; index < pos; index++) {\n this.popElement(true);\n }\n this.popElement(false);\n }\n else if (this.htmlMode && name === \"p\") {\n // Implicit open before close\n this.emitOpenTag(\"p\");\n this.closeCurrentTag(true);\n }\n }\n else if (this.htmlMode && name === \"br\") {\n // We can't use `emitOpenTag` for implicit open, as `br` would be implicitly closed.\n this.cbs.onopentagname?.(\"br\");\n this.cbs.onopentag?.(\"br\", {}, true);\n this.cbs.onclosetag?.(\"br\", false);\n }\n // Set `startIndex` for next node\n this.startIndex = endIndex + 1;\n }\n /**\n * @param endIndex End index for the current parser event.\n * @internal\n */\n onselfclosingtag(endIndex) {\n this.endIndex = endIndex;\n if (this.recognizeSelfClosing || this.isInForeignContext()) {\n this.closeCurrentTag(false);\n // Set `startIndex` for next node\n this.startIndex = endIndex + 1;\n }\n else {\n // Ignore the fact that the tag is self-closing.\n this.onopentagend(endIndex);\n }\n }\n /**\n * Pop the top element off the stack, emit a close event, and maintain\n * the foreign context stack.\n * @param implied Whether this close is implied (not from an explicit end tag).\n */\n popElement(implied) {\n // biome-ignore lint/style/noNonNullAssertion: The element is guaranteed to exist.\n const element = this.stack.shift();\n if (this.htmlMode &&\n (foreignContextElements.has(element) ||\n htmlIntegrationElements.has(element))) {\n this.foreignContext.shift();\n }\n this.cbs.onclosetag?.(element, implied);\n }\n closeCurrentTag(isOpenImplied) {\n const name = this.tagname;\n this.endOpenTag(isOpenImplied);\n // Self-closing tags will be on the top of the stack\n if (this.stack[0] === name) {\n this.popElement(!isOpenImplied);\n }\n }\n /**\n * @param start Start index for the current parser event.\n * @param endIndex End index for the current parser event.\n * @internal\n */\n onattribname(start, endIndex) {\n this.startIndex = start;\n const name = this.getSlice(start, endIndex);\n this.attribname = this.lowerCaseAttributeNames\n ? name.toLowerCase()\n : name;\n }\n /**\n * @param start Start index for the current parser event.\n * @param endIndex End index for the current parser event.\n * @internal\n */\n onattribdata(start, endIndex) {\n this.attribvalue += this.getSlice(start, endIndex);\n }\n /**\n * @param cp Current Unicode code point.\n * @internal\n */\n onattribentity(cp) {\n this.attribvalue += fromCodePoint(cp);\n }\n /**\n * @param quote Quote type used for the current attribute.\n * @param endIndex End index for the current parser event.\n * @internal\n */\n onattribend(quote, endIndex) {\n this.endIndex = endIndex;\n this.cbs.onattribute?.(this.attribname, this.attribvalue, quote === QuoteType.Double\n ? '\"'\n : quote === QuoteType.Single\n ? \"'\"\n : quote === QuoteType.NoValue\n ? undefined\n : null);\n if (this.attribs && !Object.hasOwn(this.attribs, this.attribname)) {\n this.attribs[this.attribname] = this.attribvalue;\n }\n this.attribvalue = \"\";\n }\n getInstructionName(value) {\n const index = value.search(reNameEnd);\n let name = index < 0 ? value : value.substr(0, index);\n if (this.lowerCaseTagNames) {\n name = name.toLowerCase();\n }\n return name;\n }\n /**\n * @param start Start index for the current parser event.\n * @param endIndex End index for the current parser event.\n * @internal\n */\n ondeclaration(start, endIndex) {\n this.endIndex = endIndex;\n const value = this.getSlice(start, endIndex);\n if (this.cbs.onprocessinginstruction) {\n /*\n * In HTML mode, ondeclaration is only reached for DOCTYPE\n * (the tokenizer routes everything else to bogus comments).\n */\n const name = this.htmlMode\n ? this.lowerCaseTagNames\n ? DOCUMENT_TYPE\n : value.slice(0, DOCUMENT_TYPE.length)\n : this.getInstructionName(value);\n this.cbs.onprocessinginstruction(`!${name}`, `!${value}`);\n }\n // Set `startIndex` for next node\n this.startIndex = endIndex + 1;\n }\n /**\n * @param start Start index for the current parser event.\n * @param endIndex End index for the current parser event.\n * @internal\n */\n onprocessinginstruction(start, endIndex) {\n this.endIndex = endIndex;\n const value = this.getSlice(start, endIndex);\n if (this.cbs.onprocessinginstruction) {\n const name = this.getInstructionName(value);\n this.cbs.onprocessinginstruction(`?${name}`, `?${value}`);\n }\n // Set `startIndex` for next node\n this.startIndex = endIndex + 1;\n }\n /**\n * @param start Start index for the current parser event.\n * @param endIndex End index for the current parser event.\n * @param offset Offset applied when computing parser indices.\n * @internal\n */\n oncomment(start, endIndex, offset) {\n this.endIndex = endIndex;\n this.cbs.oncomment?.(this.getSlice(start, endIndex - offset));\n this.cbs.oncommentend?.();\n // Set `startIndex` for next node\n this.startIndex = endIndex + 1;\n }\n /**\n * @param start Start index for the current parser event.\n * @param endIndex End index for the current parser event.\n * @param offset Offset applied when computing parser indices.\n * @internal\n */\n oncdata(start, endIndex, offset) {\n this.endIndex = endIndex;\n const value = this.getSlice(start, endIndex - offset);\n if (!this.htmlMode || this.options.recognizeCDATA) {\n this.cbs.oncdatastart?.();\n this.cbs.ontext?.(value);\n this.cbs.oncdataend?.();\n }\n else if (this.isInForeignContext()) {\n this.cbs.ontext?.(value);\n }\n else {\n this.cbs.oncomment?.(`[CDATA[${value}]]`);\n this.cbs.oncommentend?.();\n }\n // Set `startIndex` for next node\n this.startIndex = endIndex + 1;\n }\n /** @internal */\n onend() {\n if (this.cbs.onclosetag) {\n // Set the end index for all remaining tags\n this.endIndex = this.startIndex;\n for (let index = 0; index < this.stack.length; index++) {\n this.cbs.onclosetag(this.stack[index], true);\n }\n }\n this.cbs.onend?.();\n }\n /**\n * Resets the parser to a blank state, ready to parse a new HTML document\n */\n reset() {\n this.cbs.onreset?.();\n this.tokenizer.reset();\n this.tagname = \"\";\n this.attribname = \"\";\n this.attribvalue = \"\";\n this.attribs = null;\n this.stack.length = 0;\n this.startIndex = 0;\n this.endIndex = 0;\n this.cbs.onparserinit?.(this);\n this.buffers.length = 0;\n this.foreignContext.length = 0;\n this.foreignContext.unshift(ForeignContext.None);\n this.bufferOffset = 0;\n this.writeIndex = 0;\n this.ended = false;\n }\n /**\n * Resets the parser, then parses a complete document and\n * pushes it to the handler.\n * @param data Document to parse.\n */\n parseComplete(data) {\n this.reset();\n this.end(data);\n }\n getSlice(start, end) {\n if (start === end) {\n return \"\";\n }\n while (start - this.bufferOffset >= this.buffers[0].length) {\n this.shiftBuffer();\n }\n let slice = this.buffers[0].slice(start - this.bufferOffset, end - this.bufferOffset);\n while (end - this.bufferOffset > this.buffers[0].length) {\n this.shiftBuffer();\n slice += this.buffers[0].slice(0, end - this.bufferOffset);\n }\n return slice;\n }\n shiftBuffer() {\n this.bufferOffset += this.buffers[0].length;\n this.writeIndex--;\n this.buffers.shift();\n }\n /**\n * Parses a chunk of data and calls the corresponding callbacks.\n * @param chunk Chunk to parse.\n */\n write(chunk) {\n if (this.ended) {\n this.cbs.onerror?.(new Error(\".write() after done!\"));\n return;\n }\n this.buffers.push(chunk);\n if (this.tokenizer.running) {\n this.tokenizer.write(chunk);\n this.writeIndex++;\n }\n }\n /**\n * Parses the end of the buffer and clears the stack, calls onend.\n * @param chunk Optional final chunk to parse.\n */\n end(chunk) {\n if (this.ended) {\n this.cbs.onerror?.(new Error(\".end() after done!\"));\n return;\n }\n if (chunk)\n this.write(chunk);\n this.ended = true;\n this.tokenizer.end();\n }\n /**\n * Pauses parsing. The parser won't emit events until `resume` is called.\n */\n pause() {\n this.tokenizer.pause();\n }\n /**\n * Resumes parsing after `pause` was called.\n */\n resume() {\n this.tokenizer.resume();\n while (this.tokenizer.running &&\n this.writeIndex < this.buffers.length) {\n this.tokenizer.write(this.buffers[this.writeIndex++]);\n }\n if (this.ended)\n this.tokenizer.end();\n }\n}\n//# sourceMappingURL=Parser.js.map","/** Types of elements found in htmlparser2's DOM */\nexport var ElementType;\n(function (ElementType) {\n /** Type for the root element of a document */\n ElementType[\"Root\"] = \"root\";\n /** Type for Text */\n ElementType[\"Text\"] = \"text\";\n /** Type for <? ... ?> */\n ElementType[\"Directive\"] = \"directive\";\n /** Type for <!-- ... --> */\n ElementType[\"Comment\"] = \"comment\";\n /** Type for <script> tags */\n ElementType[\"Script\"] = \"script\";\n /** Type for <style> tags */\n ElementType[\"Style\"] = \"style\";\n /** Type for Any tag */\n ElementType[\"Tag\"] = \"tag\";\n /** Type for <![CDATA[ ... ]]> */\n ElementType[\"CDATA\"] = \"cdata\";\n /** Type for <!doctype ...> */\n ElementType[\"Doctype\"] = \"doctype\";\n})(ElementType || (ElementType = {}));\n/**\n * Tests whether an element is a tag or not.\n * @param element Element to test\n * @param element.type Node type discriminator to check.\n */\nexport function isTag(element) {\n return (element.type === ElementType.Tag ||\n element.type === ElementType.Script ||\n element.type === ElementType.Style);\n}\n// Exports for backwards compatibility\n/** Type for the root element of a document */\n// eslint-disable-next-line prefer-destructuring\nexport const Root = ElementType.Root;\n/** Type for Text */\n// eslint-disable-next-line prefer-destructuring\nexport const Text = ElementType.Text;\n/** Type for <? ... ?> */\n// eslint-disable-next-line prefer-destructuring\nexport const Directive = ElementType.Directive;\n/** Type for <!-- ... --> */\n// eslint-disable-next-line prefer-destructuring\nexport const Comment = ElementType.Comment;\n/** Type for <script> tags */\n// eslint-disable-next-line prefer-destructuring\nexport const Script = ElementType.Script;\n/** Type for <style> tags */\n// eslint-disable-next-line prefer-destructuring\nexport const Style = ElementType.Style;\n/** Type for Any tag */\n// eslint-disable-next-line prefer-destructuring\nexport const Tag = ElementType.Tag;\n/** Type for <![CDATA[ ... ]]> */\n// eslint-disable-next-line prefer-destructuring\nexport const CDATA = ElementType.CDATA;\n/** Type for <!doctype ...> */\n// eslint-disable-next-line prefer-destructuring\nexport const Doctype = ElementType.Doctype;\n","import { ElementType, isTag as isTagRaw } from \"domelementtype\";\n/**\n * This object will be used as the prototype for Nodes when creating a\n * DOM-Level-1-compliant structure.\n */\nexport class Node {\n /** Parent of the node */\n parent = null;\n /** Previous sibling */\n prev = null;\n /** Next sibling */\n next = null;\n /** The start index of the node. Requires `withStartIndices` on the handler to be `true. */\n startIndex = null;\n /** The end index of the node. Requires `withEndIndices` on the handler to be `true. */\n endIndex = null;\n // Read-write aliases for properties\n /**\n * Same as {@link parent}.\n * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.\n */\n get parentNode() {\n return this.parent;\n }\n set parentNode(parent) {\n this.parent = parent;\n }\n /**\n * Same as {@link prev}.\n * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.\n */\n get previousSibling() {\n return this.prev;\n }\n set previousSibling(previous) {\n this.prev = previous;\n }\n /**\n * Same as {@link next}.\n * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.\n */\n get nextSibling() {\n return this.next;\n }\n set nextSibling(next) {\n this.next = next;\n }\n /**\n * Clone this node, and optionally its children.\n * @param recursive Clone child nodes as well.\n * @returns A clone of the node.\n */\n cloneNode(recursive = false) {\n return cloneNode(this, recursive);\n }\n}\n/**\n * A node that contains some data.\n */\nexport class DataNode extends Node {\n data;\n /**\n * @param data The content of the data node\n */\n constructor(data) {\n super();\n this.data = data;\n }\n /**\n * Same as {@link data}.\n * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.\n */\n get nodeValue() {\n return this.data;\n }\n set nodeValue(data) {\n this.data = data;\n }\n}\n/**\n * Text within the document.\n */\nexport class Text extends DataNode {\n type = ElementType.Text;\n get nodeType() {\n return 3;\n }\n}\n/**\n * Comments within the document.\n */\nexport class Comment extends DataNode {\n type = ElementType.Comment;\n get nodeType() {\n return 8;\n }\n}\n/**\n * Processing instructions, including doc types.\n */\nexport class ProcessingInstruction extends DataNode {\n type = ElementType.Directive;\n name;\n constructor(name, data) {\n super(data);\n this.name = name;\n }\n get nodeType() {\n return 1;\n }\n /** If this is a doctype, the document type name (parse5 only). */\n \"x-name\";\n /** If this is a doctype, the document type public identifier (parse5 only). */\n \"x-publicId\";\n /** If this is a doctype, the document type system identifier (parse5 only). */\n \"x-systemId\";\n}\n/**\n * A node that can have children.\n */\nexport class NodeWithChildren extends Node {\n children;\n /**\n * @param children Children of the node. Only certain node types can have children.\n */\n constructor(children) {\n super();\n this.children = children;\n }\n // Aliases\n /** First child of the node. */\n get firstChild() {\n return this.children[0] ?? null;\n }\n /** Last child of the node. */\n get lastChild() {\n return this.children.length > 0\n ? this.children[this.children.length - 1]\n : null;\n }\n /**\n * Same as {@link children}.\n * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.\n */\n get childNodes() {\n return this.children;\n }\n set childNodes(children) {\n this.children = children;\n }\n}\n/**\n * CDATA nodes.\n */\nexport class CDATA extends NodeWithChildren {\n type = ElementType.CDATA;\n get nodeType() {\n return 4;\n }\n}\n/**\n * The root node of the document.\n */\nexport class Document extends NodeWithChildren {\n type = ElementType.Root;\n get nodeType() {\n return 9;\n }\n}\n/**\n * An element within the DOM.\n */\nexport class Element extends NodeWithChildren {\n name;\n attribs;\n type;\n /**\n * @param name Name of the tag, eg. `div`, `span`.\n * @param attribs Object mapping attribute names to attribute values.\n * @param children Children of the node.\n * @param type Node type used for the new node instance.\n */\n constructor(name, attribs, children = [], type = name === \"script\"\n ? ElementType.Script\n : name === \"style\"\n ? ElementType.Style\n : ElementType.Tag) {\n super(children);\n this.name = name;\n this.attribs = attribs;\n this.type = type;\n }\n get nodeType() {\n return 1;\n }\n // DOM Level 1 aliases\n /**\n * Same as {@link name}.\n * [DOM spec](https://dom.spec.whatwg.org)-compatible alias.\n */\n get tagName() {\n return this.name;\n }\n set tagName(name) {\n this.name = name;\n }\n get attributes() {\n return Object.keys(this.attribs).map((name) => ({\n name,\n value: this.attribs[name],\n namespace: this[\"x-attribsNamespace\"]?.[name],\n prefix: this[\"x-attribsPrefix\"]?.[name],\n }));\n }\n /** Element namespace (parse5 only). */\n namespace;\n /** Element attribute namespaces (parse5 only). */\n \"x-attribsNamespace\";\n /** Element attribute namespace-related prefixes (parse5 only). */\n \"x-attribsPrefix\";\n}\n/**\n * Checks if `node` is an element node.\n * @param node Node to check.\n * @returns `true` if the node is an element node.\n */\nexport function isTag(node) {\n return isTagRaw(node);\n}\n/**\n * Checks if `node` is a CDATA node.\n * @param node Node to check.\n * @returns `true` if the node is a CDATA node.\n */\nexport function isCDATA(node) {\n return node.type === ElementType.CDATA;\n}\n/**\n * Checks if `node` is a text node.\n * @param node Node to check.\n * @returns `true` if the node is a text node.\n */\nexport function isText(node) {\n return node.type === ElementType.Text;\n}\n/**\n * Checks if `node` is a comment node.\n * @param node Node to check.\n * @returns `true` if the node is a comment node.\n */\nexport function isComment(node) {\n return node.type === ElementType.Comment;\n}\n/**\n * Checks if `node` is a directive node.\n * @param node Node to check.\n * @returns `true` if the node is a directive node.\n */\nexport function isDirective(node) {\n return node.type === ElementType.Directive;\n}\n/**\n * Checks if `node` is a document node.\n * @param node Node to check.\n * @returns `true` if the node is a document node.\n */\nexport function isDocument(node) {\n return node.type === ElementType.Root;\n}\n/**\n * Checks if `node` has children.\n * @param node Node to check.\n * @returns `true` if the node has children.\n */\nexport function hasChildren(node) {\n return Object.hasOwn(node, \"children\");\n}\n/**\n * Clone a node, and optionally its children.\n * @param node Node to clone.\n * @param recursive Clone child nodes as well.\n * @returns A clone of the node.\n */\nexport function cloneNode(node, recursive = false) {\n let result;\n if (isText(node)) {\n result = new Text(node.data);\n }\n else if (isComment(node)) {\n result = new Comment(node.data);\n }\n else if (isTag(node)) {\n const children = recursive ? cloneChildren(node.children) : [];\n const clone = new Element(node.name, { ...node.attribs }, children);\n for (const child of children) {\n child.parent = clone;\n }\n if (node.namespace != null) {\n clone.namespace = node.namespace;\n }\n if (node[\"x-attribsNamespace\"]) {\n clone[\"x-attribsNamespace\"] = { ...node[\"x-attribsNamespace\"] };\n }\n if (node[\"x-attribsPrefix\"]) {\n clone[\"x-attribsPrefix\"] = { ...node[\"x-attribsPrefix\"] };\n }\n result = clone;\n }\n else if (isCDATA(node)) {\n const children = recursive ? cloneChildren(node.children) : [];\n const clone = new CDATA(children);\n for (const child of children) {\n child.parent = clone;\n }\n result = clone;\n }\n else if (isDocument(node)) {\n const children = recursive ? cloneChildren(node.children) : [];\n const clone = new Document(children);\n for (const child of children) {\n child.parent = clone;\n }\n if (node[\"x-mode\"]) {\n clone[\"x-mode\"] = node[\"x-mode\"];\n }\n result = clone;\n }\n else if (isDirective(node)) {\n const instruction = new ProcessingInstruction(node.name, node.data);\n if (node[\"x-name\"] != null) {\n instruction[\"x-name\"] = node[\"x-name\"];\n instruction[\"x-publicId\"] = node[\"x-publicId\"];\n instruction[\"x-systemId\"] = node[\"x-systemId\"];\n }\n result = instruction;\n }\n else {\n throw new Error(`Not implemented yet: ${node.type}`);\n }\n result.startIndex = node.startIndex;\n result.endIndex = node.endIndex;\n if (node.sourceCodeLocation != null) {\n result.sourceCodeLocation = node.sourceCodeLocation;\n }\n return result;\n}\n/**\n * Clone a list of child nodes.\n * @param childs The child nodes to clone.\n * @returns A list of cloned child nodes.\n */\nfunction cloneChildren(childs) {\n const children = childs.map((child) => cloneNode(child, true));\n for (let index = 1; index < children.length; index++) {\n children[index].prev = children[index - 1];\n children[index - 1].next = children[index];\n }\n return children;\n}\n","import { ElementType } from \"domelementtype\";\nimport { CDATA, Comment, Document, Element, ProcessingInstruction, Text, } from \"./node.js\";\nexport * from \"./node.js\";\n// Default options\nconst defaultOptions = {\n withStartIndices: false,\n withEndIndices: false,\n xmlMode: false,\n};\n/**\n * Event-based handler that builds a DOM tree from parser callbacks.\n */\nexport class DomHandler {\n /** The elements of the DOM */\n dom = [];\n /** The root element for the DOM */\n root = new Document(this.dom);\n /** Called once parsing has completed. */\n callback;\n /** Settings for the handler. */\n options;\n /** Callback whenever a tag is closed. */\n elementCB;\n /** Indicated whether parsing has been completed. */\n done = false;\n /** Stack of open tags. */\n tagStack = [this.root];\n /** A data node that is still being written to. */\n lastNode = null;\n /** Reference to the parser instance. Used for location information. */\n parser = null;\n /**\n * @param callback Called once parsing has completed.\n * @param options Settings for the handler.\n * @param elementCB Callback whenever a tag is closed.\n */\n constructor(callback, options, elementCB) {\n // Make it possible to skip arguments, for backwards-compatibility\n if (typeof options === \"function\") {\n elementCB = options;\n options = defaultOptions;\n }\n if (typeof callback === \"object\") {\n options = callback;\n callback = undefined;\n }\n this.callback = callback ?? null;\n this.options = options ?? defaultOptions;\n this.elementCB = elementCB ?? null;\n }\n onparserinit(parser) {\n this.parser = parser;\n }\n // Resets the handler back to starting state\n onreset() {\n this.dom = [];\n this.root = new Document(this.dom);\n this.done = false;\n this.tagStack = [this.root];\n this.lastNode = null;\n this.parser = null;\n }\n // Signals the handler that parsing is done\n onend() {\n if (this.done)\n return;\n this.done = true;\n this.parser = null;\n this.handleCallback(null);\n }\n onerror(error) {\n this.handleCallback(error);\n }\n onclosetag() {\n this.lastNode = null;\n const element = this.tagStack.pop();\n if (this.options.withEndIndices && this.parser) {\n element.endIndex = this.parser.endIndex;\n }\n if (this.elementCB)\n this.elementCB(element);\n }\n onopentag(name, attribs) {\n const type = this.options.xmlMode ? ElementType.Tag : undefined;\n const element = new Element(name, attribs, undefined, type);\n this.addNode(element);\n this.tagStack.push(element);\n }\n ontext(data) {\n const { lastNode } = this;\n if (lastNode && lastNode.type === ElementType.Text) {\n lastNode.data += data;\n if (this.options.withEndIndices && this.parser) {\n lastNode.endIndex = this.parser.endIndex;\n }\n }\n else {\n const node = new Text(data);\n this.addNode(node);\n this.lastNode = node;\n }\n }\n oncomment(data) {\n if (this.lastNode && this.lastNode.type === ElementType.Comment) {\n this.lastNode.data += data;\n return;\n }\n const node = new Comment(data);\n this.addNode(node);\n this.lastNode = node;\n }\n oncommentend() {\n this.lastNode = null;\n }\n oncdatastart() {\n const text = new Text(\"\");\n const node = new CDATA([text]);\n this.addNode(node);\n text.parent = node;\n this.lastNode = text;\n }\n oncdataend() {\n this.lastNode = null;\n }\n onprocessinginstruction(name, data) {\n const node = new ProcessingInstruction(name, data);\n this.addNode(node);\n }\n handleCallback(error) {\n if (typeof this.callback === \"function\") {\n this.callback(error, this.dom);\n }\n else if (error) {\n throw error;\n }\n }\n addNode(node) {\n const parent = this.tagStack[this.tagStack.length - 1];\n const previousSibling = parent.children[parent.children.length - 1];\n if (this.options.withStartIndices && this.parser) {\n node.startIndex = this.parser.startIndex;\n }\n if (this.options.withEndIndices && this.parser) {\n node.endIndex = this.parser.endIndex;\n }\n parent.children.push(node);\n if (previousSibling) {\n node.prev = previousSibling;\n previousSibling.next = node;\n }\n node.parent = parent;\n this.lastNode = null;\n }\n}\nexport default DomHandler;\n","import { Parser } from \"./Parser.js\";\nexport { Parser } from \"./Parser.js\";\nimport { DomHandler, } from \"domhandler\";\nexport { DomHandler, \n// Old name for DomHandler\nDomHandler as DefaultHandler, } from \"domhandler\";\n// Helper methods\n/**\n * Parses the data, returns the resulting document.\n * @param data The data that should be parsed.\n * @param options Optional options for the parser and DOM handler.\n */\nexport function parseDocument(data, options) {\n const handler = new DomHandler(undefined, options);\n new Parser(handler, options).end(data);\n return handler.root;\n}\n/**\n * Creates a parser instance, with an attached DOM handler.\n * @param callback A callback that will be called once parsing has been completed, with the resulting document.\n * @param options Optional options for the parser and DOM handler.\n * @param elementCallback An optional callback that will be called every time a tag has been completed inside of the DOM.\n */\nexport function createDocumentStream(callback, options, elementCallback) {\n const handler = new DomHandler((error) => callback(error, handler.root), options, elementCallback);\n return new Parser(handler, options);\n}\n/*\n * All of the following exports exist for backwards-compatibility.\n * They should probably be removed eventually.\n */\nexport * as ElementType from \"domelementtype\";\nexport { default as Tokenizer, QuoteType, } from \"./Tokenizer.js\";\nimport { getFeed } from \"domutils\";\nexport { getFeed } from \"domutils\";\nconst parseFeedDefaultOptions = { xmlMode: true };\n/**\n * Parse a feed.\n * @param feed The feed that should be parsed, as a string.\n * @param options Optionally, options for parsing. When using this, you should set `xmlMode` to `true`.\n */\nexport function parseFeed(feed, options = parseFeedDefaultOptions) {\n return getFeed(parseDocument(feed, options).children);\n}\nexport * as DomUtils from \"domutils\";\n//# sourceMappingURL=index.js.map","/**\n * Twine HTML decompiler: parse compiled Twine 2 or Twine 1 HTML back into a Story model.\n * Ported from storyload.go:loadHTML().\n */\nimport { parseDocument } from 'htmlparser2';\nimport type { Passage, PassageMetadata, Diagnostic, DecompileOptions } from './types.js';\nimport {\n createStory,\n storyAdd,\n storyPrepend,\n marshalStoryData,\n unmarshalStorySettings,\n withGeneratedName,\n freeName,\n} from './story.js';\nimport { rot13, tiddlerUnescape } from './escape.js';\nimport { normalizeIFID, validateIFID } from './ifid.js';\nimport { isObfuscatable } from './passage.js';\n\nexport interface DecompileResult {\n story: import('./types.js').Story;\n diagnostics: Diagnostic[];\n}\n\n// Structural types matching domhandler's API (avoids direct import of domhandler).\ninterface HtmlNode {\n type: string;\n name?: string;\n attribs?: Record<string, string>;\n children?: HtmlNode[];\n data?: string;\n}\n\n/** What decompiling reports beyond what it reads. */\ninterface DecompileChecks {\n /** Report a missing or invalid `tw-storydata` IFID. */\n readonly ifid: boolean;\n}\n\n/**\n * Parse a Twine 2 or Twine 1 compiled HTML file back into a Story model.\n * Tweego always trims passage text; here `trim: false` keeps it exactly, as for Twee sources.\n * A missing or invalid `tw-storydata` IFID is reported as a warning; an invalid one is kept as\n * written (uppercased), a missing one stays empty.\n */\nexport function decompileHTML(html: string, options: DecompileOptions = {}): DecompileResult {\n return decompile(html, options, { ifid: true });\n}\n\n/**\n * `decompileHTML()` for loading an HTML file into a compile. The importer's StoryData passage is\n * checked when it is added to the story being compiled, which reports a missing or invalid IFID,\n * so the IFID is not reported here as well.\n */\nexport function decompileHTMLForImport(html: string, options: DecompileOptions = {}): DecompileResult {\n return decompile(html, options, { ifid: false });\n}\n\nfunction decompile(html: string, options: DecompileOptions, checks: DecompileChecks): DecompileResult {\n const diagnostics: Diagnostic[] = [];\n const story = createStory();\n const passageText = options.trim === false ? (text: string) => text : (text: string) => text.trim();\n\n const doc = parseDocument(html) as unknown as HtmlNode;\n\n // Try Twine 2 first (<tw-storydata>), then Twine 1 (<div id=\"store-area\"> or <div id=\"storeArea\">).\n const twine2Data = findElement(doc, 'tw-storydata');\n if (twine2Data) {\n decompileTwine2(twine2Data, story, passageText, checks, diagnostics);\n return { story, diagnostics };\n }\n\n const twine1Data = findElementByIdPattern(doc, /^store(?:-a|A)rea$/);\n if (twine1Data) {\n decompileTwine1(twine1Data, story, passageText, diagnostics);\n return { story, diagnostics };\n }\n\n diagnostics.push({ level: 'error', message: 'Malformed HTML source; story data not found.' });\n return { story, diagnostics };\n}\n\n/** Turns stored passage text into passage text: trimmed at both ends, or kept as is. */\ntype PassageText = (text: string) => string;\n\nfunction decompileTwine2(\n storyData: HtmlNode,\n story: import('./types.js').Story,\n passageText: PassageText,\n checks: DecompileChecks,\n diagnostics: Diagnostic[],\n): void {\n // Parse tw-storydata attributes.\n let startnode = 0;\n const attrs = storyData.attribs ?? {};\n\n if (attrs['name']) story.name = attrs['name'];\n if (attrs['startnode']) {\n const parsed = parseInt(attrs['startnode'], 10);\n if (Number.isNaN(parsed)) {\n diagnostics.push({\n level: 'warning',\n message: `Cannot parse \"tw-storydata\" content attribute \"startnode\" as an integer; value \"${attrs['startnode']}\".`,\n });\n } else {\n startnode = parsed;\n }\n }\n if (attrs['ifid']) story.ifid = normalizeIFID(attrs['ifid']);\n if (checks.ifid) diagnostics.push(...storyDataIFIDDiagnostics(attrs['ifid'] ?? ''));\n if (attrs['zoom']) {\n const parsed = parseFloat(attrs['zoom']);\n if (Number.isNaN(parsed)) {\n diagnostics.push({\n level: 'warning',\n message: `Cannot parse \"tw-storydata\" content attribute \"zoom\" as a float; value \"${attrs['zoom']}\".`,\n });\n } else {\n story.twine2.zoom = parsed;\n }\n }\n if (attrs['tags']) story.twine2.tags = attrs['tags'];\n if (attrs['format']) story.twine2.format = attrs['format'];\n if (attrs['format-version']) story.twine2.formatVersion = attrs['format-version'];\n if (attrs['options']) {\n for (const opt of attrs['options'].split(/\\s+/).filter((s: string) => s.length > 0)) {\n story.twine2.options.set(opt, true);\n }\n }\n\n // The story stylesheet and script get generated passage names. Ordinary passages may use those\n // names too, so reserve every real passage name first and give the code passages names left free.\n const children = storyData.children ?? [];\n const takenNames = new Set(\n children.filter((node) => node.type === 'tag' && node.name === 'tw-passagedata').map(passageDataName),\n );\n\n // Process child elements.\n // htmlparser2 uses type 'style'/'script' for those elements instead of 'tag'.\n for (const node of children) {\n if (node.type !== 'tag' && node.type !== 'style' && node.type !== 'script') continue;\n\n switch (node.name) {\n case 'style':\n case 'script': {\n const content = getTextContent(node);\n // Whitespace alone is no stylesheet or script, whether or not the text is trimmed.\n if (content.trim().length === 0) continue;\n const text = passageText(content);\n const base = node.name === 'style' ? 'Story Stylesheet' : 'Story JavaScript';\n const name = freeName(base, (n) => !takenNames.has(n));\n takenNames.add(name);\n const tags = node.name === 'style' ? ['stylesheet'] : ['script'];\n // Marked as generated, so that it also yields to passages of other files (see storyAdd()).\n storyAdd(story, withGeneratedName({ name, tags, text }, { kind: 'code', base }), diagnostics);\n break;\n }\n\n case 'tw-tag': {\n const tagAttrs = node.attribs ?? {};\n const tagName = tagAttrs['name'] ?? '';\n const tagColor = tagAttrs['color'] ?? '';\n if (tagName) story.twine2.tagColors.set(tagName, tagColor);\n break;\n }\n\n case 'tw-passagedata': {\n let pid = 0;\n const pAttrs = node.attribs ?? {};\n const name = passageDataName(node);\n const tags = pAttrs['tags'] ? pAttrs['tags'].split(/\\s+/).filter((s: string) => s.length > 0) : [];\n const metadata: PassageMetadata = {};\n\n if (pAttrs['pid']) {\n const parsed = parseInt(pAttrs['pid'], 10);\n if (Number.isNaN(parsed)) {\n diagnostics.push({\n level: 'warning',\n message: `Cannot parse \"tw-passagedata\" content attribute \"pid\" as an integer; value \"${pAttrs['pid']}\".`,\n });\n } else {\n pid = parsed;\n }\n }\n\n if (pAttrs['position']) metadata.position = pAttrs['position'];\n if (pAttrs['size']) metadata.size = pAttrs['size'];\n\n if (pid === startnode && pid !== 0) {\n story.twine2.start = name;\n }\n\n const text = passageText(getTextContent(node));\n const passage: Passage = { name, tags, text };\n if (metadata.position || metadata.size) {\n passage.metadata = metadata;\n }\n storyAdd(story, passage, diagnostics);\n break;\n }\n }\n }\n\n // Prepend StoryData passage with serialized metadata.\n storyPrepend(story, { name: 'StoryData', tags: [], text: marshalStoryData(story) }, diagnostics);\n}\n\nfunction passageDataName(node: HtmlNode): string {\n return node.attribs?.['name'] ?? '';\n}\n\n/** Diagnostics for the `ifid` attribute of `tw-storydata`; `value` is empty when it is missing. */\nfunction storyDataIFIDDiagnostics(value: string): Diagnostic[] {\n if (value === '') {\n return [\n {\n level: 'warning',\n message: 'Story IFID not found; the \"tw-storydata\" content attribute \"ifid\" is missing or empty.',\n },\n ];\n }\n const err = validateIFID(value);\n if (err === null) return [];\n return [\n {\n level: 'warning',\n message: `Cannot parse \"tw-storydata\" content attribute \"ifid\" as an IFID; value \"${value}\" (${err}).`,\n },\n ];\n}\n\nfunction decompileTwine1(\n storeArea: HtmlNode,\n story: import('./types.js').Story,\n passageText: PassageText,\n diagnostics: Diagnostic[],\n): void {\n const passages = (storeArea.children ?? []).filter(isTiddler).map((node) => tiddlerToPassage(node, passageText));\n\n // When StorySettings says `obfuscate:rot13`, Twine 1.4 (and twee-ts) ROT13-encode the name, tags and text of\n // every obfuscatable tiddler, so read the settings before adding (and so interpreting) anything else. Whether a\n // tiddler is obfuscatable is decided on its stored name and tags, which such tiddlers keep unencoded.\n const obfuscated = isRot13Obfuscated(passages);\n for (const p of passages) {\n const passage =\n obfuscated && isObfuscatable(p) ? { ...p, name: rot13(p.name), tags: p.tags.map(rot13), text: rot13(p.text) } : p;\n storyAdd(story, passage, diagnostics);\n }\n}\n\nfunction isTiddler(node: HtmlNode): boolean {\n return node.type === 'tag' && node.name === 'div' && node.attribs !== undefined && 'tiddler' in node.attribs;\n}\n\nfunction tiddlerToPassage(node: HtmlNode, passageText: PassageText): Passage {\n const nodeAttrs = node.attribs ?? {};\n const name = nodeAttrs['tiddler'] ?? '';\n const tags = nodeAttrs['tags'] ? nodeAttrs['tags'].split(/\\s+/).filter((s: string) => s.length > 0) : [];\n const text = passageText(tiddlerUnescape(getTextContent(node)));\n\n const passage: Passage = { name, tags, text };\n const position = nodeAttrs['twine-position'];\n if (position) {\n passage.metadata = { position };\n }\n return passage;\n}\n\n/** Whether the StorySettings tiddlers turn on ROT13 obfuscation, read the way the writer reads them. */\nfunction isRot13Obfuscated(passages: readonly Passage[]): boolean {\n const settings = createStory();\n for (const p of passages) {\n // Diagnostics are dropped here; storyAdd() reports them when the passage is added.\n if (p.name === 'StorySettings') unmarshalStorySettings(settings, p.text, []);\n }\n return settings.twine1.settings.get('obfuscate') === 'rot13';\n}\n\nfunction findElement(node: HtmlNode, tagName: string): HtmlNode | undefined {\n if (node.type === 'tag' && node.name === tagName) return node;\n for (const child of node.children ?? []) {\n const found = findElement(child, tagName);\n if (found) return found;\n }\n return undefined;\n}\n\nfunction findElementByIdPattern(node: HtmlNode, idPattern: RegExp): HtmlNode | undefined {\n if (node.type === 'tag' && node.attribs?.['id'] && idPattern.test(node.attribs['id'])) return node;\n for (const child of node.children ?? []) {\n const found = findElementByIdPattern(child, idPattern);\n if (found) return found;\n }\n return undefined;\n}\n\nfunction getTextContent(el: HtmlNode): string {\n let text = '';\n for (const child of el.children ?? []) {\n if (child.type === 'text' && child.data) {\n text += child.data;\n }\n }\n return text;\n}\n","/**\n * File loading: dispatch by file extension.\n * Ported from storyload.go.\n */\nimport { basename, resolve } from 'node:path';\nimport { statSync } from 'node:fs';\nimport type { Story, Diagnostic, InlineSource, Passage, FileCacheEntry } from './types.js';\nimport { normalizedFileExt, mediaTypeFromFilename, mediaTypeFromExt, fontFormatHint } from './media-types.js';\nimport { storyAdd, storyHas, storyPrepend, withGeneratedName } from './story.js';\nimport { parseTwee } from './parser.js';\nimport { decompileHTMLForImport } from './html-parser.js';\nimport { readUTF8, readBase64, baseNameWithoutExt, decodeText } from './util.js';\nimport type { DecodedText } from './util.js';\nimport { normalizeSourceText } from './source-text.js';\nimport { cssStringEscape } from './escape.js';\n\ninterface LoadOptions {\n trim?: boolean;\n twee2Compat?: boolean;\n}\n\n/**\n * Load all source files into a story.\n */\nexport function loadSources(\n story: Story,\n filenames: string[],\n opts: LoadOptions,\n diagnostics: Diagnostic[],\n processedFiles: Set<string>,\n): void {\n for (const filename of filenames) {\n if (processedFiles.has(filename)) {\n diagnostics.push({ level: 'warning', message: `load ${filename}: Skipping duplicate.` });\n continue;\n }\n\n const ext = normalizedFileExt(filename);\n try {\n switch (ext) {\n case 'tw':\n case 'twee':\n loadTwee(story, filename, opts, diagnostics);\n break;\n case 'tw2':\n case 'twee2':\n loadTwee(story, filename, { ...opts, twee2Compat: true }, diagnostics);\n break;\n case 'htm':\n case 'html':\n loadHTML(story, filename, opts, diagnostics);\n break;\n case 'css':\n loadTagged(story, 'stylesheet', filename, diagnostics);\n break;\n case 'js':\n loadTagged(story, 'script', filename, diagnostics);\n break;\n case 'otf':\n case 'ttf':\n case 'woff':\n case 'woff2':\n loadFont(story, filename, diagnostics);\n break;\n case 'gif':\n case 'jpeg':\n case 'jpg':\n case 'png':\n case 'svg':\n case 'tif':\n case 'tiff':\n case 'webp':\n loadMedia(story, 'Twine.image', filename, diagnostics);\n break;\n case 'aac':\n case 'flac':\n case 'm4a':\n case 'mp3':\n case 'oga':\n case 'ogg':\n case 'opus':\n case 'wav':\n case 'wave':\n case 'weba':\n loadMedia(story, 'Twine.audio', filename, diagnostics);\n break;\n case 'mp4':\n case 'ogv':\n case 'webm':\n loadMedia(story, 'Twine.video', filename, diagnostics);\n break;\n case 'vtt':\n loadMedia(story, 'Twine.vtt', filename, diagnostics);\n break;\n default:\n continue;\n }\n } catch (e) {\n diagnostics.push({\n level: 'error',\n message: `load ${filename}: ${e instanceof Error ? e.message : String(e)}`,\n file: filename,\n });\n continue;\n }\n processedFiles.add(filename);\n }\n\n // Prepend StoryTitle if we have a name but no StoryTitle passage.\n if (story.name !== '' && !story.passages.some((p) => p.name === 'StoryTitle')) {\n storyPrepend(story, { name: 'StoryTitle', tags: [], text: story.name }, diagnostics);\n }\n}\n\n/**\n * Load inline sources (string content or InlineSource objects).\n */\nexport function loadInlineSources(\n story: Story,\n sources: (string | InlineSource)[],\n opts: LoadOptions,\n diagnostics: Diagnostic[],\n): void {\n for (const source of sources) {\n if (typeof source === 'string') {\n // Treat as a file path — handled externally\n continue;\n }\n // Decode and normalize like readUTF8() does for files, so in-memory and on-disk sources load the same.\n const decoded: DecodedText =\n typeof source.content === 'string'\n ? { text: source.content, diagnostics: [] }\n : decodeText(source.content, source.filename);\n diagnostics.push(...decoded.diagnostics);\n const content = normalizeSourceText(decoded.text);\n\n const ext = normalizedFileExt(source.filename);\n switch (ext) {\n case '':\n case 'tw':\n case 'twee':\n case 'tw2':\n case 'twee2': {\n const twee2 = ext === 'tw2' || ext === 'twee2' || opts.twee2Compat;\n const result = parseTwee(content, {\n filename: source.filename,\n trim: opts.trim ?? true,\n twee2Compat: twee2,\n });\n diagnostics.push(...result.diagnostics);\n for (const p of result.passages) {\n storyAdd(story, p, diagnostics);\n }\n break;\n }\n case 'css':\n storyAdd(story, codePassage(basename(source.filename), 'stylesheet', content), diagnostics);\n break;\n case 'js':\n storyAdd(story, codePassage(basename(source.filename), 'script', content), diagnostics);\n break;\n default:\n diagnostics.push({\n level: 'warning',\n message: `load ${source.filename}: in-memory sources of type .${ext} are not supported; skipped.`,\n });\n }\n }\n}\n\ninterface ParseResult {\n passages: Passage[];\n diagnostics: Diagnostic[];\n}\n\nfunction parseTweeFile(filename: string, opts: LoadOptions): ParseResult {\n const readDiagnostics: Diagnostic[] = [];\n const source = readUTF8(filename, readDiagnostics);\n const result = parseTwee(source, {\n filename,\n trim: opts.trim ?? true,\n twee2Compat: opts.twee2Compat ?? false,\n });\n return { passages: result.passages, diagnostics: [...readDiagnostics, ...result.diagnostics] };\n}\n\n/**\n * A stylesheet or script passage named after its file, as Tweego names it. The name only labels\n * the code, so when another passage has it, the passage takes a free one (see `storyAdd()`).\n */\nfunction codePassage(name: string, tag: string, text: string): Passage {\n return withGeneratedName({ name, tags: [tag], text }, { kind: 'code', base: name });\n}\n\n/** Mark every passage of a parse result as a code passage named after its file. */\nfunction codeNames(result: ParseResult): ParseResult {\n for (const p of result.passages) withGeneratedName(p, { kind: 'code', base: p.name });\n return result;\n}\n\nfunction parseTaggedFile(tag: string, filename: string): ParseResult {\n const diagnostics: Diagnostic[] = [];\n const source = readUTF8(filename, diagnostics);\n return { passages: [codePassage(basename(filename), tag, source)], diagnostics };\n}\n\nfunction parseMediaFile(tag: string, filename: string): ParseResult {\n const source = readBase64(filename);\n const name = baseNameWithoutExt(filename);\n const passage = { name, tags: [tag], text: `data:${mediaTypeFromFilename(filename)};base64,${source}` };\n return {\n passages: [withGeneratedName(passage, { kind: 'media', base: name, file: filename })],\n diagnostics: [],\n };\n}\n\nfunction parseFontFile(filename: string): ParseResult {\n const source = readBase64(filename);\n const name = basename(filename);\n const family = baseNameWithoutExt(filename);\n const ext = normalizedFileExt(filename);\n const mediaType = mediaTypeFromExt(ext);\n const hint = fontFormatHint(ext);\n return codeNames({\n passages: [\n {\n name,\n tags: ['stylesheet'],\n text: `@font-face {\\n\\tfont-family: \"${cssStringEscape(family)}\";\\n\\tsrc: url(\"data:${mediaType};base64,${source}\") format(\"${hint}\");\\n}`,\n },\n ],\n diagnostics: [],\n });\n}\n\nfunction parseHTMLFile(filename: string, opts: LoadOptions): ParseResult {\n const readDiagnostics: Diagnostic[] = [];\n const { story, diagnostics } = decompileHTMLForImport(readUTF8(filename, readDiagnostics), {\n trim: opts.trim ?? true,\n });\n // Twine 2 HTML keeps the story name in an attribute, not a passage. Only passages reach the\n // outer story (and the cache), so carry the name as a StoryTitle passage, as Twine 1 HTML does.\n const passages =\n story.name !== '' && !storyHas(story, 'StoryTitle')\n ? [{ name: 'StoryTitle', tags: [], text: story.name }, ...story.passages]\n : story.passages;\n return { passages, diagnostics: [...readDiagnostics, ...diagnostics] };\n}\n\n/**\n * Identity of the options that affect how a file parses, stored on its cache entry.\n * Twee files depend on `trim` and `twee2Compat`, HTML files on `trim`; every other file type\n * yields the same key for all options.\n */\nfunction parseOptionsKey(filename: string, opts: LoadOptions): string {\n const ext = normalizedFileExt(filename);\n const trim = opts.trim ?? true;\n if (ext === 'htm' || ext === 'html') return JSON.stringify({ trim });\n const twee2File = ext === 'tw2' || ext === 'twee2';\n if (!twee2File && ext !== 'tw' && ext !== 'twee') return '';\n return JSON.stringify({ trim, twee2Compat: twee2File || (opts.twee2Compat ?? false) });\n}\n\nfunction parseFile(filename: string, opts: LoadOptions): ParseResult | undefined {\n const ext = normalizedFileExt(filename);\n switch (ext) {\n case 'tw':\n case 'twee':\n return parseTweeFile(filename, opts);\n case 'tw2':\n case 'twee2':\n return parseTweeFile(filename, { ...opts, twee2Compat: true });\n case 'htm':\n case 'html':\n return parseHTMLFile(filename, opts);\n case 'css':\n return parseTaggedFile('stylesheet', filename);\n case 'js':\n return parseTaggedFile('script', filename);\n case 'otf':\n case 'ttf':\n case 'woff':\n case 'woff2':\n return parseFontFile(filename);\n case 'gif':\n case 'jpeg':\n case 'jpg':\n case 'png':\n case 'svg':\n case 'tif':\n case 'tiff':\n case 'webp':\n return parseMediaFile('Twine.image', filename);\n case 'aac':\n case 'flac':\n case 'm4a':\n case 'mp3':\n case 'oga':\n case 'ogg':\n case 'opus':\n case 'wav':\n case 'wave':\n case 'weba':\n return parseMediaFile('Twine.audio', filename);\n case 'mp4':\n case 'ogv':\n case 'webm':\n return parseMediaFile('Twine.video', filename);\n case 'vtt':\n return parseMediaFile('Twine.vtt', filename);\n default:\n return undefined;\n }\n}\n\nfunction loadHTML(story: Story, filename: string, opts: LoadOptions, diagnostics: Diagnostic[]): void {\n const result = parseHTMLFile(filename, opts);\n diagnostics.push(...result.diagnostics);\n for (const p of result.passages) {\n storyAdd(story, p, diagnostics);\n }\n}\n\nfunction loadTwee(story: Story, filename: string, opts: LoadOptions, diagnostics: Diagnostic[]): void {\n const result = parseTweeFile(filename, opts);\n diagnostics.push(...result.diagnostics);\n for (const p of result.passages) {\n storyAdd(story, p, diagnostics);\n }\n}\n\nfunction loadTagged(story: Story, tag: string, filename: string, diagnostics: Diagnostic[]): void {\n const result = parseTaggedFile(tag, filename);\n diagnostics.push(...result.diagnostics);\n for (const p of result.passages) {\n storyAdd(story, p, diagnostics);\n }\n}\n\nfunction loadMedia(story: Story, tag: string, filename: string, diagnostics: Diagnostic[]): void {\n const result = parseMediaFile(tag, filename);\n for (const p of result.passages) {\n storyAdd(story, p, diagnostics);\n }\n}\n\nfunction loadFont(story: Story, filename: string, diagnostics: Diagnostic[]): void {\n const result = parseFontFile(filename);\n for (const p of result.passages) {\n storyAdd(story, p, diagnostics);\n }\n}\n\n/**\n * Load sources with mtime-based caching for incremental rebuilds.\n * Always creates a fresh Story; cached passages are replayed via storyAdd().\n */\nexport function loadSourcesCached(\n story: Story,\n filenames: string[],\n opts: LoadOptions,\n diagnostics: Diagnostic[],\n processedFiles: Set<string>,\n cache: Map<string, FileCacheEntry>,\n changedFiles?: ReadonlySet<string>,\n buildFiles?: ReadonlySet<string>,\n): void {\n const currentFiles = new Set<string>(buildFiles);\n // changedFiles may name a file in any form (absolute, `./`-prefixed or relative to the working\n // directory); it is matched to `filenames`, whatever their form, by resolved path.\n const changedPaths = changedFiles === undefined ? undefined : new Set([...changedFiles].map((f) => resolve(f)));\n\n for (const filename of filenames) {\n if (processedFiles.has(filename)) {\n diagnostics.push({ level: 'warning', message: `load ${filename}: Skipping duplicate.` });\n continue;\n }\n\n currentFiles.add(filename);\n const optionsKey = parseOptionsKey(filename, opts);\n // An entry parsed under other options (or without a recorded key) is stale.\n const entry = cache.get(filename);\n const cached = entry?.parseOptionsKey === optionsKey ? entry : undefined;\n // A file changedFiles names is always reparsed: a save can keep the modification time\n // (a timestamp-preserving write, or a filesystem with coarse timestamps).\n const changed = changedPaths?.has(resolve(filename)) ?? false;\n\n // If changedFiles is provided and this file isn't changed and we have a cache hit, skip stat\n if (changedPaths && cached && !changed) {\n diagnostics.push(...cached.diagnostics);\n for (const p of cached.passages) {\n storyAdd(story, p, diagnostics);\n }\n processedFiles.add(filename);\n continue;\n }\n\n // stat the file to check mtime\n let mtimeMs: number;\n try {\n mtimeMs = statSync(filename).mtimeMs;\n } catch {\n // File may have been deleted between getFilenames and here. Its entry goes too, so a\n // later build that doesn't name it in changedFiles can't replay its old passages.\n cache.delete(filename);\n continue;\n }\n\n // Cache hit with matching mtime, for a file not known to have changed: replay\n if (cached && !changed && cached.mtimeMs === mtimeMs) {\n diagnostics.push(...cached.diagnostics);\n for (const p of cached.passages) {\n storyAdd(story, p, diagnostics);\n }\n processedFiles.add(filename);\n continue;\n }\n\n // Cache miss: parse and store\n try {\n const result = parseFile(filename, opts);\n if (!result) continue;\n\n cache.set(filename, {\n mtimeMs,\n parseOptionsKey: optionsKey,\n passages: result.passages,\n diagnostics: result.diagnostics,\n });\n\n diagnostics.push(...result.diagnostics);\n for (const p of result.passages) {\n storyAdd(story, p, diagnostics);\n }\n } catch (e) {\n // A file that fails to load keeps no entry: the next build tries it again, and reports\n // the error again while it persists, rather than replaying its old passages.\n cache.delete(filename);\n diagnostics.push({\n level: 'error',\n message: `load ${filename}: ${e instanceof Error ? e.message : String(e)}`,\n file: filename,\n });\n continue;\n }\n processedFiles.add(filename);\n }\n\n // Purge cache entries for deleted files\n for (const key of cache.keys()) {\n if (!currentFiles.has(key)) {\n cache.delete(key);\n }\n }\n\n // Prepend StoryTitle if we have a name but no StoryTitle passage.\n if (story.name !== '' && !story.passages.some((p) => p.name === 'StoryTitle')) {\n storyPrepend(story, { name: 'StoryTitle', tags: [], text: story.name }, diagnostics);\n }\n}\n","/**\n * Single-pass placeholder substitution for story format templates.\n *\n * Every placeholder is found in the template text before anything is inserted, so inserted text (a story title,\n * passage data, a start passage name, module or head file content) is never scanned for placeholders.\n */\n\n/** A placeholder in a template and the text that replaces it. */\nexport interface TemplateSlot {\n /** Regular expression source matching the placeholder. Must not contain capturing groups. */\n readonly pattern: string;\n /** Replace only the first match in the template, or every match. */\n readonly occurrences: 'first' | 'all';\n /** Text that replaces a match, given the matched text. Inserted literally and called only for a match. */\n readonly replacement: (match: string) => string;\n /**\n * Whether the match at `offset` in the scanned `text` is a placeholder. A match it rejects is left as it is, and\n * does not count as the first one. Every match is a placeholder when this is left out.\n */\n readonly accepts?: (text: string, offset: number) => boolean;\n}\n\n/** A piece of a template: text to scan for `slots`, or text inserted as is. */\nexport type TemplatePart =\n | { readonly kind: 'scan'; readonly text: string; readonly slots: readonly TemplateSlot[] }\n | { readonly kind: 'verbatim'; readonly text: string };\n\n/**\n * An HTML closing head tag: `</head` in any letter case, followed by whitespace, `/` or `>`, up to the next `>`.\n * This is how the HTML tokenizer reads an end tag; it ignores whatever sits between the tag name and the `>`.\n */\nexport const CLOSING_HEAD_TAG = '<\\\\/[Hh][Ee][Aa][Dd](?=[\\\\t\\\\n\\\\f\\\\r />])[^>]*>';\n\n/**\n * The start of an HTML body start tag: `<body` in any letter case, followed by whitespace, `/` or `>` (so not\n * `<bodyx>`). Only the `<body` is matched; the attributes and `>` after it are left alone.\n */\nexport const BODY_START_TAG = '<[Bb][Oo][Dd][Yy](?=[\\\\t\\\\n\\\\f\\\\r />])';\n\n/** The regular expression source matching exactly `text`. */\nexport function literal(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&');\n}\n\n/** Replace the `slots` placeholders found in `template`, without scanning inserted text. */\nexport function fillTemplate(template: string, slots: readonly TemplateSlot[]): string {\n return fillTemplateParts([{ kind: 'scan', text: template, slots }]);\n}\n\n/**\n * Fill the parts of a template in order, joined. A `'first'` slot replaced in one part is not replaced again in a\n * later part that lists the same slot object.\n */\nexport function fillTemplateParts(parts: readonly TemplatePart[]): string {\n const filled = new Set<TemplateSlot>();\n return parts\n .map((part) => {\n if (part.kind === 'verbatim' || part.slots.length === 0) return part.text;\n const { slots } = part;\n const pattern = new RegExp(slots.map((slot) => `(${slot.pattern})`).join('|'), 'g');\n return part.text.replace(pattern, (match: string, ...groups: unknown[]) => {\n const slot = slots.find((_, i) => groups[i] !== undefined);\n if (slot === undefined || (slot.occurrences === 'first' && filled.has(slot))) return match;\n // After the capture groups come the match offset and the scanned text.\n const offset = groups[slots.length];\n if (slot.accepts !== undefined && typeof offset === 'number' && !slot.accepts(part.text, offset)) return match;\n filled.add(slot);\n return slot.replacement(match);\n });\n })\n .join('');\n}\n","/**\n * Module/head injection into <head>.\n * Ported from module.go + io.go:modifyHead(). The renderers inject through `placeHead()` while filling the\n * format template, so the closing head tag is looked for in the template only, never in inserted story data.\n */\nimport type { Diagnostic } from './types.js';\nimport { normalizedFileExt, mediaTypeFromExt, fontFormatHint, slugify } from './media-types.js';\nimport { readUTF8, readBase64, baseNameWithoutExt } from './util.js';\nimport { cssStringEscape, scriptContentEscape, styleContentEscape } from './escape.js';\nimport { fillTemplate } from './template.js';\nimport type { TemplateSlot } from './template.js';\n\n/**\n * Load modules and return HTML tags to inject before the closing head tag. `diagnostics` receives a warning for\n * each module that is not valid UTF-8 (it is read as Windows-1252).\n */\nexport function loadModules(filenames: string[], diagnostics?: Diagnostic[]): string {\n const processed = new Set<string>();\n const headTags: string[] = [];\n\n for (const filename of filenames) {\n if (processed.has(filename)) continue;\n\n const ext = normalizedFileExt(filename);\n let tag: string | null = null;\n\n switch (ext) {\n case 'css':\n tag = loadModuleTagged('style', filename, diagnostics);\n break;\n case 'js':\n tag = loadModuleTagged('script', filename, diagnostics);\n break;\n case 'otf':\n case 'ttf':\n case 'woff':\n case 'woff2':\n tag = loadModuleFont(filename);\n break;\n default:\n continue;\n }\n\n if (tag) headTags.push(tag);\n processed.add(filename);\n }\n\n return headTags.join('\\n');\n}\n\nfunction loadModuleTagged(tag: 'script' | 'style', filename: string, diagnostics?: Diagnostic[]): string | null {\n const source = readUTF8(filename, diagnostics).trim();\n if (source.length === 0) return null;\n\n const family = baseNameWithoutExt(filename);\n const idSlug = `${tag}-module-${slugify(family)}`;\n const mimeType = tag === 'script' ? 'text/javascript' : 'text/css';\n const content = tag === 'script' ? scriptContentEscape(source) : styleContentEscape(source);\n\n return `<${tag} id=\"${idSlug}\" type=\"${mimeType}\">${content}</${tag}>`;\n}\n\nfunction loadModuleFont(filename: string): string | null {\n const source = readBase64(filename);\n const family = baseNameWithoutExt(filename);\n const idSlug = `style-module-${slugify(family)}`;\n const ext = normalizedFileExt(filename);\n const mediaType = mediaTypeFromExt(ext);\n const hint = fontFormatHint(ext);\n\n return `<style id=\"${idSlug}\" type=\"text/css\">@font-face {\\n\\tfont-family: \"${cssStringEscape(family)}\";\\n\\tsrc: url(\"data:${mediaType};base64,${source}\") format(\"${hint}\");\\n}</style>`;\n}\n\n/**\n * Load the module tags and head file content to inject into the head (see `placeHead()`), joined by newlines,\n * or `''` when there is nothing to inject.\n */\nexport function loadHeadContent(modulePaths: string[], headFile?: string, diagnostics?: Diagnostic[]): string {\n const parts: string[] = [];\n\n if (modulePaths.length > 0) {\n const modules = loadModules(modulePaths, diagnostics).trim();\n if (modules.length > 0) parts.push(modules);\n }\n\n if (headFile) {\n try {\n const source = readUTF8(headFile, diagnostics).trim();\n if (source.length > 0) parts.push(source);\n } catch (e) {\n diagnostics?.push({\n level: 'warning',\n message: `Failed to read head file \"${headFile}\": ${e instanceof Error ? e.message : String(e)}`,\n });\n }\n }\n\n return parts.join('\\n');\n}\n\n/** Where the head content goes in a template, and the warning when that is not before a closing head tag. */\nexport interface HeadPlacement {\n /** The template slot that inserts the content, or `undefined` when there is nothing to insert or nowhere to. */\n readonly slot: TemplateSlot | undefined;\n readonly diagnostics: readonly Diagnostic[];\n}\n\n/**\n * Place `content` in a template, given the texts that `fillTemplateParts()` scans for the slot (the template, and\n * the footer of a pre-1.4 Twine 1 format):\n *\n * - on its own line before the first closing head tag, as Tweego does; the tag may use any letter case and\n * whitespace before its `>`, and is kept as written;\n * - in a template with no closing head tag (HTML lets a document leave it out), on its own line before the first\n * body start tag, where the HTML parser still puts it in the head, with a warning (Tweego drops it);\n * - in a template with neither, nowhere, with a warning.\n *\n * `owner` names the template in the warnings. Empty `content` needs no slot and gets no warning.\n */\nexport function placeHead(content: string, texts: readonly string[], owner: string): HeadPlacement {\n if (content.length === 0) return { slot: undefined, diagnostics: [] };\n const scans = texts.map((text) => ({ text, tags: scanHeadTags(text) }));\n if (scans.some(({ tags }) => tags.closingHead !== undefined)) {\n return { slot: beforeTag(CLOSING_HEAD_PREFIX, 'closingHead', content), diagnostics: [] };\n }\n if (scans.some(({ tags }) => tags.bodyStart !== undefined)) {\n const message = `${owner} has no closing head tag; the modules and head file were injected before its body start tag.`;\n return { slot: beforeTag(BODY_START_PREFIX, 'bodyStart', content), diagnostics: [{ level: 'warning', message }] };\n }\n const message = `${owner} has no closing head tag and no body start tag; the modules and head file were not injected.`;\n return { slot: undefined, diagnostics: [{ level: 'warning', message }] };\n}\n\n/** `</head` in any letter case, followed by whitespace, `/` or `>`; the rest of the tag is left alone. */\nconst CLOSING_HEAD_PREFIX = '<\\\\/[Hh][Ee][Aa][Dd](?=[\\\\t\\\\n\\\\f\\\\r />])';\n/** `<body` in any letter case, followed by whitespace, `/` or `>` (so not `<bodyx>`). */\nconst BODY_START_PREFIX = '<[Bb][Oo][Dd][Yy](?=[\\\\t\\\\n\\\\f\\\\r />])';\n\n/** The offsets of the first real closing head tag, body start tag and head start tag end in an HTML text. */\ninterface HeadTags {\n readonly closingHead: number | undefined;\n readonly bodyStart: number | undefined;\n}\n\n/** Elements whose content is text, so a tag written there is not a tag. */\nconst RAW_TEXT_ELEMENTS: ReadonlySet<string> = new Set(['script', 'style', 'textarea', 'title']);\n\nconst isSpace = (c: string | undefined): boolean => c === ' ' || c === '\\t' || c === '\\n' || c === '\\f' || c === '\\r';\nconst isLetter = (c: string | undefined): boolean => c !== undefined && /^[A-Za-z]$/.test(c);\n\n/**\n * Find the first closing head tag and body start tag that HTML would read as tags: not those in a comment, in\n * the text of a script, style, textarea or title element, or in a quoted attribute value. A small scanner, not\n * a full HTML tokenizer; it needs no more than the tags and where they end.\n */\nexport function scanHeadTags(html: string): HeadTags {\n const { closingHead, bodyStart } = scanTags(html);\n return { closingHead, bodyStart };\n}\n\n/**\n * The offset just after the first real head start tag, where content goes to come first in the head; found like\n * the tags of `scanHeadTags()`, so not one in a comment, a script or an attribute value. `undefined` without one.\n */\nexport function findHeadStartEnd(html: string): number | undefined {\n return scanTags(html).headStartEnd;\n}\n\nfunction scanTags(html: string): HeadTags & { readonly headStartEnd: number | undefined } {\n let closingHead: number | undefined;\n let bodyStart: number | undefined;\n let headStartEnd: number | undefined;\n let i = 0;\n\n while (i < html.length) {\n const lt = html.indexOf('<', i);\n if (lt === -1) break;\n const next = html[lt + 1];\n if (html.startsWith('<!--', lt)) {\n const end = html.indexOf('-->', lt + 4);\n i = end === -1 ? html.length : end + 3;\n } else if (next === '!' || next === '?') {\n // A doctype, CDATA section or processing instruction ends at the first `>`.\n const end = html.indexOf('>', lt);\n i = end === -1 ? html.length : end + 1;\n } else if (next === '/' && isLetter(html[lt + 2])) {\n const { name, end } = readTag(html, lt + 2);\n if (name === 'head' && closingHead === undefined) closingHead = lt;\n i = end;\n } else if (isLetter(next)) {\n const { name, end } = readTag(html, lt + 1);\n if (name === 'body' && bodyStart === undefined) bodyStart = lt;\n if (name === 'head' && headStartEnd === undefined) headStartEnd = end;\n i = RAW_TEXT_ELEMENTS.has(name) ? rawTextEnd(html, name, end) : end;\n } else {\n i = lt + 1;\n }\n if (closingHead !== undefined && bodyStart !== undefined) break;\n }\n\n return { closingHead, bodyStart, headStartEnd };\n}\n\n/** Read a tag whose name starts at `from`: its lowercase name, and the offset after its `>` (or the end). */\nfunction readTag(html: string, from: number): { name: string; end: number } {\n let i = from;\n while (i < html.length && !isSpace(html[i]) && html[i] !== '/' && html[i] !== '>') i++;\n const name = html.slice(from, i).toLowerCase();\n // Attributes: a value after `=` may be quoted, and may then hold a `>`.\n while (i < html.length && html[i] !== '>') {\n if (html[i] !== '=') {\n i++;\n continue;\n }\n i++;\n while (isSpace(html[i])) i++;\n const quote = html[i];\n if (quote === '\"' || quote === \"'\") {\n const close = html.indexOf(quote, i + 1);\n i = close === -1 ? html.length : close + 1;\n }\n }\n return { name, end: Math.min(i + 1, html.length) };\n}\n\n/** The offset of the end tag that closes a raw text element, given where its text starts (or the end). */\nfunction rawTextEnd(html: string, name: string, from: number): number {\n const close = new RegExp(`</${name}(?=[\\\\t\\\\n\\\\f\\\\r />])`, 'gi');\n close.lastIndex = from;\n return close.exec(html)?.index ?? html.length;\n}\n\n/**\n * The slot that inserts `content` on its own line before the first real tag of the kind `which` names (see\n * `scanHeadTags()`), which is kept as written. A look-alike inside a script or comment is left alone.\n */\nfunction beforeTag(pattern: string, which: 'closingHead' | 'bodyStart', content: string): TemplateSlot {\n const cache = new Map<string, number | undefined>();\n const offsetIn = (text: string): number | undefined => {\n if (!cache.has(text)) cache.set(text, scanHeadTags(text)[which]);\n return cache.get(text);\n };\n return {\n pattern,\n occurrences: 'first',\n replacement: (match) => `${content}\\n${match}`,\n accepts: (text, offset) => offsetIn(text) === offset,\n };\n}\n\n/**\n * Inject modules and head file content into `html` the way the renderers inject it into a format template (see\n * `placeHead()`), adding any warning to `diagnostics`.\n */\nexport function modifyHead(html: string, modulePaths: string[], headFile?: string, diagnostics?: Diagnostic[]): string {\n const placement = placeHead(loadHeadContent(modulePaths, headFile, diagnostics), [html], 'The HTML');\n diagnostics?.push(...placement.diagnostics);\n return placement.slot === undefined ? html : fillTemplate(html, [placement.slot]);\n}\n","/**\n * The twee-ts version, read at runtime from the package's own package.json.\n *\n * The release workflow (semantic-release) writes the new version into the\n * published package.json only; git keeps the old one. Reading it at runtime\n * is the only way the CLI and `creator-version` report the published version.\n */\nimport { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst PACKAGE_NAME = '@rohal12/twee-ts';\n\n/** Walks up from `startDir` to the nearest package.json named @rohal12/twee-ts and returns its version. */\nexport function findPackageVersion(startDir: string): string | undefined {\n let dir = startDir;\n for (;;) {\n try {\n const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8')) as { name?: unknown; version?: unknown };\n if (pkg.name === PACKAGE_NAME && typeof pkg.version === 'string') return pkg.version;\n } catch {\n // No readable package.json here; keep walking up.\n }\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n/** This module's directory: `__dirname` in the CJS build, `import.meta.url` in ESM and in source. */\nfunction moduleDir(): string {\n return typeof __dirname === 'string' ? __dirname : dirname(fileURLToPath(import.meta.url));\n}\n\nexport const VERSION: string = findPackageVersion(moduleDir()) ?? '0.0.0';\n","/**\n * Twine 2 HTML and archive output.\n * Ported from storyout.go.\n */\nimport type {\n Diagnostic,\n OmittingTag,\n PassageOmission,\n ReadonlyStory,\n ReadonlyPassage,\n StoryFormatInfo,\n} from './types.js';\nimport {\n attrEscape,\n htmlEscape,\n commentSanitize,\n htmlCommentSanitize,\n scriptContentEscape,\n styleContentEscape,\n} from './escape.js';\nimport { passageToPassagedata, hasTag } from './passage.js';\nimport { readFormatSource } from './formats.js';\nimport { placeHead } from './modules.js';\nimport { fillTemplate, literal } from './template.js';\nimport type { TemplateSlot } from './template.js';\nimport { VERSION } from './version.js';\n\nconst CREATOR_NAME = 'Twee-ts';\n\nexport function toTwine2Archive(\n story: ReadonlyStory,\n startName: string,\n options?: { readonly sourceInfo?: boolean },\n): string {\n return getTwine2DataChunk(story, startName, options) + '\\n';\n}\n\n/**\n * Fill the Twine 2 format template: every `{{STORY_NAME}}` gets the escaped story name and the first\n * `{{STORY_DATA}}` the story data (as Tweego does), and `head` goes before the first closing head tag (or, with a\n * warning, the body start tag; see `placeHead()`). All three are found in the template in one pass, so a story\n * name, passage text or head content holding a placeholder or a closing head tag stays literal.\n * `options.diagnostics` receives a warning when the format file is not valid UTF-8, and any warning about where\n * `head` went.\n */\nexport function toTwine2HTML(\n story: ReadonlyStory,\n format: StoryFormatInfo,\n startName: string,\n options?: { readonly sourceInfo?: boolean; readonly head?: string; readonly diagnostics?: Diagnostic[] },\n): string {\n const name = htmlEscape(story.name);\n const template = readFormatSource(format, options?.diagnostics);\n const placement = placeHead(options?.head ?? '', [template], `Story format \"${format.name}\" ${format.version}`);\n options?.diagnostics?.push(...placement.diagnostics);\n const head = placement.slot;\n const slots: readonly TemplateSlot[] = [\n { pattern: literal('{{STORY_NAME}}'), occurrences: 'all', replacement: () => name },\n {\n pattern: literal('{{STORY_DATA}}'),\n occurrences: 'first',\n replacement: () => {\n // Advertise the format this HTML was built with (as Tweego does), not whatever StoryData named.\n const built = { ...story, twine2: { ...story.twine2, format: format.name, formatVersion: format.version } };\n return getTwine2DataChunk(built, startName, options);\n },\n },\n ...(head === undefined ? [] : [head]),\n ];\n return fillTemplate(template, slots);\n}\n\nconst OMITTING_TAGS: readonly OmittingTag[] = ['Twine.private', 'script', 'stylesheet'];\n\n/**\n * Why Twine 2 output leaves a passage out of its `<tw-passagedata>` elements,\n * or `undefined` when the passage is emitted (and so can be the starting passage).\n */\nexport function twine2PassageOmission(story: ReadonlyStory, p: ReadonlyPassage): PassageOmission | undefined {\n if (p.name === 'StoryTitle' || p.name === 'StoryData') return { kind: 'special-name', name: p.name };\n const tag = OMITTING_TAGS.find((t) => hasTag(p, t));\n if (tag !== undefined) return { kind: 'tag', tag };\n // Drop empty StorySettings\n if (p.name === 'StorySettings' && story.twine1.settings.size === 0) return { kind: 'empty-story-settings' };\n return undefined;\n}\n\nfunction getTwine2DataChunk(\n story: ReadonlyStory,\n startName: string,\n options?: { readonly sourceInfo?: boolean },\n): string {\n const parts: string[] = [];\n let startID = '';\n let pid = 0;\n\n // Gather script and stylesheet passages.\n const scripts: ReadonlyPassage[] = [];\n const stylesheets: ReadonlyPassage[] = [];\n for (const p of story.passages) {\n if (hasTag(p, 'Twine.private')) continue;\n if (hasTag(p, 'script')) scripts.push(p);\n else if (hasTag(p, 'stylesheet')) stylesheets.push(p);\n }\n\n // Style element\n let styleContent = '';\n if (stylesheets.length === 1) {\n styleContent = stylesheets[0]?.text ?? '';\n } else if (stylesheets.length > 1) {\n let pidS = 1;\n for (const p of stylesheets) {\n if (pidS > 1 && !styleContent.endsWith('\\n')) styleContent += '\\n';\n styleContent += `/* twine-user-stylesheet #${pidS}: \"${commentSanitize(p.name)}\" */\\n`;\n styleContent += p.text;\n pidS++;\n }\n }\n parts.push(\n `<style role=\"stylesheet\" id=\"twine-user-stylesheet\" type=\"text/twine-css\">${styleContentEscape(styleContent)}</style>`,\n );\n\n // Script element\n let scriptContent = '';\n if (scripts.length === 1) {\n scriptContent = scripts[0]?.text ?? '';\n } else if (scripts.length > 1) {\n let pidS = 1;\n for (const p of scripts) {\n if (pidS > 1 && !scriptContent.endsWith('\\n')) scriptContent += '\\n';\n scriptContent += `/* twine-user-script #${pidS}: \"${commentSanitize(p.name)}\" */\\n`;\n scriptContent += p.text;\n pidS++;\n }\n }\n parts.push(\n `<script role=\"script\" id=\"twine-user-script\" type=\"text/twine-javascript\">${scriptContentEscape(scriptContent)}</script>`,\n );\n\n // Tag color elements (only spec-valid colors: 7 named colors or hex values)\n const validTagColors = new Set(['gray', 'red', 'orange', 'yellow', 'green', 'blue', 'purple']);\n const hexColorPattern = /^#[0-9a-fA-F]{3,8}$/;\n for (const [tag, color] of story.twine2.tagColors) {\n if (validTagColors.has(color) || hexColorPattern.test(color)) {\n parts.push(`<tw-tag name=\"${attrEscape(tag)}\" color=\"${attrEscape(color)}\"></tw-tag>`);\n }\n }\n\n // Normal passage elements\n pid = 1;\n for (const p of story.passages) {\n if (twine2PassageOmission(story, p) !== undefined) continue;\n\n parts.push(passageToPassagedata(p, pid, options));\n if (startName === p.name) {\n startID = String(pid);\n }\n pid++;\n }\n\n // Build options string\n const opts: string[] = [];\n for (const [opt, val] of story.twine2.options) {\n if (val) opts.push(opt);\n }\n const optionsStr = opts.join(' ');\n\n // Wrap in tw-storydata\n const zoom = String(story.twine2.zoom);\n\n const wrapper =\n `<!-- UUID://${htmlCommentSanitize(story.ifid)}// -->` +\n `<tw-storydata name=\"${attrEscape(story.name)}\" startnode=\"${attrEscape(startID)}\" ` +\n `creator=\"${attrEscape(CREATOR_NAME)}\" creator-version=\"${attrEscape(VERSION)}\" ` +\n `ifid=\"${attrEscape(story.ifid)}\" zoom=\"${attrEscape(zoom)}\" ` +\n `format=\"${attrEscape(story.twine2.format)}\" ` +\n `format-version=\"${attrEscape(story.twine2.formatVersion)}\" ` +\n `options=\"${attrEscape(optionsStr)}\" tags=\"${attrEscape(story.twine2.tags)}\" hidden>`;\n\n return wrapper + parts.join('') + '</tw-storydata>';\n}\n","/**\n * Twine 1 HTML and archive output.\n * Ported from storyout.go.\n */\nimport { join, dirname } from 'node:path';\nimport type { Diagnostic, PassageOmission, ReadonlyPassage, ReadonlyStory, StoryFormatInfo } from './types.js';\nimport { readUTF8 } from './util.js';\nimport { hasTag, passageToTiddler } from './passage.js';\nimport { readFormatSource } from './formats.js';\nimport { placeHead } from './modules.js';\nimport { fillTemplateParts, literal } from './template.js';\nimport type { TemplateSlot } from './template.js';\nimport { jsStringEscape, htmlCommentSanitize } from './escape.js';\nimport { VERSION } from './version.js';\n\nconst CREATOR_NAME = 'twee-ts';\n\nexport function toTwine1Archive(story: ReadonlyStory, _startName: string): string {\n const { data, count } = getTwine1PassageChunk(story);\n return `<div id=\"storeArea\" data-size=\"${count}\">${data}</div>\\n`;\n}\n\n/**\n * Fill the Twine 1 format template. The format's components are inserted first, one after another, as Tweego and\n * Twine 1 do. Then the first of each story placeholder (`\"VERSION\"`, `\"TIME\"`, `\"START_AT\"`, `\"STORY_SIZE\"`,\n * `\"STORY\"`), the IFID comment and `head` (before the first closing head tag or, with a warning, the body start\n * tag; see `placeHead()`) are found in one pass, so a start passage name or story data holding a placeholder or a\n * closing head tag stays literal. `options.diagnostics` receives a warning for each format file that is not valid\n * UTF-8, and any warning about where `head` went.\n */\nexport function toTwine1HTML(\n story: ReadonlyStory,\n format: StoryFormatInfo,\n startName: string,\n options?: { readonly head?: string; readonly diagnostics?: Diagnostic[] },\n): string {\n const formatDir = dirname(format.filename);\n const parentDir = dirname(formatDir);\n const diagnostics = options?.diagnostics;\n let template = readFormatSource(format, diagnostics);\n const { data, count } = getTwine1PassageChunk(story);\n\n // Component replacements\n template = tryReplaceComponent(template, '\"USER_LIB\"', join(formatDir, 'userlib.js'), false, diagnostics);\n template = tryReplaceComponent(template, '\"ENGINE\"', join(parentDir, 'engine.js'), true, diagnostics);\n template = tryReplaceComponent(template, '\"SUGARCANE\"', join(formatDir, 'code.js'), true, diagnostics);\n template = tryReplaceComponent(template, '\"JONAH\"', join(formatDir, 'code.js'), true, diagnostics);\n\n if (story.twine1.settings.get('jquery') === 'on') {\n template = tryReplaceComponent(template, '\"JQUERY\"', join(parentDir, 'jquery.js'), true, diagnostics);\n }\n if (story.twine1.settings.get('modernizr') === 'on') {\n template = tryReplaceComponent(template, '\"MODERNIZR\"', join(parentDir, 'modernizr.js'), true, diagnostics);\n }\n\n // A pre-1.4 format has no \"STORY\" placeholder: the story data and a footer go after the template.\n const isPre14 = !template.includes('\"STORY\"');\n const footer = isPre14 ? readFooter(formatDir, diagnostics) : '';\n\n // The IFID comment and the head content are also looked for in the footer, if the template has no place for them.\n const storeArea = (template + footer).includes('<div id=\"store-area\"')\n ? '<div id=\"store-area\"'\n : '<div id=\"storeArea\"';\n const safeIfid = htmlCommentSanitize(story.ifid);\n const ifid: TemplateSlot | undefined = story.ifid\n ? { pattern: literal(storeArea), occurrences: 'first', replacement: (div) => `<!-- UUID://${safeIfid}// -->${div}` }\n : undefined;\n const placement = placeHead(\n options?.head ?? '',\n isPre14 ? [template, footer] : [template],\n `Story format \"${format.name}\"`,\n );\n diagnostics?.push(...placement.diagnostics);\n const late = [ifid, placement.slot].filter((slot) => slot !== undefined);\n\n // Story instance replacements. \"START_AT\" sits in a script element (`testplay = \"START_AT\";` in Sugarcane),\n // which jsStringEscape() keeps whole.\n const displayStart = startName === 'Start' ? '' : startName;\n const slots: readonly TemplateSlot[] = [\n firstSlot('\"VERSION\"', `Compiled with ${CREATOR_NAME}, ${VERSION}`),\n firstSlot('\"TIME\"', `Built on ${new Date().toUTCString()}`),\n firstSlot('\"START_AT\"', `\"${jsStringEscape(displayStart)}\"`),\n firstSlot('\"STORY_SIZE\"', `\"${count}\"`),\n firstSlot('\"STORY\"', data),\n ...late,\n ];\n\n return fillTemplateParts(\n isPre14\n ? [\n { kind: 'scan', text: template, slots },\n { kind: 'verbatim', text: data },\n { kind: 'scan', text: footer, slots: late },\n ]\n : [{ kind: 'scan', text: template, slots }],\n );\n}\n\n/** A slot replacing the first `token` with `value`. */\nfunction firstSlot(token: string, value: string): TemplateSlot {\n return { pattern: literal(token), occurrences: 'first', replacement: () => value };\n}\n\n/** The footer of a pre-1.4 format, or the default one when the format has none. */\nfunction readFooter(formatDir: string, diagnostics: Diagnostic[] | undefined): string {\n try {\n return readUTF8(join(formatDir, 'footer.html'), diagnostics);\n } catch {\n return '</div>\\n</body>\\n</html>\\n';\n }\n}\n\n/**\n * Why Twine 1 output leaves a passage out of its tiddlers, or `undefined` when the passage is emitted.\n */\nexport function twine1PassageOmission(p: ReadonlyPassage): PassageOmission | undefined {\n return hasTag(p, 'Twine.private') ? { kind: 'tag', tag: 'Twine.private' } : undefined;\n}\n\nfunction getTwine1PassageChunk(story: ReadonlyStory): { data: string; count: number } {\n const obfuscateRot13 = story.twine1.settings.get('obfuscate') === 'rot13';\n let data = '';\n let count = 0;\n\n for (const p of story.passages) {\n if (twine1PassageOmission(p) !== undefined) continue;\n count++;\n data += passageToTiddler(p, count, obfuscateRot13);\n }\n\n return { data, count };\n}\n\nfunction tryReplaceComponent(\n template: string,\n placeholder: string,\n componentPath: string,\n required: boolean,\n diagnostics: Diagnostic[] | undefined,\n): string {\n if (!template.includes(placeholder)) return template;\n try {\n const content = readUTF8(componentPath, diagnostics);\n return template.replace(placeholder, () => content);\n } catch (e) {\n if (required) {\n throw new Error(\n `Required format component not found: ${componentPath}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n return template;\n }\n}\n","/**\n * Twee 3/1 decompile output.\n * Ported from storyout.go.\n */\nimport type { Diagnostic, ReadonlyStory, ReadonlyPassage, OutputMode } from './types.js';\nimport { passageToTwee } from './passage.js';\nimport { createStory, marshalStoryData, unmarshalStoryData } from './story.js';\n\n/**\n * Serialize the story as Twee. The StoryData passage is written from the story model rather than\n * from its loaded text, so changes made after loading (a start passage override, test mode) are kept.\n * Tweego writes the loaded text; its own normalization makes the two the same for an unchanged story.\n *\n * Twee cannot write every passage so that it reads back the same (see `tweeRoundTrip()`); `diagnostics`\n * receives a warning for each passage that will not. Tweego writes the same Twee without one.\n *\n * `addStoryData`: add a StoryData passage when the story has none, so that StoryData fields the\n * compile options set are recorded. Default: false.\n */\nexport function toTwee(\n story: ReadonlyStory,\n outMode: OutputMode,\n options: { readonly addStoryData?: boolean; readonly diagnostics?: Diagnostic[] } = {},\n): string {\n const written = withEffectiveStoryData(story, options.addStoryData ?? false).map((p) => tweeRoundTrip(p, outMode));\n options.diagnostics?.push(...written.flatMap(({ diagnostics }) => diagnostics));\n return written.map(({ passage }) => passageToTwee(passage, outMode)).join('');\n}\n\nfunction withEffectiveStoryData(story: ReadonlyStory, addStoryData: boolean): readonly ReadonlyPassage[] {\n const storyData: ReadonlyPassage = { name: 'StoryData', tags: [], text: marshalStoryData(story) };\n const index = story.passages.findIndex((p) => p.name === 'StoryData');\n if (index !== -1) {\n return story.passages.map((p, i) => (i === index && isStoryDataJSON(p.text) ? { ...p, text: storyData.text } : p));\n }\n if (!addStoryData) return story.passages;\n // Place it where Twine and the HTML decompiler do: first, or right after a leading StoryTitle.\n const at = story.passages[0]?.name === 'StoryTitle' ? 1 : 0;\n return [...story.passages.slice(0, at), storyData, ...story.passages.slice(at)];\n}\n\n/** Whether the text loaded as StoryData. Text that did not is kept as written, for the author to fix. */\nfunction isStoryDataJSON(text: string): boolean {\n return unmarshalStoryData(createStory(), text) === null;\n}\n\n/** A passage as it is written to Twee, and the warnings about what will not read back the same. */\ninterface WrittenPassage {\n readonly passage: ReadonlyPassage;\n readonly diagnostics: readonly Diagnostic[];\n}\n\n/** Characters Twee 3 escapes in names and tags, and Twee 1 cannot write there at all. */\nconst TWEE1_UNWRITABLE = /[[\\]{}\\\\]/;\n\n/**\n * Check that Twee reads `p` back as written, and say what it will not. Twee has no way to escape passage text,\n * and its parser trims names and splits tags at whitespace, so these do not survive:\n *\n * - a text line that starts with `::`, which reads as a new passage header. In stylesheet and script passages such\n * a line is indented by one space, which keeps the CSS or JavaScript working (only a template literal or a\n * string continued across lines, in either, would see the space); the warning says so. Other passages' text is\n * written as it is.\n * - a name that is empty, has leading or trailing whitespace, or holds a line break;\n * - a tag that is empty or holds whitespace;\n * - in Twee 1, which escapes nothing, a name or tag holding `[`, `]`, `{`, `}` or `\\`.\n */\nfunction tweeRoundTrip(p: ReadonlyPassage, outMode: OutputMode): WrittenPassage {\n const label = `Passage ${JSON.stringify(p.name)}`;\n const diagnostics: Diagnostic[] = [];\n const warn = (problem: string): void => {\n diagnostics.push({\n level: 'warning',\n message: `${label} cannot be written as Twee that reads back the same: ${problem}.`,\n });\n };\n\n if (p.name.trim() === '') warn('its name is empty');\n else if (p.name.trim() !== p.name) warn('its name has leading or trailing whitespace, which Twee drops');\n if (/[\\r\\n]/.test(p.name)) warn('its name has a line break, which ends a Twee passage header');\n if (outMode === 'twee1' && TWEE1_UNWRITABLE.test(p.name)) {\n warn('its name has \"[\", \"]\", \"{\", \"}\" or \"\\\\\", which Twee 1 cannot escape');\n }\n\n for (const tag of p.tags) {\n if (tag === '' || /\\s/.test(tag)) {\n warn(`its tag ${JSON.stringify(tag)} is empty or has whitespace, which splits tags in Twee`);\n }\n if (outMode === 'twee1' && TWEE1_UNWRITABLE.test(tag)) {\n warn(`its tag ${JSON.stringify(tag)} has \"[\", \"]\", \"{\", \"}\" or \"\\\\\", which Twee 1 cannot escape`);\n }\n }\n\n // Twee source is read with CRLF and CR line endings turned into LF, so a CR breaks a line too.\n const lines = p.text.split(/(\\r\\n?|\\n)/);\n const headerLines = lines.flatMap((line, i) => (i % 2 === 0 && line.startsWith('::') ? [i / 2 + 1] : []));\n if (headerLines.length === 0) return { passage: p, diagnostics };\n\n const where = `${headerLines.length === 1 ? 'line' : 'lines'} ${headerLines.join(', ')} of its text start${headerLines.length === 1 ? 's' : ''} with \"::\", which Twee reads as a passage header`;\n if (!p.tags.some((tag) => tag === 'stylesheet' || tag === 'script')) {\n warn(where);\n return { passage: p, diagnostics };\n }\n diagnostics.push({\n level: 'warning',\n message: `${label}: ${where}; ${headerLines.length === 1 ? 'it was' : 'they were'} written indented by one space.`,\n });\n const text = lines.map((line, i) => (i % 2 === 0 && line.startsWith('::') ? ` ${line}` : line)).join('');\n return { passage: { ...p, text }, diagnostics };\n}\n","/**\n * Which passages an output leaves out of its passage elements, and how to say why.\n * The rules themselves live with each output renderer; this module picks one by target.\n */\nimport type { PassageOmission, PassageOutputTarget, ReadonlyPassage, ReadonlyStory } from './types.js';\nimport { twine2PassageOmission } from './output-twine2.js';\nimport { twine1PassageOmission } from './output-twine1.js';\n\n/**\n * Why the `target` output leaves `passage` out of its passage elements, or `undefined` when it\n * emits the passage (and so a link or the start can name it).\n */\nexport function passageOmission(\n story: ReadonlyStory,\n passage: ReadonlyPassage,\n target: PassageOutputTarget,\n): PassageOmission | undefined {\n switch (target) {\n case 'twine2':\n return twine2PassageOmission(story, passage);\n case 'twine1':\n return twine1PassageOmission(passage);\n default: {\n const _exhaustive: never = target;\n throw new Error(`unhandled passage output target: ${String(_exhaustive)}`);\n }\n }\n}\n\n/** Why a passage is left out, as a predicate: `Passage \"X\" ${describeOmission(o)}`. */\nexport function describeOmission(omission: PassageOmission): string {\n switch (omission.kind) {\n case 'special-name':\n return `is the special \"${omission.name}\" passage`;\n case 'tag':\n return `is tagged \"${omission.tag}\"`;\n case 'empty-story-settings':\n return 'is an empty \"StorySettings\" passage';\n default: {\n const _exhaustive: never = omission;\n throw new Error(`unhandled passage omission: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n","/**\n * Starting passage validation: the effective start must exist and be a\n * passage that the output actually emits, or the story has nowhere to begin.\n */\nimport type { Diagnostic, PassageOutputTarget, ReadonlyStory } from './types.js';\nimport { describeOmission, passageOmission } from './passage-omission.js';\n\n/**\n * Check that `startName` names a passage the `target` output emits.\n * Returns the error diagnostics to report (empty when the start is usable).\n */\nexport function startPassageDiagnostics(\n story: ReadonlyStory,\n startName: string,\n target: PassageOutputTarget,\n): readonly Diagnostic[] {\n const passage = story.passages.find((p) => p.name === startName);\n if (passage === undefined) {\n return [{ level: 'error', message: `Starting passage \"${startName}\" not found.` }];\n }\n const omission = passageOmission(story, passage, target);\n if (omission === undefined) return [];\n return [\n {\n level: 'error',\n message: `Starting passage \"${startName}\" ${describeOmission(omission)}, so it is left out of the story data. Choose a story passage.`,\n },\n ];\n}\n","/**\n * Main compiler orchestrator.\n * compile(), compileToFile(), watch().\n * Ported from tweego.go + config.go.\n */\nimport { resolve, sep } from 'node:path';\nimport type {\n CompileOptions,\n CompileToFileOptions,\n WatchOptions,\n CompileResult,\n CompileStats,\n Diagnostic,\n Story,\n StoryFormatInfo,\n OutputMode,\n InlineSource,\n FileCacheEntry,\n} from './types.js';\nimport { createStory, storyHas, getStoryStats } from './story.js';\nimport { getFilenames, isExcluded, outputPaths, realPathOf, toBuildOutputs, watchFilesystem } from './filesystem.js';\nimport type { BuildOutputs } from './filesystem.js';\nimport { formatRequestFor, resolveStoryFormat } from './format-resolution.js';\nimport { loadSources, loadInlineSources, loadSourcesCached } from './loader.js';\nimport { applyTagAliases, hasTag } from './passage.js';\nimport { generateIFID } from './ifid.js';\nimport { toTwine2HTML, toTwine2Archive } from './output-twine2.js';\nimport { toTwine1HTML, toTwine1Archive } from './output-twine1.js';\nimport { toTwee } from './output-twee.js';\nimport { loadHeadContent } from './modules.js';\nimport { startPassageDiagnostics } from './start-passage.js';\nimport { clearIndexCache } from './remote-formats.js';\nimport { writeFileAtomic } from './atomic-write.js';\nimport { VERSION } from './version.js';\n\nconst CREATOR_NAME = 'Twee-ts';\n\nconst DEFAULT_FORMAT_ID = 'sugarcube-2';\nconst DEFAULT_START_NAME = 'Start';\n\nexport class TweeTsError extends Error {\n constructor(\n message: string,\n public diagnostics: Diagnostic[] = [],\n ) {\n super(message);\n this.name = 'TweeTsError';\n }\n}\n\n/**\n * Compile Twee sources to HTML, Twee, or JSON.\n */\nexport async function compile(options: CompileOptions): Promise<CompileResult> {\n return buildOutput(options);\n}\n\n/**\n * Compile and write to a file. The file is replaced atomically: a reader sees the previous\n * build or the new one, never part of it, and a failed write leaves the previous build.\n */\nexport async function compileToFile(options: CompileToFileOptions): Promise<CompileResult> {\n const result = await compileForOutputFile(options, options.outFile);\n // The build may have been aborted after it finished: the previous output stays.\n options.signal?.throwIfAborted();\n writeFileAtomic(options.outFile, result.output);\n return result;\n}\n\n/**\n * Builds as compileToFile() does for `outputs`, without writing them: an output may sit\n * inside a source folder, so its last build is left out of the sources and modules and\n * never read back. `outputs` is the one file the CLI writes, or every path a bundler's\n * build writes (see BuildOutputs). The caller decides whether the result is written.\n * With no outputs (output to stdout, or none), this is compile(). With `cache`, files\n * are cached as compileIncremental() caches them.\n *\n * Throws a TweeTsError when a source, module or head file named directly is an output.\n *\n * Internal, for the CLI and the bundler plugins; not part of the public API.\n */\nexport async function compileForOutputFile(\n options: CompileOptions,\n outputs: BuildOutputs | string | undefined,\n cache?: Map<string, FileCacheEntry>,\n): Promise<CompileResult> {\n return buildOutput(options, cache, undefined, outputs);\n}\n\n/**\n * Compile with incremental caching support.\n * Plugins and advanced users can manage their own cache and changed-file tracking.\n *\n * Without `changedFiles`, a cached file is reused while its modification time is unchanged.\n * With it, a file it names is always reparsed, whatever its modification time, and every\n * other cached file is reused as it is. A file may be named by an absolute path or by a path\n * relative to the working directory, with or without a leading `./`: entries are matched to\n * the source files by resolved path. A file that fails to load is dropped from the cache, so\n * the next build tries it again.\n */\nexport async function compileIncremental(\n options: CompileOptions,\n cache: Map<string, FileCacheEntry>,\n changedFiles?: ReadonlySet<string>,\n): Promise<CompileResult> {\n return buildOutput(options, cache, changedFiles);\n}\n\n/**\n * Watch for file changes and recompile. Every build is written to `outFile` (replacing it\n * atomically, as compileToFile() does), including one whose diagnostics report errors.\n * Builds run one at a time, and each one is written and reported as it finishes, in order:\n * changes made during a build go into one follow-up build after it. A watched path that\n * can't be watched is passed to `onError`.\n *\n * Aborting the returned controller, or the `signal` in the options, stops watching and\n * aborts the story format requests of the build in progress.\n */\nexport async function watch(options: WatchOptions): Promise<AbortController> {\n return watchWithWriteFilter(options, () => true);\n}\n\n/**\n * watch(), writing to `outFile` only the builds `shouldWrite` accepts. A rejected build\n * leaves the output file as it was; `onBuild` receives every build either way.\n *\n * Internal, for the CLI, which keeps the last good output when a rebuild reports errors;\n * not part of the public API.\n */\nexport async function watchWithWriteFilter(\n options: WatchOptions,\n shouldWrite: (result: CompileResult) => boolean,\n hooks: WatchHooks = {},\n): Promise<AbortController> {\n const controller = new AbortController();\n const cache = new Map<string, FileCacheEntry>();\n // Every build runs with the controller's signal, which the caller's own signal also aborts (below).\n const buildOptions: WatchOptions = { ...options, signal: controller.signal };\n\n // Separate file paths from inline sources\n const filePaths = options.sources.filter((s): s is string => typeof s === 'string');\n const modulePaths = options.modules ?? [];\n const headPaths = options.headFile ? [options.headFile] : [];\n const allPaths = [...filePaths, ...modulePaths, ...headPaths];\n\n // A change to an excluded source builds nothing. `exclude` leaves modules and the\n // head file alone, so a module (or a file in a module folder) or the head file\n // still rebuilds when a glob matches it.\n const exclude = options.exclude ?? [];\n const notExcludable = [...modulePaths, ...headPaths].map((p) => resolve(p));\n const ignore = (filename: string): boolean => {\n if (!isExcluded(filename, exclude)) return false;\n const abs = resolve(filename);\n return !notExcludable.some((root) => abs === root || abs.startsWith(root + sep));\n };\n\n // One build at a time. Changes reported while a build is in flight wait in `queued` and go\n // into a single follow-up build once it finishes. Every finished build is delivered first:\n // it can't be older than what was delivered before it, and delivering each one means a\n // steady stream of changes still produces regular output and reports.\n let building = false;\n let queued: WatchBuildRequest | undefined;\n\n // onError is the last place an error can go; an exception from it is reported to the\n // console instead, so that it never ends the watch as an unhandled rejection.\n const reportError = (error: Error): void => {\n try {\n options.onError?.(error);\n } catch (e) {\n console.error(`twee-ts watch: onError threw while handling \"${error.message}\": ${toError(e).message}`);\n }\n };\n\n const deliver = (outcome: WatchBuildOutcome): void => {\n try {\n if (!outcome.ok) throw outcome.error;\n if (shouldWrite(outcome.result)) writeFileAtomic(options.outFile, outcome.result.output);\n options.onBuild?.(outcome.result);\n } catch (e) {\n reportError(toError(e));\n }\n };\n\n // Runs `first`, then the follow-up for whatever was queued meanwhile, until nothing is.\n // `building` is cleared in the same step as the last delivery, so a change reported\n // right after it starts a new build rather than waiting in `queued`.\n const drain = async (first: WatchBuildRequest): Promise<void> => {\n building = true;\n try {\n let request: WatchBuildRequest | undefined = first;\n while (request !== undefined) {\n const outcome = await buildOutput(buildOptions, cache, request.changedFiles, options.outFile).then(\n (result): WatchBuildOutcome => ({ ok: true, result }),\n (e: unknown): WatchBuildOutcome => ({ ok: false, error: toError(e) }),\n );\n if (controller.signal.aborted) return;\n deliver(outcome);\n request = queued;\n queued = undefined;\n }\n } finally {\n building = false;\n hooks.onIdle?.();\n }\n };\n\n const handle = watchFilesystem(\n allPaths,\n options.outFile,\n (changedFiles) => {\n if (controller.signal.aborted) return;\n const request: WatchBuildRequest = { changedFiles };\n if (building) {\n queued = queued === undefined ? request : mergeBuildRequests(queued, request);\n return;\n }\n drain(request).catch((e: unknown) => reportError(toError(e)));\n },\n ignore,\n reportError,\n );\n\n const outer = options.signal;\n const onOuterAbort = (): void => controller.abort(outer?.reason);\n controller.signal.addEventListener('abort', () => {\n queued = undefined;\n handle.close();\n outer?.removeEventListener('abort', onOuterAbort);\n });\n if (outer?.aborted) onOuterAbort();\n else outer?.addEventListener('abort', onOuterAbort, { once: true });\n return controller;\n}\n\n/** Internal hooks into watchWithWriteFilter(); not part of the public API. */\nexport interface WatchHooks {\n /**\n * Called each time the watch's builds have run out: the last one was delivered or, after\n * an abort, dropped, and none is in flight. Lets a test wait for a build to finish when\n * nothing it does shows.\n */\n readonly onIdle?: () => void;\n}\n\n/** A watch-mode build: the files that changed, or `undefined` for a full build. */\ninterface WatchBuildRequest {\n readonly changedFiles: ReadonlySet<string> | undefined;\n}\n\ntype WatchBuildOutcome =\n { readonly ok: true; readonly result: CompileResult } | { readonly ok: false; readonly error: Error };\n\n/** One build covering both requests: a full build if either is one, else every changed file. */\nfunction mergeBuildRequests(a: WatchBuildRequest, b: WatchBuildRequest): WatchBuildRequest {\n if (a.changedFiles === undefined || b.changedFiles === undefined) return { changedFiles: undefined };\n return { changedFiles: new Set([...a.changedFiles, ...b.changedFiles]) };\n}\n\nfunction toError(e: unknown): Error {\n return e instanceof Error ? e : new Error(String(e));\n}\n\n/**\n * `outputs`: what the build writes (an output file's path, or a bundler's outputs),\n * which source and module discovery skip, so an output inside a source folder is\n * never loaded back. A source, module or head file named directly that is an output\n * is a TweeTsError, as in Tweego: writing the build would overwrite it.\n */\nasync function buildOutput(\n options: CompileOptions,\n cache?: Map<string, FileCacheEntry>,\n changedFiles?: ReadonlySet<string>,\n outputs?: BuildOutputs | string,\n): Promise<CompileResult> {\n const written = toBuildOutputs(outputs);\n const diagnostics: Diagnostic[] = [];\n const outputMode: OutputMode = options.outputMode ?? 'html';\n const trim = options.trim ?? true;\n const twee2Compat = options.twee2Compat ?? false;\n const testMode = options.testMode ?? false;\n const noRemote = options.noRemote ?? false;\n const sourceInfo = options.sourceInfo ?? false;\n\n options.signal?.throwIfAborted();\n const timeout = options.formatFetchTimeout;\n if (timeout !== undefined && !(timeout >= 0)) {\n throw new TweeTsError(`formatFetchTimeout must be 0 or more milliseconds, not ${timeout}.`);\n }\n\n // Clear per-compile index cache\n clearIndexCache();\n\n // Group the sources in the order supplied: each run of file paths is walked (directories\n // expanded in place) and each run of inline sources is kept together, so a later source\n // overrides an earlier one whatever kind each is.\n const groups: SourceGroup[] = [];\n const outputSources: string[] = [];\n for (const source of options.sources) {\n const last = groups[groups.length - 1];\n if (typeof source === 'string') {\n if (last?.kind === 'paths') last.paths.push(source);\n else groups.push({ kind: 'paths', paths: [source] });\n } else if (last?.kind === 'inline') {\n last.sources.push(source);\n } else {\n groups.push({ kind: 'inline', sources: [source] });\n }\n }\n\n const walked = groups.map((group) => {\n if (group.kind === 'inline') return group;\n const found = getFilenames(group.paths, written, options.exclude);\n diagnostics.push(...found.diagnostics);\n outputSources.push(...found.outputSources);\n return { kind: 'files' as const, filenames: found.filenames };\n });\n rejectOutputSources(outputSources, diagnostics);\n // Every file of the build, so that a cache purge while loading one group keeps the others' entries.\n const buildFiles = new Set(walked.flatMap((group) => (group.kind === 'files' ? group.filenames : [])));\n\n // Create story and load sources\n const story = createStory();\n const processedFiles = new Set<string>();\n\n for (const group of walked) {\n if (group.kind === 'inline') {\n loadInlineSources(story, group.sources, { trim, twee2Compat }, diagnostics);\n } else if (cache) {\n loadSourcesCached(\n story,\n group.filenames,\n { trim, twee2Compat },\n diagnostics,\n processedFiles,\n cache,\n changedFiles,\n buildFiles,\n );\n } else {\n loadSources(story, group.filenames, { trim, twee2Compat }, diagnostics, processedFiles);\n }\n }\n if (cache && buildFiles.size === 0) {\n loadSourcesCached(story, [], { trim, twee2Compat }, diagnostics, processedFiles, cache, changedFiles);\n }\n\n // Apply tag aliases (e.g. library → script)\n if (options.tagAliases) {\n story.passages = applyTagAliases(story.passages, options.tagAliases);\n }\n\n // Resolve format: explicit formatId > StoryData format > default, looked up locally,\n // in the download cache, then remotely. An unavailable request is an error, never another format.\n let format: StoryFormatInfo | undefined;\n\n if (outputMode === 'html') {\n const request = formatRequestFor(\n options.formatId,\n story.twine2.format,\n story.twine2.formatVersion,\n DEFAULT_FORMAT_ID,\n );\n format = await resolveStoryFormat(request, { ...options, noRemote }, diagnostics);\n // The caller may have aborted while the format was being found.\n options.signal?.throwIfAborted();\n }\n\n // Merge config from StoryData: command-line > StoryData > default.\n // An explicit override is recorded on the story so JSON output and inspection see it too.\n if (options.startPassage) story.twine2.start = options.startPassage;\n const startName = story.twine2.start || DEFAULT_START_NAME;\n\n // Apply test mode\n if (testMode) {\n story.twine2.options.set('debug', true);\n }\n\n // Ensure IFID is set before output generation\n ensureIFID(story, diagnostics);\n\n // Generate output\n let output: string;\n\n switch (outputMode) {\n case 'twee3':\n case 'twee1':\n // Without a StoryData passage, add one only to record what the options changed.\n output = toTwee(story, outputMode, { addStoryData: Boolean(options.startPassage) || testMode, diagnostics });\n break;\n\n case 'twine2-archive':\n output = toTwine2Archive(story, startName, { sourceInfo });\n break;\n\n case 'twine1-archive':\n output = toTwine1Archive(story, startName);\n break;\n\n case 'json':\n output = storyToJSON(story);\n break;\n\n case 'html': {\n // Sanity checks for HTML mode\n diagnostics.push(...startPassageDiagnostics(story, startName, format?.isTwine2 === false ? 'twine1' : 'twine2'));\n\n if (!format) {\n throw new TweeTsError('No story format available for HTML output.', diagnostics);\n }\n\n if (!format.isTwine2 && story.name === '' && !storyHas(story, 'StoryTitle')) {\n diagnostics.push({\n level: 'error',\n message: 'Special passage \"StoryTitle\" not found.',\n });\n }\n\n // Modules and head file, injected before the template's closing head tag while the template is filled\n const modules = getFilenames(options.modules ?? [], written);\n diagnostics.push(...modules.diagnostics);\n const { headFile } = options;\n const headIsOutput = headFile !== undefined && outputPaths(written).isFile(realPathOf(headFile));\n rejectOutputSources([...modules.outputSources, ...(headIsOutput ? [headFile] : [])], diagnostics);\n const head = loadHeadContent(modules.filenames, options.headFile, diagnostics);\n\n output = format.isTwine2\n ? toTwine2HTML(story, format, startName, { sourceInfo, head, diagnostics })\n : toTwine1HTML(story, format, startName, { head, diagnostics });\n break;\n }\n\n default: {\n const _exhaustive: never = outputMode;\n throw new TweeTsError(`Unhandled output mode: ${_exhaustive as string}`, diagnostics);\n }\n }\n\n // Compute stats\n const stats: CompileStats = {\n ...getStoryStats(story, options.wordCountMethod),\n files: [...processedFiles],\n };\n\n // Nothing is delivered, or written by the caller, for a build that was aborted meanwhile.\n options.signal?.throwIfAborted();\n return { output, story, format, diagnostics, stats };\n}\n\n/** A run of sources of one kind, in the order supplied. */\ntype SourceGroup =\n { readonly kind: 'paths'; readonly paths: string[] } | { readonly kind: 'inline'; readonly sources: InlineSource[] };\n\n/**\n * Throws for the first of `paths`, inputs named directly that are also an output:\n * writing the build would overwrite them. An output found while walking a source\n * folder is skipped instead (see getFilenames).\n */\nfunction rejectOutputSources(paths: readonly string[], diagnostics: readonly Diagnostic[]): void {\n const [first] = paths;\n if (first === undefined) return;\n throw new TweeTsError(`path ${first}: Output file cannot be an input source.`, [...diagnostics]);\n}\n\nfunction ensureIFID(story: Story, diagnostics: Diagnostic[]): void {\n if (story.ifid !== '') return;\n\n if (story.legacyIFID !== '') {\n story.ifid = story.legacyIFID;\n diagnostics.push({\n level: 'warning',\n message: 'Story IFID not found; reusing \"ifid\" entry from the \"StorySettings\" special passage.',\n });\n } else {\n const ifid = generateIFID();\n story.ifid = ifid;\n diagnostics.push({\n level: 'error',\n message: `Story IFID not found. Add an IFID to your story: {\"ifid\":\"${ifid}\"}`,\n });\n }\n}\n\n/**\n * Serialize a Story to JSON per the Twine 2 JSON Output Specification (v1.0):\n * https://github.com/iftechfoundation/twine-specs/blob/master/twine-2-jsonoutput-doc.md\n */\nfunction storyToJSON(story: Story): string {\n // Gather script and stylesheet content, excluding them from passages.\n const scripts: string[] = [];\n const stylesheets: string[] = [];\n const storyPassages: { name: string; tags: string[]; text: string; metadata?: Record<string, string> }[] = [];\n\n for (const p of story.passages) {\n if (p.name === 'StoryTitle' || p.name === 'StoryData') continue;\n if (hasTag(p, 'Twine.private')) continue;\n\n if (hasTag(p, 'script')) {\n scripts.push(p.text);\n } else if (hasTag(p, 'stylesheet')) {\n stylesheets.push(p.text);\n } else {\n const entry: { name: string; tags: string[]; text: string; metadata?: Record<string, string> } = {\n name: p.name,\n tags: p.tags,\n text: p.text,\n };\n if (p.metadata) {\n const meta: Record<string, string> = {};\n for (const [key, value] of Object.entries(p.metadata)) {\n if (typeof value === 'string') meta[key] = value;\n }\n if (Object.keys(meta).length > 0) {\n entry.metadata = meta;\n }\n }\n storyPassages.push(entry);\n }\n }\n\n const obj: Record<string, unknown> = {\n name: story.name,\n };\n\n if (story.ifid) obj.ifid = story.ifid;\n if (story.twine2.format) obj.format = story.twine2.format;\n if (story.twine2.formatVersion) obj['format-version'] = story.twine2.formatVersion;\n if (story.twine2.start) obj.start = story.twine2.start;\n if (story.twine2.tagColors.size > 0) obj['tag-colors'] = Object.fromEntries(story.twine2.tagColors);\n if (story.twine2.zoom !== 1) obj.zoom = story.twine2.zoom;\n obj.creator = CREATOR_NAME;\n obj['creator-version'] = VERSION;\n obj.style = stylesheets.join('\\n');\n obj.script = scripts.join('\\n');\n obj.passages = storyPassages;\n\n return JSON.stringify(obj, null, 2);\n}\n","/**\n * How the build plugins turn compile results into bundler errors and warnings.\n */\nimport type { CompileResult, Diagnostic } from '../types.js';\nimport { TweeTsError } from '../compiler.js';\n\n/** An error carrying the file and line the bundler reports (and Vite shows in its overlay). */\nexport interface LocatedError extends Error {\n id?: string;\n loc?: { file: string; line: number; column: number };\n}\n\nexport function formatDiagnostic(d: Readonly<Diagnostic>): string {\n const where = d.file ? `${d.file}${d.line ? `:${d.line}` : ''}: ` : '';\n // The parser starts its messages with \"line N: \"; the location already says it.\n const message = d.file && d.line ? d.message.replace(/^line \\d+: /, '') : d.message;\n return `${where}${message}`;\n}\n\n/** Returns the warnings; throws a LocatedError when the compile reported errors. */\nexport function splitDiagnostics(result: Readonly<CompileResult>): Diagnostic[] {\n const errors = result.diagnostics.filter((d) => d.level === 'error');\n if (errors.length === 0) return result.diagnostics.filter((d) => d.level === 'warning');\n const error: LocatedError = new Error(errors.map(formatDiagnostic).join('\\n'));\n const [first] = errors;\n if (first?.file) {\n error.id = first.file;\n error.loc = { file: first.file, line: first.line ?? 1, column: 1 };\n }\n throw error;\n}\n\n/** An error thrown by the compiler or bundler, with a TweeTsError's error diagnostics folded into its message. */\nexport function fatalError(e: unknown): LocatedError {\n if (e instanceof TweeTsError) {\n const errors = e.diagnostics.filter((d) => d.level === 'error').map(formatDiagnostic);\n return new Error([...errors, e.message].join('\\n'));\n }\n return e instanceof Error ? e : new Error(String(e));\n}\n","/**\n * Path helpers for the bundler plugins. Vite reports module ids with forward\n * slashes on every platform, while node:path gives backslashes on Windows, so\n * the Vite plugin compares paths in forward-slash form only. Paths a build\n * writes are compared by real path instead (see filesystem.ts).\n */\nimport { dirname, resolve } from 'node:path';\nimport type { BuildOutputs } from '../filesystem.js';\n\n/** The output settings that say where a bundle is written, as Rollup and Vite pass them to generateBundle. */\nexport interface OutputLocation {\n readonly dir?: string | undefined;\n readonly file?: string | undefined;\n}\n\n/**\n * The absolute path a bundle writes the file it emits as `fileName` to: inside\n * `output.dir`, or next to `output.file`, either resolved against the working\n * directory, as the bundler resolves them. Undefined when the output names\n * neither, as for a bundle only generated in memory.\n */\nexport function emittedFilePath(output: OutputLocation, fileName: string): string | undefined {\n const dir = output.dir ?? (output.file === undefined ? undefined : dirname(output.file));\n return dir === undefined ? undefined : resolve(dir, fileName);\n}\n\n/**\n * The locations a bundler's `output` option names: one output's settings or an\n * array of them, as a config gives them. Outputs that name neither `dir` nor\n * `file`, and anything that isn't an output's settings, are left out.\n */\nexport function outputLocations(option: unknown): OutputLocation[] {\n return (Array.isArray(option) ? option : [option]).flatMap((output: unknown): OutputLocation[] => {\n if (typeof output !== 'object' || output === null) return [];\n const { dir, file } = output as { readonly dir?: unknown; readonly file?: unknown };\n const location = {\n ...(typeof dir === 'string' ? { dir } : {}),\n ...(typeof file === 'string' ? { file } : {}),\n };\n return location.dir === undefined && location.file === undefined ? [] : [location];\n });\n}\n\n/**\n * Every path the builds of one plugin instance write, gathered from what the\n * bundler reports: each output's location (`output.dir`, `output.file`, the\n * story inside it) and the files of each bundle written there. It is kept across\n * builds, so a compile also leaves out what another output of the same build\n * writes, before or after it, and files an earlier build wrote that the current\n * one doesn't (an old hashed chunk).\n */\nexport interface OutputRecord {\n /** Records an output location: its folder, its file, and the story it writes. */\n addLocation(output: OutputLocation): void;\n /** Records the files a bundle writes to `output`, by output file name. */\n addFiles(output: OutputLocation, fileNames: Iterable<string>): void;\n /** Every path recorded so far: `output.dir` folders as folders, the rest as files. */\n outputs(): BuildOutputs;\n}\n\n/** An empty OutputRecord for a plugin that writes its story as `storyFileName`. */\nexport function createOutputRecord(storyFileName: string): OutputRecord {\n const files = new Set<string>();\n const dirs = new Set<string>();\n const addFiles = (output: OutputLocation, fileNames: Iterable<string>): void => {\n for (const fileName of fileNames) {\n const path = emittedFilePath(output, fileName);\n if (path !== undefined) files.add(path);\n }\n };\n return {\n addLocation(output) {\n if (output.dir !== undefined) dirs.add(resolve(output.dir));\n if (output.file !== undefined) files.add(resolve(output.file));\n addFiles(output, [storyFileName]);\n },\n addFiles,\n outputs: () => ({ files: [...files], dirs: [...dirs] }),\n };\n}\n\n/** The path with Windows separators turned into forward slashes. */\nexport function toPosix(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n/** Whether `file` is one of `dirs` or inside one of them. All paths in forward-slash form. */\nexport function isInside(file: string, dirs: readonly string[]): boolean {\n return dirs.some((dir) => file === dir || file.startsWith(dir.endsWith('/') ? dir : `${dir}/`));\n}\n\n/**\n * Whether `file` is a temporary copy of a Vite config file. Vite writes one next\n * to the config file each time it loads it (when no node_modules folder is\n * above the config, and always under Deno), then deletes it.\n */\nexport function isViteConfigTemp(file: string): boolean {\n return /\\.timestamp-\\d+-[0-9a-f]*\\.mjs$/.test(file);\n}\n"],"x_google_ignoreList":[18,19,20,21,22,23,24,25,26,27,28,29],"mappings":";;;;;;;;;;;;AAQA,SAAgB,eAAqB;CACnC,OAAO,WAAW,CAAC,CAAC,YAAY;AAClC;;AAaA,MAAM,iBAAiB;;;;;;;;AASvB,SAAgB,cAAc,OAAqB;CACjD,MAAM,QAAQ,MAAM,YAAY;CAEhC,OADa,MAAM,WAAW,kBAAkB,aAAa,KAAK,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE,IAAI;AAEtG;;;;;;AAOA,SAAgB,aAAa,MAA6B;CACxD,IAAI,OAAO;CAEX,QAAQ,KAAK,QAAb;EACE,KAAK,IACH;EACF,KAAK;GACH,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,YAAY,MAAM,aAAa,KAAK,MAAM,EAAE,MAAM,MACrE,OAAO;GAET,OAAO,KAAK,MAA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