the editable site (validation-lab)

This commit is contained in:
kpgarrod committed 2026-11-21 08:03:55 +01:00
commit 3ac81d5a52
13454 files changed
+2227005

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
export function association(node: import("mdast").Association): string;
//# sourceMappingURL=association.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"association.d.ts","sourceRoot":"","sources":["association.js"],"names":[],"mappings":""}
+33
View File
@@ -0,0 +1,33 @@
/**
* @import {AssociationId} from '../types.js'
*/
import {decodeString} from 'micromark-util-decode-string'
/**
* Get an identifier from an association to match it to others.
*
* Associations are nodes that match to something else through an ID:
* <https://github.com/syntax-tree/mdast#association>.
*
* The `label` of an association is the string value: character escapes and
* references work, and casing is intact.
* The `identifier` is used to match one association to another:
* controversially, character escapes and references don’t work in this
* matching: `&copy;` does not match `©`, and `\+` does not match `+`.
*
* But casing is ignored (and whitespace) is trimmed and collapsed: ` A\nb`
* matches `a b`.
* So, we do prefer the label when figuring out how we’re going to serialize:
* it has whitespace, casing, and we can ignore most useless character
* escapes and all character references.
*
* @type {AssociationId}
*/
export function association(node) {
if (node.label || !node.identifier) {
return node.label || ''
}
return decodeString(node.identifier)
}
+23
View File
@@ -0,0 +1,23 @@
/**
* Get the first character of a value.
*
* Is aware of astral characters (such as emoji).
*
* @param {string} value
* Value.
* @returns {string}
* First character; empty if `value` is empty.
*/
export function firstCharacter(value: string): string;
/**
* Get the last character of a value.
*
* Is aware of astral characters (such as emoji).
*
* @param {string} value
* Value.
* @returns {string}
* Last character; empty if `value` is empty.
*/
export function lastCharacter(value: string): string;
//# sourceMappingURL=character.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"character.d.ts","sourceRoot":"","sources":["character.js"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,sCALW,MAAM,GAEJ,MAAM,CAMlB;AAED;;;;;;;;;GASG;AACH,qCALW,MAAM,GAEJ,MAAM,CASlB"}
+32
View File
@@ -0,0 +1,32 @@
/**
* Get the first character of a value.
*
* Is aware of astral characters (such as emoji).
*
* @param {string} value
* Value.
* @returns {string}
* First character; empty if `value` is empty.
*/
export function firstCharacter(value) {
const code = value.codePointAt(0)
return code === undefined ? '' : String.fromCodePoint(code)
}
/**
* Get the last character of a value.
*
* Is aware of astral characters (such as emoji).
*
* @param {string} value
* Value.
* @returns {string}
* Last character; empty if `value` is empty.
*/
export function lastCharacter(value) {
// Only a surrogate pair gives a code point above the BMP.
const code = value.codePointAt(value.length - 2)
return code !== undefined && code > 0xff_ff
? value.slice(-2)
: value.slice(-1)
}
+15
View File
@@ -0,0 +1,15 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred ordered list bullet option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['bulletOrdered'], null | undefined>}
* Preferred ordered list bullet.
*/
export function checkBulletOrdered(state: State): Exclude<Options["bulletOrdered"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-bullet-ordered.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"check-bullet-ordered.d.ts","sourceRoot":"","sources":["check-bullet-ordered.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;GAOG;AACH,0CALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CAe/D;2BAvBgC,wBAAwB;6BAAxB,wBAAwB"}
+25
View File
@@ -0,0 +1,25 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred ordered list bullet option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['bulletOrdered'], null | undefined>}
* Preferred ordered list bullet.
*/
export function checkBulletOrdered(state) {
const marker = state.options.bulletOrdered || '.'
if (marker !== '.' && marker !== ')') {
throw new Error(
'Cannot serialize items with `' +
marker +
'` for `options.bulletOrdered`, expected `.` or `)`'
)
}
return marker
}
+12
View File
@@ -0,0 +1,12 @@
/**
* Checks the preferred alternate list bullet option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['bullet'], null | undefined>}
* Preferred alternate list bullet.
*/
export function checkBulletOther(state: State): Exclude<Options["bullet"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-bullet-other.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"check-bullet-other.d.ts","sourceRoot":"","sources":["check-bullet-other.js"],"names":[],"mappings":"AAMA;;;;;;;GAOG;AACH,wCALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CA8BxD;2BAxCgC,wBAAwB;6BAAxB,wBAAwB"}
+42
View File
@@ -0,0 +1,42 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
import {checkBullet} from './check-bullet.js'
/**
* Checks the preferred alternate list bullet option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['bullet'], null | undefined>}
* Preferred alternate list bullet.
*/
export function checkBulletOther(state) {
const bullet = checkBullet(state)
const bulletOther = state.options.bulletOther
if (!bulletOther) {
return bullet === '*' ? '-' : '*'
}
if (bulletOther !== '*' && bulletOther !== '+' && bulletOther !== '-') {
throw new Error(
'Cannot serialize items with `' +
bulletOther +
'` for `options.bulletOther`, expected `*`, `+`, or `-`'
)
}
if (bulletOther === bullet) {
throw new Error(
'Expected `bullet` (`' +
bullet +
'`) and `bulletOther` (`' +
bulletOther +
'`) to be different'
)
}
return bulletOther
}
+15
View File
@@ -0,0 +1,15 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred list bullet option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['bullet'], null | undefined>}
* Preferred list bullet.
*/
export function checkBullet(state: State): Exclude<Options["bullet"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-bullet.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"check-bullet.d.ts","sourceRoot":"","sources":["check-bullet.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;GAOG;AACH,mCALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CAexD;2BAvBgC,wBAAwB;6BAAxB,wBAAwB"}
+25
View File
@@ -0,0 +1,25 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred list bullet option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['bullet'], null | undefined>}
* Preferred list bullet.
*/
export function checkBullet(state) {
const marker = state.options.bullet || '*'
if (marker !== '*' && marker !== '+' && marker !== '-') {
throw new Error(
'Cannot serialize items with `' +
marker +
'` for `options.bullet`, expected `*`, `+`, or `-`'
)
}
return marker
}
+15
View File
@@ -0,0 +1,15 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred emphasis option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['emphasis'], null | undefined>}
* Preferred emphasis marker.
*/
export function checkEmphasis(state: State): Exclude<Options["emphasis"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-emphasis.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"check-emphasis.d.ts","sourceRoot":"","sources":["check-emphasis.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;GAOG;AACH,qCALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CAe1D;2BAvBgC,wBAAwB;6BAAxB,wBAAwB"}
+25
View File
@@ -0,0 +1,25 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred emphasis option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['emphasis'], null | undefined>}
* Preferred emphasis marker.
*/
export function checkEmphasis(state) {
const marker = state.options.emphasis || '*'
if (marker !== '*' && marker !== '_') {
throw new Error(
'Cannot serialize emphasis with `' +
marker +
'` for `options.emphasis`, expected `*`, or `_`'
)
}
return marker
}
+15
View File
@@ -0,0 +1,15 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred fence option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['fence'], null | undefined>}
* Preferred fence marker.
*/
export function checkFence(state: State): Exclude<Options["fence"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-fence.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"check-fence.d.ts","sourceRoot":"","sources":["check-fence.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;GAOG;AACH,kCALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CAevD;2BAvBgC,wBAAwB;6BAAxB,wBAAwB"}
+25
View File
@@ -0,0 +1,25 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred fence option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['fence'], null | undefined>}
* Preferred fence marker.
*/
export function checkFence(state) {
const marker = state.options.fence || '`'
if (marker !== '`' && marker !== '~') {
throw new Error(
'Cannot serialize code with `' +
marker +
'` for `options.fence`, expected `` ` `` or `~`'
)
}
return marker
}
@@ -0,0 +1,15 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred list item indent option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['listItemIndent'], null | undefined>}
* Preferred list item indent.
*/
export function checkListItemIndent(state: State): Exclude<Options["listItemIndent"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-list-item-indent.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"check-list-item-indent.d.ts","sourceRoot":"","sources":["check-list-item-indent.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;GAOG;AACH,2CALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,gBAAgB,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CAehE;2BAvBgC,wBAAwB;6BAAxB,wBAAwB"}
+25
View File
@@ -0,0 +1,25 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred list item indent option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['listItemIndent'], null | undefined>}
* Preferred list item indent.
*/
export function checkListItemIndent(state) {
const style = state.options.listItemIndent || 'one'
if (style !== 'tab' && style !== 'one' && style !== 'mixed') {
throw new Error(
'Cannot serialize items with `' +
style +
'` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`'
)
}
return style
}
+15
View File
@@ -0,0 +1,15 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred quote option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['quote'], null | undefined>}
* Preferred quote.
*/
export function checkQuote(state: State): Exclude<Options["quote"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-quote.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"check-quote.d.ts","sourceRoot":"","sources":["check-quote.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;GAOG;AACH,kCALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CAevD;2BAvBgC,wBAAwB;6BAAxB,wBAAwB"}
+25
View File
@@ -0,0 +1,25 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred quote option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['quote'], null | undefined>}
* Preferred quote.
*/
export function checkQuote(state) {
const marker = state.options.quote || '"'
if (marker !== '"' && marker !== "'") {
throw new Error(
'Cannot serialize title with `' +
marker +
'` for `options.quote`, expected `"`, or `\'`'
)
}
return marker
}
@@ -0,0 +1,15 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred rule repetition option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['ruleRepetition'], null | undefined>}
* Preferred rule repetition.
*/
export function checkRuleRepetition(state: State): Exclude<Options["ruleRepetition"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-rule-repetition.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"check-rule-repetition.d.ts","sourceRoot":"","sources":["check-rule-repetition.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;GAOG;AACH,2CALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,gBAAgB,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CAehE;2BAvBgC,wBAAwB;6BAAxB,wBAAwB"}
+25
View File
@@ -0,0 +1,25 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred rule repetition option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['ruleRepetition'], null | undefined>}
* Preferred rule repetition.
*/
export function checkRuleRepetition(state) {
const repetition = state.options.ruleRepetition || 3
if (repetition < 3) {
throw new Error(
'Cannot serialize rules with repetition `' +
repetition +
'` for `options.ruleRepetition`, expected `3` or more'
)
}
return repetition
}
+15
View File
@@ -0,0 +1,15 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred rule option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['rule'], null | undefined>}
* Preferred rule marker.
*/
export function checkRule(state: State): Exclude<Options["rule"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-rule.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"check-rule.d.ts","sourceRoot":"","sources":["check-rule.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;GAOG;AACH,iCALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CAetD;2BAvBgC,wBAAwB;6BAAxB,wBAAwB"}
+25
View File
@@ -0,0 +1,25 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred rule option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['rule'], null | undefined>}
* Preferred rule marker.
*/
export function checkRule(state) {
const marker = state.options.rule || '*'
if (marker !== '*' && marker !== '-' && marker !== '_') {
throw new Error(
'Cannot serialize rules with `' +
marker +
'` for `options.rule`, expected `*`, `-`, or `_`'
)
}
return marker
}
+15
View File
@@ -0,0 +1,15 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred strong option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['strong'], null | undefined>}
* Preferred strong marker.
*/
export function checkStrong(state: State): Exclude<Options["strong"], null | undefined>;
import type { State } from 'mdast-util-to-markdown';
import type { Options } from 'mdast-util-to-markdown';
//# sourceMappingURL=check-strong.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"check-strong.d.ts","sourceRoot":"","sources":["check-strong.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;GAOG;AACH,mCALW,KAAK,GAEH,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC,CAexD;2BAvBgC,wBAAwB;6BAAxB,wBAAwB"}
+25
View File
@@ -0,0 +1,25 @@
/**
* @import {Options, State} from 'mdast-util-to-markdown'
*/
/**
* Checks the preferred strong option.
*
* @param {State} state
* Info passed around.
* @returns {Exclude<Options['strong'], null | undefined>}
* Preferred strong marker.
*/
export function checkStrong(state) {
const marker = state.options.strong || '*'
if (marker !== '*' && marker !== '_') {
throw new Error(
'Cannot serialize strong with `' +
marker +
'` for `options.strong`, expected `*`, or `_`'
)
}
return marker
}
+2
View File
@@ -0,0 +1,2 @@
export function compilePattern(info: import("../types.js").Unsafe): RegExp;
//# sourceMappingURL=compile-pattern.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"compile-pattern.d.ts","sourceRoot":"","sources":["compile-pattern.js"],"names":[],"mappings":""}
+30
View File
@@ -0,0 +1,30 @@
/**
* @import {CompilePattern} from '../types.js'
*/
/**
* Compiles a pattern object into a regular expression.
*
* @type {CompilePattern}
*/
export function compilePattern(pattern) {
if (!pattern._compiled) {
const before =
(pattern.atBreak ? '[\\r\\n][\\t ]*' : '') +
(pattern.before ? '(?:' + pattern.before + ')' : '')
pattern._compiled = new RegExp(
(pattern.beforeNode ? '^' : before ? '(' + before + ')' : '') +
(/[$()*+.?[\\\]^{|}]/.test(pattern.character) ? '\\' : '') +
pattern.character +
(pattern.afterNode
? '$'
: pattern.after
? '(?:' + pattern.after + ')'
: ''),
pattern.unicode ? 'gu' : 'g'
)
}
return pattern._compiled
}
+21
View File
@@ -0,0 +1,21 @@
/**
* @import {State} from 'mdast-util-to-markdown'
* @import {FlowChildren, FlowParents, TrackFields} from '../types.js'
*/
/**
* Serialize the children of a parent that contains flow children.
*
* @param {FlowParents} parent
* Parent of flow nodes.
* @param {State} state
* Info passed around about the current state.
* @param {TrackFields} info
* Info on where we are in the document we are generating.
* @returns {string}
* Serialized children, joined by (blank) lines.
*/
export function containerFlow(parent: FlowParents, state: State, info: TrackFields): string;
import type { FlowParents } from '../types.js';
import type { State } from 'mdast-util-to-markdown';
import type { TrackFields } from '../types.js';
//# sourceMappingURL=container-flow.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"container-flow.d.ts","sourceRoot":"","sources":["container-flow.js"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;;;;;;;GAWG;AACH,sCATW,WAAW,SAEX,KAAK,QAEL,WAAW,GAET,MAAM,CA0ClB;iCAtDwD,aAAa;2BAD9C,wBAAwB;iCACS,aAAa"}
+93
View File
@@ -0,0 +1,93 @@
/**
* @import {State} from 'mdast-util-to-markdown'
* @import {FlowChildren, FlowParents, TrackFields} from '../types.js'
*/
/**
* Serialize the children of a parent that contains flow children.
*
* @param {FlowParents} parent
* Parent of flow nodes.
* @param {State} state
* Info passed around about the current state.
* @param {TrackFields} info
* Info on where we are in the document we are generating.
* @returns {string}
* Serialized children, joined by (blank) lines.
*/
export function containerFlow(parent, state, info) {
const indexStack = state.indexStack
const children = parent.children || []
const tracker = state.createTracker(info)
/** @type {Array<string>} */
const results = []
let index = -1
indexStack.push(-1)
while (++index < children.length) {
const child = children[index]
indexStack[indexStack.length - 1] = index
results.push(
tracker.move(
state.handle(child, parent, state, {
before: '\n',
after: '\n',
...tracker.current()
})
)
)
if (child.type !== 'list') {
state.bulletLastUsed = undefined
}
if (index < children.length - 1) {
results.push(
tracker.move(between(child, children[index + 1], parent, state))
)
}
}
indexStack.pop()
return results.join('')
}
/**
* Determine the markdown to insert between two flow nodes.
*
* @param {FlowChildren} left
* Left flow node.
* @param {FlowChildren} right
* Right flow node.
* @param {FlowParents} parent
* Parent of the flow nodes.
* @param {State} state
* Info passed around.
* @returns {string}
* Markdown to insert between the two flow nodes.
*/
function between(left, right, parent, state) {
let index = state.join.length
while (index--) {
const result = state.join[index](left, right, parent, state)
if (result === true || result === 1) {
break
}
if (typeof result === 'number') {
return '\n'.repeat(1 + result)
}
if (result === false) {
return '\n\n<!---->\n\n'
}
}
return '\n\n'
}
+144
View File
@@ -0,0 +1,144 @@
/**
* Serialize the children of a parent that contains phrasing children.
*
* @param {PhrasingParents} parent
* Parent of phrasing nodes.
* @param {State} state
* Info passed around about the current state.
* @param {Info} info
* Info on where we are in the document we are generating.
* @returns {string}
* Serialized result.
*/
export function containerPhrasing(parent: PhrasingParents, state: State, info: Info): string;
/**
* Serialize a node as attention,
* with its sequence chosen later.
*
* @param {PhrasingParents} node
* Node.
* @param {Attention} attention
* Attention of the node.
* @param {State} state
* Info passed around about the current state.
* @param {Tracker} tracker
* Tracker.
* @returns {AttentionResult | undefined}
* Attention or nothing.
*/
export function attentionItem(node: PhrasingParents, attention: Attention, state: State, tracker: Tracker): AttentionResult | undefined;
/**
* Serialize phrasing with attention.
*
* Whether attention forms depends on everything around it.
* This checks that it does and tries other sequences if not.
*
* @param {Array<Item>} items
* Phrasing items.
* @param {string} before
* Characters before.
* @param {string} after
* Characters after.
* @returns {string}
* Serialized markdown.
*/
export function serialize(items: Array<Item>, before: string, after: string): string;
/**
* Attention, of which the sequence is chosen later.
*/
export type AttentionResult = {
/**
* Serialized children.
*/
children: Array<Item>;
/**
* Sequences that can be used, in order of preference.
*/
sequences: Array<string>;
};
/**
* Improvement of attention sequences.
*/
export type Improvement = {
/**
* Chosen sequences for each attention.
*/
chosen: Map<AttentionResult, string>;
/**
* Tokens involved in the improvement.
*/
tokens: Array<Token>;
/**
* Mistake that led to this improvement, if any.
*/
mistake: Mistake | undefined;
};
/**
* Serialized phrasing.
*/
export type Item = AttentionResult | string;
/**
* Sequence that does not form its attention.
*/
export type Mistake = {
/**
* Attention to try other sequences for.
*/
attention: Array<AttentionResult>;
/**
* Index of the token.
*/
index: number;
};
/**
* Sequences next to each other with the same marker.
*/
export type Run = {
/**
* Whether it can close.
*/
close: boolean;
/**
* Index after the last marker not used (to open).
*/
end: number;
/**
* Sequence of each marker.
*/
markers: Array<Token>;
/**
* Whether it can open.
*/
open: boolean;
/**
* Whether it can be split (built-in attention).
*/
split: boolean;
/**
* Index of the first marker not used (to close).
*/
start: number;
/**
* Sequences.
*/
tokens: Array<Token>;
};
/**
* Rendered phrasing.
*/
export type Token = {
/**
* Attention, if this is one of its sequences.
*/
attention: AttentionResult | undefined;
/**
* Value.
*/
value: string;
};
import type { PhrasingParents } from '../types.js';
import type { State } from 'mdast-util-to-markdown';
import type { Info } from 'mdast-util-to-markdown';
import type { Attention } from 'mdast-util-to-markdown';
import type { Tracker } from 'mdast-util-to-markdown';
//# sourceMappingURL=container-phrasing.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"container-phrasing.d.ts","sourceRoot":"","sources":["container-phrasing.js"],"names":[],"mappings":"AA+NA;;;;;;;;;;;GAWG;AACH,0CATW,eAAe,SAEf,KAAK,QAEL,IAAI,GAEF,MAAM,CAKlB;AAkWD;;;;;;;;;;;;;;GAcG;AACH,oCAXW,eAAe,aAEf,SAAS,SAET,KAAK,WAEL,OAAO,GAEL,eAAe,GAAG,SAAS,CAwBvC;AAuKD;;;;;;;;;;;;;;GAcG;AACH,iCATW,KAAK,CAAC,IAAI,CAAC,UAEX,MAAM,SAEN,MAAM,GAEJ,MAAM,CAmBlB;;;;;;;;cAxxBa,KAAK,CAAC,IAAI,CAAC;;;;eAEX,KAAK,CAAC,MAAM,CAAC;;;;;;;;;YAOb,GAAG,CAAC,eAAe,EAAE,MAAM,CAAC;;;;YAE5B,KAAK,CAAC,KAAK,CAAC;;;;aAEZ,OAAO,GAAG,SAAS;;;;;mBAKpB,eAAe,GAAG,MAAM;;;;;;;;eAOvB,KAAK,CAAC,eAAe,CAAC;;;;WAEtB,MAAM;;;;;;;;;WAON,OAAO;;;;SAEP,MAAM;;;;aAEN,KAAK,CAAC,KAAK,CAAC;;;;UAEZ,OAAO;;;;WAEP,OAAO;;;;WAEP,MAAM;;;;YAEN,KAAK,CAAC,KAAK,CAAC;;;;;;;;;eAOZ,eAAe,GAAG,SAAS;;;;WAE3B,MAAM;;qCAtFc,aAAa;2BADW,wBAAwB;0BAAxB,wBAAwB;+BAAxB,wBAAwB;6BAAxB,wBAAwB"}
+826
View File
@@ -0,0 +1,826 @@
/**
* @import {Attention, Handle, Info, State, Tracker} from 'mdast-util-to-markdown'
* @import {PhrasingParents} from '../types.js'
*/
import {asciiPunctuation} from 'micromark-util-character'
import {classifyCharacter} from 'micromark-util-classify-character'
import {firstCharacter, lastCharacter} from './character.js'
import {encodeCharacterReference} from './encode-character-reference.js'
import {encodeInfo} from './encode-info.js'
import {htmlKind} from './html-kind.js'
/**
* Markers for builtin attention (emphasis, strong) to whether they are stricter:
* whether they cannot open and close inside words.
*
* Builtin runs pair following CommonMark rules for emphasis and strong:
* they are split,
* using one or two markers at a time,
* with the rule of 3.
* Other markers pair like GFM strikethrough:
* whole runs pair with a run of the same size.
*
* @type {Map<string, boolean>}
*/
const builtins = new Map([
['*', false],
['_', true]
])
/**
* @typedef AttentionResult
* Attention, of which the sequence is chosen later.
* @property {Array<Item>} children
* Serialized children.
* @property {Array<string>} sequences
* Sequences that can be used, in order of preference.
*/
/**
* @typedef Improvement
* Improvement of attention sequences.
* @property {Map<AttentionResult, string>} chosen
* Chosen sequences for each attention.
* @property {Array<Token>} tokens
* Tokens involved in the improvement.
* @property {Mistake | undefined} mistake
* Mistake that led to this improvement, if any.
*/
/**
* @typedef {AttentionResult | string} Item
* Serialized phrasing.
*/
/**
* @typedef Mistake
* Sequence that does not form its attention.
* @property {Array<AttentionResult>} attention
* Attention to try other sequences for.
* @property {number} index
* Index of the token.
*/
/**
* @typedef Run
* Sequences next to each other with the same marker.
* @property {boolean} close
* Whether it can close.
* @property {number} end
* Index after the last marker not used (to open).
* @property {Array<Token>} markers
* Sequence of each marker.
* @property {boolean} open
* Whether it can open.
* @property {boolean} split
* Whether it can be split (built-in attention).
* @property {number} start
* Index of the first marker not used (to close).
* @property {Array<Token>} tokens
* Sequences.
*/
/**
* @typedef Token
* Rendered phrasing.
* @property {AttentionResult | undefined} attention
* Attention, if this is one of its sequences.
* @property {string} value
* Value.
*/
/**
* Get candidates for a mistake:
* attention to try other sequences for,
* later first.
*
* @param {Array<Token>} tokens
* Tokens.
* @param {Array<Token>} involved
* Sequences involved in the mistake.
* @param {Map<Token, Run>} runOf
* Run of each sequence.
* @returns {Array<AttentionResult>}
* Candidates.
*/
function candidates(tokens, involved, runOf) {
/** @type {Set<AttentionResult | undefined>} */
const related = new Set()
// The attention involved, and attention in runs with its sequences.
for (const token of tokens) {
const siblings = runOf.get(token)
if (
siblings &&
token.attention &&
involved.some((d) => d.attention === token.attention)
) {
for (const sibling of siblings.tokens) {
related.add(sibling.attention)
}
}
}
/** @type {Array<AttentionResult>} */
const ordered = []
for (const token of tokens) {
if (token.attention && related.delete(token.attention)) {
ordered.push(token.attention)
}
}
// Later first: attention that opens later is inner or next.
ordered.reverse()
return ordered
}
/**
* Check whether sequences form their attention, like `micromark`.
*
* Sequences of `*` and `_` pair like emphasis and strong in CommonMark,
* others like strikethrough in GFM.
*
* @param {Array<Token>} tokens
* Tokens.
* @param {string} before
* Characters before.
* @param {string} after
* Characters after.
* @returns {Mistake | undefined}
* First mistake, if any.
*/
function check(tokens, before, after) {
/** @type {Array<Run>} */
const runs = []
/** @type {Map<Token, Array<Token>>} */
const wrong = new Map()
/** @type {Map<Token, Run>} */
const runOf = new Map()
let index = 0
while (index < tokens.length) {
if (!tokens[index].attention) {
index++
continue
}
const marker = tokens[index].value.charAt(0)
const strict = builtins.get(marker)
let end = index + 1
while (
end < tokens.length &&
tokens[end].attention &&
tokens[end].value.charAt(0) === marker
) {
end++
}
const head = index ? tokens[index - 1].value : before
const previous = classifyCharacter(head.charCodeAt(head.length - 1))
const next = classifyCharacter(
(end < tokens.length ? tokens[end].value : after).charCodeAt(0)
)
const open = !next || (next === 2 && Boolean(previous))
const close = !previous || (previous === 2 && Boolean(next))
/** @type {Run} */
const run = {
tokens: tokens.slice(index, end),
markers: [],
start: 0,
end: 0,
// Underscores are strict, they cannot open or close inside words.
open: strict ? open && (Boolean(previous) || !close) : open,
close: strict ? close && (Boolean(next) || !open) : close,
// All builtins can split runs.
split: strict !== undefined
}
for (const token of run.tokens) {
// Every sequence is wrong until it pairs with its other sequence.
wrong.set(token, [...run.tokens])
runOf.set(token, run)
let size = token.value.length
while (size--) run.markers.push(token)
}
run.end = run.markers.length
runs.push(run)
index = end
}
pair(runs, wrong)
index = -1
while (++index < tokens.length) {
const involved = wrong.get(tokens[index])
if (involved) return {attention: candidates(tokens, involved, runOf), index}
}
}
/**
* Serialize the children of a parent that contains phrasing children.
*
* @param {PhrasingParents} parent
* Parent of phrasing nodes.
* @param {State} state
* Info passed around about the current state.
* @param {Info} info
* Info on where we are in the document we are generating.
* @returns {string}
* Serialized result.
*/
export function containerPhrasing(parent, state, info) {
return serialize(phrasing(parent, state, info), info.before, info.after)
}
/**
* Encode the first or last character of tokens as a character reference,
* if it is text.
*
* @param {Array<Token>} tokens
* Tokens.
* @param {boolean} start
* Whether to encode the first or last character.
* @returns {undefined}
* Nothing.
*/
function encode(tokens, start) {
const token = tokens[start ? 0 : tokens.length - 1]
if (!token || token.attention) return
const character = start
? firstCharacter(token.value)
: lastCharacter(token.value)
const reference = encodeCharacterReference(
/** @type {number} */ (character.codePointAt(0))
)
if (start) {
token.value = reference + token.value.slice(character.length)
} else {
let value = token.value.slice(0, token.value.length - character.length)
let escapes = 0
while (value.charCodeAt(value.length - 1 - escapes) === 92 /* `\` */) {
escapes++
}
// Odd number would escape the `&` again.
if (escapes % 2) value += '\\'
token.value = value + reference
}
}
/**
* Try other sequences for the candidates of a mistake and use the first that
* moves the mistake further.
*
* @param {Array<Item>} items
* Items.
* @param {Map<AttentionResult, string>} chosen
* Sequences to use instead of preferred sequences.
* @param {Mistake} mistake
* Mistake.
* @param {string} before
* Characters before.
* @param {string} after
* Characters after.
* @returns {Improvement | undefined}
* Result if better.
*/
function improve(items, chosen, mistake, before, after) {
for (const attention of mistake.attention) {
const current = chosen.get(attention) || attention.sequences[0]
for (const sequence of attention.sequences) {
if (sequence === current) continue
const trial = new Map(chosen)
trial.set(attention, sequence)
const tokens = render(items, trial, before, after)
const next = check(tokens, before, after)
if (!next || next.index > mistake.index) {
return {chosen: trial, mistake: next, tokens}
}
}
}
}
/**
* Pair runs like `micromark` and mark sequences that do form their attention
* as fine.
*
* Each pair uses markers from the end of an opener and the start of a closer.
* It forms the intended attention if those markers are exactly the whole
* opening and closing sequence of one attention.
* Otherwise attention is mixed up:
* either sequences of different attention pair,
* part of a sequence is used (such as `**` of strong as `*`),
* or several sequences are used together (such as `*` and `*` as `**`).
* Then the sequences involved are recorded with each other.
*
* @param {Array<Run>} runs
* Runs.
* @param {Map<Token, Array<Token>>} wrong
* Sequences that are wrong, with the sequences involved.
* @returns {undefined}
* Nothing, `wrong` is changed.
*/
function pair(runs, wrong) {
/** @type {Map<string, Array<Run>>} */
const openersByMarker = new Map()
for (const closer of runs) {
const marker = closer.tokens[0].value.charAt(0)
let openers = openersByMarker.get(marker)
if (!openers) {
openers = []
openersByMarker.set(marker, openers)
}
let open = closer.close ? openers.length : 0
while (open-- && closer.start < closer.end) {
const opener = openers[open]
const openerSize = opener.end - opener.start
const closerSize = closer.end - closer.start
if (
closer.split
? // The rule of 3, on the sizes that are left.
(opener.close || closer.open) &&
closerSize % 3 &&
!((openerSize + closerSize) % 3)
: // Others pair whole runs of the same size.
openerSize !== opener.markers.length || openerSize !== closerSize
) {
continue
}
const size = closer.split
? openerSize > 1 && closerSize > 1
? 2
: 1
: closerSize
const opening = opener.markers.slice(opener.end - size, opener.end)
const closing = closer.markers.slice(closer.start, closer.start + size)
const openToken = opening[0]
const closeToken = closing[0]
if (
// Whole sequences:
// the markers of a sequence are next to each other,
// so if the first and last marker are of one sequence of that size,
// all markers are exactly that sequence.
openToken === opening[size - 1] &&
openToken.value.length === size &&
closeToken === closing[size - 1] &&
closeToken.value.length === size &&
// Of the same attention, so its opening and closing sequence.
openToken.attention === closeToken.attention
) {
wrong.delete(openToken)
wrong.delete(closeToken)
} else {
const involved = [...new Set([...opening, ...closing])]
// Add to what is involved already: a sequence can be in several pairs.
for (const token of involved) {
const list = wrong.get(token)
if (list) list.push(...involved)
}
}
opener.end -= size
closer.start += size
if (opener.start === opener.end) openers.splice(open, 1)
// Search again from the start, as this run may close more.
open = openers.length
}
if (closer.open && closer.start < closer.end) openers.push(closer)
}
}
/**
* Get the sequences that can be used for attention, in order of preference.
*
* @param {string} type
* Node type.
* @param {Array<string>} markers
* Markers.
* @param {Array<number>} sizes
* Sizes.
* @returns {Array<string>}
* Sequences.
*/
function attentionSequences(type, markers, sizes) {
if (markers.length === 0) {
throw new Error(
'Cannot serialize `' +
type +
'` as attention without markers, expected one or more markers'
)
}
if (sizes.length === 0) {
throw new Error(
'Cannot serialize `' +
type +
'` as attention without sizes, expected one or more sizes'
)
}
for (const size of sizes) {
if (!Number.isSafeInteger(size) || size < 1) {
throw new Error(
'Cannot serialize `' +
type +
'` as attention with `' +
size +
'` as size, expected positive integer'
)
}
}
/** @type {Array<string>} */
const sequences = []
for (const marker of markers) {
if (marker.length !== 1) {
throw new Error(
'Cannot serialize `' +
type +
'` as attention with `' +
marker +
'` as marker, expected a single ascii character'
)
}
if (!asciiPunctuation(marker.charCodeAt(0))) {
throw new Error(
'Cannot serialize `' +
type +
'` as attention with `' +
marker +
'` as marker, expected ascii punctuation'
)
}
for (const size of sizes) {
sequences.push(marker.repeat(size))
}
}
return sequences
}
/**
* Serialize the children of a parent that contains phrasing children,
* keeping attention separate,
* so that its markers can be chosen later.
*
* @param {PhrasingParents} parent
* Parent of phrasing nodes.
* @param {State} state
* Info passed around about the current state.
* @param {Info} info
* Info on where we are in the document we are generating.
* @returns {Array<Item>}
* Items.
*/
function phrasing(parent, state, info) {
const indexStack = state.indexStack
const children = parent.children || []
/** @type {Array<Item>} */
const results = []
let index = -1
let before = info.before
indexStack.push(-1)
let tracker = state.createTracker(info)
while (++index < children.length) {
const child = children[index]
/** @type {string} */
let after
indexStack[indexStack.length - 1] = index
if (index + 1 < children.length) {
/** @type {Handle} */
// @ts-expect-error: hush, it’s actually a `zwitch`.
let handle = state.handle.handlers[children[index + 1].type]
// @ts-expect-error: hush, it’s actually a `zwitch`.
if (handle && handle.peek) handle = handle.peek
after = handle
? firstCharacter(
handle(children[index + 1], parent, state, {
before: '',
after: '',
...tracker.current()
})
)
: ''
} else {
after = info.after
}
// In some cases, html (text) can be found in phrasing right after an eol.
// When we’d serialize that, it could be seen as html (flow): all its kinds
// except 7 can interrupt a paragraph.
// As we can’t escape or so to prevent it from happening,
// we take a somewhat reasonable approach:
// replace that eol with a space.
// See: <https://github.com/syntax-tree/mdast-util-to-markdown/issues/15>
const previous = results[results.length - 1]
if (
typeof previous === 'string' &&
(before === '\r' || before === '\n') &&
child.type === 'html' &&
htmlKind(child.value) !== 7
) {
results[results.length - 1] = previous.replace(/(\r?\n|\r)$/, ' ')
before = ' '
// To do: does this work to reset tracker?
tracker = state.createTracker(info)
tracker.move(serialize(results, info.before, info.after))
}
/** @type {(Handle & {attention?: Attention | undefined}) | undefined} */
// @ts-expect-error: hush, it’s actually a `zwitch`.
const handle = state.handle.handlers[child.type]
if (handle && handle.attention) {
const item = attentionItem(
/** @type {PhrasingParents} */ (child),
handle.attention,
state,
tracker
)
if (!item) continue
results.push(item)
before = lastCharacter(item.sequences[0])
} else {
const value = state.handle(child, parent, state, {
...tracker.current(),
after,
before
})
if (!value) continue
tracker.move(value)
results.push(value)
before = lastCharacter(value)
}
}
indexStack.pop()
return results
}
/**
* Serialize a node as attention,
* with its sequence chosen later.
*
* @param {PhrasingParents} node
* Node.
* @param {Attention} attention
* Attention of the node.
* @param {State} state
* Info passed around about the current state.
* @param {Tracker} tracker
* Tracker.
* @returns {AttentionResult | undefined}
* Attention or nothing.
*/
export function attentionItem(node, attention, state, tracker) {
const {construct, markers, sizes} = attention(node, state)
const sequences = attentionSequences(node.type, markers, sizes)
const sequence = sequences[0]
const exit = state.enter(construct)
const inside = state.createTracker(tracker.current())
inside.move(sequence)
const children = phrasing(node, state, {
...inside.current(),
before: sequence,
after: sequence
})
exit()
// Empty attention cannot form.
if (children.length === 0) return
tracker.move(sequence)
tracker.move(serialize(children, sequence, sequence))
tracker.move(sequence)
return {children, sequences}
}
/**
* Fix mistakes one at a time.
*
* @param {Array<Item>} items
* Phrasing items.
* @param {Map<AttentionResult, string>} chosen
* Sequences to start with.
* @param {string} before
* Characters before.
* @param {string} after
* Characters after.
* @returns {Array<Token> | undefined}
* Tokens, if all mistakes could be fixed.
*/
function fix(items, chosen, before, after) {
let tokens = render(items, chosen, before, after)
let mistake = check(tokens, before, after)
while (mistake) {
const next = improve(items, chosen, mistake, before, after)
if (!next) return
chosen = next.chosen
tokens = next.tokens
mistake = next.mistake
}
return tokens
}
/**
* Guess sequences for attention so that few mistakes are left to fix because
* each fix is slow.
*
* Prefers another marker when a sequence would touch one with the same marker
* of a sibling or parent (`**a**` and `*b*` as `**a***b*`).
* Except for an only child with a longer builtin sequence,
* as that forms (`***a***`).
*
* @param {Array<Item>} items
* Phrasing items.
* @param {Map<AttentionResult, string>} chosen
* Guesses that are not the preferred sequence.
* @param {string} before
* Sequence of the parent or characters before.
* @param {string} after
* Sequence of the parent or characters after.
* @returns {undefined}
* Nothing.
*/
function guess(items, chosen, before, after) {
let previous = before
let index = -1
while (++index < items.length) {
const item = items[index]
if (typeof item === 'string') {
previous = ''
continue
}
const next = index === items.length - 1 ? after : ''
const sequence =
item.sequences.find(function (value) {
const marker = value.charAt(0)
return (
(marker !== previous.charAt(0) && marker !== next.charAt(0)) ||
(items.length === 1 &&
builtins.has(marker) &&
value.length > before.length)
)
}) || item.sequences[0]
if (sequence !== item.sequences[0]) chosen.set(item, sequence)
guess(item.children, chosen, sequence, sequence)
previous = sequence
}
}
/**
* Render items with sequences;
* encoding characters around attention where needed.
*
* @param {Array<Item>} items
* Serialized phrasing.
* @param {Map<AttentionResult, string>} chosen
* Sequences to use instead of preferred sequences.
* @param {string} before
* Characters before.
* @param {string} after
* Characters after.
* @returns {Array<Token>}
* Tokens.
*/
function render(items, chosen, before, after) {
/** @type {Array<Token>} */
const tokens = []
/** @type {string | undefined} */
let encodeAfter
let previous = lastCharacter(before)
let index = -1
while (++index < items.length) {
const item = items[index]
if (typeof item === 'string') {
/** @type {Token} */
const token = {value: item, attention: undefined}
// If attention before had to encode the character after it, encode it.
if (encodeAfter && encodeAfter === firstCharacter(item)) {
encode([token], true)
}
encodeAfter = undefined
tokens.push(token)
if (token.value) previous = lastCharacter(token.value)
continue
}
const sequence = chosen.get(item) || item.sequences[0]
const marker = sequence.charAt(0)
const next = items[index + 1]
const outsideBefore = previous
const outsideAfter = firstCharacter(
next === undefined
? after
: typeof next === 'string'
? next
: chosen.get(next) || next.sequences[0]
)
const inside = render(item.children, chosen, sequence, sequence)
const head = inside[0].value
const open = encodeInfo(
outsideBefore.charCodeAt(outsideBefore.length - 1),
head.charCodeAt(0),
marker
)
if (open.inside) encode(inside, true)
const tail = lastCharacter(inside[inside.length - 1].value)
const close = encodeInfo(
outsideAfter.charCodeAt(0),
tail.charCodeAt(tail.length - 1),
marker
)
if (close.inside) encode(inside, false)
if (open.outside && outsideBefore !== '\n' && outsideBefore !== '\r') {
encode(tokens, false)
}
if (close.outside) encodeAfter = outsideAfter
tokens.push({value: sequence, attention: item}, ...inside, {
value: sequence,
attention: item
})
previous = sequence.charAt(sequence.length - 1)
}
return tokens
}
/**
* Serialize phrasing with attention.
*
* Whether attention forms depends on everything around it.
* This checks that it does and tries other sequences if not.
*
* @param {Array<Item>} items
* Phrasing items.
* @param {string} before
* Characters before.
* @param {string} after
* Characters after.
* @returns {string}
* Serialized markdown.
*/
export function serialize(items, before, after) {
/** @type {Map<AttentionResult, string>} */
const guessed = new Map()
guess(items, guessed, before, after)
const tokens =
// Start from guesses (based on the preferred sequences).
(guessed.size > 0 ? fix(items, guessed, before, after) : undefined) ||
// If stuck, start from the preferred sequences instead.
fix(items, new Map(), before, after) ||
// If stuck again, use the preferred sequences as they are.
render(items, new Map(), before, after)
// Join the tokens.
let result = ''
for (const token of tokens) result += token.value
return result
}
@@ -0,0 +1,10 @@
/**
* Encode a code point as a character reference.
*
* @param {number} code
* Code point to encode.
* @returns {string}
* Encoded character reference.
*/
export function encodeCharacterReference(code: number): string;
//# sourceMappingURL=encode-character-reference.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"encode-character-reference.d.ts","sourceRoot":"","sources":["encode-character-reference.js"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,+CALW,MAAM,GAEJ,MAAM,CAKlB"}
@@ -0,0 +1,11 @@
/**
* Encode a code point as a character reference.
*
* @param {number} code
* Code point to encode.
* @returns {string}
* Encoded character reference.
*/
export function encodeCharacterReference(code) {
return '&#x' + code.toString(16).toUpperCase() + ';'
}
+33
View File
@@ -0,0 +1,33 @@
/**
* Check whether to encode (as a character reference) the characters
* surrounding an attention run.
*
* Which characters are around an attention run influence whether it works or
* not.
*
* See <https://github.com/orgs/syntax-tree/discussions/60> for more info.
* See this markdown in a particular renderer to see what works:
*
* ```markdown
* | | A (letter inside) | B (punctuation inside) | C (whitespace inside) | D (nothing inside) |
* | ----------------------- | ----------------- | ---------------------- | --------------------- | ------------------ |
* | 1 (letter outside) | x*y*z | x*.*z | x* *z | x**z |
* | 2 (punctuation outside) | .*y*. | .*.*. | .* *. | .**. |
* | 3 (whitespace outside) | x *y* z | x *.* z | x * * z | x ** z |
* | 4 (nothing outside) | *x* | *.* | * * | ** |
* ```
*
* @param {number} outside
* Code point on the outer side of the run.
* @param {number} inside
* Code point on the inner side of the run.
* @param {string} marker
* Marker of the run.
* Underscores are handled more strictly (they form less often) than
* asterisks.
* @returns {EncodeSides}
* Whether to encode characters.
*/
export function encodeInfo(outside: number, inside: number, marker: string): EncodeSides;
import type { EncodeSides } from '../types.js';
//# sourceMappingURL=encode-info.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"encode-info.d.ts","sourceRoot":"","sources":["encode-info.js"],"names":[],"mappings":"AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAKH,oCAfW,MAAM,UAEN,MAAM,UAEN,MAAM,GAIJ,WAAW,CAgDvB;iCAhF6B,aAAa"}
+82
View File
@@ -0,0 +1,82 @@
/**
* @import {EncodeSides} from '../types.js'
*/
import {classifyCharacter} from 'micromark-util-classify-character'
/**
* Check whether to encode (as a character reference) the characters
* surrounding an attention run.
*
* Which characters are around an attention run influence whether it works or
* not.
*
* See <https://github.com/orgs/syntax-tree/discussions/60> for more info.
* See this markdown in a particular renderer to see what works:
*
* ```markdown
* | | A (letter inside) | B (punctuation inside) | C (whitespace inside) | D (nothing inside) |
* | ----------------------- | ----------------- | ---------------------- | --------------------- | ------------------ |
* | 1 (letter outside) | x*y*z | x*.*z | x* *z | x**z |
* | 2 (punctuation outside) | .*y*. | .*.*. | .* *. | .**. |
* | 3 (whitespace outside) | x *y* z | x *.* z | x * * z | x ** z |
* | 4 (nothing outside) | *x* | *.* | * * | ** |
* ```
*
* @param {number} outside
* Code point on the outer side of the run.
* @param {number} inside
* Code point on the inner side of the run.
* @param {string} marker
* Marker of the run.
* Underscores are handled more strictly (they form less often) than
* asterisks.
* @returns {EncodeSides}
* Whether to encode characters.
*/
// Important: punctuation must never be encoded.
// Punctuation is solely used by markdown constructs.
// And by encoding itself.
// Encoding them will break constructs or double encode things.
export function encodeInfo(outside, inside, marker) {
const outsideKind = classifyCharacter(outside)
const insideKind = classifyCharacter(inside)
// Letter outside:
if (outsideKind === undefined) {
return insideKind === undefined
? // Letter inside:
// we have to encode *both* letters for `_` as it is looser.
// it already forms for `*` (and GFMs `~`).
marker === '_'
? {inside: true, outside: true}
: {inside: false, outside: false}
: insideKind === 1
? // Whitespace inside: encode both (letter, whitespace).
{inside: true, outside: true}
: // Punctuation inside: encode outer (letter)
{inside: false, outside: true}
}
// Whitespace outside:
if (outsideKind === 1) {
return insideKind === undefined
? // Letter inside: already forms.
{inside: false, outside: false}
: insideKind === 1
? // Whitespace inside: encode both (whitespace).
{inside: true, outside: true}
: // Punctuation inside: already forms.
{inside: false, outside: false}
}
// Punctuation outside:
return insideKind === undefined
? // Letter inside: already forms.
{inside: false, outside: false}
: insideKind === 1
? // Whitespace inside: encode inner (whitespace).
{inside: true, outside: false}
: // Punctuation inside: already forms.
{inside: false, outside: false}
}
@@ -0,0 +1,18 @@
/**
* @import {State} from 'mdast-util-to-markdown'
* @import {Code} from 'mdast'
*/
/**
* Checks if a code block can be formatted as an indented code block.
*
* @param {Code} node
* Node to check.
* @param {State} state
* Info passed around.
* @returns {boolean}
* Whether the code can be formatted as an indented code block.
*/
export function formatCodeAsIndented(node: Code, state: State): boolean;
import type { Code } from 'mdast';
import type { State } from 'mdast-util-to-markdown';
//# sourceMappingURL=format-code-as-indented.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"format-code-as-indented.d.ts","sourceRoot":"","sources":["format-code-as-indented.js"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;;;;;GASG;AACH,2CAPW,IAAI,SAEJ,KAAK,GAEH,OAAO,CAcnB;0BAxBsB,OAAO;2BADN,wBAAwB"}
@@ -0,0 +1,27 @@
/**
* @import {State} from 'mdast-util-to-markdown'
* @import {Code} from 'mdast'
*/
/**
* Checks if a code block can be formatted as an indented code block.
*
* @param {Code} node
* Node to check.
* @param {State} state
* Info passed around.
* @returns {boolean}
* Whether the code can be formatted as an indented code block.
*/
export function formatCodeAsIndented(node, state) {
return Boolean(
state.options.fences === false &&
node.value &&
// If there’s no info…
!node.lang &&
// And there’s a non-whitespace character…
/[^\n\r ]/.test(node.value) &&
// And the value doesn’t start or end in a blank…
!/^[\t ]*(?:[\n\r]|$)|(?:^|[\n\r])[\t ]*$/.test(node.value)
)
}
@@ -0,0 +1,14 @@
/**
* Checks if a heading can be formatted as a setext heading.
*
* @param {Heading} node
* Node to check.
* @param {State} state
* Info passed around.
* @returns {boolean}
* Whether the heading can be formatted as a setext heading.
*/
export function formatHeadingAsSetext(node: Heading, state: State): boolean;
import type { Heading } from 'mdast';
import type { State } from 'mdast-util-to-markdown';
//# sourceMappingURL=format-heading-as-setext.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"format-heading-as-setext.d.ts","sourceRoot":"","sources":["format-heading-as-setext.js"],"names":[],"mappings":"AAQA;;;;;;;;;GASG;AACH,4CAPW,OAAO,SAEP,KAAK,GAEH,OAAO,CAuBnB;6BApCyB,OAAO;2BADT,wBAAwB"}
@@ -0,0 +1,39 @@
/**
* @import {State} from 'mdast-util-to-markdown'
* @import {Heading} from 'mdast'
*/
import {EXIT, visit} from 'unist-util-visit'
import {toString} from 'mdast-util-to-string'
/**
* Checks if a heading can be formatted as a setext heading.
*
* @param {Heading} node
* Node to check.
* @param {State} state
* Info passed around.
* @returns {boolean}
* Whether the heading can be formatted as a setext heading.
*/
export function formatHeadingAsSetext(node, state) {
let literalWithBreak = false
// Look for literals with a line break.
// Note that this also
visit(node, function (node) {
if (
('value' in node && /\r?\n|\r/.test(node.value)) ||
node.type === 'break'
) {
literalWithBreak = true
return EXIT
}
})
return Boolean(
(!node.depth || node.depth < 3) &&
toString(node) &&
(state.options.setext || literalWithBreak)
)
}
@@ -0,0 +1,14 @@
/**
* Checks if a link can be formatted as an autolink.
*
* @param {Link} node
* Node to check.
* @param {State} state
* Info passed around.
* @returns {boolean}
* Whether the link can be formatted as an autolink.
*/
export function formatLinkAsAutolink(node: Link, state: State): boolean;
import type { Link } from 'mdast';
import type { State } from 'mdast-util-to-markdown';
//# sourceMappingURL=format-link-as-autolink.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"format-link-as-autolink.d.ts","sourceRoot":"","sources":["format-link-as-autolink.js"],"names":[],"mappings":"AAOA;;;;;;;;;GASG;AACH,2CAPW,IAAI,SAEJ,KAAK,GAEH,OAAO,CAwBnB;0BApCsB,OAAO;2BADN,wBAAwB"}
@@ -0,0 +1,39 @@
/**
* @import {State} from 'mdast-util-to-markdown'
* @import {Link} from 'mdast'
*/
import {toString} from 'mdast-util-to-string'
/**
* Checks if a link can be formatted as an autolink.
*
* @param {Link} node
* Node to check.
* @param {State} state
* Info passed around.
* @returns {boolean}
* Whether the link can be formatted as an autolink.
*/
export function formatLinkAsAutolink(node, state) {
const raw = toString(node)
return Boolean(
!state.options.resourceLink &&
// If there’s a url…
node.url &&
// And there’s no title…
!node.title &&
// And the content of `node` is a single text node…
node.children &&
node.children.length === 1 &&
node.children[0].type === 'text' &&
// And if the url is the same as the content…
(raw === node.url || 'mailto:' + raw === node.url) &&
// And that starts w/ a protocol…
/^[a-z][+\-.a-z]+:/i.test(node.url) &&
// And that doesn’t contain ASCII control codes (character escapes and
// references don’t work), space, or angle brackets…
!/[\0- <>\u007F]/.test(node.url)
)
}
+31
View File
@@ -0,0 +1,31 @@
/**
* @typedef {1 | 2 | 3 | 4 | 5 | 6 | 7} Kind
* Kind of HTML (flow) element.
*/
/**
* Infer the kind of HTML that `value` is.
*
* This works on valid trees as produced by `micromark`.
* Kinds:
*
* 1. raw
* 2. comment
* 3. instruction
* 4. declaration
* 5. cdata
* 6. block
* 7. other
*
* See: <https://spec.commonmark.org/0.31.2/#html-blocks>.
*
* @param {string} value
* HTML.
* @returns {Kind | undefined}
* Kind; `undefined` if unknown.
*/
export function htmlKind(value: string): Kind | undefined;
/**
* Kind of HTML (flow) element.
*/
export type Kind = 1 | 2 | 3 | 4 | 5 | 6 | 7;
//# sourceMappingURL=html-kind.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"html-kind.d.ts","sourceRoot":"","sources":["html-kind.js"],"names":[],"mappings":"AAGA;;;GAGG;AAEH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,gCALW,MAAM,GAEJ,IAAI,GAAG,SAAS,CAoC5B;;;;mBA1DY,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC"}
+63
View File
@@ -0,0 +1,63 @@
import {asciiAlpha, asciiAlphanumeric} from 'micromark-util-character'
import {htmlBlockNames, htmlRawNames} from 'micromark-util-html-tag-name'
/**
* @typedef {1 | 2 | 3 | 4 | 5 | 6 | 7} Kind
* Kind of HTML (flow) element.
*/
/**
* Infer the kind of HTML that `value` is.
*
* This works on valid trees as produced by `micromark`.
* Kinds:
*
* 1. raw
* 2. comment
* 3. instruction
* 4. declaration
* 5. cdata
* 6. block
* 7. other
*
* See: <https://spec.commonmark.org/0.31.2/#html-blocks>.
*
* @param {string} value
* HTML.
* @returns {Kind | undefined}
* Kind; `undefined` if unknown.
*/
export function htmlKind(value) {
if (value.charCodeAt(0) !== 60 /* `<` */) return
const next = value.charCodeAt(1)
if (next === 33 /* `!` */) {
const code = value.charCodeAt(2)
if (code === 45 /* `-` */) return 2
if (code === 91 /* `[` */) return 5
if (asciiAlpha(code)) return 4
return
}
if (next === 63 /* `?` */) return 3
const closing = next === 47 /* `/` */
const start = closing ? 2 : 1
let end = start
let code = value.charCodeAt(end)
if (!asciiAlpha(code)) return
while (code === 45 /* `-` */ || asciiAlphanumeric(code)) {
code = value.charCodeAt(++end)
}
const name = value.slice(start, end).toLowerCase()
if (!closing && code !== 47 /* `/` */ && htmlRawNames.includes(name)) {
return 1
}
return htmlBlockNames.includes(name) ? 6 : 7
}
+2
View File
@@ -0,0 +1,2 @@
export function indentLines(value: string, map: import("../types.js").Map): string;
//# sourceMappingURL=indent-lines.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"indent-lines.d.ts","sourceRoot":"","sources":["indent-lines.js"],"names":[],"mappings":""}
+40
View File
@@ -0,0 +1,40 @@
/**
* @import {IndentLines} from '../types.js'
*/
const eol = /\r?\n|\r/g
/**
* Indents each line.
*
* @type {IndentLines}
*/
export function indentLines(value, map) {
/** @type {Array<string>} */
const result = []
let start = 0
let line = 0
/** @type {RegExpExecArray | null} */
let match
while ((match = eol.exec(value))) {
one(value.slice(start, match.index))
result.push(match[0])
start = match.index + match[0].length
line++
}
one(value.slice(start))
return result.join('')
/**
* Indents a single line.
*
* @param {string} value
* Line.
*/
function one(value) {
result.push(map(value, line, !value))
}
}
+17
View File
@@ -0,0 +1,17 @@
/**
* @import {ConstructName, Unsafe} from 'mdast-util-to-markdown'
*/
/**
* Check if a pattern is in scope based on the current stack of constructs.
*
* @param {Array<ConstructName>} stack
* Current stack of constructs.
* @param {Unsafe} pattern
* Pattern to check.
* @returns {boolean}
* Whether the pattern is in scope.
*/
export function patternInScope(stack: Array<ConstructName>, pattern: Unsafe): boolean;
import type { ConstructName } from 'mdast-util-to-markdown';
import type { Unsafe } from 'mdast-util-to-markdown';
//# sourceMappingURL=pattern-in-scope.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"pattern-in-scope.d.ts","sourceRoot":"","sources":["pattern-in-scope.js"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;;;GASG;AACH,sCAPW,KAAK,CAAC,aAAa,CAAC,WAEpB,MAAM,GAEJ,OAAO,CAQnB;mCAlBuC,wBAAwB;4BAAxB,wBAAwB"}
+52
View File
@@ -0,0 +1,52 @@
/**
* @import {ConstructName, Unsafe} from 'mdast-util-to-markdown'
*/
/**
* Check if a pattern is in scope based on the current stack of constructs.
*
* @param {Array<ConstructName>} stack
* Current stack of constructs.
* @param {Unsafe} pattern
* Pattern to check.
* @returns {boolean}
* Whether the pattern is in scope.
*/
export function patternInScope(stack, pattern) {
return (
listInScope(stack, pattern.inConstruct, true) &&
!listInScope(stack, pattern.notInConstruct, false)
)
}
/**
* Check if any of the constructs in the list are present in the stack.
*
* @param {Array<ConstructName>} stack
* Current stack of constructs.
* @param {Unsafe['inConstruct']} list
* List of constructs to check for in the stack.
* @param {boolean} none
* Value to return if the list is empty or not provided.
* @returns {boolean}
* Whether any of the constructs in the list are present in the stack.
*/
function listInScope(stack, list, none) {
if (typeof list === 'string') {
list = [list]
}
if (!list || list.length === 0) {
return none
}
let index = -1
while (++index < list.length) {
if (stack.includes(list[index])) {
return true
}
}
return false
}
+29
View File
@@ -0,0 +1,29 @@
/**
* Make a string safe for embedding in markdown constructs.
*
* In markdown, almost all punctuation characters can, in certain cases,
* result in something.
* Whether they do is highly subjective to where they happen and in what
* they happen.
*
* To solve this, `mdast-util-to-markdown` tracks:
*
* * characters before and after something;
* * what “constructs” we are in.
*
* This information is then used by this function to escape or encode
* special characters.
*
* @param {State} state
* Info passed around about the current state.
* @param {string | null | undefined} input
* Raw value to make safe.
* @param {SafeConfig} config
* Configuration.
* @returns {string}
* Serialized markdown safe for embedding.
*/
export function safe(state: State, input: string | null | undefined, config: SafeConfig): string;
import type { State } from 'mdast-util-to-markdown';
import type { SafeConfig } from 'mdast-util-to-markdown';
//# sourceMappingURL=safe.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"safe.d.ts","sourceRoot":"","sources":["safe.js"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,4BATW,KAAK,SAEL,MAAM,GAAG,IAAI,GAAG,SAAS,UAEzB,UAAU,GAER,MAAM,CA4JlB;2BA3L2C,wBAAwB;gCAAxB,wBAAwB"}
+262
View File
@@ -0,0 +1,262 @@
/**
* @import {Nodes} from 'mdast'
* @import {SafeConfig, State, Unsafe} from 'mdast-util-to-markdown'
*/
import {classifyCharacter} from 'micromark-util-classify-character'
import {encodeCharacterReference} from './encode-character-reference.js'
import {patternInScope} from './pattern-in-scope.js'
const own = {}.hasOwnProperty
/**
* Make a string safe for embedding in markdown constructs.
*
* In markdown, almost all punctuation characters can, in certain cases,
* result in something.
* Whether they do is highly subjective to where they happen and in what
* they happen.
*
* To solve this, `mdast-util-to-markdown` tracks:
*
* * characters before and after something;
* * what “constructs” we are in.
*
* This information is then used by this function to escape or encode
* special characters.
*
* @param {State} state
* Info passed around about the current state.
* @param {string | null | undefined} input
* Raw value to make safe.
* @param {SafeConfig} config
* Configuration.
* @returns {string}
* Serialized markdown safe for embedding.
*/
export function safe(state, input, config) {
const value = (config.before || '') + (input || '') + (config.after || '')
/** @type {Array<number>} */
const positions = []
/** @type {Array<string>} */
const result = []
/** @type {Record<number, {before: boolean, after: boolean}>} */
const infos = {}
// Character escapes and references do not work in autolinks, so
// percent-encoding is used instead.
const percentEncode = state.stack.includes('autolink')
const offset = config.before ? config.before.length : 0
const end = value.length - (config.after ? config.after.length : 0)
let index = -1
while (++index < state.unsafe.length) {
const pattern = state.unsafe[index]
if (
!patternInScope(state.stack, pattern) ||
!nodeInScope(pattern.beforeNode, config.beforeNode) ||
!nodeInScope(pattern.afterNode, config.afterNode)
) {
continue
}
const expression = state.compilePattern(pattern)
const from = pattern.beforeNode ? offset : 0
const subject = value.slice(from, pattern.afterNode ? end : undefined)
/** @type {RegExpExecArray | null} */
let match
while ((match = expression.exec(subject))) {
const before = Boolean(pattern.before || pattern.atBreak)
const after = Boolean(pattern.after)
const position = from + match.index + (before ? match[1].length : 0)
if (own.call(infos, position)) {
if (infos[position].before && !before) {
infos[position].before = false
}
if (infos[position].after && !after) {
infos[position].after = false
}
} else {
positions.push(position)
infos[position] = {before, after}
}
}
}
positions.sort(numerical)
let start = offset
index = -1
while (++index < positions.length) {
const position = positions[index]
// Character before or after matched:
if (position < start || position >= end) {
continue
}
// Special handling for “intraword” underscores (`a_b`, `a__b`).
// Those are different from asterisks in forming attention.
// Note that `a _ b` also cannot form but not escaping it is very complex,
// so that’s not handled.
if (
value.charAt(position) === '_' &&
// Preceded by an unescaped character that is not punctuation or whitespace:
position > 0 &&
classifyCharacter(value.charCodeAt(position - 1)) === undefined &&
!own.call(infos, position - 1) &&
// Characters next to attention markers can become character references
// later, turning `a` into `&#x61;`, so those do not count.
!(position - 1 === offset && /[*_]/.test(value.charAt(offset - 1)))
) {
let sequenceEnd = position + 1
// Look for the whole run.
while (sequenceEnd < end && value.charAt(sequenceEnd) === '_') {
sequenceEnd++
}
const skip = sequenceEnd - position - 1
if (
// All underscores in the run are unsafe positions, so they can be
// skipped.
positions[index + skip] === sequenceEnd - 1 &&
// Rest as above.
sequenceEnd < value.length &&
classifyCharacter(value.charCodeAt(sequenceEnd)) === undefined &&
!own.call(infos, sequenceEnd) &&
!(sequenceEnd === end - 1 && /[*_]/.test(value.charAt(end)))
) {
index += skip
continue
}
}
// If this character is supposed to be escaped because it has a condition on
// the next character, and the next character is definitly being escaped,
// then skip this escape.
if (
(position + 1 < end &&
positions[index + 1] === position + 1 &&
infos[position].after &&
!infos[position + 1].before &&
!infos[position + 1].after) ||
(position - 1 >= offset &&
positions[index - 1] === position - 1 &&
infos[position].before &&
!infos[position - 1].before &&
!infos[position - 1].after)
) {
continue
}
if (start !== position) {
const slice = value.slice(start, position)
// If we have to use a character reference, an ampersand would be more
// correct, but as backslashes only care about punctuation, either will
// do the trick
result.push(percentEncode ? slice : escapeBackslashes(slice, '\\'))
}
start = position + 1
// Percent-encoding such as `%20`.
if (percentEncode) {
result.push(
'%' +
value.charCodeAt(position).toString(16).toUpperCase().padStart(2, '0')
)
} else if (
/[!-/:-@[-`{-~]/.test(value.charAt(position)) &&
(!config.encode || !config.encode.includes(value.charAt(position)))
) {
// Character escape.
result.push('\\' + value.charAt(position))
} else {
// Character reference.
result.push(encodeCharacterReference(value.charCodeAt(position)))
}
}
const rest = value.slice(start, end)
result.push(percentEncode ? rest : escapeBackslashes(rest, config.after))
return result.join('')
}
/**
* Check if a node matches the node types of a pattern.
*
* @param {Array<Nodes['type']> | Nodes['type'] | null | undefined} types
* Node types.
* @param {Nodes | undefined} node
* Node.
* @returns {boolean}
* Whether `node` matches `types`.
*/
function nodeInScope(types, node) {
if (!types) return true
if (!node) return false
return typeof types === 'string'
? types === node.type
: types.includes(node.type)
}
/**
* Compare two numbers.
*
* @param {number} a
* Number.
* @param {number} b
* Other number.
* @returns {number}
* Result.
*/
function numerical(a, b) {
return a - b
}
/**
* Escape backslashes in a string, considering characters that follow.
*
* @param {string} value
* Value.
* @param {string} after
* Characters that follow the value.
* @returns {string}
* Escaped string.
*/
function escapeBackslashes(value, after) {
const expression = /\\(?=[!-/:-@[-`{-~])/g
/** @type {Array<number>} */
const positions = []
/** @type {Array<string>} */
const results = []
const whole = value + after
let index = -1
let start = 0
/** @type {RegExpExecArray | null} */
let match
while ((match = expression.exec(whole))) {
positions.push(match.index)
}
while (++index < positions.length) {
if (start !== positions[index]) {
results.push(value.slice(start, positions[index]))
}
results.push('\\')
start = positions[index]
}
results.push(value.slice(start))
return results.join('')
}
+2
View File
@@ -0,0 +1,2 @@
export function track(info: import("../types.js").TrackFields): import("../types.js").Tracker;
//# sourceMappingURL=track.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"track.d.ts","sourceRoot":"","sources":["track.js"],"names":[],"mappings":""}
+55
View File
@@ -0,0 +1,55 @@
/**
* @import {CreateTracker, TrackCurrent, TrackMove, TrackShift} from '../types.js'
*/
/**
* Track positional info in the output.
*
* @type {CreateTracker}
*/
export function track(config) {
// Defaults are used to prevent crashes when older utilities somehow activate
// this code.
/* c8 ignore next 5 */
const options = config || {}
const now = options.now || {}
let lineShift = options.lineShift || 0
let line = now.line || 1
let column = now.column || 1
return {move, current, shift}
/**
* Get the current tracked info.
*
* @type {TrackCurrent}
*/
function current() {
return {now: {line, column}, lineShift}
}
/**
* Define an increased line shift (the typical indent for lines).
*
* @type {TrackShift}
*/
function shift(value) {
lineShift += value
}
/**
* Move past some generated markdown.
*
* @type {TrackMove}
*/
function move(input) {
// eslint-disable-next-line unicorn/prefer-default-parameters
const value = input || ''
const chunks = value.split(/\r?\n|\r/g)
const tail = chunks[chunks.length - 1]
line += chunks.length - 1
column =
chunks.length === 1 ? column + tail.length : 1 + tail.length + lineShift
return value
}
}