🎉 initiate project *astro_rewrite*

This commit is contained in:
sindrekjelsrud 2023-07-19 21:31:30 +02:00
parent ffd4d5e86c
commit 2ba37bfbe3
8658 changed files with 2268794 additions and 2538 deletions

View file

@ -0,0 +1,104 @@
/**
* Parse a list of micromark events with acorn.
*
* @param {Array<Event>} events
* Events.
* @param {Options} options
* Configuration.
* @returns {Result}
* Result.
*/
export function eventsToAcorn(
events: Array<import('micromark-util-types').Event>,
options: Options
): Result
export type Comment = import('acorn').Comment
export type AcornNode = import('acorn').Node
export type AcornOptions = import('acorn').Options
export type Token = import('acorn').Token
export type EstreeNode = import('estree').Node
export type Program = import('estree').Program
export type Chunk = import('micromark-util-types').Chunk
export type Event = import('micromark-util-types').Event
export type MicromarkPoint = import('micromark-util-types').Point
export type UnistPoint = import('unist').Point
/**
* Acorn-like interface.
*/
export type Acorn = {
/**
* Parse a program.
*/
parse: typeof import('acorn').parse
/**
* Parse an expression.
*/
parseExpressionAt: typeof import('acorn').parseExpressionAt
}
export type AcornLoc = {
line: number
column: number
}
export type AcornErrorFields = {
raisedAt: number
pos: number
loc: AcornLoc
}
export type AcornError = Error & AcornErrorFields
/**
* Configuration.
*/
export type Options = {
/**
* Typically `acorn`, object with `parse` and `parseExpressionAt` fields.
*/
acorn: Acorn
/**
* Configuration for `acorn`.
*/
acornOptions?: AcornOptions | null | undefined
/**
* Place where events start.
*/
start?: MicromarkPoint | null | undefined
/**
* Text to place before events.
*/
prefix?: string | null | undefined
/**
* Text to place after events.
*/
suffix?: string | null | undefined
/**
* Whether this is a program or expression.
*/
expression?: boolean | null | undefined
/**
* Whether an empty expression is allowed (programs are always allowed to
* be empty).
*/
allowEmpty?: boolean | null | undefined
}
/**
* Result.
*/
export type Result = {
/**
* Program.
*/
estree: Program | undefined
/**
* Error if unparseable
*/
error: AcornError | undefined
/**
* Whether the error, if there is one, can be swallowed and more JavaScript
* could be valid.
*/
swallow: boolean
}
export type Stop = [number, MicromarkPoint]
export type Collection = {
value: string
stops: Array<Stop>
}

View file

@ -0,0 +1,477 @@
/**
* @typedef {import('acorn').Comment} Comment
* @typedef {import('acorn').Node} AcornNode
* @typedef {import('acorn').Options} AcornOptions
* @typedef {import('acorn').Token} Token
* @typedef {import('estree').Node} EstreeNode
* @typedef {import('estree').Program} Program
* @typedef {import('micromark-util-types').Chunk} Chunk
* @typedef {import('micromark-util-types').Event} Event
* @typedef {import('micromark-util-types').Point} MicromarkPoint
* @typedef {import('unist').Point} UnistPoint
*/
/**
* @typedef Acorn
* Acorn-like interface.
* @property {import('acorn').parse} parse
* Parse a program.
* @property {import('acorn').parseExpressionAt} parseExpressionAt
* Parse an expression.
*
* @typedef AcornLoc
* @property {number} line
* @property {number} column
*
* @typedef AcornErrorFields
* @property {number} raisedAt
* @property {number} pos
* @property {AcornLoc} loc
*
* @typedef {Error & AcornErrorFields} AcornError
*
* @typedef Options
* Configuration.
* @property {Acorn} acorn
* Typically `acorn`, object with `parse` and `parseExpressionAt` fields.
* @property {AcornOptions | null | undefined} [acornOptions]
* Configuration for `acorn`.
* @property {MicromarkPoint | null | undefined} [start]
* Place where events start.
* @property {string | null | undefined} [prefix='']
* Text to place before events.
* @property {string | null | undefined} [suffix='']
* Text to place after events.
* @property {boolean | null | undefined} [expression=false]
* Whether this is a program or expression.
* @property {boolean | null | undefined} [allowEmpty=false]
* Whether an empty expression is allowed (programs are always allowed to
* be empty).
*
* @typedef Result
* Result.
* @property {Program | undefined} estree
* Program.
* @property {AcornError | undefined} error
* Error if unparseable
* @property {boolean} swallow
* Whether the error, if there is one, can be swallowed and more JavaScript
* could be valid.
*
* @typedef {[number, MicromarkPoint]} Stop
*
* @typedef Collection
* @property {string} value
* @property {Array<Stop>} stops
*/
import {visit} from 'estree-util-visit'
import {codes} from 'micromark-util-symbol/codes.js'
import {values} from 'micromark-util-symbol/values.js'
import {types} from 'micromark-util-symbol/types.js'
import {ok as assert} from 'uvu/assert'
import {VFileMessage} from 'vfile-message'
/**
* Parse a list of micromark events with acorn.
*
* @param {Array<Event>} events
* Events.
* @param {Options} options
* Configuration.
* @returns {Result}
* Result.
*/
// eslint-disable-next-line complexity
export function eventsToAcorn(events, options) {
const prefix = options.prefix || ''
const suffix = options.suffix || ''
const acornOptions = Object.assign({}, options.acornOptions)
/** @type {Array<Comment>} */
const comments = []
/** @type {Array<Token>} */
const tokens = []
const onComment = acornOptions.onComment
const onToken = acornOptions.onToken
let swallow = false
/** @type {AcornNode | undefined} */
let estree
/** @type {AcornError | undefined} */
let exception
/** @type {AcornOptions} */
const acornConfig = Object.assign({}, acornOptions, {
onComment: comments,
preserveParens: true
})
if (onToken) {
acornConfig.onToken = tokens
}
const collection = collect(events, [
types.lineEnding,
// To do: these should be passed by users in parameters.
'expressionChunk', // From tests.
'mdxFlowExpressionChunk', // Flow chunk.
'mdxTextExpressionChunk', // Text chunk.
// JSX:
'mdxJsxTextTagExpressionAttributeValue',
'mdxJsxTextTagAttributeValueExpressionValue',
'mdxJsxFlowTagExpressionAttributeValue',
'mdxJsxFlowTagAttributeValueExpressionValue',
// ESM:
'mdxjsEsmData'
])
const source = collection.value
const value = prefix + source + suffix
const isEmptyExpression = options.expression && empty(source)
if (isEmptyExpression && !options.allowEmpty) {
throw new VFileMessage(
'Unexpected empty expression',
parseOffsetToUnistPoint(0),
'micromark-extension-mdx-expression:unexpected-empty-expression'
)
}
try {
estree =
options.expression && !isEmptyExpression
? options.acorn.parseExpressionAt(value, 0, acornConfig)
: options.acorn.parse(value, acornConfig)
} catch (error_) {
const error = /** @type {AcornError} */ (error_)
const point = parseOffsetToUnistPoint(error.pos)
error.message = String(error.message).replace(/ \(\d+:\d+\)$/, '')
// Always defined in our unist points that come from micromark.
assert(point.offset !== undefined, 'expected `offset`')
error.pos = point.offset
error.loc = {line: point.line, column: point.column - 1}
exception = error
swallow =
error.raisedAt >= prefix.length + source.length ||
// Broken comments are raised at their start, not their end.
error.message === 'Unterminated comment'
}
if (estree && options.expression && !isEmptyExpression) {
if (empty(value.slice(estree.end, value.length - suffix.length))) {
estree = {
type: 'Program',
start: 0,
end: prefix.length + source.length,
// @ts-expect-error: Its good.
body: [
{
type: 'ExpressionStatement',
expression: estree,
start: 0,
end: prefix.length + source.length
}
],
sourceType: 'module',
comments: []
}
} else {
const point = parseOffsetToUnistPoint(estree.end)
const error = /** @type {AcornError} */ (
new Error('Unexpected content after expression')
)
// Always defined in our unist points that come from micromark.
assert(point.offset !== undefined, 'expected `offset`')
error.pos = point.offset
error.loc = {line: point.line, column: point.column - 1}
exception = error
estree = undefined
}
}
if (estree) {
// @ts-expect-error: acorn *does* allow comments
estree.comments = comments
// @ts-expect-error: acorn looks enough like estree.
visit(estree, (esnode, field, index, parents) => {
let context = /** @type {AcornNode | Array<AcornNode>} */ (
parents[parents.length - 1]
)
/** @type {string | number | null} */
let prop = field
// Remove non-standard `ParenthesizedExpression`.
// @ts-expect-error: included in acorn.
if (esnode.type === 'ParenthesizedExpression' && context && prop) {
/* c8 ignore next 5 */
if (typeof index === 'number') {
// @ts-expect-error: indexable.
context = context[prop]
prop = index
}
// @ts-expect-error: indexable.
context[prop] = esnode.expression
}
fixPosition(esnode)
})
// Comment positions are fixed by `visit` because theyre in the tree.
if (Array.isArray(onComment)) {
onComment.push(...comments)
} else if (typeof onComment === 'function') {
for (const comment of comments) {
assert(comment.loc, 'expected `loc` on comment')
onComment(
comment.type === 'Block',
comment.value,
comment.start,
comment.end,
comment.loc.start,
comment.loc.end
)
}
}
for (const token of tokens) {
// Ignore tokens that ends in prefix or start in suffix:
if (
token.end <= prefix.length ||
token.start - prefix.length >= source.length
) {
continue
}
fixPosition(token)
if (Array.isArray(onToken)) {
onToken.push(token)
} else {
// `tokens` are not added if `onToken` is not defined, so it must be a
// function.
assert(typeof onToken === 'function', 'expected function')
onToken(token)
}
}
}
// @ts-expect-error: Its a program now.
return {estree, error: exception, swallow}
/**
* Update the position of a node.
*
* @param {AcornNode | EstreeNode | Token} nodeOrToken
* @returns {void}
*/
function fixPosition(nodeOrToken) {
assert(
'start' in nodeOrToken,
'expected `start` in node or token from acorn'
)
assert('end' in nodeOrToken, 'expected `end` in node or token from acorn')
const pointStart = parseOffsetToUnistPoint(nodeOrToken.start)
const pointEnd = parseOffsetToUnistPoint(nodeOrToken.end)
// Always defined in our unist points that come from micromark.
assert(pointStart.offset !== undefined, 'expected `offset`')
assert(pointEnd.offset !== undefined, 'expected `offset`')
nodeOrToken.start = pointStart.offset
nodeOrToken.end = pointEnd.offset
nodeOrToken.loc = {
start: {
line: pointStart.line,
column: pointStart.column - 1,
offset: pointStart.offset
},
end: {
line: pointEnd.line,
column: pointEnd.column - 1,
offset: pointEnd.offset
}
}
nodeOrToken.range = [nodeOrToken.start, nodeOrToken.end]
}
/**
* Turn an arbitrary offset into the parsed value, into a point in the source
* value.
*
* @param {number} acornOffset
* @returns {UnistPoint}
*/
function parseOffsetToUnistPoint(acornOffset) {
let sourceOffset = acornOffset - prefix.length
if (sourceOffset < 0) {
sourceOffset = 0
} else if (sourceOffset > source.length) {
sourceOffset = source.length
}
let point = relativeToPoint(collection.stops, sourceOffset)
if (!point) {
assert(
options.start,
'empty expressions are need `options.start` being passed'
)
point = {
line: options.start.line,
column: options.start.column,
offset: options.start.offset
}
}
return point
}
}
/**
* @param {string} value
* @returns {boolean}
*/
function empty(value) {
return /^\s*$/.test(
value
// Multiline comments.
.replace(/\/\*[\s\S]*?\*\//g, '')
// Line comments.
// EOF instead of EOL is specifically not allowed, because that would
// mean the closing brace is on the commented-out line
.replace(/\/\/[^\r\n]*(\r\n|\n|\r)/g, '')
)
}
// Port from <https://github.com/wooorm/markdown-rs/blob/e692ab0/src/util/mdx_collect.rs#L15>.
/**
* @param {Array<Event>} events
* @param {Array<string>} names
* @returns {Collection}
*/
function collect(events, names) {
/** @type {Collection} */
const result = {value: '', stops: []}
let index = -1
while (++index < events.length) {
const event = events[index]
// Assume void.
if (event[0] === 'enter' && names.includes(event[1].type)) {
const chunks = event[2].sliceStream(event[1])
// Drop virtual spaces.
while (chunks.length > 0 && chunks[0] === codes.virtualSpace) {
chunks.shift()
}
const value = serializeChunks(chunks)
result.stops.push([result.value.length, event[1].start])
result.value += value
result.stops.push([result.value.length, event[1].end])
}
}
return result
}
// Port from <https://github.com/wooorm/markdown-rs/blob/e692ab0/src/util/location.rs#L91>.
/**
* Turn a relative offset into an absolute offset.
*
* @param {Array<Stop>} stops
* @param {number} relative
* @returns {UnistPoint | undefined}
*/
function relativeToPoint(stops, relative) {
let index = 0
while (index < stops.length && stops[index][0] <= relative) {
index += 1
}
// There are no points: that only occurs if there was an empty string.
if (index === 0) {
return undefined
}
const [stopRelative, stopAbsolute] = stops[index - 1]
const rest = relative - stopRelative
return {
line: stopAbsolute.line,
column: stopAbsolute.column + rest,
offset: stopAbsolute.offset + rest
}
}
// Copy from <https://github.com/micromark/micromark/blob/ce3593a/packages/micromark/dev/lib/create-tokenizer.js#L595>
// To do: expose that?
/**
* Get the string value of a slice of chunks.
*
* @param {Array<Chunk>} chunks
* @returns {string}
*/
function serializeChunks(chunks) {
let index = -1
/** @type {Array<string>} */
const result = []
/** @type {boolean | undefined} */
let atTab
while (++index < chunks.length) {
const chunk = chunks[index]
/** @type {string} */
let value
if (typeof chunk === 'string') {
value = chunk
} else
switch (chunk) {
case codes.carriageReturn: {
value = values.cr
break
}
case codes.lineFeed: {
value = values.lf
break
}
case codes.carriageReturnLineFeed: {
value = values.cr + values.lf
break
}
case codes.horizontalTab: {
value = values.ht
break
}
/* c8 ignore next 6 */
case codes.virtualSpace: {
if (atTab) continue
value = values.space
break
}
default: {
assert(typeof chunk === 'number', 'expected number')
// Currently only replacement character.
// eslint-disable-next-line unicorn/prefer-code-point
value = String.fromCharCode(chunk)
}
}
atTab = chunk === codes.horizontalTab
result.push(value)
}
return result.join('')
}

104
node_modules/micromark-util-events-to-acorn/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,104 @@
/**
* Parse a list of micromark events with acorn.
*
* @param {Array<Event>} events
* Events.
* @param {Options} options
* Configuration.
* @returns {Result}
* Result.
*/
export function eventsToAcorn(
events: Array<import('micromark-util-types').Event>,
options: Options
): Result
export type Comment = import('acorn').Comment
export type AcornNode = import('acorn').Node
export type AcornOptions = import('acorn').Options
export type Token = import('acorn').Token
export type EstreeNode = import('estree').Node
export type Program = import('estree').Program
export type Chunk = import('micromark-util-types').Chunk
export type Event = import('micromark-util-types').Event
export type MicromarkPoint = import('micromark-util-types').Point
export type UnistPoint = import('unist').Point
/**
* Acorn-like interface.
*/
export type Acorn = {
/**
* Parse a program.
*/
parse: typeof import('acorn').parse
/**
* Parse an expression.
*/
parseExpressionAt: typeof import('acorn').parseExpressionAt
}
export type AcornLoc = {
line: number
column: number
}
export type AcornErrorFields = {
raisedAt: number
pos: number
loc: AcornLoc
}
export type AcornError = Error & AcornErrorFields
/**
* Configuration.
*/
export type Options = {
/**
* Typically `acorn`, object with `parse` and `parseExpressionAt` fields.
*/
acorn: Acorn
/**
* Configuration for `acorn`.
*/
acornOptions?: AcornOptions | null | undefined
/**
* Place where events start.
*/
start?: MicromarkPoint | null | undefined
/**
* Text to place before events.
*/
prefix?: string | null | undefined
/**
* Text to place after events.
*/
suffix?: string | null | undefined
/**
* Whether this is a program or expression.
*/
expression?: boolean | null | undefined
/**
* Whether an empty expression is allowed (programs are always allowed to
* be empty).
*/
allowEmpty?: boolean | null | undefined
}
/**
* Result.
*/
export type Result = {
/**
* Program.
*/
estree: Program | undefined
/**
* Error if unparseable
*/
error: AcornError | undefined
/**
* Whether the error, if there is one, can be swallowed and more JavaScript
* could be valid.
*/
swallow: boolean
}
export type Stop = [number, MicromarkPoint]
export type Collection = {
value: string
stops: Array<Stop>
}

443
node_modules/micromark-util-events-to-acorn/index.js generated vendored Normal file
View file

@ -0,0 +1,443 @@
/**
* @typedef {import('acorn').Comment} Comment
* @typedef {import('acorn').Node} AcornNode
* @typedef {import('acorn').Options} AcornOptions
* @typedef {import('acorn').Token} Token
* @typedef {import('estree').Node} EstreeNode
* @typedef {import('estree').Program} Program
* @typedef {import('micromark-util-types').Chunk} Chunk
* @typedef {import('micromark-util-types').Event} Event
* @typedef {import('micromark-util-types').Point} MicromarkPoint
* @typedef {import('unist').Point} UnistPoint
*/
/**
* @typedef Acorn
* Acorn-like interface.
* @property {import('acorn').parse} parse
* Parse a program.
* @property {import('acorn').parseExpressionAt} parseExpressionAt
* Parse an expression.
*
* @typedef AcornLoc
* @property {number} line
* @property {number} column
*
* @typedef AcornErrorFields
* @property {number} raisedAt
* @property {number} pos
* @property {AcornLoc} loc
*
* @typedef {Error & AcornErrorFields} AcornError
*
* @typedef Options
* Configuration.
* @property {Acorn} acorn
* Typically `acorn`, object with `parse` and `parseExpressionAt` fields.
* @property {AcornOptions | null | undefined} [acornOptions]
* Configuration for `acorn`.
* @property {MicromarkPoint | null | undefined} [start]
* Place where events start.
* @property {string | null | undefined} [prefix='']
* Text to place before events.
* @property {string | null | undefined} [suffix='']
* Text to place after events.
* @property {boolean | null | undefined} [expression=false]
* Whether this is a program or expression.
* @property {boolean | null | undefined} [allowEmpty=false]
* Whether an empty expression is allowed (programs are always allowed to
* be empty).
*
* @typedef Result
* Result.
* @property {Program | undefined} estree
* Program.
* @property {AcornError | undefined} error
* Error if unparseable
* @property {boolean} swallow
* Whether the error, if there is one, can be swallowed and more JavaScript
* could be valid.
*
* @typedef {[number, MicromarkPoint]} Stop
*
* @typedef Collection
* @property {string} value
* @property {Array<Stop>} stops
*/
import {visit} from 'estree-util-visit'
import {VFileMessage} from 'vfile-message'
/**
* Parse a list of micromark events with acorn.
*
* @param {Array<Event>} events
* Events.
* @param {Options} options
* Configuration.
* @returns {Result}
* Result.
*/
// eslint-disable-next-line complexity
export function eventsToAcorn(events, options) {
const prefix = options.prefix || ''
const suffix = options.suffix || ''
const acornOptions = Object.assign({}, options.acornOptions)
/** @type {Array<Comment>} */
const comments = []
/** @type {Array<Token>} */
const tokens = []
const onComment = acornOptions.onComment
const onToken = acornOptions.onToken
let swallow = false
/** @type {AcornNode | undefined} */
let estree
/** @type {AcornError | undefined} */
let exception
/** @type {AcornOptions} */
const acornConfig = Object.assign({}, acornOptions, {
onComment: comments,
preserveParens: true
})
if (onToken) {
acornConfig.onToken = tokens
}
const collection = collect(events, [
'lineEnding',
// To do: these should be passed by users in parameters.
'expressionChunk',
// From tests.
'mdxFlowExpressionChunk',
// Flow chunk.
'mdxTextExpressionChunk',
// Text chunk.
// JSX:
'mdxJsxTextTagExpressionAttributeValue',
'mdxJsxTextTagAttributeValueExpressionValue',
'mdxJsxFlowTagExpressionAttributeValue',
'mdxJsxFlowTagAttributeValueExpressionValue',
// ESM:
'mdxjsEsmData'
])
const source = collection.value
const value = prefix + source + suffix
const isEmptyExpression = options.expression && empty(source)
if (isEmptyExpression && !options.allowEmpty) {
throw new VFileMessage(
'Unexpected empty expression',
parseOffsetToUnistPoint(0),
'micromark-extension-mdx-expression:unexpected-empty-expression'
)
}
try {
estree =
options.expression && !isEmptyExpression
? options.acorn.parseExpressionAt(value, 0, acornConfig)
: options.acorn.parse(value, acornConfig)
} catch (error_) {
const error = /** @type {AcornError} */ error_
const point = parseOffsetToUnistPoint(error.pos)
error.message = String(error.message).replace(/ \(\d+:\d+\)$/, '')
// Always defined in our unist points that come from micromark.
error.pos = point.offset
error.loc = {
line: point.line,
column: point.column - 1
}
exception = error
swallow =
error.raisedAt >= prefix.length + source.length ||
// Broken comments are raised at their start, not their end.
error.message === 'Unterminated comment'
}
if (estree && options.expression && !isEmptyExpression) {
if (empty(value.slice(estree.end, value.length - suffix.length))) {
estree = {
type: 'Program',
start: 0,
end: prefix.length + source.length,
// @ts-expect-error: Its good.
body: [
{
type: 'ExpressionStatement',
expression: estree,
start: 0,
end: prefix.length + source.length
}
],
sourceType: 'module',
comments: []
}
} else {
const point = parseOffsetToUnistPoint(estree.end)
const error =
/** @type {AcornError} */
new Error('Unexpected content after expression')
// Always defined in our unist points that come from micromark.
error.pos = point.offset
error.loc = {
line: point.line,
column: point.column - 1
}
exception = error
estree = undefined
}
}
if (estree) {
// @ts-expect-error: acorn *does* allow comments
estree.comments = comments
// @ts-expect-error: acorn looks enough like estree.
visit(estree, (esnode, field, index, parents) => {
let context =
/** @type {AcornNode | Array<AcornNode>} */
parents[parents.length - 1]
/** @type {string | number | null} */
let prop = field
// Remove non-standard `ParenthesizedExpression`.
// @ts-expect-error: included in acorn.
if (esnode.type === 'ParenthesizedExpression' && context && prop) {
/* c8 ignore next 5 */
if (typeof index === 'number') {
// @ts-expect-error: indexable.
context = context[prop]
prop = index
}
// @ts-expect-error: indexable.
context[prop] = esnode.expression
}
fixPosition(esnode)
})
// Comment positions are fixed by `visit` because theyre in the tree.
if (Array.isArray(onComment)) {
onComment.push(...comments)
} else if (typeof onComment === 'function') {
for (const comment of comments) {
onComment(
comment.type === 'Block',
comment.value,
comment.start,
comment.end,
comment.loc.start,
comment.loc.end
)
}
}
for (const token of tokens) {
// Ignore tokens that ends in prefix or start in suffix:
if (
token.end <= prefix.length ||
token.start - prefix.length >= source.length
) {
continue
}
fixPosition(token)
if (Array.isArray(onToken)) {
onToken.push(token)
} else {
// `tokens` are not added if `onToken` is not defined, so it must be a
// function.
onToken(token)
}
}
}
// @ts-expect-error: Its a program now.
return {
estree,
error: exception,
swallow
}
/**
* Update the position of a node.
*
* @param {AcornNode | EstreeNode | Token} nodeOrToken
* @returns {void}
*/
function fixPosition(nodeOrToken) {
const pointStart = parseOffsetToUnistPoint(nodeOrToken.start)
const pointEnd = parseOffsetToUnistPoint(nodeOrToken.end)
// Always defined in our unist points that come from micromark.
nodeOrToken.start = pointStart.offset
nodeOrToken.end = pointEnd.offset
nodeOrToken.loc = {
start: {
line: pointStart.line,
column: pointStart.column - 1,
offset: pointStart.offset
},
end: {
line: pointEnd.line,
column: pointEnd.column - 1,
offset: pointEnd.offset
}
}
nodeOrToken.range = [nodeOrToken.start, nodeOrToken.end]
}
/**
* Turn an arbitrary offset into the parsed value, into a point in the source
* value.
*
* @param {number} acornOffset
* @returns {UnistPoint}
*/
function parseOffsetToUnistPoint(acornOffset) {
let sourceOffset = acornOffset - prefix.length
if (sourceOffset < 0) {
sourceOffset = 0
} else if (sourceOffset > source.length) {
sourceOffset = source.length
}
let point = relativeToPoint(collection.stops, sourceOffset)
if (!point) {
point = {
line: options.start.line,
column: options.start.column,
offset: options.start.offset
}
}
return point
}
}
/**
* @param {string} value
* @returns {boolean}
*/
function empty(value) {
return /^\s*$/.test(
value
// Multiline comments.
.replace(/\/\*[\s\S]*?\*\//g, '')
// Line comments.
// EOF instead of EOL is specifically not allowed, because that would
// mean the closing brace is on the commented-out line
.replace(/\/\/[^\r\n]*(\r\n|\n|\r)/g, '')
)
}
// Port from <https://github.com/wooorm/markdown-rs/blob/e692ab0/src/util/mdx_collect.rs#L15>.
/**
* @param {Array<Event>} events
* @param {Array<string>} names
* @returns {Collection}
*/
function collect(events, names) {
/** @type {Collection} */
const result = {
value: '',
stops: []
}
let index = -1
while (++index < events.length) {
const event = events[index]
// Assume void.
if (event[0] === 'enter' && names.includes(event[1].type)) {
const chunks = event[2].sliceStream(event[1])
// Drop virtual spaces.
while (chunks.length > 0 && chunks[0] === -1) {
chunks.shift()
}
const value = serializeChunks(chunks)
result.stops.push([result.value.length, event[1].start])
result.value += value
result.stops.push([result.value.length, event[1].end])
}
}
return result
}
// Port from <https://github.com/wooorm/markdown-rs/blob/e692ab0/src/util/location.rs#L91>.
/**
* Turn a relative offset into an absolute offset.
*
* @param {Array<Stop>} stops
* @param {number} relative
* @returns {UnistPoint | undefined}
*/
function relativeToPoint(stops, relative) {
let index = 0
while (index < stops.length && stops[index][0] <= relative) {
index += 1
}
// There are no points: that only occurs if there was an empty string.
if (index === 0) {
return undefined
}
const [stopRelative, stopAbsolute] = stops[index - 1]
const rest = relative - stopRelative
return {
line: stopAbsolute.line,
column: stopAbsolute.column + rest,
offset: stopAbsolute.offset + rest
}
}
// Copy from <https://github.com/micromark/micromark/blob/ce3593a/packages/micromark/dev/lib/create-tokenizer.js#L595>
// To do: expose that?
/**
* Get the string value of a slice of chunks.
*
* @param {Array<Chunk>} chunks
* @returns {string}
*/
function serializeChunks(chunks) {
let index = -1
/** @type {Array<string>} */
const result = []
/** @type {boolean | undefined} */
let atTab
while (++index < chunks.length) {
const chunk = chunks[index]
/** @type {string} */
let value
if (typeof chunk === 'string') {
value = chunk
} else
switch (chunk) {
case -5: {
value = '\r'
break
}
case -4: {
value = '\n'
break
}
case -3: {
value = '\r' + '\n'
break
}
case -2: {
value = '\t'
break
}
/* c8 ignore next 6 */
case -1: {
if (atTab) continue
value = ' '
break
}
default: {
// Currently only replacement character.
// eslint-disable-next-line unicorn/prefer-code-point
value = String.fromCharCode(chunk)
}
}
atTab = chunk === -2
result.push(value)
}
return result.join('')
}

View file

@ -0,0 +1 @@
../../../uvu/bin.js

View file

@ -0,0 +1,61 @@
{
"name": "micromark-util-events-to-acorn",
"version": "1.2.3",
"description": "micromark utility to try and parse events w/ acorn",
"license": "MIT",
"keywords": [
"micromark",
"factory",
"mdx",
"expression"
],
"repository": "https://github.com/micromark/micromark-extension-mdx-expression/tree/main/packages/micromark-util-events-to-acorn",
"bugs": "https://github.com/micromark/micromark-extension-mdx-expression/issues",
"funding": [
{
"type": "GitHub Sponsors",
"url": "https://github.com/sponsors/unifiedjs"
},
{
"type": "OpenCollective",
"url": "https://opencollective.com/unified"
}
],
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"sideEffects": false,
"type": "module",
"main": "index.js",
"types": "dev/index.d.ts",
"files": [
"dev/",
"index.d.ts",
"index.js"
],
"exports": {
"development": "./dev/index.js",
"default": "./index.js"
},
"dependencies": {
"@types/acorn": "^4.0.0",
"@types/estree": "^1.0.0",
"@types/unist": "^2.0.0",
"estree-util-visit": "^1.0.0",
"micromark-util-symbol": "^1.0.0",
"micromark-util-types": "^1.0.0",
"uvu": "^0.5.0",
"vfile-message": "^3.0.0"
},
"scripts": {
"build": "micromark-build"
},
"xo": false,
"typeCoverage": {
"atLeast": 100,
"detail": true,
"strict": true,
"ignoreCatch": true
}
}

235
node_modules/micromark-util-events-to-acorn/readme.md generated vendored Normal file
View file

@ -0,0 +1,235 @@
# micromark-util-events-to-acorn
[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][bundle-size-badge]][bundle-size]
[![Sponsors][sponsors-badge]][opencollective]
[![Backers][backers-badge]][opencollective]
[![Chat][chat-badge]][chat]
[micromark][] utility to try and parse events with acorn.
## Contents
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`eventsToAcorn(events, options)`](#eventstoacornevents-options)
* [`Options`](#options)
* [`Result`](#result)
* [Types](#types)
* [Compatibility](#compatibility)
* [Security](#security)
* [Contribute](#contribute)
* [License](#license)
## Install
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
```sh
npm install micromark-util-events-to-acorn
```
In Deno with [`esm.sh`][esmsh]:
```js
import {eventsToAcorn} from 'https://esm.sh/micromark-util-events-to-acorn@1'
```
In browsers with [`esm.sh`][esmsh]:
```html
<script type="module">
import {eventsToAcorn} from 'https://esm.sh/micromark-util-events-to-acorn@1?bundle'
</script>
```
## Use
```js
import {eventsToAcorn} from 'micromark-util-events-to-acorn'
// A factory that uses the utility:
/** @type {Tokenizer} */
function factoryMdxExpression(effects, ok, nok) {
return start
// …
// …
// Gnostic mode: parse w/ acorn.
const result = eventsToAcorn(this.events.slice(eventStart), {
acorn,
acornOptions,
start: pointStart,
expression: true,
allowEmpty,
prefix: spread ? '({' : '',
suffix: spread ? '})' : ''
})
// …
// …
}
```
## API
This module exports the identifier [`eventsToAcorn`][api-events-to-acorn].
There is no default export.
The export map supports the [`development` condition][development].
Run `node --conditions development module.js` to get instrumented dev code.
Without this condition, production code is loaded.
### `eventsToAcorn(events, options)`
###### Parameters
* `events` (`Array<Event>`)
— events
* `options` ([`Options`][api-options])
— configuration
###### Returns
Result ([`Result`][api-result]).
### `Options`
Configuration (TypeScript type).
###### Fields
* `acorn` ([`Acorn`][acorn], required)
— typically `acorn`, object with `parse` and `parseExpressionAt` fields
* `acornOptions` ([`AcornOptions`][acorn-options], optional)
— configuration for `acorn`
* `start` (`Point`, optional)
— place where events start
* `prefix` (`string`, default: `''`)
— text to place before events
* `suffix` (`string`, default: `''`)
— text to place after events
* `expression` (`boolean`, default: `false`)
— whether this is a program or expression
* `allowEmpty` (`boolean`, default: `false`)
— whether an empty expression is allowed (programs are always allowed to be
empty)
### `Result`
Result (TypeScript type).
###### Fields
* `estree` ([`Program`][program] or `undefined`)
— Program
* `error` (`Error` or `undefined`)
— error if unparseable
* `swallow` (`boolean`)
— whether the error, if there is one, can be swallowed and more JavaScript
could be valid
## Types
This package is fully typed with [TypeScript][].
It exports the additional types [`Acorn`][acorn],
[`AcornOptions`][acorn-options], [`Options`][api-options], and
[`Result`][api-result].
## Compatibility
Projects maintained by the unified collective are compatible with all maintained
versions of Node.js.
As of now, that is Node.js 16+.
Our projects sometimes work with older versions, but this is not guaranteed.
These extensions work with `micromark` version 3+.
## Security
This package is safe.
## Contribute
See [`contributing.md`][contributing] in [`micromark/.github`][health] for ways
to get started.
See [`support.md`][support] for ways to get help.
This project has a [code of conduct][coc].
By interacting with this repository, organisation, or community you agree to
abide by its terms.
## License
[MIT][license] © [Titus Wormer][author]
<!-- Definitions -->
[build-badge]: https://github.com/micromark/micromark-extension-mdx-expression/workflows/main/badge.svg
[build]: https://github.com/micromark/micromark-extension-mdx-expression/actions
[coverage-badge]: https://img.shields.io/codecov/c/github/micromark/micromark-extension-mdx-expression.svg
[coverage]: https://codecov.io/github/micromark/micromark-extension-mdx-expression
[downloads-badge]: https://img.shields.io/npm/dm/micromark-util-events-to-acorn.svg
[downloads]: https://www.npmjs.com/package/micromark-util-events-to-acorn
[bundle-size-badge]: https://img.shields.io/bundlephobia/minzip/micromark-util-events-to-acorn.svg
[bundle-size]: https://bundlephobia.com/result?p=micromark-util-events-to-acorn
[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg
[backers-badge]: https://opencollective.com/unified/backers/badge.svg
[opencollective]: https://opencollective.com/unified
[npm]: https://docs.npmjs.com/cli/install
[esmsh]: https://esm.sh
[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg
[chat]: https://github.com/micromark/micromark/discussions
[license]: https://github.com/micromark/micromark-extension-mdx-expression/blob/main/license
[author]: https://wooorm.com
[health]: https://github.com/micromark/.github
[contributing]: https://github.com/micromark/.github/blob/main/contributing.md
[support]: https://github.com/micromark/.github/blob/main/support.md
[coc]: https://github.com/micromark/.github/blob/main/code-of-conduct.md
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[typescript]: https://www.typescriptlang.org
[development]: https://nodejs.org/api/packages.html#packages_resolving_user_conditions
[acorn]: https://github.com/acornjs/acorn
[acorn-options]: https://github.com/acornjs/acorn/blob/96c721dbf89d0ccc3a8c7f39e69ef2a6a3c04dfa/acorn/dist/acorn.d.ts#L16
[micromark]: https://github.com/micromark/micromark
[program]: https://github.com/estree/estree/blob/master/es2015.md#programs
[api-events-to-acorn]: #eventstoacornevents-options
[api-options]: #options
[api-result]: #result