3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-18 22:25:44 +01:00

Replace isAdfDocument with readAdfDocument, reading the input once into a plain copy

This commit is contained in:
2026-11-09 07:14:07 +01:00
committed by Lillem4n
parent 899b854d53
commit ca6016b4b6
17 changed files with 332 additions and 134 deletions
+131 -27
View File
@@ -5,13 +5,23 @@ import vm from 'node:vm'
import type { AdfDocument, AdfNode } from './document.ts'
import type { JsonValue } from '../json-value.ts'
import { adfToHtml, adfToLosslessMarkdown, adfToPortableMarkdown } from '../index.ts'
import { adfDocumentFault, isAdfDocument, writableContent } from './document.ts'
import { adfDocumentFault, readAdfDocument, writableContent } from './document.ts'
import { largestNesting } from '../nesting.ts'
import { mostValues } from './plain-copy.ts'
function fault(value: unknown): string {
return adfDocumentFault(value)?.message ?? 'accepted'
}
function readable(value: unknown): boolean {
return readAdfDocument(value).ok
}
function readFault(value: unknown): string {
const result = readAdfDocument(value)
return result.ok ? 'accepted' : `${result.error.code}: ${result.error.message}`
}
function faultCode(value: unknown): string {
return adfDocumentFault(value)?.code ?? 'accepted'
}
@@ -27,13 +37,13 @@ function withAttribute(value: JsonValue): unknown {
}
test('accepts an editor-normal document', () => {
assert.equal(isAdfDocument({ content: [{ content: [{ text: 'x', type: 'text' }], type: 'paragraph' }], type: 'doc', version: 1 }), true)
assert.equal(isAdfDocument({ type: 'doc', version: 1 }), true)
assert.equal(readable({ content: [{ content: [{ text: 'x', type: 'text' }], type: 'paragraph' }], type: 'doc', version: 1 }), true)
assert.equal(readable({ type: 'doc', version: 1 }), true)
assert.equal(fault({ content: [{ content: [{ text: 'x', type: 'text' }], type: 'paragraph' }], type: 'doc', version: 1 }), 'accepted')
})
test('names the check anything that is not a doc node failed', () => {
assert.equal(isAdfDocument(null), false)
assert.equal(readable(null), false)
assert.equal(fault(null), 'an ADF document is an object: found null')
assert.equal(fault(undefined), 'an ADF document is an object: found undefined')
assert.equal(fault([]), 'an ADF document is an object: found an array')
@@ -54,13 +64,13 @@ test('names the check anything that is not a doc node failed', () => {
test('rejects a node whose shape ProseMirror JSON cannot hold', () => {
assert.equal(fault({ content: {}, type: 'doc', version: 1 }), "an ADF document's content is an array: found an object")
assert.equal(fault({ content: [{ type: 1 }], type: 'doc', version: 1 }), "an ADF document's content holds ADF nodes: one of them is not")
assert.equal(isAdfDocument({ content: [{ type: 1 }], type: 'doc', version: 1 }), false)
assert.equal(isAdfDocument({ content: [{ text: 1, type: 'text' }], type: 'doc', version: 1 }), false)
assert.equal(isAdfDocument({ content: [{ node: 'x', type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(isAdfDocument({ content: [{ content: {}, type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(isAdfDocument({ content: [{ marks: [{ type: 1 }], text: 'x', type: 'text' }], type: 'doc', version: 1 }), false)
assert.equal(isAdfDocument({ content: [{ attrs: { a: Number.POSITIVE_INFINITY }, type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(isAdfDocument({ content: [{ attrs: [], type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ type: 1 }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ text: 1, type: 'text' }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ node: 'x', type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ content: {}, type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ marks: [{ type: 1 }], text: 'x', type: 'text' }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ attrs: { a: Number.POSITIVE_INFINITY }, type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ attrs: [], type: 'paragraph' }], type: 'doc', version: 1 }), false)
})
test('names the attribute nesting past the levels the parser reads one at, and still calls the value a document', () => {
@@ -68,48 +78,48 @@ test('names the attribute nesting past the levels the parser reads one at, and s
assert.equal(fault(withAttribute(nested(largestNesting))), 'accepted')
assert.equal(fault(withAttribute(nested(largestNesting + 1))), deeper('a', 'paragraph'))
assert.equal(faultCode(withAttribute(nested(largestNesting + 1))), 'unsupported-nesting-depth')
assert.equal(isAdfDocument(withAttribute(nested(largestNesting + 1))), true)
assert.equal(readable(withAttribute(nested(largestNesting + 1))), true)
const marked = (levels: number): unknown => ({ content: [{ marks: [{ attrs: { a: nested(levels) }, type: 'link' }], text: 'x', type: 'text' }], type: 'doc', version: 1 })
assert.equal(fault(marked(largestNesting)), 'accepted')
assert.equal(fault(marked(largestNesting + 1)), deeper('a', 'link'))
assert.equal(isAdfDocument(marked(largestNesting + 1)), true)
assert.equal(readable(marked(largestNesting + 1)), true)
})
test('accepts the JSON values an attribute may hold', () => {
assert.equal(isAdfDocument({ content: [{ attrs: { a: [1, 'x', null, true, { b: 2 }] }, type: 'paragraph' }], type: 'doc', version: 1 }), true)
assert.equal(isAdfDocument({ content: [{ attrs: { a: [() => 1] }, type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(isAdfDocument({ content: [{ attrs: { a: Object.assign(Object.create(null), { b: 1 }) }, type: 'paragraph' }], type: 'doc', version: 1 }), true)
assert.equal(isAdfDocument(vm.runInNewContext("({ content: [{ attrs: { a: { b: [1] } }, type: 'paragraph' }], type: 'doc', version: 1 })")), true)
assert.equal(readable({ content: [{ attrs: { a: [1, 'x', null, true, { b: 2 }] }, type: 'paragraph' }], type: 'doc', version: 1 }), true)
assert.equal(readable({ content: [{ attrs: { a: [() => 1] }, type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ attrs: { a: Object.assign(Object.create(null), { b: 1 }) }, type: 'paragraph' }], type: 'doc', version: 1 }), true)
assert.equal(readable(vm.runInNewContext("({ content: [{ attrs: { a: { b: [1] } }, type: 'paragraph' }], type: 'doc', version: 1 })")), true)
})
test('refuses an attribute value that is an object JSON does not hold', () => {
class Point { x = 1 }
for (const value of [new Date(0), new Map([['b', 1]]), new Set([1]), new Uint8Array([1, 2]), new Point(), [new Map()], { b: new Set() }]) {
assert.equal(isAdfDocument({ content: [{ attrs: { a: value }, type: 'paragraph' }], type: 'doc', version: 1 }), false, String(value))
assert.equal(readable({ content: [{ attrs: { a: value }, type: 'paragraph' }], type: 'doc', version: 1 }), false, String(value))
}
assert.equal(isAdfDocument({ content: [{ attrs: new Map(), type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(isAdfDocument({ content: [{ marks: [{ attrs: { href: new URL('https://x.test') }, type: 'link' }], text: 'x', type: 'text' }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ attrs: new Map(), type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(readable({ content: [{ marks: [{ attrs: { href: new URL('https://x.test') }, type: 'link' }], text: 'x', type: 'text' }], type: 'doc', version: 1 }), false)
})
test("reads a node's siblings as a walk rather than as one call's arguments", () => {
const wide = { content: [{ content: Array.from({ length: 200000 }, () => ({ type: 'rule' })), type: 'blockquote' }], type: 'doc', version: 1 }
assert.equal(isAdfDocument(wide), true)
assert.equal(readable(wide), true)
assert.equal(fault(wide), 'accepted')
})
test('refuses an object holding itself, and accepts one shared', () => {
const holdsItself = 'an ADF document is a tree: an object in it holds itself'
const holdsItself = 'not-an-adf-document: an ADF document is a tree: an object in it holds itself'
const paragraph: { content: unknown[]; type: string } = { content: [], type: 'paragraph' }
paragraph.content.push(paragraph)
assert.equal(fault({ content: [paragraph], type: 'doc', version: 1 }), holdsItself)
assert.equal(readFault({ content: [paragraph], type: 'doc', version: 1 }), holdsItself)
const document: { content: unknown[]; type: string; version: number } = { content: [], type: 'doc', version: 1 }
document.content.push(document)
assert.equal(fault(document), holdsItself)
assert.equal(readFault(document), holdsItself)
const attrs: Record<string, unknown> = {}
attrs['a'] = [attrs]
assert.equal(fault({ content: [{ attrs, type: 'paragraph' }], type: 'doc', version: 1 }), holdsItself)
assert.equal(fault({ content: [{ marks: [{ attrs, type: 'link' }], text: 'x', type: 'text' }], type: 'doc', version: 1 }), holdsItself)
assert.equal(isAdfDocument({ content: [{ attrs, type: 'paragraph' }], type: 'doc', version: 1 }), false)
assert.equal(readFault({ content: [{ attrs, type: 'paragraph' }], type: 'doc', version: 1 }), holdsItself)
assert.equal(readFault({ content: [{ marks: [{ attrs, type: 'link' }], text: 'x', type: 'text' }], type: 'doc', version: 1 }), holdsItself)
assert.equal(readable({ content: [{ attrs, type: 'paragraph' }], type: 'doc', version: 1 }), false)
const bold = { type: 'strong' }
const text = { marks: [bold], text: 'x', type: 'text' }
const shared = { content: [text, text], type: 'paragraph' }
@@ -217,3 +227,97 @@ test('names a link-marked card at any depth by its path alone, with no step quad
assert.equal(!refused.ok && refused.error.path.length, 2 * (depth + 1))
assert.deepEqual(!refused.ok && refused.error.path.slice(0, 4), ['content', 0, 'content', 0])
})
const writers = [adfToHtml, adfToLosslessMarkdown, adfToPortableMarkdown]
function documentOf(attrs: unknown): unknown {
return { content: [{ attrs, type: 'paragraph' }], type: 'doc', version: 1 }
}
test('reads a document once into a copy that shares nothing with the original', () => {
const original = { content: [{ attrs: { a: [1, { b: 'x' }] }, content: [{ text: 'x', type: 'text' }], type: 'paragraph' }], type: 'doc', version: 1 }
const result = readAdfDocument(original)
assert.ok(result.ok)
assert.deepEqual(result.value, original)
assert.notEqual(result.value, original)
original.content[0]?.content.push({ text: 'y', type: 'text' })
assert.equal(result.value.content?.[0]?.content?.length, 1)
})
test('refuses a value holding an accessor property, whichever object or array holds it', () => {
const refused = 'not-an-adf-document: an ADF document is plain data: one of its objects holds a getter or a setter'
assert.equal(readFault({ get content() { return [] }, type: 'doc', version: 1 }), refused)
assert.equal(readFault({ content: [{ get type() { return 'rule' } }], type: 'doc', version: 1 }), refused)
assert.equal(readFault(documentOf({ set a(value: number) { void value } })), refused)
assert.equal(readFault(documentOf({ a: Object.defineProperty([], 0, { enumerable: true, get: () => 1 }) })), refused)
})
test('refuses a getter minting a fresh child per access without walking it', () => {
const endless = (): unknown => ({ get next() { return endless() } })
assert.equal(readFault(documentOf(endless())), 'not-an-adf-document: an ADF document is plain data: one of its objects holds a getter or a setter')
})
test('refuses a Proxy that throws, and a revoked one, wherever they stand', () => {
const unreadable = 'not-an-adf-document: an ADF document is plain data: reading one of its objects threw'
const throwing = (target: object, trap: string): object => new Proxy(target, { [trap]: () => { throw new Error('trap') } })
for (const trap of ['getOwnPropertyDescriptor', 'getPrototypeOf', 'ownKeys']) {
assert.equal(readFault(throwing({ type: 'doc', version: 1 }, trap)), unreadable, trap)
assert.equal(readFault(documentOf(throwing({ b: 1 }, trap))), unreadable, trap)
}
assert.equal(readFault({ content: throwing([1], 'getOwnPropertyDescriptor'), type: 'doc', version: 1 }), unreadable)
assert.equal(readFault({ content: throwing([], 'get'), type: 'doc', version: 1 }), unreadable)
const revoked = Proxy.revocable({}, {})
revoked.revoke()
assert.equal(readFault(revoked.proxy), unreadable)
assert.equal(readFault(documentOf(revoked.proxy)), unreadable)
})
test('copies own enumerable string keys alone, as JSON.stringify does', () => {
const keyed = Object.defineProperty({ own: 2, [Symbol('symbol')]: 4 }, 'hidden', { enumerable: false, value: 3 })
const result = readAdfDocument(documentOf(keyed))
assert.ok(result.ok)
assert.deepEqual(result.value.content?.[0]?.attrs, { own: 2 })
assert.equal(readable({ content: [Object.create({ type: 'rule' })], type: 'doc', version: 1 }), false)
const proxied = new Proxy({ b: 1 }, { getOwnPropertyDescriptor: () => undefined })
const dropped = readAdfDocument(documentOf(proxied))
assert.ok(dropped.ok)
assert.deepEqual(dropped.value.content?.[0]?.attrs, {})
})
test('copies a key named __proto__ as a key, leaving the copy a plain object', () => {
const result = readAdfDocument(documentOf(JSON.parse('{"__proto__":{"polluted":1}}')))
assert.ok(result.ok)
const attrs = result.value.content?.[0]?.attrs
assert.deepEqual(Object.keys(attrs ?? {}), ['__proto__'])
assert.equal(Object.getPrototypeOf(attrs), Object.prototype)
assert.equal(Reflect.get(attrs ?? {}, 'polluted'), undefined)
})
test('reads an array by index, so no iterator runs and a hole is no JSON value', () => {
const iterated = Object.assign([1, 2], { [Symbol.iterator]: () => { throw new Error('iterated') } })
const result = readAdfDocument(documentOf({ a: iterated }))
assert.ok(result.ok)
assert.deepEqual(result.value.content?.[0]?.attrs, { a: [1, 2] })
assert.equal(readable(documentOf({ a: [1, , 3] })), false)
})
test('refuses an array claiming more elements than the values left, before it reads any', () => {
const claimed = `unsupported-node-shape: an ADF document holds at most ${mostValues} JSON values: this one holds more`
const claiming = (length: unknown): object => new Proxy([], { get: (target, key) => (key === 'length' ? length : Reflect.get(target, key)) })
assert.equal(readFault({ content: claiming(2 ** 32 - 1), type: 'doc', version: 1 }), claimed)
assert.equal(readFault({ content: new Array(mostValues - 1), type: 'doc', version: 1 }), claimed)
assert.equal(readFault({ content: claiming('many'), type: 'doc', version: 1 }), 'not-an-adf-document: an ADF document is plain data: reading one of its objects threw')
assert.equal(readFault({ content: claiming(-1), type: 'doc', version: 1 }), 'not-an-adf-document: an ADF document is plain data: reading one of its objects threw')
})
test('returns a result for a hostile document from every writer', () => {
const throwing = new Proxy({ type: 'rule' }, { ownKeys: () => { throw new Error('trap') } })
const hostile: AdfDocument[] = [{ get content() { return [] }, type: 'doc', version: 1 }, { content: [throwing], type: 'doc', version: 1 }]
for (const write of writers) {
for (const document of hostile) {
const result = write(document)
assert.ok(!result.ok)
assert.equal(result.error.code, 'not-an-adf-document')
}
}
})
+27 -36
View File
@@ -1,8 +1,9 @@
import { blockNodeModel } from './block-nodes.ts'
import { failure, faulted, success, type ConvertError, type ConvertFault, type Result } from '../result.ts'
import { failure, faulted, success, type ConvertError, type ConvertFault, type Read, type Result } from '../result.ts'
import { inlineNodeModel } from './inline-nodes.ts'
import { isJsonValue, overNested, type JsonValue } from '../json-value.ts'
import { largestNesting } from '../nesting.ts'
import { plainCopy } from './plain-copy.ts'
import { withinLongest } from '../length-bound.ts'
import { serializeCanonicalJson } from '../canonical-json.ts'
@@ -34,21 +35,34 @@ const markKeys = ['attrs', 'type']
const nodeKeys = ['attrs', 'content', 'marks', 'text', 'type']
export function adfDocumentFault(value: unknown): ConvertFault | undefined {
const shaped = shapedDocument(value)
return shaped.fault ?? nestingFault(shaped.value.content ?? [])
}
// Reads `value` once into a plain copy and checks the copy's shape. Depth is the walks' business, not the shape's: a deep document reads as blocks and marks do.
export function readAdfDocument(value: unknown): Result<AdfDocument> {
const copy = plainCopy(value)
if (copy.fault !== undefined) return faulted(copy.fault, [])
const shaped = shapedDocument(copy.value)
return shaped.fault === undefined ? success(shaped.value) : faulted(shaped.fault, [])
}
function shapedDocument(value: unknown): Read<AdfDocument> {
if (!isRecord(value)) return notADocument(`an ADF document is an object: found ${describe(value)}`)
const extra = extraKey(value, documentKeys)
if (extra !== undefined) return notADocument(`an ADF document holds content, type and version alone: found the key ${extra}`)
if (!('type' in value)) return notADocument('an ADF document holds type "doc": found no type field')
if (value['type'] !== 'doc') return notADocument(`an ADF document holds type "doc": found ${describe(value['type'])}`)
const type: unknown = value['type']
if (type !== 'doc') return notADocument(`an ADF document holds type "doc": found ${describe(type)}`)
if (!('version' in value)) return notADocument('an ADF document holds a version number: found no version field')
const version = value['version']
const version: unknown = value['version']
if (typeof version !== 'number' || !Number.isFinite(version)) return notADocument(`an ADF document holds a version number: found ${describe(version)}`)
if (!('content' in value)) return undefined
const held: unknown = value['content']
if (!Array.isArray(held)) return notADocument(`an ADF document's content is an array: found ${describe(held)}`)
const content: readonly unknown[] = held
if (holdsItself(content)) return notADocument('an ADF document is a tree: an object in it holds itself')
if (!isNodeArray(content)) return notADocument("an ADF document's content holds ADF nodes: one of them is not")
return nestingFault(content)
if (!('content' in value)) return { value: { type, version } }
const content: unknown = value['content']
if (!Array.isArray(content)) return notADocument(`an ADF document's content is an array: found ${describe(content)}`)
const nodes: readonly unknown[] = content
if (!isNodeArray(nodes)) return notADocument("an ADF document's content holds ADF nodes: one of them is not")
return { value: { content: nodes, type, version } }
}
// The checks every writer opens with; `undefined` where the document holds no `content` key, which each format spells its own way.
@@ -126,12 +140,6 @@ export function mergedTextRuns(nodes: readonly AdfNode[], joins: (previous: AdfN
return merged
}
// Depth is the walks' business, not the shape's: the guard waves a deep document through as blocks and marks do.
export function isAdfDocument(value: unknown): value is AdfDocument {
const fault = adfDocumentFault(value)
return fault === undefined || fault.code === 'unsupported-nesting-depth'
}
export function isAdfNode(value: unknown): value is AdfNode {
return isNodeArray([value])
}
@@ -184,24 +192,7 @@ function shapeRefusal(node: AdfNode): string | undefined {
return model.contentModel === 'none' && holdsContent ? `a node of type ${node.type} holds no content: this one holds some` : undefined
}
// Tracks ancestors alone: a tree may share an object, but an object holding itself walks the guards forever.
function holdsItself(root: object): boolean {
const pending = [{ depth: 0, item: root }]
const ancestors: object[] = []
const onPath = new Set<unknown>()
while (pending.length > 0) {
const entry = pending.pop()
if (entry === undefined) continue
while (ancestors.length > entry.depth) onPath.delete(ancestors.pop())
if (onPath.has(entry.item)) return true
ancestors.push(entry.item)
onPath.add(entry.item)
for (const child of Object.values(entry.item)) if (typeof child === 'object' && child !== null) pending.push({ depth: entry.depth + 1, item: child })
}
return false
}
function isNodeArray(value: readonly unknown[]): value is readonly AdfNode[] {
function isNodeArray(value: readonly unknown[]): value is AdfNode[] {
const pending: unknown[] = [...value]
while (pending.length > 0) {
const node = pending.pop()
@@ -265,8 +256,8 @@ export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function notADocument(message: string): ConvertFault {
return { code: 'not-an-adf-document', message }
function notADocument(message: string): { fault: ConvertFault } {
return { fault: { code: 'not-an-adf-document', message } }
}
function describe(value: unknown): string {
+80
View File
@@ -0,0 +1,80 @@
import type { ConvertFault, Read } from '../result.ts'
import { isPlainObject } from '../json-value.ts'
// Each object, array, string, number, boolean and null counts one: far past any real page, and it stops a Proxy claiming unbounded width.
export const mostValues = 10_000_000
// An object that is no plain object is copied with this prototype, so `isJsonValue` refuses the copy as it refuses the original.
const unplain = {}
type Step = { depth: number; key: number | string; source: unknown; target: object }
type Held = { entries: [number | string, unknown][]; kind: 'array' | 'object' | 'unplain' }
const holdsItself: ConvertFault = { code: 'not-an-adf-document', message: 'an ADF document is a tree: an object in it holds itself' }
const tooMany: ConvertFault = { code: 'unsupported-node-shape', message: `an ADF document holds at most ${mostValues} JSON values: this one holds more` }
const unreadable: ConvertFault = { code: 'not-an-adf-document', message: 'an ADF document is plain data: reading one of its objects threw' }
const withAccessor: ConvertFault = { code: 'not-an-adf-document', message: 'an ADF document is plain data: one of its objects holds a getter or a setter' }
// Every later step reads the copy, never the caller's object: a getter, a Proxy trap or an iterator of theirs runs at most once here, and never an accessor.
export function plainCopy(value: unknown): Read<unknown> {
const root: unknown[] = []
const pending: Step[] = [{ depth: 0, key: 0, source: value, target: root }]
const ancestors: object[] = []
const onPath = new Set<unknown>()
let left = mostValues - 1
for (let step = pending.pop(); step !== undefined; step = pending.pop()) {
const source = step.source
if (typeof source !== 'object' || source === null) {
place(step.target, step.key, source)
continue
}
// A pre-order walk: a step at depth d has the d objects above it as its ancestors, and the stack pops it before its later siblings.
while (ancestors.length > step.depth) onPath.delete(ancestors.pop())
if (onPath.has(source)) return { fault: holdsItself }
ancestors.push(source)
onPath.add(source)
const read = heldBy(source, left)
if (read.fault !== undefined) return read
const { entries, kind } = read.value
left -= entries.length
const copy = kind === 'array' ? [] : kind === 'object' ? {} : Object.create(unplain)
place(step.target, step.key, copy)
for (const [key, held] of entries.reverse()) pending.push({ depth: step.depth + 1, key, source: held, target: copy })
}
return { value: root[0] }
}
// The only reads of the caller's object, so the only `try`: a throw there is the caller's Proxy.
function heldBy(source: object, left: number): Read<Held> {
try {
const entries: [number | string, unknown][] = []
if (Array.isArray(source)) {
const length: unknown = source.length
if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) return { fault: unreadable }
if (length > left) return { fault: tooMany }
for (let index = 0; index < length; index += 1) {
const descriptor = Object.getOwnPropertyDescriptor(source, index)
if (descriptor !== undefined && !('value' in descriptor)) return { fault: withAccessor }
entries.push([index, descriptor?.value])
}
return { value: { entries, kind: 'array' } }
}
const keys = Reflect.ownKeys(source)
if (keys.length > left) return { fault: tooMany }
for (const key of keys) {
if (typeof key !== 'string') continue
const descriptor = Object.getOwnPropertyDescriptor(source, key)
if (descriptor === undefined || descriptor.enumerable !== true) continue
if (!('value' in descriptor)) return { fault: withAccessor }
entries.push([key, descriptor.value])
}
return { value: { entries, kind: isPlainObject(source) ? 'object' : 'unplain' } }
} catch {
return { fault: unreadable }
}
}
function place(target: object, key: number | string, copy: unknown): void {
if (key === '__proto__') Object.defineProperty(target, key, { configurable: true, enumerable: true, value: copy, writable: true })
else Reflect.set(target, key, copy)
}
+14 -13
View File
@@ -4,12 +4,13 @@ import { fileURLToPath } from 'node:url'
import { readFileSync, readdirSync } from 'node:fs'
import test from 'node:test'
import type { AdfDocument } from '../adf/document.ts'
import { adfToHtml } from '../html/emit/adf-to-html.ts'
import { adfToLosslessMarkdown } from '../markdown/emit/adf-to-markdown.ts'
import { blockNodes } from '../adf/block-nodes.ts'
import { htmlToAdf } from '../html/parse/html-to-adf.ts'
import { inlineNodes } from '../adf/inline-nodes.ts'
import { isAdfDocument, isRecord } from '../adf/document.ts'
import { isRecord, readAdfDocument } from '../adf/document.ts'
import { isJsonValue } from '../json-value.ts'
import { losslessMarkdownToAdf } from '../markdown/parse/markdown-to-adf.ts'
import { markVocabularies } from '../adf/mark-attributes.ts'
@@ -25,6 +26,12 @@ const roundTripRoot = join(corpusRoot, 'round-trip')
const roundTripDirectories = ['block-nodes', 'combinations', 'commonmark-subset', 'inline-nodes', 'opaque-carry']
const typesNoFetchedDocumentHolds = ['bodiedSyncBlock', 'decisionItem', 'decisionList', 'extensionFrame', 'fragment', 'multiBodiedExtension', 'syncBlock']
function documentIn(json: unknown, name: string): AdfDocument {
const read = readAdfDocument(json)
assert.ok(read.ok, `${name}.json is not an ADF document`)
return read.value
}
function directoryNames(root: string): string[] {
return readdirSync(root, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
@@ -84,8 +91,7 @@ for (const directory of roundTripDirectories) {
for (const name of names) {
test(`${directory}/${name} emits its markdown byte for byte`, () => {
const parsed: unknown = JSON.parse(readFileSync(join(roundTripRoot, directory, `${name}.json`), 'utf8'))
assert.ok(isAdfDocument(parsed), `${name}.json is not an ADF document`)
const parsed = documentIn(JSON.parse(readFileSync(join(roundTripRoot, directory, `${name}.json`), 'utf8')), name)
const result = adfToLosslessMarkdown(parsed)
assert.ok(result.ok, result.ok ? '' : `${result.error.code}: ${result.error.message}`)
const expected = readFileSync(join(roundTripRoot, directory, `${name}.md`))
@@ -99,8 +105,7 @@ for (const directory of roundTripDirectories) {
for (const directory of roundTripDirectories) {
for (const name of fixtureNames(directory, '.md')) {
test(`${directory}/${name} reads its markdown back to the document beside it`, () => {
const expected: unknown = JSON.parse(readFileSync(join(roundTripRoot, directory, `${name}.json`), 'utf8'))
assert.ok(isAdfDocument(expected), `${name}.json is not an ADF document`)
const expected = documentIn(JSON.parse(readFileSync(join(roundTripRoot, directory, `${name}.json`), 'utf8')), name)
const result = losslessMarkdownToAdf(readFileSync(join(roundTripRoot, directory, `${name}.md`), 'utf8'))
assert.ok(result.ok, result.ok ? '' : `${result.error.code}: ${result.error.message}`)
assert.deepEqual(result.value, expected)
@@ -127,8 +132,7 @@ test('no round-trip fixture repeats the document another holds', () => {
for (const name of pairedNames(normalizationRoot, '.md', '.json')) {
test(`normalization/${name} parses to the document beside it, which emits and reads back to itself`, () => {
const expected: unknown = JSON.parse(readFileSync(join(normalizationRoot, `${name}.json`), 'utf8'))
assert.ok(isAdfDocument(expected), `${name}.json is not an ADF document`)
const expected = documentIn(JSON.parse(readFileSync(join(normalizationRoot, `${name}.json`), 'utf8')), name)
const result = losslessMarkdownToAdf(readFileSync(join(normalizationRoot, `${name}.md`), 'utf8'))
assert.ok(result.ok, result.ok ? '' : `${result.error.code}: ${result.error.message}`)
assert.deepEqual(result.value, expected)
@@ -149,8 +153,7 @@ for (const root of [realPayloadsRoot, realWorldRoot]) {
for (const name of names(root, '.json')) {
test(`${kind}/${name} emits markdown that reads back to it`, () => {
const payload: unknown = JSON.parse(readFileSync(join(root, `${name}.json`), 'utf8'))
assert.ok(isAdfDocument(payload), `${name}.json is not an ADF document`)
const payload = documentIn(JSON.parse(readFileSync(join(root, `${name}.json`), 'utf8')), name)
const emitted = adfToLosslessMarkdown(payload)
assert.ok(emitted.ok, emitted.ok ? '' : `${emitted.error.code}: ${emitted.error.message}`)
const parsed = losslessMarkdownToAdf(emitted.value)
@@ -159,8 +162,7 @@ for (const root of [realPayloadsRoot, realWorldRoot]) {
})
test(`${kind}/${name} writes HTML that reads back to it`, () => {
const payload: unknown = JSON.parse(readFileSync(join(root, `${name}.json`), 'utf8'))
assert.ok(isAdfDocument(payload), `${name}.json is not an ADF document`)
const payload = documentIn(JSON.parse(readFileSync(join(root, `${name}.json`), 'utf8')), name)
const written = adfToHtml(payload)
assert.ok(written.ok, written.ok ? '' : `${written.error.code}: ${written.error.message}`)
assert.deepEqual(htmlToAdf(written.value), { ok: true, value: payload })
@@ -174,8 +176,7 @@ const blockElements: Readonly<Record<string, string>> = { blockquote: '<blockquo
for (const root of [realPayloadsRoot, realWorldRoot]) {
for (const name of names(root, '.json')) {
test(`${basename(root)}/${name} writes each block holding only its id as its element`, () => {
const payload: unknown = JSON.parse(readFileSync(join(root, `${name}.json`), 'utf8'))
assert.ok(isAdfDocument(payload), `${name}.json is not an ADF document`)
const payload = documentIn(JSON.parse(readFileSync(join(root, `${name}.json`), 'utf8')), name)
assert.ok(adfToHtml(payload).ok)
for (const block of payload.content ?? []) {
const opening = Object.hasOwn(blockElements, block.type) ? blockElements[block.type] : undefined
+5 -2
View File
@@ -10,7 +10,7 @@ import { failure, success, type ConvertErrorPath, type Result } from '../../resu
import { firstParagraphForm } from '../first-paragraph.ts'
import { imageElement } from '../image-element.ts'
import { inlineHtml, writableText } from './inline.ts'
import { isUnmarkedSpellableText, nodeAttrs, nodeContent, writableContent } from '../../adf/document.ts'
import { isUnmarkedSpellableText, nodeAttrs, nodeContent, readAdfDocument, writableContent } from '../../adf/document.ts'
import { languageClass } from '../language-class.ts'
import { largestNesting } from '../../nesting.ts'
import { longestOutput, tooLong, withinEngineLimits } from '../../length-bound.ts'
@@ -24,7 +24,10 @@ type Row = { depth: number; kind: 'row'; path: ConvertErrorPath; pieces: Pending
type Pending = Block | Item | Row | string
export function adfToHtml(document: AdfDocument): Result<string> {
return withinEngineLimits(() => writeHtml(document))
return withinEngineLimits(() => {
const read = readAdfDocument(document)
return read.ok ? writeHtml(read.value) : read
})
}
// A stack rather than recursion, since each level would cost several frames: a block returns its pieces in document order, and only this loop pushes them.
+2 -2
View File
@@ -1,4 +1,4 @@
// Export only the conversions, their types, isAdfDocument and what a guarantee or a persona needs.
// Export only the conversions, their types, readAdfDocument and what a guarantee or a persona needs.
export type { AdfAttributes, AdfDocument, AdfMark, AdfNode } from './adf/document.ts'
export type { ConvertError, ConvertErrorCode, ConvertErrorPath, ParseError, Result, SourcePosition } from './result.ts'
export type { JsonValue } from './json-value.ts'
@@ -7,5 +7,5 @@ export { adfToLosslessMarkdown } from './markdown/emit/adf-to-markdown.ts'
export { adfToPortableMarkdown } from './markdown/portable/adf-to-portable-markdown.ts'
export { commonMarkToAdf, losslessMarkdownToAdf } from './markdown/parse/markdown-to-adf.ts'
export { htmlToAdf } from './html/parse/html-to-adf.ts'
export { isAdfDocument } from './adf/document.ts'
export { portableMarkdownToAdf } from './markdown/portable/portable-markdown-to-adf.ts'
export { readAdfDocument } from './adf/document.ts'
+1 -1
View File
@@ -20,7 +20,7 @@ export function isJsonValue(value: unknown): value is JsonValue {
}
// Any realm's Object.prototype has a null prototype; serializeCanonicalJson writes a Date or Map as {}.
function isPlainObject(value: unknown): value is object {
export function isPlainObject(value: unknown): value is object {
if (typeof value !== 'object' || value === null) return false
const prototype: unknown = Object.getPrototypeOf(value)
return prototype === null || (typeof prototype === 'object' && Object.getPrototypeOf(prototype) === null)
+5 -2
View File
@@ -10,7 +10,7 @@ import { failure, success, type ConvertErrorPath, type Result } from '../../resu
import { fencedCodeBlock } from '../commonmark/backtick-runs.ts'
import { flavourClaims } from '../flavour.ts'
import { holdsNullCharacter, markerInterruptsParagraph } from '../commonmark/grammar.ts'
import { holdsOnlyAttributes, isUnmarkedSpellableText, nodeAttrs, nodeContent, writableContent } from '../../adf/document.ts'
import { holdsOnlyAttributes, isUnmarkedSpellableText, nodeAttrs, nodeContent, readAdfDocument, writableContent } from '../../adf/document.ts'
import { languageSlot, type LanguageSlot } from '../code-language.ts'
import { largestNesting } from '../../nesting.ts'
import { withinEngineLimits, withinLongest } from '../../length-bound.ts'
@@ -48,7 +48,10 @@ const listItemOpener = spellDirectiveOpener('listItem', undefined, '')
const orderedDelimiters: Delimiters = ['.', ')']
export function adfToLosslessMarkdown(document: AdfDocument): Result<string> {
return withinEngineLimits(() => writeMarkdown(document, { flavour: 'lossless' }))
return withinEngineLimits(() => {
const read = readAdfDocument(document)
return read.ok ? writeMarkdown(read.value, { flavour: 'lossless' }) : read
})
}
export function writeMarkdown(document: AdfDocument, writtenAs: WrittenAs): Result<string> {
@@ -10,7 +10,7 @@ import { isBlockNodeType, oneLine } from '../../adf/shown-text.ts'
import { languageSlot } from '../code-language.ts'
import { largestNesting } from '../../nesting.ts'
import { linkAttrs } from '../../adf/mark-attributes.ts'
import { nodeAttrs, nodeContent, nodeMarks, writableContent } from '../../adf/document.ts'
import { nodeAttrs, nodeContent, nodeMarks, readAdfDocument, writableContent } from '../../adf/document.ts'
import { portableWriting } from './block-spelling.ts'
import { splitTaskList, taskListItems } from './task-list.ts'
import { taskMarker } from './conventions.ts'
@@ -53,7 +53,8 @@ const blockReducers: Readonly<Record<string, BlockReducer>> = {
export function adfToPortableMarkdown(document: AdfDocument): Result<string> {
return withinEngineLimits(() => {
const reduced = reduceToPortable(document)
const read = readAdfDocument(document)
const reduced = read.ok ? reduceToPortable(read.value) : read
return reduced.ok ? writeMarkdown(reduced.value, portableWriting) : reduced
})
}