123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703 |
- /**
- * @typedef {import('unist').Node} Node
- * @typedef {import('unist').Point} Point
- * @typedef {import('unist').Position} Position
- * @typedef {import('vfile-message').Options} MessageOptions
- * @typedef {import('../index.js').Data} Data
- * @typedef {import('../index.js').Value} Value
- */
- /**
- * @typedef {object & {type: string, position?: Position | undefined}} NodeLike
- *
- * @typedef {Options | URL | VFile | Value} Compatible
- * Things that can be passed to the constructor.
- *
- * @typedef VFileCoreOptions
- * Set multiple values.
- * @property {string | null | undefined} [basename]
- * Set `basename` (name).
- * @property {string | null | undefined} [cwd]
- * Set `cwd` (working directory).
- * @property {Data | null | undefined} [data]
- * Set `data` (associated info).
- * @property {string | null | undefined} [dirname]
- * Set `dirname` (path w/o basename).
- * @property {string | null | undefined} [extname]
- * Set `extname` (extension with dot).
- * @property {Array<string> | null | undefined} [history]
- * Set `history` (paths the file moved between).
- * @property {URL | string | null | undefined} [path]
- * Set `path` (current path).
- * @property {string | null | undefined} [stem]
- * Set `stem` (name without extension).
- * @property {Value | null | undefined} [value]
- * Set `value` (the contents of the file).
- *
- * @typedef Map
- * Raw source map.
- *
- * See:
- * <https://github.com/mozilla/source-map/blob/60adcb0/source-map.d.ts#L15-L23>.
- * @property {number} version
- * Which version of the source map spec this map is following.
- * @property {Array<string>} sources
- * An array of URLs to the original source files.
- * @property {Array<string>} names
- * An array of identifiers which can be referenced by individual mappings.
- * @property {string | undefined} [sourceRoot]
- * The URL root from which all sources are relative.
- * @property {Array<string> | undefined} [sourcesContent]
- * An array of contents of the original source files.
- * @property {string} mappings
- * A string of base64 VLQs which contain the actual mappings.
- * @property {string} file
- * The generated file this source map is associated with.
- *
- * @typedef {Record<string, unknown> & VFileCoreOptions} Options
- * Configuration.
- *
- * A bunch of keys that will be shallow copied over to the new file.
- *
- * @typedef {Record<string, unknown>} ReporterSettings
- * Configuration for reporters.
- */
- /**
- * @template [Settings=ReporterSettings]
- * Options type.
- * @callback Reporter
- * Type for a reporter.
- * @param {Array<VFile>} files
- * Files to report.
- * @param {Settings} options
- * Configuration.
- * @returns {string}
- * Report.
- */
- import {VFileMessage} from 'vfile-message'
- import {path} from 'vfile/do-not-use-conditional-minpath'
- import {proc} from 'vfile/do-not-use-conditional-minproc'
- import {urlToPath, isUrl} from 'vfile/do-not-use-conditional-minurl'
- /**
- * Order of setting (least specific to most), we need this because otherwise
- * `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a
- * stem can be set.
- */
- const order = /** @type {const} */ ([
- 'history',
- 'path',
- 'basename',
- 'stem',
- 'extname',
- 'dirname'
- ])
- export class VFile {
- /**
- * Create a new virtual file.
- *
- * `options` is treated as:
- *
- * * `string` or `Uint8Array` — `{value: options}`
- * * `URL` — `{path: options}`
- * * `VFile` — shallow copies its data over to the new file
- * * `object` — all fields are shallow copied over to the new file
- *
- * Path related fields are set in the following order (least specific to
- * most specific): `history`, `path`, `basename`, `stem`, `extname`,
- * `dirname`.
- *
- * You cannot set `dirname` or `extname` without setting either `history`,
- * `path`, `basename`, or `stem` too.
- *
- * @param {Compatible | null | undefined} [value]
- * File value.
- * @returns
- * New instance.
- */
- constructor(value) {
- /** @type {Options | VFile} */
- let options
- if (!value) {
- options = {}
- } else if (isUrl(value)) {
- options = {path: value}
- } else if (typeof value === 'string' || isUint8Array(value)) {
- options = {value}
- } else {
- options = value
- }
- /* eslint-disable no-unused-expressions */
- /**
- * Base of `path` (default: `process.cwd()` or `'/'` in browsers).
- *
- * @type {string}
- */
- this.cwd = proc.cwd()
- /**
- * Place to store custom info (default: `{}`).
- *
- * It’s OK to store custom data directly on the file but moving it to
- * `data` is recommended.
- *
- * @type {Data}
- */
- this.data = {}
- /**
- * List of file paths the file moved between.
- *
- * The first is the original path and the last is the current path.
- *
- * @type {Array<string>}
- */
- this.history = []
- /**
- * List of messages associated with the file.
- *
- * @type {Array<VFileMessage>}
- */
- this.messages = []
- /**
- * Raw value.
- *
- * @type {Value}
- */
- this.value
- // The below are non-standard, they are “well-known”.
- // As in, used in several tools.
- /**
- * Source map.
- *
- * This type is equivalent to the `RawSourceMap` type from the `source-map`
- * module.
- *
- * @type {Map | null | undefined}
- */
- this.map
- /**
- * Custom, non-string, compiled, representation.
- *
- * This is used by unified to store non-string results.
- * One example is when turning markdown into React nodes.
- *
- * @type {unknown}
- */
- this.result
- /**
- * Whether a file was saved to disk.
- *
- * This is used by vfile reporters.
- *
- * @type {boolean}
- */
- this.stored
- /* eslint-enable no-unused-expressions */
- // Set path related properties in the correct order.
- let index = -1
- while (++index < order.length) {
- const prop = order[index]
- // Note: we specifically use `in` instead of `hasOwnProperty` to accept
- // `vfile`s too.
- if (
- prop in options &&
- options[prop] !== undefined &&
- options[prop] !== null
- ) {
- // @ts-expect-error: TS doesn’t understand basic reality.
- this[prop] = prop === 'history' ? [...options[prop]] : options[prop]
- }
- }
- /** @type {string} */
- let prop
- // Set non-path related properties.
- for (prop in options) {
- // @ts-expect-error: fine to set other things.
- if (!order.includes(prop)) {
- // @ts-expect-error: fine to set other things.
- this[prop] = options[prop]
- }
- }
- }
- /**
- * Get the basename (including extname) (example: `'index.min.js'`).
- *
- * @returns {string | undefined}
- * Basename.
- */
- get basename() {
- return typeof this.path === 'string' ? path.basename(this.path) : undefined
- }
- /**
- * Set basename (including extname) (`'index.min.js'`).
- *
- * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
- * on windows).
- * Cannot be nullified (use `file.path = file.dirname` instead).
- *
- * @param {string} basename
- * Basename.
- * @returns {undefined}
- * Nothing.
- */
- set basename(basename) {
- assertNonEmpty(basename, 'basename')
- assertPart(basename, 'basename')
- this.path = path.join(this.dirname || '', basename)
- }
- /**
- * Get the parent path (example: `'~'`).
- *
- * @returns {string | undefined}
- * Dirname.
- */
- get dirname() {
- return typeof this.path === 'string' ? path.dirname(this.path) : undefined
- }
- /**
- * Set the parent path (example: `'~'`).
- *
- * Cannot be set if there’s no `path` yet.
- *
- * @param {string | undefined} dirname
- * Dirname.
- * @returns {undefined}
- * Nothing.
- */
- set dirname(dirname) {
- assertPath(this.basename, 'dirname')
- this.path = path.join(dirname || '', this.basename)
- }
- /**
- * Get the extname (including dot) (example: `'.js'`).
- *
- * @returns {string | undefined}
- * Extname.
- */
- get extname() {
- return typeof this.path === 'string' ? path.extname(this.path) : undefined
- }
- /**
- * Set the extname (including dot) (example: `'.js'`).
- *
- * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
- * on windows).
- * Cannot be set if there’s no `path` yet.
- *
- * @param {string | undefined} extname
- * Extname.
- * @returns {undefined}
- * Nothing.
- */
- set extname(extname) {
- assertPart(extname, 'extname')
- assertPath(this.dirname, 'extname')
- if (extname) {
- if (extname.codePointAt(0) !== 46 /* `.` */) {
- throw new Error('`extname` must start with `.`')
- }
- if (extname.includes('.', 1)) {
- throw new Error('`extname` cannot contain multiple dots')
- }
- }
- this.path = path.join(this.dirname, this.stem + (extname || ''))
- }
- /**
- * Get the full path (example: `'~/index.min.js'`).
- *
- * @returns {string}
- * Path.
- */
- get path() {
- return this.history[this.history.length - 1]
- }
- /**
- * Set the full path (example: `'~/index.min.js'`).
- *
- * Cannot be nullified.
- * You can set a file URL (a `URL` object with a `file:` protocol) which will
- * be turned into a path with `url.fileURLToPath`.
- *
- * @param {URL | string} path
- * Path.
- * @returns {undefined}
- * Nothing.
- */
- set path(path) {
- if (isUrl(path)) {
- path = urlToPath(path)
- }
- assertNonEmpty(path, 'path')
- if (this.path !== path) {
- this.history.push(path)
- }
- }
- /**
- * Get the stem (basename w/o extname) (example: `'index.min'`).
- *
- * @returns {string | undefined}
- * Stem.
- */
- get stem() {
- return typeof this.path === 'string'
- ? path.basename(this.path, this.extname)
- : undefined
- }
- /**
- * Set the stem (basename w/o extname) (example: `'index.min'`).
- *
- * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
- * on windows).
- * Cannot be nullified (use `file.path = file.dirname` instead).
- *
- * @param {string} stem
- * Stem.
- * @returns {undefined}
- * Nothing.
- */
- set stem(stem) {
- assertNonEmpty(stem, 'stem')
- assertPart(stem, 'stem')
- this.path = path.join(this.dirname || '', stem + (this.extname || ''))
- }
- // Normal prototypal methods.
- /**
- * Create a fatal message for `reason` associated with the file.
- *
- * The `fatal` field of the message is set to `true` (error; file not usable)
- * and the `file` field is set to the current file path.
- * The message is added to the `messages` field on `file`.
- *
- * > 🪦 **Note**: also has obsolete signatures.
- *
- * @overload
- * @param {string} reason
- * @param {MessageOptions | null | undefined} [options]
- * @returns {never}
- *
- * @overload
- * @param {string} reason
- * @param {Node | NodeLike | null | undefined} parent
- * @param {string | null | undefined} [origin]
- * @returns {never}
- *
- * @overload
- * @param {string} reason
- * @param {Point | Position | null | undefined} place
- * @param {string | null | undefined} [origin]
- * @returns {never}
- *
- * @overload
- * @param {string} reason
- * @param {string | null | undefined} [origin]
- * @returns {never}
- *
- * @overload
- * @param {Error | VFileMessage} cause
- * @param {Node | NodeLike | null | undefined} parent
- * @param {string | null | undefined} [origin]
- * @returns {never}
- *
- * @overload
- * @param {Error | VFileMessage} cause
- * @param {Point | Position | null | undefined} place
- * @param {string | null | undefined} [origin]
- * @returns {never}
- *
- * @overload
- * @param {Error | VFileMessage} cause
- * @param {string | null | undefined} [origin]
- * @returns {never}
- *
- * @param {Error | VFileMessage | string} causeOrReason
- * Reason for message, should use markdown.
- * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
- * Configuration (optional).
- * @param {string | null | undefined} [origin]
- * Place in code where the message originates (example:
- * `'my-package:my-rule'` or `'my-rule'`).
- * @returns {never}
- * Never.
- * @throws {VFileMessage}
- * Message.
- */
- fail(causeOrReason, optionsOrParentOrPlace, origin) {
- // @ts-expect-error: the overloads are fine.
- const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)
- message.fatal = true
- throw message
- }
- /**
- * Create an info message for `reason` associated with the file.
- *
- * The `fatal` field of the message is set to `undefined` (info; change
- * likely not needed) and the `file` field is set to the current file path.
- * The message is added to the `messages` field on `file`.
- *
- * > 🪦 **Note**: also has obsolete signatures.
- *
- * @overload
- * @param {string} reason
- * @param {MessageOptions | null | undefined} [options]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {string} reason
- * @param {Node | NodeLike | null | undefined} parent
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {string} reason
- * @param {Point | Position | null | undefined} place
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {string} reason
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {Error | VFileMessage} cause
- * @param {Node | NodeLike | null | undefined} parent
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {Error | VFileMessage} cause
- * @param {Point | Position | null | undefined} place
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {Error | VFileMessage} cause
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @param {Error | VFileMessage | string} causeOrReason
- * Reason for message, should use markdown.
- * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
- * Configuration (optional).
- * @param {string | null | undefined} [origin]
- * Place in code where the message originates (example:
- * `'my-package:my-rule'` or `'my-rule'`).
- * @returns {VFileMessage}
- * Message.
- */
- info(causeOrReason, optionsOrParentOrPlace, origin) {
- // @ts-expect-error: the overloads are fine.
- const message = this.message(causeOrReason, optionsOrParentOrPlace, origin)
- message.fatal = undefined
- return message
- }
- /**
- * Create a message for `reason` associated with the file.
- *
- * The `fatal` field of the message is set to `false` (warning; change may be
- * needed) and the `file` field is set to the current file path.
- * The message is added to the `messages` field on `file`.
- *
- * > 🪦 **Note**: also has obsolete signatures.
- *
- * @overload
- * @param {string} reason
- * @param {MessageOptions | null | undefined} [options]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {string} reason
- * @param {Node | NodeLike | null | undefined} parent
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {string} reason
- * @param {Point | Position | null | undefined} place
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {string} reason
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {Error | VFileMessage} cause
- * @param {Node | NodeLike | null | undefined} parent
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {Error | VFileMessage} cause
- * @param {Point | Position | null | undefined} place
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @overload
- * @param {Error | VFileMessage} cause
- * @param {string | null | undefined} [origin]
- * @returns {VFileMessage}
- *
- * @param {Error | VFileMessage | string} causeOrReason
- * Reason for message, should use markdown.
- * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
- * Configuration (optional).
- * @param {string | null | undefined} [origin]
- * Place in code where the message originates (example:
- * `'my-package:my-rule'` or `'my-rule'`).
- * @returns {VFileMessage}
- * Message.
- */
- message(causeOrReason, optionsOrParentOrPlace, origin) {
- const message = new VFileMessage(
- // @ts-expect-error: the overloads are fine.
- causeOrReason,
- optionsOrParentOrPlace,
- origin
- )
- if (this.path) {
- message.name = this.path + ':' + message.name
- message.file = this.path
- }
- message.fatal = false
- this.messages.push(message)
- return message
- }
- /**
- * Serialize the file.
- *
- * > **Note**: which encodings are supported depends on the engine.
- * > For info on Node.js, see:
- * > <https://nodejs.org/api/util.html#whatwg-supported-encodings>.
- *
- * @param {string | null | undefined} [encoding='utf8']
- * Character encoding to understand `value` as when it’s a `Uint8Array`
- * (default: `'utf-8'`).
- * @returns {string}
- * Serialized file.
- */
- toString(encoding) {
- if (this.value === undefined) {
- return ''
- }
- if (typeof this.value === 'string') {
- return this.value
- }
- const decoder = new TextDecoder(encoding || undefined)
- return decoder.decode(this.value)
- }
- }
- /**
- * Assert that `part` is not a path (as in, does not contain `path.sep`).
- *
- * @param {string | null | undefined} part
- * File path part.
- * @param {string} name
- * Part name.
- * @returns {undefined}
- * Nothing.
- */
- function assertPart(part, name) {
- if (part && part.includes(path.sep)) {
- throw new Error(
- '`' + name + '` cannot be a path: did not expect `' + path.sep + '`'
- )
- }
- }
- /**
- * Assert that `part` is not empty.
- *
- * @param {string | undefined} part
- * Thing.
- * @param {string} name
- * Part name.
- * @returns {asserts part is string}
- * Nothing.
- */
- function assertNonEmpty(part, name) {
- if (!part) {
- throw new Error('`' + name + '` cannot be empty')
- }
- }
- /**
- * Assert `path` exists.
- *
- * @param {string | undefined} path
- * Path.
- * @param {string} name
- * Dependency name.
- * @returns {asserts path is string}
- * Nothing.
- */
- function assertPath(path, name) {
- if (!path) {
- throw new Error('Setting `' + name + '` requires `path` to be set too')
- }
- }
- /**
- * Assert `value` is an `Uint8Array`.
- *
- * @param {unknown} value
- * thing.
- * @returns {value is Uint8Array}
- * Whether `value` is an `Uint8Array`.
- */
- function isUint8Array(value) {
- return Boolean(
- value &&
- typeof value === 'object' &&
- 'byteLength' in value &&
- 'byteOffset' in value
- )
- }
|