@pixerate/editor 0.23.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -1
- package/THIRD_PARTY_NOTICES.md +51 -0
- package/dist/agent/index.cjs +9 -8
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +4 -3
- package/dist/agent/index.d.ts +4 -3
- package/dist/agent/index.js +3 -2
- package/dist/agent/index.js.map +1 -1
- package/dist/canvas/index.cjs +1210 -17
- package/dist/canvas/index.cjs.map +1 -1
- package/dist/canvas/index.d.cts +318 -1
- package/dist/canvas/index.d.ts +318 -1
- package/dist/canvas/index.js +1199 -6
- package/dist/canvas/index.js.map +1 -1
- package/dist/{chunk-QBJ22YZR.js → chunk-3CN2WD3X.js} +1354 -206
- package/dist/chunk-3CN2WD3X.js.map +1 -0
- package/dist/{chunk-JJDLPEWL.js → chunk-3LV6RRPH.js} +2 -2
- package/dist/{chunk-MJZBNWG7.js → chunk-5S3Z4PPF.js} +78 -557
- package/dist/chunk-5S3Z4PPF.js.map +1 -0
- package/dist/chunk-664LQYFJ.js +115 -0
- package/dist/chunk-664LQYFJ.js.map +1 -0
- package/dist/{chunk-AA4ZEVCC.cjs → chunk-D27YFC46.cjs} +101 -580
- package/dist/chunk-D27YFC46.cjs.map +1 -0
- package/dist/chunk-D6FH2YAX.cjs +131 -0
- package/dist/chunk-D6FH2YAX.cjs.map +1 -0
- package/dist/{chunk-4SUNJZWB.cjs → chunk-FD4LPFAE.cjs} +48 -200
- package/dist/chunk-FD4LPFAE.cjs.map +1 -0
- package/dist/chunk-FODNLX5N.js +749 -0
- package/dist/chunk-FODNLX5N.js.map +1 -0
- package/dist/{chunk-OYXSKQFR.js → chunk-FPENXAEJ.js} +35 -187
- package/dist/chunk-FPENXAEJ.js.map +1 -0
- package/dist/chunk-HLIMTC6N.js +1 -0
- package/dist/chunk-HLIMTC6N.js.map +1 -0
- package/dist/{chunk-QGHGJ56O.js → chunk-ITBSKI26.js} +1483 -19
- package/dist/chunk-ITBSKI26.js.map +1 -0
- package/dist/{chunk-XDMXXC4Z.cjs → chunk-MA2F5KHF.cjs} +350 -227
- package/dist/chunk-MA2F5KHF.cjs.map +1 -0
- package/dist/{chunk-RIKBJLS2.cjs → chunk-MCSJFWAO.cjs} +1356 -208
- package/dist/chunk-MCSJFWAO.cjs.map +1 -0
- package/dist/chunk-MKA3AHLV.cjs +256 -0
- package/dist/chunk-MKA3AHLV.cjs.map +1 -0
- package/dist/chunk-OLZJXL4R.cjs +749 -0
- package/dist/chunk-OLZJXL4R.cjs.map +1 -0
- package/dist/chunk-OXSV64JX.js +689 -0
- package/dist/chunk-OXSV64JX.js.map +1 -0
- package/dist/chunk-P3RQ5UJE.cjs +689 -0
- package/dist/chunk-P3RQ5UJE.cjs.map +1 -0
- package/dist/chunk-P6ODPZ4W.js +256 -0
- package/dist/chunk-P6ODPZ4W.js.map +1 -0
- package/dist/chunk-PGNZKFQS.js +685 -0
- package/dist/chunk-PGNZKFQS.js.map +1 -0
- package/dist/chunk-PL4JB3BF.cjs +1 -0
- package/dist/chunk-PL4JB3BF.cjs.map +1 -0
- package/dist/{chunk-GVSMRPHB.cjs → chunk-SBCZ6RN5.cjs} +1568 -104
- package/dist/chunk-SBCZ6RN5.cjs.map +1 -0
- package/dist/{chunk-CL37JGFW.cjs → chunk-SML64VJG.cjs} +4 -4
- package/dist/{chunk-CL37JGFW.cjs.map → chunk-SML64VJG.cjs.map} +1 -1
- package/dist/chunk-TNNJXF46.cjs +115 -0
- package/dist/chunk-TNNJXF46.cjs.map +1 -0
- package/dist/chunk-U5HZSFCS.js +131 -0
- package/dist/chunk-U5HZSFCS.js.map +1 -0
- package/dist/{chunk-K3R5NG2D.js → chunk-U5KWZU4X.js} +251 -128
- package/dist/chunk-U5KWZU4X.js.map +1 -0
- package/dist/chunk-XNORY7M6.cjs +685 -0
- package/dist/chunk-XNORY7M6.cjs.map +1 -0
- package/dist/commands/index.d.cts +5 -353
- package/dist/commands/index.d.ts +5 -353
- package/dist/comment-store-BEMgVlAA.d.cts +135 -0
- package/dist/comment-store-BEMgVlAA.d.ts +135 -0
- package/dist/compare/index.cjs +15 -0
- package/dist/compare/index.cjs.map +1 -0
- package/dist/compare/index.d.cts +58 -0
- package/dist/compare/index.d.ts +58 -0
- package/dist/compare/index.js +15 -0
- package/dist/compare/index.js.map +1 -0
- package/dist/{controller-pePCJLT1.d.cts → controller-BhLLAoi8.d.cts} +45 -4
- package/dist/{controller-pePCJLT1.d.ts → controller-BhLLAoi8.d.ts} +45 -4
- package/dist/documents-BQjzJNe2.d.ts +76 -0
- package/dist/documents-KRTPhvst.d.cts +76 -0
- package/dist/extensions/index.cjs +53 -5
- package/dist/extensions/index.cjs.map +1 -1
- package/dist/extensions/index.d.cts +7 -3
- package/dist/extensions/index.d.ts +7 -3
- package/dist/extensions/index.js +52 -4
- package/dist/generation/index.cjs +1373 -0
- package/dist/generation/index.cjs.map +1 -0
- package/dist/generation/index.d.cts +554 -0
- package/dist/generation/index.d.ts +554 -0
- package/dist/generation/index.js +1373 -0
- package/dist/generation/index.js.map +1 -0
- package/dist/grammar/index.cjs +48 -3
- package/dist/grammar/index.cjs.map +1 -1
- package/dist/grammar/index.d.cts +322 -100
- package/dist/grammar/index.d.ts +322 -100
- package/dist/grammar/index.js +54 -9
- package/dist/image-editor/index.cjs +1831 -30
- package/dist/image-editor/index.cjs.map +1 -1
- package/dist/image-editor/index.d.cts +590 -3
- package/dist/image-editor/index.d.ts +590 -3
- package/dist/image-editor/index.js +1807 -6
- package/dist/image-editor/index.js.map +1 -1
- package/dist/{index-CCr_z9kF.d.cts → index-BhJBSm2d.d.cts} +370 -4
- package/dist/{index-Ck6ajwXh.d.ts → index-fJrlkJCd.d.ts} +370 -4
- package/dist/index.cjs +162 -25
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -8
- package/dist/index.d.ts +14 -8
- package/dist/index.js +174 -37
- package/dist/index.js.map +1 -1
- package/dist/migrate-iTlm3a8h.d.cts +112 -0
- package/dist/migrate-iTlm3a8h.d.ts +112 -0
- package/dist/persistence/index.cjs +676 -0
- package/dist/persistence/index.cjs.map +1 -0
- package/dist/persistence/index.d.cts +347 -0
- package/dist/persistence/index.d.ts +347 -0
- package/dist/persistence/index.js +676 -0
- package/dist/persistence/index.js.map +1 -0
- package/dist/{registry-D5-R90p0.d.cts → registry-BDe-vlv3.d.ts} +2 -40
- package/dist/registry-D32LpIc4.d.cts +354 -0
- package/dist/{registry-D5-R90p0.d.ts → registry-DnzpgY27.d.cts} +2 -40
- package/dist/registry-evKTP4ls.d.ts +354 -0
- package/dist/schema-DYDGdYL9.d.cts +41 -0
- package/dist/schema-DYDGdYL9.d.ts +41 -0
- package/dist/serializers/index.cjs +4 -3
- package/dist/serializers/index.cjs.map +1 -1
- package/dist/serializers/index.d.cts +2 -1
- package/dist/serializers/index.d.ts +2 -1
- package/dist/serializers/index.js +3 -2
- package/dist/sourcemap-C8AH3MBQ.d.cts +91 -0
- package/dist/sourcemap-DA1Evhrv.d.ts +91 -0
- package/dist/spreadsheet/index.cjs +37 -3
- package/dist/spreadsheet/index.cjs.map +1 -1
- package/dist/spreadsheet/index.d.cts +188 -17
- package/dist/spreadsheet/index.d.ts +188 -17
- package/dist/spreadsheet/index.js +43 -9
- package/dist/{tokens-CyLZmIei.d.cts → tokens-D7yXvUU6.d.cts} +15 -2
- package/dist/{tokens-CyLZmIei.d.ts → tokens-D7yXvUU6.d.ts} +15 -2
- package/dist/{track-changes-BSF58RK0.d.ts → track-changes-BK5sVf4_.d.cts} +18 -136
- package/dist/{track-changes-BSF58RK0.d.cts → track-changes-CDjCrwKe.d.ts} +18 -136
- package/package.json +16 -1
- package/dist/chunk-4SUNJZWB.cjs.map +0 -1
- package/dist/chunk-AA4ZEVCC.cjs.map +0 -1
- package/dist/chunk-AXV2ZW34.cjs +0 -118
- package/dist/chunk-AXV2ZW34.cjs.map +0 -1
- package/dist/chunk-B2ZRLN4S.js +0 -118
- package/dist/chunk-B2ZRLN4S.js.map +0 -1
- package/dist/chunk-GVSMRPHB.cjs.map +0 -1
- package/dist/chunk-K3R5NG2D.js.map +0 -1
- package/dist/chunk-MJZBNWG7.js.map +0 -1
- package/dist/chunk-OYXSKQFR.js.map +0 -1
- package/dist/chunk-QBJ22YZR.js.map +0 -1
- package/dist/chunk-QGHGJ56O.js.map +0 -1
- package/dist/chunk-RIKBJLS2.cjs.map +0 -1
- package/dist/chunk-XDMXXC4Z.cjs.map +0 -1
- /package/dist/{chunk-JJDLPEWL.js.map → chunk-3LV6RRPH.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/controller.ts","../src/import/controller.ts","../src/import/pdf.ts","../src/import/zip-export.ts"],"sourcesContent":["import { Editor, EditorOptions, Content, Extensions } from \"@tiptap/core\";\nimport { Slice } from \"@tiptap/pm/model\";\nimport { Token, tokenizePrompt } from \"./grammar\";\nimport {\n plainTextToTipTapHtml,\n plainTextToSlice,\n getEditorText,\n markdownToTipTapHtml,\n getEditorMarkdown,\n} from \"./serializers\";\n\nexport interface EditorControllerOptions extends Partial<\n Omit<EditorOptions, \"element\" | \"content\">\n> {\n element?: Element | HTMLElement | null;\n content?: string | Content;\n plainTextMode?: boolean;\n markdownMode?: boolean;\n extensions?: Extensions;\n onPlainTextChange?: (text: string) => void;\n onMarkdownChange?: (markdown: string) => void;\n onTokensChange?: (tokens: Token[]) => void;\n onSelectionChange?: (range: { from: number; to: number } | null) => void;\n}\n\n/**\n * UI-agnostic controller managing the lifecycle, commands, and plain-text/token\n * synchronization of a rich text or prompt editor.\n */\nexport class EditorController {\n public readonly editor: Editor;\n private readonly plainTextMode: boolean;\n private readonly markdownMode: boolean;\n private readonly onPlainTextChange?: (text: string) => void;\n private readonly onMarkdownChange?: (markdown: string) => void;\n private readonly onTokensChange?: (tokens: Token[]) => void;\n private readonly onSelectionChange?: (\n range: { from: number; to: number } | null,\n ) => void;\n private baselineContent: string;\n\n constructor(options: EditorControllerOptions = {}) {\n const {\n element,\n content,\n plainTextMode = false,\n markdownMode = false,\n extensions = [],\n onPlainTextChange,\n onMarkdownChange,\n onTokensChange,\n onSelectionChange,\n ...editorOptions\n } = options;\n\n this.plainTextMode = plainTextMode;\n this.markdownMode = markdownMode;\n this.onPlainTextChange = onPlainTextChange;\n this.onMarkdownChange = onMarkdownChange;\n this.onTokensChange = onTokensChange;\n this.onSelectionChange = onSelectionChange;\n\n const initialContent =\n plainTextMode && typeof content === \"string\"\n ? plainTextToTipTapHtml(content)\n : markdownMode && typeof content === \"string\"\n ? markdownToTipTapHtml(content)\n : content;\n\n this.editor = new Editor({\n element: element || undefined,\n content: initialContent,\n extensions,\n ...editorOptions,\n onUpdate: (props) => {\n editorOptions.onUpdate?.(props);\n this.handleUpdate();\n },\n onSelectionUpdate: (props) => {\n editorOptions.onSelectionUpdate?.(props);\n this.handleSelectionUpdate();\n },\n });\n\n if (plainTextMode) {\n this.enforcePlainTextClipboard();\n }\n\n this.baselineContent = this.getCurrentContentString();\n }\n\n private enforcePlainTextClipboard() {\n // Opt-in rich clipboard / file import must not bypass the plain-text invariant.\n const richClipboard = this.editor.storage?.richClipboard;\n if (richClipboard) richClipboard.plainTextMode = true;\n const fileImport = this.editor.extensionManager?.extensions.find(\n (ext) => ext.name === \"fileImport\",\n );\n if (fileImport) fileImport.options.asPlainText = true;\n\n this.editor.setOptions({\n editorProps: {\n ...this.editor.options.editorProps,\n clipboardTextParser: (\n text: string,\n context: any,\n _plain: boolean,\n view?: any,\n ) => {\n const schema =\n context?.doc?.type?.schema ||\n context?.schema ||\n view?.state?.schema ||\n this.editor.schema;\n\n if (!schema) return Slice.empty;\n\n return plainTextToSlice(text, schema);\n },\n },\n });\n }\n\n private handleUpdate() {\n if (this.plainTextMode || this.onPlainTextChange || this.onTokensChange) {\n const text = this.getPlainText();\n this.onPlainTextChange?.(text);\n\n if (this.onTokensChange) {\n const tokens = tokenizePrompt(text);\n this.onTokensChange(tokens);\n }\n }\n\n if (this.markdownMode || this.onMarkdownChange) {\n const markdown = this.getMarkdown();\n this.onMarkdownChange?.(markdown);\n }\n }\n\n private handleSelectionUpdate() {\n if (this.onSelectionChange) {\n const { from, to } = this.editor.state.selection;\n this.onSelectionChange({ from, to });\n }\n }\n\n public getPlainText(): string {\n return getEditorText(this.editor);\n }\n\n public setPlainText(text: string, emitUpdate = true) {\n const html = plainTextToTipTapHtml(text);\n this.editor.commands.setContent(html, emitUpdate);\n }\n\n public getMarkdown(): string {\n return getEditorMarkdown(this.editor);\n }\n\n public setMarkdown(markdown: string, emitUpdate = true) {\n if (this.editor.storage?.markdown?.parser) {\n this.editor.commands.setContent(markdown, emitUpdate);\n } else {\n const html = markdownToTipTapHtml(markdown);\n this.editor.commands.setContent(html, emitUpdate);\n }\n }\n\n /**\n * Replaces `from`..`to` with literal text: HTML in `text` is not parsed, and\n * newlines split paragraphs.\n */\n private insertPlainText(from: number, to: number, text: string) {\n const { state, view } = this.editor;\n const tr = text.includes(\"\\n\") || text.includes(\"\\r\")\n ? state.tr.replace(from, to, plainTextToSlice(text, state.schema))\n : text\n ? state.tr.insertText(text, from, to)\n : state.tr.delete(from, to);\n view.dispatch(tr.scrollIntoView());\n }\n\n /** Inserts text literally at the selection; HTML in `text` is not parsed. */\n public insertText(text: string) {\n const { from, to } = this.editor.state.selection;\n this.insertPlainText(from, to, text);\n }\n\n /** Inserts text literally at `pos`; HTML in `text` is not parsed. */\n public insertTextAt(pos: number, text: string) {\n this.insertPlainText(pos, pos, text);\n this.editor.commands.focus();\n }\n\n /** Replaces a range with literal text; HTML in `text` is not parsed. */\n public replaceRange(from: number, to: number, text: string) {\n this.insertPlainText(from, to, text);\n this.editor.commands.focus();\n }\n\n public getCurrentContentString(): string {\n if (this.plainTextMode) return this.getPlainText();\n if (this.markdownMode) return this.getMarkdown();\n return this.editor.getHTML();\n }\n\n public isDirty(): boolean {\n return this.getCurrentContentString() !== this.baselineContent;\n }\n\n public setCheckpoint(content?: string): void {\n this.baselineContent =\n content !== undefined ? content : this.getCurrentContentString();\n }\n\n public resetDirty(): void {\n this.setCheckpoint();\n }\n\n public getBaselineContent(): string {\n return this.baselineContent;\n }\n\n public destroy() {\n this.editor.destroy();\n }\n}\n\n/**\n * Creates and initializes an EditorController instance.\n */\nexport function createEditor(\n options: EditorControllerOptions = {},\n): EditorController {\n return new EditorController(options);\n}\n","import { defaultImportRegistry, type DocumentImport } from \"./adapters\";\nimport {\n importFilesIntoEditor,\n type ImportEditorTarget,\n type ImportFilesIntoEditorOptions,\n} from \"./editor\";\nimport type { FileLike, ImportOutcome } from \"./registry\";\n\n/**\n * Opens the browser file picker and resolves with the chosen files (an empty\n * array when the dialog is cancelled). `accept` defaults to every extension\n * and MIME type the default registry can import as a document.\n */\nexport function pickImportFiles(options: { accept?: string; multiple?: boolean } = {}): Promise<File[]> {\n if (typeof document === \"undefined\") return Promise.resolve([]);\n return new Promise((resolve) => {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n input.accept = options.accept ?? defaultImportRegistry.accept(\"document\");\n input.multiple = options.multiple ?? true;\n input.style.display = \"none\";\n const finish = (files: File[]) => {\n input.remove();\n resolve(files);\n };\n input.addEventListener(\"change\", () => finish(Array.from(input.files ?? [])), { once: true });\n input.addEventListener(\"cancel\", () => finish([]), { once: true });\n document.body.appendChild(input);\n input.click();\n });\n}\n\nexport interface FileImportState {\n isImporting: boolean;\n /** Last import error (cleared when a new import starts). */\n error: Error | null;\n /** Outcomes of the most recent import. */\n lastOutcomes: ImportOutcome<DocumentImport>[];\n}\n\nexport interface FileImportControllerOptions extends Omit<ImportFilesIntoEditorOptions, \"at\"> {\n /** Allow choosing several files in the picker (default `true`). */\n multiple?: boolean;\n}\n\n/**\n * Framework-agnostic state for a file-import button: tracks `isImporting` /\n * `error`, opens the file picker and inserts the imported content into the\n * editor returned by `getTarget`. React's `useFileImport` and Svelte's\n * `createFileImport` wrap it.\n */\nexport class FileImportController {\n private state: FileImportState = { isImporting: false, error: null, lastOutcomes: [] };\n private readonly listeners = new Set<(state: FileImportState) => void>();\n private pending = 0;\n\n constructor(\n private readonly getTarget: () => ImportEditorTarget | null | undefined,\n private options: FileImportControllerOptions = {},\n ) {}\n\n setOptions(options: FileImportControllerOptions): void {\n this.options = options;\n }\n\n /** `accept` attribute value for document imports. */\n get accept(): string {\n return (this.options.registry ?? defaultImportRegistry).accept(\"document\");\n }\n\n getState = (): FileImportState => this.state;\n\n subscribe = (listener: (state: FileImportState) => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n private setState(patch: Partial<FileImportState>) {\n this.state = { ...this.state, ...patch };\n this.listeners.forEach((listener) => listener(this.state));\n }\n\n /** Imports files into the editor at `at` (default: the selection). */\n importFiles = async (\n files: Iterable<FileLike> | ArrayLike<FileLike>,\n at?: number,\n ): Promise<ImportOutcome<DocumentImport>[]> => {\n const target = this.getTarget();\n const list = Array.from(files as ArrayLike<FileLike>);\n if (!target || list.length === 0) return [];\n this.pending++;\n this.setState({ isImporting: true, error: null });\n let error: Error | null = null;\n try {\n const outcomes = await importFilesIntoEditor(target, list, {\n ...this.options,\n at,\n onError: (err, file) => {\n error = err;\n this.options.onError?.(err, file);\n },\n });\n this.pending--;\n this.setState({ isImporting: this.pending > 0, error, lastOutcomes: outcomes });\n return outcomes;\n } catch (err) {\n this.pending--;\n this.setState({ isImporting: this.pending > 0, error: err instanceof Error ? err : new Error(String(err)) });\n return [];\n }\n };\n\n /** Opens the file picker and imports the chosen files at the selection. */\n openFilePicker = async (): Promise<ImportOutcome<DocumentImport>[]> => {\n const files = await pickImportFiles({ accept: this.accept, multiple: this.options.multiple });\n return this.importFiles(files);\n };\n}\n\nexport function createFileImportController(\n getTarget: () => ImportEditorTarget | null | undefined,\n options?: FileImportControllerOptions,\n): FileImportController {\n return new FileImportController(getTarget, options);\n}\n","import { plainTextToParagraphHtml } from \"../serializers/html\";\nimport type { DocumentImportAdapter } from \"./adapters\";\n\n/**\n * PDF text import through an injected pdf.js-compatible library. The editor\n * ships no PDF parser; consumers that already bundle `pdfjs-dist` register\n * the adapter themselves:\n *\n * ```ts\n * import * as pdfjs from \"pdfjs-dist\";\n * registerImportAdapter(createPdfImportAdapter(pdfjs));\n * ```\n *\n * Text items are grouped into lines by baseline (`transform[5]`) and lines\n * into paragraphs by vertical gaps larger than the page's typical line\n * spacing (or blank `hasEOL` lines). Only text is imported: no images,\n * tables, links or styling.\n */\n\n/** A text item from `page.getTextContent()` (marked-content items have no `str`). */\nexport interface PdfJsTextItem {\n str: string;\n /** `[a, b, c, d, x, y]` transform; `x` / `y` are the baseline origin. */\n transform?: readonly number[];\n width?: number;\n height?: number;\n /** pdf.js sets this when a line break follows the item. */\n hasEOL?: boolean;\n}\n\nexport interface PdfJsTextContent {\n items: ReadonlyArray<PdfJsTextItem | { type: string }>;\n}\n\nexport interface PdfJsPage {\n getTextContent(): Promise<PdfJsTextContent>;\n cleanup?(): unknown;\n}\n\nexport interface PdfJsDocument {\n numPages: number;\n getPage(pageNumber: number): Promise<PdfJsPage>;\n destroy?(): unknown;\n}\n\n/** The subset of the pdf.js API the adapter uses (`pdfjs-dist` satisfies it). */\nexport interface PdfJsLike {\n getDocument(source: { data: Uint8Array; [option: string]: unknown }): { promise: Promise<PdfJsDocument> };\n}\n\nexport interface PdfTextOptions {\n /**\n * A line gap larger than this multiple of the page's typical line spacing\n * starts a new paragraph (default `1.4`).\n */\n paragraphGap?: number;\n}\n\nexport interface PdfImportOptions extends PdfTextOptions {\n /** Adapter id (default `\"pdf\"`). */\n id?: string;\n /** Import at most this many pages (default: all). */\n maxPages?: number;\n /** Extra `getDocument` parameters, e.g. `{ disableFontFace: true }`. */\n documentParams?: Record<string, unknown>;\n}\n\ninterface Line {\n text: string;\n y: number;\n height: number;\n /** A blank line (empty `hasEOL` item) follows this one. */\n blankAfter: boolean;\n}\n\nconst isTextItem = (item: PdfJsTextItem | { type: string }): item is PdfJsTextItem =>\n typeof (item as PdfJsTextItem).str === \"string\";\n\nfunction median(values: number[]): number {\n if (!values.length) return 0;\n const sorted = [...values].sort((a, b) => a - b);\n const mid = sorted.length >> 1;\n return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction groupLines(items: ReadonlyArray<PdfJsTextItem | { type: string }>): Line[] {\n const lines: Line[] = [];\n let current: (Line & { endX?: number }) | null = null;\n let breakNext = false;\n for (const item of items) {\n if (!isTextItem(item)) continue;\n const x = item.transform?.[4] ?? 0;\n const y: number = item.transform?.[5] ?? (current?.y ?? 0);\n const height: number = item.height || Math.abs(item.transform?.[3] ?? 0) || current?.height || 10;\n const tolerance = Math.max(1, height * 0.5);\n if (!item.str) {\n // Empty items mark line ends; two in a row mean a blank line.\n if (item.hasEOL) {\n if (breakNext && current) current.blankAfter = true;\n breakNext = true;\n }\n continue;\n }\n if (!current || breakNext || Math.abs(y - current.y) > tolerance) {\n current = { text: \"\", y, height, blankAfter: false };\n lines.push(current);\n } else if (current.endX !== undefined && x - current.endX > height * 0.15) {\n // A horizontal gap without an explicit space item.\n if (!/\\s$/.test(current.text) && !/^\\s/.test(item.str)) current.text += \" \";\n }\n current.text += item.str;\n current.height = Math.max(current.height, height);\n current.endX = item.width !== undefined ? x + item.width : undefined;\n breakNext = !!item.hasEOL;\n }\n return lines;\n}\n\n/**\n * Groups one page's pdf.js text items into paragraphs. Exposed for custom\n * adapters and tests.\n */\nexport function pdfTextItemsToParagraphs(\n items: ReadonlyArray<PdfJsTextItem | { type: string }>,\n options: PdfTextOptions = {},\n): string[] {\n const lines = groupLines(items).filter((line) => line.text.trim() || line.blankAfter);\n const gaps: number[] = [];\n for (let i = 1; i < lines.length; i++) {\n const gap = lines[i - 1].y - lines[i].y;\n if (gap > 0) gaps.push(gap);\n }\n const typical = median(gaps);\n const factor = options.paragraphGap ?? 1.4;\n\n const paragraphs: string[] = [];\n let current: string[] = [];\n const flush = () => {\n const text = current.join(\" \").replace(/\\s+/g, \" \").trim();\n if (text) paragraphs.push(text);\n current = [];\n };\n lines.forEach((line, i) => {\n if (i > 0) {\n const prev = lines[i - 1];\n const gap = prev.y - line.y;\n const bigGap = typical > 0 ? gap > typical * factor : gap > prev.height * 1.8;\n // A line above the previous one (gap < 0) starts a new column or block.\n if (prev.blankAfter || bigGap || gap < -prev.height * 0.5) flush();\n }\n const text = line.text.trim();\n if (!text) return;\n if (current.length && /\\w-$/.test(current[current.length - 1]) && /^[a-z]/.test(text)) {\n // Re-join words hyphenated across lines.\n current[current.length - 1] = current[current.length - 1].slice(0, -1) + text;\n } else {\n current.push(text);\n }\n });\n flush();\n return paragraphs;\n}\n\n/** Creates a PDF `document` adapter backed by an injected pdf.js-compatible library. */\nexport function createPdfImportAdapter(pdfjs: PdfJsLike, options: PdfImportOptions = {}): DocumentImportAdapter {\n return {\n id: options.id ?? \"pdf\",\n label: \"PDF\",\n mimeTypes: [\"application/pdf\"],\n extensions: [\".pdf\"],\n target: \"document\",\n async import(_input, context) {\n // pdf.js may transfer (detach) the buffer it receives, so pass a copy.\n const data = new Uint8Array((await context.readArrayBuffer()).slice(0));\n const doc = await pdfjs.getDocument({ ...options.documentParams, data }).promise;\n const paragraphs: string[] = [];\n try {\n const pages = Math.min(doc.numPages, options.maxPages ?? Infinity);\n for (let n = 1; n <= pages; n++) {\n const page = await doc.getPage(n);\n const content = await page.getTextContent();\n paragraphs.push(...pdfTextItemsToParagraphs(content.items, options));\n page.cleanup?.();\n }\n } finally {\n await doc.destroy?.();\n }\n const text = paragraphs.join(\"\\n\");\n return { html: plainTextToParagraphHtml(text), text };\n },\n };\n}\n","import { escapeHtml } from \"../serializers/plain-text\";\nimport { defaultImportRegistry, type DocumentImport, type DocumentImportAdapter } from \"./adapters\";\nimport { ImportError, type ImportAdapterRegistry } from \"./registry\";\nimport { readZip, type ZipReadOptions } from \"./zip\";\n\n/**\n * Zipped document exports (Notion, Confluence, Obsidian, static-site dumps):\n * a `.zip` of markdown / HTML / text / DOCX files. Each entry is imported\n * with the registry's other `document` adapters and the results are\n * concatenated, with a heading per file.\n *\n * Not registered by default: `.zip` is a generic container, and claiming\n * every dropped archive as a document would steal drops from other handlers\n * (e.g. attachment uploads). Opt in with\n * `registerImportAdapter(zipImportAdapter)`.\n */\n\nexport interface ZipDocumentImport extends DocumentImport {\n /** Imported entries in document order, with the adapter that handled each. */\n files: { name: string; adapterId: string }[];\n /** Entries that were left out, with the reason. */\n skipped: { name: string; reason: string }[];\n}\n\nexport interface ZipImportOptions {\n /** Adapter id (default `\"zip\"`). */\n id?: string;\n /**\n * Registry used for the entries. Defaults to the registry running the\n * import (`context.registry`), then the default registry.\n */\n registry?: ImportAdapterRegistry;\n /** Add a heading with each file's title before its content (default `true`). */\n headings?: boolean;\n /** Heading level for file titles (default `2`). */\n headingLevel?: 1 | 2 | 3 | 4 | 5 | 6;\n /** Import at most this many files (default 500); the rest are reported as skipped. */\n maxFiles?: number;\n /** Archive limits (default: 100 MiB extracted, 5 000 entries). */\n zip?: ZipReadOptions;\n}\n\nconst INDEX_NAMES = /^(index|readme|home|_index|start)$/i;\n\nconst baseName = (path: string) => path.slice(path.lastIndexOf(\"/\") + 1);\nconst stem = (name: string) => name.replace(/\\.[^./]+$/, \"\");\n\n/** File title: the name without extension, path or a trailing Notion-style id. */\nexport function zipEntryTitle(path: string): string {\n const title = stem(baseName(path))\n .replace(/\\s+[0-9a-f]{32}$/i, \"\")\n .replace(/[_]+/g, \" \")\n .trim();\n return title || baseName(path);\n}\n\n/**\n * Orders entries for import: index / README files first (shallowest first),\n * then by path with natural number ordering (`2` before `10`).\n */\nexport function sortZipEntryNames(names: readonly string[]): string[] {\n const isIndex = (name: string) => INDEX_NAMES.test(stem(baseName(name)));\n const depth = (name: string) => name.split(\"/\").length;\n return [...names].sort((a, b) => {\n const ai = isIndex(a);\n const bi = isIndex(b);\n if (ai !== bi) return ai ? -1 : 1;\n if (ai && bi && depth(a) !== depth(b)) return depth(a) - depth(b);\n return a.localeCompare(b, undefined, { numeric: true, sensitivity: \"base\" });\n });\n}\n\nconst isJunk = (name: string) =>\n name.startsWith(\"__MACOSX/\") || name.split(\"/\").some((segment) => segment.startsWith(\".\"));\n\n/** Creates a `document` adapter for zipped exports. */\nexport function createZipImportAdapter(options: ZipImportOptions = {}): DocumentImportAdapter {\n const id = options.id ?? \"zip\";\n return {\n id,\n label: \"Zipped documents\",\n mimeTypes: [\"application/zip\", \"application/x-zip-compressed\"],\n extensions: [\".zip\"],\n target: \"document\",\n async import(_input, context): Promise<ZipDocumentImport> {\n const registry = options.registry ?? context.registry ?? defaultImportRegistry;\n const zip = await readZip(await context.readArrayBuffer(), {\n maxTotalSize: 100 * 1024 * 1024,\n maxEntries: 5_000,\n ...options.zip,\n });\n const maxFiles = options.maxFiles ?? 500;\n const level = options.headingLevel ?? 2;\n const files: ZipDocumentImport[\"files\"] = [];\n const skipped: ZipDocumentImport[\"skipped\"] = [];\n let html = \"\";\n let text = \"\";\n\n const names = zip.entries.filter((entry) => !entry.isDirectory).map((entry) => entry.name);\n for (const name of sortZipEntryNames(names)) {\n if (isJunk(name)) continue;\n const adapter = registry.find({ fileName: name, target: \"document\" });\n if (!adapter) {\n skipped.push({ name, reason: \"unsupported type\" });\n continue;\n }\n if (adapter.id === id || adapter.extensions.some((ext) => ext.toLowerCase() === \".zip\")) {\n skipped.push({ name, reason: \"nested archive\" });\n continue;\n }\n if (files.length >= maxFiles) {\n skipped.push({ name, reason: \"file limit reached\" });\n continue;\n }\n try {\n const outcome = await registry.importFile<DocumentImport>(await zip.read(name), {\n fileName: name,\n adapterId: adapter.id,\n });\n const title = zipEntryTitle(name);\n if (options.headings !== false) {\n html += `<h${level}>${escapeHtml(title)}</h${level}>`;\n text += `${text ? \"\\n\" : \"\"}${title}\\n`;\n } else if (text) {\n text += \"\\n\";\n }\n html += outcome.result.html.trim();\n text += outcome.result.text;\n files.push({ name, adapterId: adapter.id });\n } catch (error) {\n // Archive-wide limits stop the whole import; other failures skip the entry.\n const code = (error as { code?: string })?.code;\n if (code === \"too_large\") throw error;\n skipped.push({ name, reason: error instanceof Error ? error.message : String(error) });\n }\n }\n if (!files.length) {\n throw new ImportError(\"invalid_file\", \"The archive contains no importable documents.\", {\n fileName: context.fileName,\n });\n }\n return { html, text, files, skipped };\n },\n };\n}\n\n/** Zipped-export adapter with default options. Opt in with `registerImportAdapter(zipImportAdapter)`. */\nexport const zipImportAdapter: DocumentImportAdapter = createZipImportAdapter();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAkD;AAC3D,SAAS,aAAa;AA4Bf,IAAM,mBAAN,MAAuB;AAAA,EACZ;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGT;AAAA,EAER,YAAY,UAAmC,CAAC,GAAG;AACjD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,aAAa,CAAC;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IACL,IAAI;AAEJ,SAAK,gBAAgB;AACrB,SAAK,eAAe;AACpB,SAAK,oBAAoB;AACzB,SAAK,mBAAmB;AACxB,SAAK,iBAAiB;AACtB,SAAK,oBAAoB;AAEzB,UAAM,iBACJ,iBAAiB,OAAO,YAAY,WAChC,sBAAsB,OAAO,IAC7B,gBAAgB,OAAO,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AQ,IAAI,YAAY,MAAM,MAAM,GAAG;AACvF,kBAAQ,KAAK,EAAE,MAAM,QAAQ,iBAAiB,CAAC;AAC/C;AAAA,QACF;AACA,YAAI,MAAM,UAAU,UAAU;AAC5B,kBAAQ,KAAK,EAAE,MAAM,QAAQ,qBAAqB,CAAC;AACnD;AAAA,QACF;AACA,YAAI;AACF,gBAAM,UAAU,MAAM,SAAS,WAA2B,MAAM,IAAI,KAAK,IAAI,GAAG;AAAA,YAC9E,UAAU;AAAA,YACV,WAAW,QAAQ;AAAA,UACrB,CAAC;AACD,gBAAM,QAAQ,cAAc,IAAI;AAChC,cAAI,QAAQ,aAAa,OAAO;AAC9B,oBAAQ,KAAK,KAAK,IAAI,WAAW,KAAK,CAAC,MAAM,KAAK;AAClD,oBAAQ,GAAG,OAAO,OAAO,EAAE,GAAG,KAAK;AAAA;AAAA,UACrC,WAAW,MAAM;AACf,oBAAQ;AAAA,UACV;AACA,kBAAQ,QAAQ,OAAO,KAAK,KAAK;AACjC,kBAAQ,QAAQ,OAAO;AACvB,gBAAM,KAAK,EAAE,MAAM,WAAW,QAAQ,GAAG,CAAC;AAAA,QAC5C,SAAS,OAAO;AAEd,gBAAM,OAAQ,OAA6B;AAC3C,cAAI,SAAS,YAAa,OAAM;AAChC,kBAAQ,KAAK,EAAE,MAAM,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;AAAA,QACvF;AAAA,MACF;AACA,UAAI,CAAC,MAAM,QAAQ;AACjB,cAAM,IAAI,YAAY,gBAAgB,iDAAiD;AAAA,UACrF,UAAU,QAAQ;AAAA,QACpB,CAAC;AAAA,MACH;AACA,aAAO,EAAE,MAAM,MAAM,OAAO,QAAQ;AAAA,IACtC;AAAA,EACF;AACF;AAGO,IAAM,mBAA0C,uBAAuB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/controller.ts","../src/import/controller.ts","../src/import/pdf.ts","../src/import/zip-export.ts"],"sourcesContent":["import { Editor, EditorOptions, Content, Extensions } from \"@tiptap/core\";\nimport { Slice } from \"@tiptap/pm/model\";\nimport { Token, tokenizePrompt } from \"./grammar\";\nimport {\n plainTextToTipTapHtml,\n plainTextToSlice,\n getEditorText,\n markdownToTipTapHtml,\n getEditorMarkdown,\n} from \"./serializers\";\n\nexport interface EditorControllerOptions extends Partial<\n Omit<EditorOptions, \"element\" | \"content\">\n> {\n element?: Element | HTMLElement | null;\n content?: string | Content;\n plainTextMode?: boolean;\n markdownMode?: boolean;\n extensions?: Extensions;\n onPlainTextChange?: (text: string) => void;\n onMarkdownChange?: (markdown: string) => void;\n onTokensChange?: (tokens: Token[]) => void;\n onSelectionChange?: (range: { from: number; to: number } | null) => void;\n}\n\n/**\n * UI-agnostic controller managing the lifecycle, commands, and plain-text/token\n * synchronization of a rich text or prompt editor.\n */\nexport class EditorController {\n public readonly editor: Editor;\n private readonly plainTextMode: boolean;\n private readonly markdownMode: boolean;\n private readonly onPlainTextChange?: (text: string) => void;\n private readonly onMarkdownChange?: (markdown: string) => void;\n private readonly onTokensChange?: (tokens: Token[]) => void;\n private readonly onSelectionChange?: (\n range: { from: number; to: number } | null,\n ) => void;\n private baselineContent: string;\n\n constructor(options: EditorControllerOptions = {}) {\n const {\n element,\n content,\n plainTextMode = false,\n markdownMode = false,\n extensions = [],\n onPlainTextChange,\n onMarkdownChange,\n onTokensChange,\n onSelectionChange,\n ...editorOptions\n } = options;\n\n this.plainTextMode = plainTextMode;\n this.markdownMode = markdownMode;\n this.onPlainTextChange = onPlainTextChange;\n this.onMarkdownChange = onMarkdownChange;\n this.onTokensChange = onTokensChange;\n this.onSelectionChange = onSelectionChange;\n\n const initialContent =\n plainTextMode && typeof content === \"string\"\n ? plainTextToTipTapHtml(content)\n : markdownMode && typeof content === \"string\"\n ? markdownToTipTapHtml(content)\n : content;\n\n this.editor = new Editor({\n element: element || undefined,\n content: initialContent,\n extensions,\n ...editorOptions,\n onUpdate: (props) => {\n editorOptions.onUpdate?.(props);\n this.handleUpdate();\n },\n onSelectionUpdate: (props) => {\n editorOptions.onSelectionUpdate?.(props);\n this.handleSelectionUpdate();\n },\n });\n\n if (plainTextMode) {\n this.enforcePlainTextClipboard();\n }\n\n this.baselineContent = this.getCurrentContentString();\n }\n\n private enforcePlainTextClipboard() {\n // Opt-in rich clipboard / file import must not bypass the plain-text invariant.\n const richClipboard = this.editor.storage?.richClipboard;\n if (richClipboard) richClipboard.plainTextMode = true;\n const fileImport = this.editor.extensionManager?.extensions.find(\n (ext) => ext.name === \"fileImport\",\n );\n if (fileImport) fileImport.options.asPlainText = true;\n\n this.editor.setOptions({\n editorProps: {\n ...this.editor.options.editorProps,\n clipboardTextParser: (\n text: string,\n context: any,\n _plain: boolean,\n view?: any,\n ) => {\n const schema =\n context?.doc?.type?.schema ||\n context?.schema ||\n view?.state?.schema ||\n this.editor.schema;\n\n if (!schema) return Slice.empty;\n\n return plainTextToSlice(text, schema);\n },\n },\n });\n }\n\n private handleUpdate() {\n if (this.plainTextMode || this.onPlainTextChange || this.onTokensChange) {\n const text = this.getPlainText();\n this.onPlainTextChange?.(text);\n\n if (this.onTokensChange) {\n const tokens = tokenizePrompt(text);\n this.onTokensChange(tokens);\n }\n }\n\n if (this.markdownMode || this.onMarkdownChange) {\n const markdown = this.getMarkdown();\n this.onMarkdownChange?.(markdown);\n }\n }\n\n private handleSelectionUpdate() {\n if (this.onSelectionChange) {\n const { from, to } = this.editor.state.selection;\n this.onSelectionChange({ from, to });\n }\n }\n\n public getPlainText(): string {\n return getEditorText(this.editor);\n }\n\n public setPlainText(text: string, emitUpdate = true) {\n const html = plainTextToTipTapHtml(text);\n this.editor.commands.setContent(html, emitUpdate);\n }\n\n public getMarkdown(): string {\n return getEditorMarkdown(this.editor);\n }\n\n public setMarkdown(markdown: string, emitUpdate = true) {\n if (this.editor.storage?.markdown?.parser) {\n this.editor.commands.setContent(markdown, emitUpdate);\n } else {\n const html = markdownToTipTapHtml(markdown);\n this.editor.commands.setContent(html, emitUpdate);\n }\n }\n\n /**\n * Replaces `from`..`to` with literal text: HTML in `text` is not parsed, and\n * newlines split paragraphs.\n */\n private insertPlainText(from: number, to: number, text: string) {\n const { state, view } = this.editor;\n const tr = text.includes(\"\\n\") || text.includes(\"\\r\")\n ? state.tr.replace(from, to, plainTextToSlice(text, state.schema))\n : text\n ? state.tr.insertText(text, from, to)\n : state.tr.delete(from, to);\n view.dispatch(tr.scrollIntoView());\n }\n\n /** Inserts text literally at the selection; HTML in `text` is not parsed. */\n public insertText(text: string) {\n const { from, to } = this.editor.state.selection;\n this.insertPlainText(from, to, text);\n }\n\n /** Inserts text literally at `pos`; HTML in `text` is not parsed. */\n public insertTextAt(pos: number, text: string) {\n this.insertPlainText(pos, pos, text);\n this.editor.commands.focus();\n }\n\n /** Replaces a range with literal text; HTML in `text` is not parsed. */\n public replaceRange(from: number, to: number, text: string) {\n this.insertPlainText(from, to, text);\n this.editor.commands.focus();\n }\n\n public getCurrentContentString(): string {\n if (this.plainTextMode) return this.getPlainText();\n if (this.markdownMode) return this.getMarkdown();\n return this.editor.getHTML();\n }\n\n public isDirty(): boolean {\n return this.getCurrentContentString() !== this.baselineContent;\n }\n\n public setCheckpoint(content?: string): void {\n this.baselineContent =\n content !== undefined ? content : this.getCurrentContentString();\n }\n\n public resetDirty(): void {\n this.setCheckpoint();\n }\n\n public getBaselineContent(): string {\n return this.baselineContent;\n }\n\n public destroy() {\n this.editor.destroy();\n }\n}\n\n/**\n * Creates and initializes an EditorController instance.\n */\nexport function createEditor(\n options: EditorControllerOptions = {},\n): EditorController {\n return new EditorController(options);\n}\n","import { defaultImportRegistry, type DocumentImport } from \"./adapters\";\nimport {\n importFilesIntoEditor,\n type ImportEditorTarget,\n type ImportFilesIntoEditorOptions,\n} from \"./editor\";\nimport type { FileLike, ImportOutcome } from \"./registry\";\n\n/**\n * Opens the browser file picker and resolves with the chosen files (an empty\n * array when the dialog is cancelled). `accept` defaults to every extension\n * and MIME type the default registry can import as a document.\n */\nexport function pickImportFiles(options: { accept?: string; multiple?: boolean } = {}): Promise<File[]> {\n if (typeof document === \"undefined\") return Promise.resolve([]);\n return new Promise((resolve) => {\n const input = document.createElement(\"input\");\n input.type = \"file\";\n input.accept = options.accept ?? defaultImportRegistry.accept(\"document\");\n input.multiple = options.multiple ?? true;\n input.style.display = \"none\";\n const finish = (files: File[]) => {\n input.remove();\n resolve(files);\n };\n input.addEventListener(\"change\", () => finish(Array.from(input.files ?? [])), { once: true });\n input.addEventListener(\"cancel\", () => finish([]), { once: true });\n document.body.appendChild(input);\n input.click();\n });\n}\n\nexport interface FileImportState {\n isImporting: boolean;\n /** Last import error (cleared when a new import starts). */\n error: Error | null;\n /** Outcomes of the most recent import. */\n lastOutcomes: ImportOutcome<DocumentImport>[];\n}\n\nexport interface FileImportControllerOptions extends Omit<ImportFilesIntoEditorOptions, \"at\"> {\n /** Allow choosing several files in the picker (default `true`). */\n multiple?: boolean;\n}\n\n/**\n * Framework-agnostic state for a file-import button: tracks `isImporting` /\n * `error`, opens the file picker and inserts the imported content into the\n * editor returned by `getTarget`. React's `useFileImport` and Svelte's\n * `createFileImport` wrap it.\n */\nexport class FileImportController {\n private state: FileImportState = { isImporting: false, error: null, lastOutcomes: [] };\n private readonly listeners = new Set<(state: FileImportState) => void>();\n private pending = 0;\n\n constructor(\n private readonly getTarget: () => ImportEditorTarget | null | undefined,\n private options: FileImportControllerOptions = {},\n ) {}\n\n setOptions(options: FileImportControllerOptions): void {\n this.options = options;\n }\n\n /** `accept` attribute value for document imports. */\n get accept(): string {\n return (this.options.registry ?? defaultImportRegistry).accept(\"document\");\n }\n\n getState = (): FileImportState => this.state;\n\n subscribe = (listener: (state: FileImportState) => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n private setState(patch: Partial<FileImportState>) {\n this.state = { ...this.state, ...patch };\n this.listeners.forEach((listener) => listener(this.state));\n }\n\n /** Imports files into the editor at `at` (default: the selection). */\n importFiles = async (\n files: Iterable<FileLike> | ArrayLike<FileLike>,\n at?: number,\n ): Promise<ImportOutcome<DocumentImport>[]> => {\n const target = this.getTarget();\n const list = Array.from(files as ArrayLike<FileLike>);\n if (!target || list.length === 0) return [];\n this.pending++;\n this.setState({ isImporting: true, error: null });\n let error: Error | null = null;\n try {\n const outcomes = await importFilesIntoEditor(target, list, {\n ...this.options,\n at,\n onError: (err, file) => {\n error = err;\n this.options.onError?.(err, file);\n },\n });\n this.pending--;\n this.setState({ isImporting: this.pending > 0, error, lastOutcomes: outcomes });\n return outcomes;\n } catch (err) {\n this.pending--;\n this.setState({ isImporting: this.pending > 0, error: err instanceof Error ? err : new Error(String(err)) });\n return [];\n }\n };\n\n /** Opens the file picker and imports the chosen files at the selection. */\n openFilePicker = async (): Promise<ImportOutcome<DocumentImport>[]> => {\n const files = await pickImportFiles({ accept: this.accept, multiple: this.options.multiple });\n return this.importFiles(files);\n };\n}\n\nexport function createFileImportController(\n getTarget: () => ImportEditorTarget | null | undefined,\n options?: FileImportControllerOptions,\n): FileImportController {\n return new FileImportController(getTarget, options);\n}\n","import { plainTextToParagraphHtml } from \"../serializers/html\";\nimport type { DocumentImportAdapter } from \"./adapters\";\n\n/**\n * PDF text import through an injected pdf.js-compatible library. The editor\n * ships no PDF parser; consumers that already bundle `pdfjs-dist` register\n * the adapter themselves:\n *\n * ```ts\n * import * as pdfjs from \"pdfjs-dist\";\n * registerImportAdapter(createPdfImportAdapter(pdfjs));\n * ```\n *\n * Text items are grouped into lines by baseline (`transform[5]`) and lines\n * into paragraphs by vertical gaps larger than the page's typical line\n * spacing (or blank `hasEOL` lines). Only text is imported: no images,\n * tables, links or styling.\n */\n\n/** A text item from `page.getTextContent()` (marked-content items have no `str`). */\nexport interface PdfJsTextItem {\n str: string;\n /** `[a, b, c, d, x, y]` transform; `x` / `y` are the baseline origin. */\n transform?: readonly number[];\n width?: number;\n height?: number;\n /** pdf.js sets this when a line break follows the item. */\n hasEOL?: boolean;\n}\n\nexport interface PdfJsTextContent {\n items: ReadonlyArray<PdfJsTextItem | { type: string }>;\n}\n\nexport interface PdfJsPage {\n getTextContent(): Promise<PdfJsTextContent>;\n cleanup?(): unknown;\n}\n\nexport interface PdfJsDocument {\n numPages: number;\n getPage(pageNumber: number): Promise<PdfJsPage>;\n destroy?(): unknown;\n}\n\n/** The subset of the pdf.js API the adapter uses (`pdfjs-dist` satisfies it). */\nexport interface PdfJsLike {\n getDocument(source: { data: Uint8Array; [option: string]: unknown }): { promise: Promise<PdfJsDocument> };\n}\n\nexport interface PdfTextOptions {\n /**\n * A line gap larger than this multiple of the page's typical line spacing\n * starts a new paragraph (default `1.4`).\n */\n paragraphGap?: number;\n}\n\nexport interface PdfImportOptions extends PdfTextOptions {\n /** Adapter id (default `\"pdf\"`). */\n id?: string;\n /** Import at most this many pages (default: all). */\n maxPages?: number;\n /** Extra `getDocument` parameters, e.g. `{ disableFontFace: true }`. */\n documentParams?: Record<string, unknown>;\n}\n\ninterface Line {\n text: string;\n y: number;\n height: number;\n /** A blank line (empty `hasEOL` item) follows this one. */\n blankAfter: boolean;\n}\n\nconst isTextItem = (item: PdfJsTextItem | { type: string }): item is PdfJsTextItem =>\n typeof (item as PdfJsTextItem).str === \"string\";\n\nfunction median(values: number[]): number {\n if (!values.length) return 0;\n const sorted = [...values].sort((a, b) => a - b);\n const mid = sorted.length >> 1;\n return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction groupLines(items: ReadonlyArray<PdfJsTextItem | { type: string }>): Line[] {\n const lines: Line[] = [];\n let current: (Line & { endX?: number }) | null = null;\n let breakNext = false;\n for (const item of items) {\n if (!isTextItem(item)) continue;\n const x = item.transform?.[4] ?? 0;\n const y: number = item.transform?.[5] ?? (current?.y ?? 0);\n const height: number = item.height || Math.abs(item.transform?.[3] ?? 0) || current?.height || 10;\n const tolerance = Math.max(1, height * 0.5);\n if (!item.str) {\n // Empty items mark line ends; two in a row mean a blank line.\n if (item.hasEOL) {\n if (breakNext && current) current.blankAfter = true;\n breakNext = true;\n }\n continue;\n }\n if (!current || breakNext || Math.abs(y - current.y) > tolerance) {\n current = { text: \"\", y, height, blankAfter: false };\n lines.push(current);\n } else if (current.endX !== undefined && x - current.endX > height * 0.15) {\n // A horizontal gap without an explicit space item.\n if (!/\\s$/.test(current.text) && !/^\\s/.test(item.str)) current.text += \" \";\n }\n current.text += item.str;\n current.height = Math.max(current.height, height);\n current.endX = item.width !== undefined ? x + item.width : undefined;\n breakNext = !!item.hasEOL;\n }\n return lines;\n}\n\n/**\n * Groups one page's pdf.js text items into paragraphs. Exposed for custom\n * adapters and tests.\n */\nexport function pdfTextItemsToParagraphs(\n items: ReadonlyArray<PdfJsTextItem | { type: string }>,\n options: PdfTextOptions = {},\n): string[] {\n const lines = groupLines(items).filter((line) => line.text.trim() || line.blankAfter);\n const gaps: number[] = [];\n for (let i = 1; i < lines.length; i++) {\n const gap = lines[i - 1].y - lines[i].y;\n if (gap > 0) gaps.push(gap);\n }\n const typical = median(gaps);\n const factor = options.paragraphGap ?? 1.4;\n\n const paragraphs: string[] = [];\n let current: string[] = [];\n const flush = () => {\n const text = current.join(\" \").replace(/\\s+/g, \" \").trim();\n if (text) paragraphs.push(text);\n current = [];\n };\n lines.forEach((line, i) => {\n if (i > 0) {\n const prev = lines[i - 1];\n const gap = prev.y - line.y;\n const bigGap = typical > 0 ? gap > typical * factor : gap > prev.height * 1.8;\n // A line above the previous one (gap < 0) starts a new column or block.\n if (prev.blankAfter || bigGap || gap < -prev.height * 0.5) flush();\n }\n const text = line.text.trim();\n if (!text) return;\n if (current.length && /\\w-$/.test(current[current.length - 1]) && /^[a-z]/.test(text)) {\n // Re-join words hyphenated across lines.\n current[current.length - 1] = current[current.length - 1].slice(0, -1) + text;\n } else {\n current.push(text);\n }\n });\n flush();\n return paragraphs;\n}\n\n/** Creates a PDF `document` adapter backed by an injected pdf.js-compatible library. */\nexport function createPdfImportAdapter(pdfjs: PdfJsLike, options: PdfImportOptions = {}): DocumentImportAdapter {\n return {\n id: options.id ?? \"pdf\",\n label: \"PDF\",\n mimeTypes: [\"application/pdf\"],\n extensions: [\".pdf\"],\n target: \"document\",\n async import(_input, context) {\n // pdf.js may transfer (detach) the buffer it receives, so pass a copy.\n const data = new Uint8Array((await context.readArrayBuffer()).slice(0));\n const doc = await pdfjs.getDocument({ ...options.documentParams, data }).promise;\n const paragraphs: string[] = [];\n try {\n const pages = Math.min(doc.numPages, options.maxPages ?? Infinity);\n for (let n = 1; n <= pages; n++) {\n const page = await doc.getPage(n);\n const content = await page.getTextContent();\n paragraphs.push(...pdfTextItemsToParagraphs(content.items, options));\n page.cleanup?.();\n }\n } finally {\n await doc.destroy?.();\n }\n const text = paragraphs.join(\"\\n\");\n return { html: plainTextToParagraphHtml(text), text };\n },\n };\n}\n","import { escapeHtml } from \"../serializers/plain-text\";\nimport { defaultImportRegistry, type DocumentImport, type DocumentImportAdapter } from \"./adapters\";\nimport { ImportError, type ImportAdapterRegistry } from \"./registry\";\nimport { readZip, type ZipReadOptions } from \"./zip\";\n\n/**\n * Zipped document exports (Notion, Confluence, Obsidian, static-site dumps):\n * a `.zip` of markdown / HTML / text / DOCX files. Each entry is imported\n * with the registry's other `document` adapters and the results are\n * concatenated, with a heading per file.\n *\n * Not registered by default: `.zip` is a generic container, and claiming\n * every dropped archive as a document would steal drops from other handlers\n * (e.g. attachment uploads). Opt in with\n * `registerImportAdapter(zipImportAdapter)`.\n */\n\nexport interface ZipDocumentImport extends DocumentImport {\n /** Imported entries in document order, with the adapter that handled each. */\n files: { name: string; adapterId: string }[];\n /** Entries that were left out, with the reason. */\n skipped: { name: string; reason: string }[];\n}\n\nexport interface ZipImportOptions {\n /** Adapter id (default `\"zip\"`). */\n id?: string;\n /**\n * Registry used for the entries. Defaults to the registry running the\n * import (`context.registry`), then the default registry.\n */\n registry?: ImportAdapterRegistry;\n /** Add a heading with each file's title before its content (default `true`). */\n headings?: boolean;\n /** Heading level for file titles (default `2`). */\n headingLevel?: 1 | 2 | 3 | 4 | 5 | 6;\n /** Import at most this many files (default 500); the rest are reported as skipped. */\n maxFiles?: number;\n /** Archive limits (default: 100 MiB extracted, 5 000 entries). */\n zip?: ZipReadOptions;\n}\n\nconst INDEX_NAMES = /^(index|readme|home|_index|start)$/i;\n\nconst baseName = (path: string) => path.slice(path.lastIndexOf(\"/\") + 1);\nconst stem = (name: string) => name.replace(/\\.[^./]+$/, \"\");\n\n/** File title: the name without extension, path or a trailing Notion-style id. */\nexport function zipEntryTitle(path: string): string {\n const title = stem(baseName(path))\n .replace(/\\s+[0-9a-f]{32}$/i, \"\")\n .replace(/[_]+/g, \" \")\n .trim();\n return title || baseName(path);\n}\n\n/**\n * Orders entries for import: index / README files first (shallowest first),\n * then by path with natural number ordering (`2` before `10`).\n */\nexport function sortZipEntryNames(names: readonly string[]): string[] {\n const isIndex = (name: string) => INDEX_NAMES.test(stem(baseName(name)));\n const depth = (name: string) => name.split(\"/\").length;\n return [...names].sort((a, b) => {\n const ai = isIndex(a);\n const bi = isIndex(b);\n if (ai !== bi) return ai ? -1 : 1;\n if (ai && bi && depth(a) !== depth(b)) return depth(a) - depth(b);\n return a.localeCompare(b, undefined, { numeric: true, sensitivity: \"base\" });\n });\n}\n\nconst isJunk = (name: string) =>\n name.startsWith(\"__MACOSX/\") || name.split(\"/\").some((segment) => segment.startsWith(\".\"));\n\n/** Creates a `document` adapter for zipped exports. */\nexport function createZipImportAdapter(options: ZipImportOptions = {}): DocumentImportAdapter {\n const id = options.id ?? \"zip\";\n return {\n id,\n label: \"Zipped documents\",\n mimeTypes: [\"application/zip\", \"application/x-zip-compressed\"],\n extensions: [\".zip\"],\n target: \"document\",\n async import(_input, context): Promise<ZipDocumentImport> {\n const registry = options.registry ?? context.registry ?? defaultImportRegistry;\n const zip = await readZip(await context.readArrayBuffer(), {\n maxTotalSize: 100 * 1024 * 1024,\n maxEntries: 5_000,\n ...options.zip,\n });\n const maxFiles = options.maxFiles ?? 500;\n const level = options.headingLevel ?? 2;\n const files: ZipDocumentImport[\"files\"] = [];\n const skipped: ZipDocumentImport[\"skipped\"] = [];\n let html = \"\";\n let text = \"\";\n\n const names = zip.entries.filter((entry) => !entry.isDirectory).map((entry) => entry.name);\n for (const name of sortZipEntryNames(names)) {\n if (isJunk(name)) continue;\n const adapter = registry.find({ fileName: name, target: \"document\" });\n if (!adapter) {\n skipped.push({ name, reason: \"unsupported type\" });\n continue;\n }\n if (adapter.id === id || adapter.extensions.some((ext) => ext.toLowerCase() === \".zip\")) {\n skipped.push({ name, reason: \"nested archive\" });\n continue;\n }\n if (files.length >= maxFiles) {\n skipped.push({ name, reason: \"file limit reached\" });\n continue;\n }\n try {\n const outcome = await registry.importFile<DocumentImport>(await zip.read(name), {\n fileName: name,\n adapterId: adapter.id,\n });\n const title = zipEntryTitle(name);\n if (options.headings !== false) {\n html += `<h${level}>${escapeHtml(title)}</h${level}>`;\n text += `${text ? \"\\n\" : \"\"}${title}\\n`;\n } else if (text) {\n text += \"\\n\";\n }\n html += outcome.result.html.trim();\n text += outcome.result.text;\n files.push({ name, adapterId: adapter.id });\n } catch (error) {\n // Archive-wide limits stop the whole import; other failures skip the entry.\n const code = (error as { code?: string })?.code;\n if (code === \"too_large\") throw error;\n skipped.push({ name, reason: error instanceof Error ? error.message : String(error) });\n }\n }\n if (!files.length) {\n throw new ImportError(\"invalid_file\", \"The archive contains no importable documents.\", {\n fileName: context.fileName,\n });\n }\n return { html, text, files, skipped };\n },\n };\n}\n\n/** Zipped-export adapter with default options. Opt in with `registerImportAdapter(zipImportAdapter)`. */\nexport const zipImportAdapter: DocumentImportAdapter = createZipImportAdapter();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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I,WAAW,KAAK,CAAC,MAAM,KAAK;AAClD,oBAAQ,GAAG,OAAO,OAAO,EAAE,GAAG,KAAK;AAAA;AAAA,UACrC,WAAW,MAAM;AACf,oBAAQ;AAAA,UACV;AACA,kBAAQ,QAAQ,OAAO,KAAK,KAAK;AACjC,kBAAQ,QAAQ,OAAO;AACvB,gBAAM,KAAK,EAAE,MAAM,WAAW,QAAQ,GAAG,CAAC;AAAA,QAC5C,SAAS,OAAO;AAEd,gBAAM,OAAQ,OAA6B;AAC3C,cAAI,SAAS,YAAa,OAAM;AAChC,kBAAQ,KAAK,EAAE,MAAM,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;AAAA,QACvF;AAAA,MACF;AACA,UAAI,CAAC,MAAM,QAAQ;AACjB,cAAM,IAAI,YAAY,gBAAgB,iDAAiD;AAAA,UACrF,UAAU,QAAQ;AAAA,QACpB,CAAC;AAAA,MACH;AACA,aAAO,EAAE,MAAM,MAAM,OAAO,QAAQ;AAAA,IACtC;AAAA,EACF;AACF;AAGO,IAAM,mBAA0C,uBAAuB;","names":[]}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** A section whose stored value did not fit; its defaults were used instead. */
|
|
2
|
+
interface SectionProblem {
|
|
3
|
+
/** Top-level key of the section. */
|
|
4
|
+
section: string;
|
|
5
|
+
message: string;
|
|
6
|
+
}
|
|
7
|
+
/** Why a loaded document must not be written back. */
|
|
8
|
+
type ReadOnlyReason = {
|
|
9
|
+
kind: "newerVersion";
|
|
10
|
+
version: number;
|
|
11
|
+
supported: number;
|
|
12
|
+
message: string;
|
|
13
|
+
} | {
|
|
14
|
+
kind: "migrationFailed";
|
|
15
|
+
from: number;
|
|
16
|
+
message: string;
|
|
17
|
+
} | {
|
|
18
|
+
kind: "invalid";
|
|
19
|
+
message: string;
|
|
20
|
+
};
|
|
21
|
+
/** What happened while loading a document. Nothing in here is fatal. */
|
|
22
|
+
interface LoadReport {
|
|
23
|
+
/** Set when the document was upgraded step by step from this older version. */
|
|
24
|
+
migratedFrom: number | null;
|
|
25
|
+
/** The version found in the input (`null` when it had none). */
|
|
26
|
+
version: number | null;
|
|
27
|
+
/** Sections replaced by their defaults (see `loadSections`). */
|
|
28
|
+
problems: SectionProblem[];
|
|
29
|
+
/**
|
|
30
|
+
* Set when the document must not be saved over: written by a newer build,
|
|
31
|
+
* a migration step failed, or the input was not an object. Show the values,
|
|
32
|
+
* but never overwrite the stored document.
|
|
33
|
+
*/
|
|
34
|
+
readOnly: ReadOnlyReason | null;
|
|
35
|
+
/** Top-level keys this build does not know; kept in `unknown` so a save can write them back. */
|
|
36
|
+
unknownKeys: string[];
|
|
37
|
+
}
|
|
38
|
+
/** True when something should be shown to the user. */
|
|
39
|
+
declare function hasLoadProblems(report: LoadReport): boolean;
|
|
40
|
+
declare function createLoadReport(partial?: Partial<LoadReport>): LoadReport;
|
|
41
|
+
type JsonObject = Record<string, unknown>;
|
|
42
|
+
/** One migration step: turns a document at version `from` into version `from + 1`. */
|
|
43
|
+
type MigrationStep = (doc: JsonObject) => JsonObject | void;
|
|
44
|
+
interface MigrateOptions {
|
|
45
|
+
/** The version this build writes. */
|
|
46
|
+
currentVersion: number;
|
|
47
|
+
/** Steps keyed by the version they start from. */
|
|
48
|
+
steps?: Record<number, MigrationStep>;
|
|
49
|
+
/** Key holding the version (default `"version"`). */
|
|
50
|
+
versionKey?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Version assumed when the key is missing (default: `currentVersion`, i.e. a
|
|
53
|
+
* hand-written document is taken as current and the key is added).
|
|
54
|
+
*/
|
|
55
|
+
missingVersion?: number;
|
|
56
|
+
}
|
|
57
|
+
interface MigrateResult {
|
|
58
|
+
/** The migrated document (a deep copy; the input is never modified). */
|
|
59
|
+
doc: JsonObject;
|
|
60
|
+
report: LoadReport;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Brings a stored document up to `currentVersion` by running one step per
|
|
64
|
+
* version (`steps[v]` turns version `v` into `v + 1`).
|
|
65
|
+
*
|
|
66
|
+
* - Missing version: taken as `missingVersion` (default current); the key is added.
|
|
67
|
+
* - Newer than `currentVersion`: left alone and reported `readOnly` (never overwrite
|
|
68
|
+
* a file written by a newer build).
|
|
69
|
+
* - A missing or throwing step: the document is returned as it was before
|
|
70
|
+
* migrating and reported `readOnly`.
|
|
71
|
+
* - Keys the steps do not touch are preserved.
|
|
72
|
+
*/
|
|
73
|
+
declare function migrateDocument(json: unknown, options: MigrateOptions): MigrateResult;
|
|
74
|
+
/** How one top-level section is read. */
|
|
75
|
+
interface SectionSpec<V> {
|
|
76
|
+
/** Validates / converts the stored value; throw (or return `undefined`) to reject it. */
|
|
77
|
+
parse: (value: unknown) => V | undefined;
|
|
78
|
+
/** Used when the section is missing or rejected. */
|
|
79
|
+
defaults: V | (() => V);
|
|
80
|
+
}
|
|
81
|
+
type SectionSpecs<T> = {
|
|
82
|
+
[K in keyof T]: SectionSpec<T[K]>;
|
|
83
|
+
};
|
|
84
|
+
interface LoadSectionsOptions {
|
|
85
|
+
/** Keys that are neither sections nor unknown (default `["version"]`). */
|
|
86
|
+
ignore?: string[];
|
|
87
|
+
}
|
|
88
|
+
interface LoadSectionsResult<T> {
|
|
89
|
+
value: T;
|
|
90
|
+
/** Sections that were present but rejected (missing ones are not problems). */
|
|
91
|
+
problems: SectionProblem[];
|
|
92
|
+
/** Top-level keys not described by `sections`; write them back to keep them. */
|
|
93
|
+
unknown: JsonObject;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Reads `doc` one top-level section at a time: a section that does not parse
|
|
97
|
+
* is reported and replaced by its defaults, every other section is kept. This
|
|
98
|
+
* keeps one bad value (e.g. a renamed enum) from resetting the whole document.
|
|
99
|
+
*/
|
|
100
|
+
declare function loadSections<T>(doc: unknown, sections: SectionSpecs<T>, options?: LoadSectionsOptions): LoadSectionsResult<T>;
|
|
101
|
+
interface LoadDocumentOptions extends MigrateOptions, LoadSectionsOptions {
|
|
102
|
+
}
|
|
103
|
+
interface LoadDocumentResult<T> extends LoadSectionsResult<T> {
|
|
104
|
+
report: LoadReport;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* `migrateDocument` followed by `loadSections`, with one `LoadReport`
|
|
108
|
+
* (`problems` and `unknownKeys` filled in).
|
|
109
|
+
*/
|
|
110
|
+
declare function loadDocument<T>(json: unknown, sections: SectionSpecs<T>, options: LoadDocumentOptions): LoadDocumentResult<T>;
|
|
111
|
+
|
|
112
|
+
export { type JsonObject as J, type LoadDocumentOptions as L, type MigrateOptions as M, type ReadOnlyReason as R, type SectionProblem as S, type LoadDocumentResult as a, type LoadReport as b, type LoadSectionsOptions as c, type LoadSectionsResult as d, type MigrateResult as e, type MigrationStep as f, type SectionSpec as g, type SectionSpecs as h, createLoadReport as i, hasLoadProblems as j, loadSections as k, loadDocument as l, migrateDocument as m };
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** A section whose stored value did not fit; its defaults were used instead. */
|
|
2
|
+
interface SectionProblem {
|
|
3
|
+
/** Top-level key of the section. */
|
|
4
|
+
section: string;
|
|
5
|
+
message: string;
|
|
6
|
+
}
|
|
7
|
+
/** Why a loaded document must not be written back. */
|
|
8
|
+
type ReadOnlyReason = {
|
|
9
|
+
kind: "newerVersion";
|
|
10
|
+
version: number;
|
|
11
|
+
supported: number;
|
|
12
|
+
message: string;
|
|
13
|
+
} | {
|
|
14
|
+
kind: "migrationFailed";
|
|
15
|
+
from: number;
|
|
16
|
+
message: string;
|
|
17
|
+
} | {
|
|
18
|
+
kind: "invalid";
|
|
19
|
+
message: string;
|
|
20
|
+
};
|
|
21
|
+
/** What happened while loading a document. Nothing in here is fatal. */
|
|
22
|
+
interface LoadReport {
|
|
23
|
+
/** Set when the document was upgraded step by step from this older version. */
|
|
24
|
+
migratedFrom: number | null;
|
|
25
|
+
/** The version found in the input (`null` when it had none). */
|
|
26
|
+
version: number | null;
|
|
27
|
+
/** Sections replaced by their defaults (see `loadSections`). */
|
|
28
|
+
problems: SectionProblem[];
|
|
29
|
+
/**
|
|
30
|
+
* Set when the document must not be saved over: written by a newer build,
|
|
31
|
+
* a migration step failed, or the input was not an object. Show the values,
|
|
32
|
+
* but never overwrite the stored document.
|
|
33
|
+
*/
|
|
34
|
+
readOnly: ReadOnlyReason | null;
|
|
35
|
+
/** Top-level keys this build does not know; kept in `unknown` so a save can write them back. */
|
|
36
|
+
unknownKeys: string[];
|
|
37
|
+
}
|
|
38
|
+
/** True when something should be shown to the user. */
|
|
39
|
+
declare function hasLoadProblems(report: LoadReport): boolean;
|
|
40
|
+
declare function createLoadReport(partial?: Partial<LoadReport>): LoadReport;
|
|
41
|
+
type JsonObject = Record<string, unknown>;
|
|
42
|
+
/** One migration step: turns a document at version `from` into version `from + 1`. */
|
|
43
|
+
type MigrationStep = (doc: JsonObject) => JsonObject | void;
|
|
44
|
+
interface MigrateOptions {
|
|
45
|
+
/** The version this build writes. */
|
|
46
|
+
currentVersion: number;
|
|
47
|
+
/** Steps keyed by the version they start from. */
|
|
48
|
+
steps?: Record<number, MigrationStep>;
|
|
49
|
+
/** Key holding the version (default `"version"`). */
|
|
50
|
+
versionKey?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Version assumed when the key is missing (default: `currentVersion`, i.e. a
|
|
53
|
+
* hand-written document is taken as current and the key is added).
|
|
54
|
+
*/
|
|
55
|
+
missingVersion?: number;
|
|
56
|
+
}
|
|
57
|
+
interface MigrateResult {
|
|
58
|
+
/** The migrated document (a deep copy; the input is never modified). */
|
|
59
|
+
doc: JsonObject;
|
|
60
|
+
report: LoadReport;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Brings a stored document up to `currentVersion` by running one step per
|
|
64
|
+
* version (`steps[v]` turns version `v` into `v + 1`).
|
|
65
|
+
*
|
|
66
|
+
* - Missing version: taken as `missingVersion` (default current); the key is added.
|
|
67
|
+
* - Newer than `currentVersion`: left alone and reported `readOnly` (never overwrite
|
|
68
|
+
* a file written by a newer build).
|
|
69
|
+
* - A missing or throwing step: the document is returned as it was before
|
|
70
|
+
* migrating and reported `readOnly`.
|
|
71
|
+
* - Keys the steps do not touch are preserved.
|
|
72
|
+
*/
|
|
73
|
+
declare function migrateDocument(json: unknown, options: MigrateOptions): MigrateResult;
|
|
74
|
+
/** How one top-level section is read. */
|
|
75
|
+
interface SectionSpec<V> {
|
|
76
|
+
/** Validates / converts the stored value; throw (or return `undefined`) to reject it. */
|
|
77
|
+
parse: (value: unknown) => V | undefined;
|
|
78
|
+
/** Used when the section is missing or rejected. */
|
|
79
|
+
defaults: V | (() => V);
|
|
80
|
+
}
|
|
81
|
+
type SectionSpecs<T> = {
|
|
82
|
+
[K in keyof T]: SectionSpec<T[K]>;
|
|
83
|
+
};
|
|
84
|
+
interface LoadSectionsOptions {
|
|
85
|
+
/** Keys that are neither sections nor unknown (default `["version"]`). */
|
|
86
|
+
ignore?: string[];
|
|
87
|
+
}
|
|
88
|
+
interface LoadSectionsResult<T> {
|
|
89
|
+
value: T;
|
|
90
|
+
/** Sections that were present but rejected (missing ones are not problems). */
|
|
91
|
+
problems: SectionProblem[];
|
|
92
|
+
/** Top-level keys not described by `sections`; write them back to keep them. */
|
|
93
|
+
unknown: JsonObject;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Reads `doc` one top-level section at a time: a section that does not parse
|
|
97
|
+
* is reported and replaced by its defaults, every other section is kept. This
|
|
98
|
+
* keeps one bad value (e.g. a renamed enum) from resetting the whole document.
|
|
99
|
+
*/
|
|
100
|
+
declare function loadSections<T>(doc: unknown, sections: SectionSpecs<T>, options?: LoadSectionsOptions): LoadSectionsResult<T>;
|
|
101
|
+
interface LoadDocumentOptions extends MigrateOptions, LoadSectionsOptions {
|
|
102
|
+
}
|
|
103
|
+
interface LoadDocumentResult<T> extends LoadSectionsResult<T> {
|
|
104
|
+
report: LoadReport;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* `migrateDocument` followed by `loadSections`, with one `LoadReport`
|
|
108
|
+
* (`problems` and `unknownKeys` filled in).
|
|
109
|
+
*/
|
|
110
|
+
declare function loadDocument<T>(json: unknown, sections: SectionSpecs<T>, options: LoadDocumentOptions): LoadDocumentResult<T>;
|
|
111
|
+
|
|
112
|
+
export { type JsonObject as J, type LoadDocumentOptions as L, type MigrateOptions as M, type ReadOnlyReason as R, type SectionProblem as S, type LoadDocumentResult as a, type LoadReport as b, type LoadSectionsOptions as c, type LoadSectionsResult as d, type MigrateResult as e, type MigrationStep as f, type SectionSpec as g, type SectionSpecs as h, createLoadReport as i, hasLoadProblems as j, loadSections as k, loadDocument as l, migrateDocument as m };
|