WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
'use strict'
|
||||
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const { join } = require('path')
|
||||
const { readFile } = require('fs')
|
||||
const { file } = require('./helper')
|
||||
const ThreadStream = require('..')
|
||||
|
||||
test('destroy support', function (t, done) {
|
||||
const dest = file()
|
||||
const stream = new ThreadStream({
|
||||
filename: join(__dirname, 'to-file-on-destroy.js'),
|
||||
workerData: { dest },
|
||||
sync: true
|
||||
})
|
||||
|
||||
stream.on('close', () => {
|
||||
assert.ok(!stream.writable)
|
||||
readFile(dest, 'utf8', (err, data) => {
|
||||
assert.ifError(err)
|
||||
assert.strictEqual(data, 'hello world\nsomething else\n')
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
assert.ok(stream.write('hello world\n'))
|
||||
assert.ok(stream.write('something else\n'))
|
||||
assert.ok(stream.writable)
|
||||
|
||||
stream.end()
|
||||
})
|
||||
|
||||
test('synchronous _final support', function (t, done) {
|
||||
const dest = file()
|
||||
const stream = new ThreadStream({
|
||||
filename: join(__dirname, 'to-file-on-final.js'),
|
||||
workerData: { dest },
|
||||
sync: true
|
||||
})
|
||||
|
||||
stream.on('close', () => {
|
||||
assert.ok(!stream.writable)
|
||||
readFile(dest, 'utf8', (err, data) => {
|
||||
assert.ifError(err)
|
||||
assert.strictEqual(data, 'hello world\nsomething else\n')
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
assert.ok(stream.write('hello world\n'))
|
||||
assert.ok(stream.write('something else\n'))
|
||||
assert.ok(stream.writable)
|
||||
|
||||
stream.end()
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"moduleResolutionKind.enum.d.ts","sourceRoot":"","sources":["../../src/enums/moduleResolutionKind.enum.ts"],"names":[],"mappings":"AAEA,oBAAY,oBAAoB;IAC5B,OAAO,IAAI;IACX,OAAO,IAAI;IACX,MAAM,IAAI;IACV,MAAM,IAAI;IACV,QAAQ,KAAK;IACb,OAAO,MAAM;CAChB"}
|
||||
@@ -0,0 +1,59 @@
|
||||
'use strict'
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const { join } = require('node:path')
|
||||
const { fork } = require('node:child_process')
|
||||
const tspl = require('@matteo.collina/tspl')
|
||||
const { once } = require('./helper')
|
||||
const pino = require('..')
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
console.log('skipping on windows')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (process.env.CITGM) {
|
||||
// This looks like a some form of limitations of the CITGM test runner
|
||||
// or the HW/SW we run it on. This file can hang on Node.js v18.x.
|
||||
// The failure does not reproduce locally or on our CI.
|
||||
// Skipping it is the only way to keep pino in CITGM.
|
||||
// https://github.com/nodejs/citgm/pull/1002#issuecomment-1751942988
|
||||
console.log('Skipping on Node.js core CITGM because it hangs on v18.x')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
function testFile (file) {
|
||||
file = join('fixtures', 'broken-pipe', file)
|
||||
test(file, async () => {
|
||||
const child = fork(join(__dirname, file), { silent: true })
|
||||
child.stdout.destroy()
|
||||
|
||||
child.stderr.pipe(process.stdout)
|
||||
|
||||
const res = await once(child, 'close')
|
||||
assert.equal(res, 0) // process exits successfully
|
||||
})
|
||||
}
|
||||
|
||||
testFile('basic.js')
|
||||
testFile('destination.js')
|
||||
testFile('syncfalse.js')
|
||||
|
||||
test('let error pass through', async (t) => {
|
||||
const plan = tspl(t, { plan: 3 })
|
||||
const stream = pino.destination({ sync: true })
|
||||
|
||||
// side effect of the pino constructor is that it will set an
|
||||
// event handler for error
|
||||
pino(stream)
|
||||
|
||||
process.nextTick(() => stream.emit('error', new Error('kaboom')))
|
||||
process.nextTick(() => stream.emit('error', new Error('kaboom')))
|
||||
|
||||
stream.on('error', (err) => {
|
||||
plan.equal(err.message, 'kaboom')
|
||||
})
|
||||
|
||||
await plan
|
||||
})
|
||||
Binary file not shown.
@@ -0,0 +1,547 @@
|
||||
'use strict'
|
||||
|
||||
const format = require('quick-format-unescaped')
|
||||
|
||||
module.exports = pino
|
||||
|
||||
const _console = pfGlobalThisOrFallback().console || {}
|
||||
const stdSerializers = {
|
||||
mapHttpRequest: mock,
|
||||
mapHttpResponse: mock,
|
||||
wrapRequestSerializer: passthrough,
|
||||
wrapResponseSerializer: passthrough,
|
||||
wrapErrorSerializer: passthrough,
|
||||
req: mock,
|
||||
res: mock,
|
||||
err: asErrValue,
|
||||
errWithCause: asErrValue
|
||||
}
|
||||
function levelToValue (level, logger) {
|
||||
return level === 'silent'
|
||||
? Infinity
|
||||
: logger.levels.values[level]
|
||||
}
|
||||
const baseLogFunctionSymbol = Symbol('pino.logFuncs')
|
||||
const hierarchySymbol = Symbol('pino.hierarchy')
|
||||
|
||||
const logFallbackMap = {
|
||||
error: 'log',
|
||||
fatal: 'error',
|
||||
warn: 'error',
|
||||
info: 'log',
|
||||
debug: 'log',
|
||||
trace: 'log'
|
||||
}
|
||||
|
||||
function appendChildLogger (parentLogger, childLogger) {
|
||||
const newEntry = {
|
||||
logger: childLogger,
|
||||
parent: parentLogger[hierarchySymbol]
|
||||
}
|
||||
childLogger[hierarchySymbol] = newEntry
|
||||
}
|
||||
|
||||
function setupBaseLogFunctions (logger, levels, proto) {
|
||||
const logFunctions = {}
|
||||
levels.forEach(level => {
|
||||
logFunctions[level] = proto[level] ? proto[level] : (_console[level] || _console[logFallbackMap[level] || 'log'] || noop)
|
||||
})
|
||||
logger[baseLogFunctionSymbol] = logFunctions
|
||||
}
|
||||
|
||||
function shouldSerialize (serialize, serializers) {
|
||||
if (Array.isArray(serialize)) {
|
||||
const hasToFilter = serialize.filter(function (k) {
|
||||
return k !== '!stdSerializers.err'
|
||||
})
|
||||
return hasToFilter
|
||||
} else if (serialize === true) {
|
||||
return Object.keys(serializers)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function pino (opts) {
|
||||
opts = opts || {}
|
||||
opts.browser = opts.browser || {}
|
||||
|
||||
const transmit = opts.browser.transmit
|
||||
if (transmit && typeof transmit.send !== 'function') { throw Error('pino: transmit option must have a send function') }
|
||||
|
||||
const proto = opts.browser.write || _console
|
||||
if (opts.browser.write) opts.browser.asObject = true
|
||||
const serializers = opts.serializers || {}
|
||||
const serialize = shouldSerialize(opts.browser.serialize, serializers)
|
||||
let stdErrSerialize = opts.browser.serialize
|
||||
|
||||
if (
|
||||
Array.isArray(opts.browser.serialize) &&
|
||||
opts.browser.serialize.indexOf('!stdSerializers.err') > -1
|
||||
) stdErrSerialize = false
|
||||
|
||||
const customLevels = Object.keys(opts.customLevels || {})
|
||||
const levels = ['error', 'fatal', 'warn', 'info', 'debug', 'trace'].concat(customLevels)
|
||||
|
||||
if (typeof proto === 'function') {
|
||||
levels.forEach(function (level) {
|
||||
proto[level] = proto
|
||||
})
|
||||
}
|
||||
if (opts.enabled === false || opts.browser.disabled) opts.level = 'silent'
|
||||
const level = opts.level || 'info'
|
||||
const logger = Object.create(proto)
|
||||
if (!logger.log) logger.log = noop
|
||||
|
||||
setupBaseLogFunctions(logger, levels, proto)
|
||||
// setup root hierarchy entry
|
||||
appendChildLogger({}, logger)
|
||||
|
||||
Object.defineProperty(logger, 'levelVal', {
|
||||
get: getLevelVal
|
||||
})
|
||||
Object.defineProperty(logger, 'level', {
|
||||
get: getLevel,
|
||||
set: setLevel
|
||||
})
|
||||
|
||||
const setOpts = {
|
||||
transmit,
|
||||
serialize,
|
||||
asObject: opts.browser.asObject,
|
||||
asObjectBindingsOnly: opts.browser.asObjectBindingsOnly,
|
||||
formatters: opts.browser.formatters,
|
||||
reportCaller: opts.browser.reportCaller,
|
||||
levels,
|
||||
timestamp: getTimeFunction(opts),
|
||||
messageKey: opts.messageKey || 'msg',
|
||||
onChild: opts.onChild || noop
|
||||
}
|
||||
logger.levels = getLevels(opts)
|
||||
logger.level = level
|
||||
|
||||
logger.isLevelEnabled = function (level) {
|
||||
if (!this.levels.values[level]) {
|
||||
return false
|
||||
}
|
||||
|
||||
return this.levels.values[level] >= this.levels.values[this.level]
|
||||
}
|
||||
logger.setMaxListeners = logger.getMaxListeners =
|
||||
logger.emit = logger.addListener = logger.on =
|
||||
logger.prependListener = logger.once =
|
||||
logger.prependOnceListener = logger.removeListener =
|
||||
logger.removeAllListeners = logger.listeners =
|
||||
logger.listenerCount = logger.eventNames =
|
||||
logger.write = logger.flush = noop
|
||||
logger.serializers = serializers
|
||||
logger._serialize = serialize
|
||||
logger._stdErrSerialize = stdErrSerialize
|
||||
logger.child = function (...args) { return child.call(this, setOpts, ...args) }
|
||||
|
||||
if (transmit) logger._logEvent = createLogEventShape()
|
||||
|
||||
function getLevelVal () {
|
||||
return levelToValue(this.level, this)
|
||||
}
|
||||
|
||||
function getLevel () {
|
||||
return this._level
|
||||
}
|
||||
function setLevel (level) {
|
||||
if (level !== 'silent' && !this.levels.values[level]) {
|
||||
throw Error('unknown level ' + level)
|
||||
}
|
||||
this._level = level
|
||||
|
||||
set(this, setOpts, logger, 'error') // <-- must stay first
|
||||
set(this, setOpts, logger, 'fatal')
|
||||
set(this, setOpts, logger, 'warn')
|
||||
set(this, setOpts, logger, 'info')
|
||||
set(this, setOpts, logger, 'debug')
|
||||
set(this, setOpts, logger, 'trace')
|
||||
|
||||
customLevels.forEach((level) => {
|
||||
set(this, setOpts, logger, level)
|
||||
})
|
||||
}
|
||||
|
||||
function child (setOpts, bindings, childOptions) {
|
||||
if (!bindings) {
|
||||
throw new Error('missing bindings for child Pino')
|
||||
}
|
||||
childOptions = childOptions || {}
|
||||
if (serialize && bindings.serializers) {
|
||||
childOptions.serializers = bindings.serializers
|
||||
}
|
||||
const childOptionsSerializers = childOptions.serializers
|
||||
if (serialize && childOptionsSerializers) {
|
||||
var childSerializers = Object.assign({}, serializers, childOptionsSerializers)
|
||||
var childSerialize = opts.browser.serialize === true
|
||||
? Object.keys(childSerializers)
|
||||
: serialize
|
||||
delete bindings.serializers
|
||||
applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize)
|
||||
}
|
||||
function Child (parent) {
|
||||
this._childLevel = (parent._childLevel | 0) + 1
|
||||
|
||||
// make sure bindings are available in the `set` function
|
||||
this.bindings = bindings
|
||||
|
||||
if (childSerializers) {
|
||||
this.serializers = childSerializers
|
||||
this._serialize = childSerialize
|
||||
}
|
||||
if (transmit) {
|
||||
this._logEvent = createLogEventShape(
|
||||
[].concat(parent._logEvent.bindings, bindings)
|
||||
)
|
||||
}
|
||||
}
|
||||
Child.prototype = this
|
||||
const newLogger = new Child(this)
|
||||
|
||||
// must happen before the level is assigned
|
||||
appendChildLogger(this, newLogger)
|
||||
newLogger.child = function (...args) { return child.call(this, setOpts, ...args) }
|
||||
// required to actually initialize the logger functions for any given child
|
||||
newLogger.level = childOptions.level || this.level // allow level to be set by childOptions
|
||||
setOpts.onChild(newLogger)
|
||||
|
||||
return newLogger
|
||||
}
|
||||
return logger
|
||||
}
|
||||
|
||||
function getLevels (opts) {
|
||||
const customLevels = opts.customLevels || {}
|
||||
|
||||
const values = Object.assign({}, pino.levels.values, customLevels)
|
||||
const labels = Object.assign({}, pino.levels.labels, invertObject(customLevels))
|
||||
|
||||
return {
|
||||
values,
|
||||
labels
|
||||
}
|
||||
}
|
||||
|
||||
function invertObject (obj) {
|
||||
const inverted = {}
|
||||
Object.keys(obj).forEach(function (key) {
|
||||
inverted[obj[key]] = key
|
||||
})
|
||||
return inverted
|
||||
}
|
||||
|
||||
pino.levels = {
|
||||
values: {
|
||||
fatal: 60,
|
||||
error: 50,
|
||||
warn: 40,
|
||||
info: 30,
|
||||
debug: 20,
|
||||
trace: 10
|
||||
},
|
||||
labels: {
|
||||
10: 'trace',
|
||||
20: 'debug',
|
||||
30: 'info',
|
||||
40: 'warn',
|
||||
50: 'error',
|
||||
60: 'fatal'
|
||||
}
|
||||
}
|
||||
|
||||
pino.stdSerializers = stdSerializers
|
||||
pino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime })
|
||||
|
||||
function getBindingChain (logger) {
|
||||
const bindings = []
|
||||
if (logger.bindings) {
|
||||
bindings.push(logger.bindings)
|
||||
}
|
||||
|
||||
// traverse up the tree to get all bindings
|
||||
let hierarchy = logger[hierarchySymbol]
|
||||
while (hierarchy.parent) {
|
||||
hierarchy = hierarchy.parent
|
||||
if (hierarchy.logger.bindings) {
|
||||
bindings.push(hierarchy.logger.bindings)
|
||||
}
|
||||
}
|
||||
|
||||
return bindings.reverse()
|
||||
}
|
||||
|
||||
function set (self, opts, rootLogger, level) {
|
||||
// override the current log functions with either `noop` or the base log function
|
||||
Object.defineProperty(self, level, {
|
||||
value: (levelToValue(self.level, rootLogger) > levelToValue(level, rootLogger)
|
||||
? noop
|
||||
: rootLogger[baseLogFunctionSymbol][level]),
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
})
|
||||
|
||||
if (self[level] === noop) {
|
||||
if (!opts.transmit) return
|
||||
|
||||
const transmitLevel = opts.transmit.level || self.level
|
||||
const transmitValue = levelToValue(transmitLevel, rootLogger)
|
||||
const methodValue = levelToValue(level, rootLogger)
|
||||
if (methodValue < transmitValue) return
|
||||
}
|
||||
|
||||
// make sure the log format is correct
|
||||
self[level] = createWrap(self, opts, rootLogger, level)
|
||||
|
||||
// prepend bindings if it is not the root logger
|
||||
const bindings = getBindingChain(self)
|
||||
if (bindings.length === 0) {
|
||||
// early exit in case for rootLogger
|
||||
return
|
||||
}
|
||||
self[level] = prependBindingsInArguments(bindings, self[level])
|
||||
}
|
||||
|
||||
function prependBindingsInArguments (bindings, logFunc) {
|
||||
return function () {
|
||||
return logFunc.apply(this, [...bindings, ...arguments])
|
||||
}
|
||||
}
|
||||
|
||||
function createWrap (self, opts, rootLogger, level) {
|
||||
return (function (write) {
|
||||
return function LOG () {
|
||||
const ts = opts.timestamp()
|
||||
const args = new Array(arguments.length)
|
||||
const proto = (Object.getPrototypeOf && Object.getPrototypeOf(this) === _console) ? _console : this
|
||||
for (var i = 0; i < args.length; i++) args[i] = arguments[i]
|
||||
|
||||
var argsIsSerialized = false
|
||||
if (opts.serialize) {
|
||||
applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize)
|
||||
argsIsSerialized = true
|
||||
}
|
||||
if (opts.asObject || opts.formatters) {
|
||||
const out = asObject(this, level, args, ts, opts)
|
||||
if (opts.reportCaller && out && out.length > 0 && out[0] && typeof out[0] === 'object') {
|
||||
try {
|
||||
const caller = getCallerLocation()
|
||||
if (caller) out[0].caller = caller
|
||||
} catch (e) {}
|
||||
}
|
||||
write.call(proto, ...out)
|
||||
} else {
|
||||
if (opts.reportCaller) {
|
||||
try {
|
||||
const caller = getCallerLocation()
|
||||
if (caller) args.push(caller)
|
||||
} catch (e) {}
|
||||
}
|
||||
write.apply(proto, args)
|
||||
}
|
||||
|
||||
if (opts.transmit) {
|
||||
const transmitLevel = opts.transmit.level || self._level
|
||||
const transmitValue = levelToValue(transmitLevel, rootLogger)
|
||||
const methodValue = levelToValue(level, rootLogger)
|
||||
if (methodValue < transmitValue) return
|
||||
transmit(this, {
|
||||
ts,
|
||||
methodLevel: level,
|
||||
methodValue,
|
||||
transmitLevel,
|
||||
transmitValue: rootLogger.levels.values[opts.transmit.level || self._level],
|
||||
send: opts.transmit.send,
|
||||
val: levelToValue(self._level, rootLogger)
|
||||
}, args, argsIsSerialized)
|
||||
}
|
||||
}
|
||||
})(self[baseLogFunctionSymbol][level])
|
||||
}
|
||||
|
||||
function asObject (logger, level, args, ts, opts) {
|
||||
const {
|
||||
level: levelFormatter,
|
||||
log: logObjectFormatter = (obj) => obj
|
||||
} = opts.formatters || {}
|
||||
const argsCloned = args.slice()
|
||||
let msg = argsCloned[0]
|
||||
const logObject = {}
|
||||
|
||||
let lvl = (logger._childLevel | 0) + 1
|
||||
if (lvl < 1) lvl = 1
|
||||
|
||||
if (ts) {
|
||||
logObject.time = ts
|
||||
}
|
||||
|
||||
if (levelFormatter) {
|
||||
const formattedLevel = levelFormatter(level, logger.levels.values[level])
|
||||
Object.assign(logObject, formattedLevel)
|
||||
} else {
|
||||
logObject.level = logger.levels.values[level]
|
||||
}
|
||||
|
||||
if (opts.asObjectBindingsOnly) {
|
||||
if (msg !== null && typeof msg === 'object') {
|
||||
while (lvl-- && typeof argsCloned[0] === 'object') {
|
||||
Object.assign(logObject, argsCloned.shift())
|
||||
}
|
||||
}
|
||||
|
||||
const formattedLogObject = logObjectFormatter(logObject)
|
||||
return [formattedLogObject, ...argsCloned]
|
||||
} else {
|
||||
// deliberate, catching objects, arrays
|
||||
if (msg !== null && typeof msg === 'object') {
|
||||
while (lvl-- && typeof argsCloned[0] === 'object') {
|
||||
Object.assign(logObject, argsCloned.shift())
|
||||
}
|
||||
msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : undefined
|
||||
} else if (typeof msg === 'string') msg = format(argsCloned.shift(), argsCloned)
|
||||
if (msg !== undefined) logObject[opts.messageKey] = msg
|
||||
|
||||
const formattedLogObject = logObjectFormatter(logObject)
|
||||
return [formattedLogObject]
|
||||
}
|
||||
}
|
||||
|
||||
function applySerializers (args, serialize, serializers, stdErrSerialize) {
|
||||
for (const i in args) {
|
||||
if (stdErrSerialize && args[i] instanceof Error) {
|
||||
args[i] = pino.stdSerializers.err(args[i])
|
||||
} else if (typeof args[i] === 'object' && !Array.isArray(args[i]) && serialize) {
|
||||
for (const k in args[i]) {
|
||||
if (serialize.indexOf(k) > -1 && k in serializers) {
|
||||
args[i][k] = serializers[k](args[i][k])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function transmit (logger, opts, args, argsIsSerialized = false) {
|
||||
const send = opts.send
|
||||
const ts = opts.ts
|
||||
const methodLevel = opts.methodLevel
|
||||
const methodValue = opts.methodValue
|
||||
const val = opts.val
|
||||
const bindings = logger._logEvent.bindings
|
||||
|
||||
if (!argsIsSerialized) {
|
||||
applySerializers(
|
||||
args,
|
||||
logger._serialize || Object.keys(logger.serializers),
|
||||
logger.serializers,
|
||||
logger._stdErrSerialize === undefined ? true : logger._stdErrSerialize
|
||||
)
|
||||
}
|
||||
|
||||
logger._logEvent.ts = ts
|
||||
logger._logEvent.messages = args.filter(function (arg) {
|
||||
// bindings can only be objects, so reference equality check via indexOf is fine
|
||||
return bindings.indexOf(arg) === -1
|
||||
})
|
||||
|
||||
logger._logEvent.level.label = methodLevel
|
||||
logger._logEvent.level.value = methodValue
|
||||
|
||||
send(methodLevel, logger._logEvent, val)
|
||||
|
||||
logger._logEvent = createLogEventShape(bindings)
|
||||
}
|
||||
|
||||
function createLogEventShape (bindings) {
|
||||
return {
|
||||
ts: 0,
|
||||
messages: [],
|
||||
bindings: bindings || [],
|
||||
level: { label: '', value: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
function asErrValue (err) {
|
||||
const obj = {
|
||||
type: err.constructor.name,
|
||||
msg: err.message,
|
||||
stack: err.stack
|
||||
}
|
||||
for (const key in err) {
|
||||
if (obj[key] === undefined) {
|
||||
obj[key] = err[key]
|
||||
}
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
function getTimeFunction (opts) {
|
||||
if (typeof opts.timestamp === 'function') {
|
||||
return opts.timestamp
|
||||
}
|
||||
if (opts.timestamp === false) {
|
||||
return nullTime
|
||||
}
|
||||
return epochTime
|
||||
}
|
||||
|
||||
function mock () { return {} }
|
||||
function passthrough (a) { return a }
|
||||
function noop () {}
|
||||
|
||||
function nullTime () { return false }
|
||||
function epochTime () { return Date.now() }
|
||||
function unixTime () { return Math.round(Date.now() / 1000.0) }
|
||||
function isoTime () { return new Date(Date.now()).toISOString() } // using Date.now() for testability
|
||||
|
||||
/* eslint-disable */
|
||||
/* istanbul ignore next */
|
||||
function pfGlobalThisOrFallback () {
|
||||
function defd (o) { return typeof o !== 'undefined' && o }
|
||||
try {
|
||||
if (typeof globalThis !== 'undefined') return globalThis
|
||||
Object.defineProperty(Object.prototype, 'globalThis', {
|
||||
get: function () {
|
||||
delete Object.prototype.globalThis
|
||||
return (this.globalThis = this)
|
||||
},
|
||||
configurable: true
|
||||
})
|
||||
return globalThis
|
||||
} catch (e) {
|
||||
return defd(self) || defd(window) || defd(this) || {}
|
||||
}
|
||||
}
|
||||
/* eslint-enable */
|
||||
|
||||
module.exports.default = pino
|
||||
module.exports.pino = pino
|
||||
|
||||
// Attempt to extract the user callsite (file:line:column)
|
||||
/* istanbul ignore next */
|
||||
function getCallerLocation () {
|
||||
const stack = (new Error()).stack
|
||||
if (!stack) return null
|
||||
const lines = stack.split('\n')
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const l = lines[i].trim()
|
||||
// skip frames from this file and internals
|
||||
if (/(^at\s+)?(createWrap|LOG|set\s*\(|asObject|Object\.apply|Function\.apply)/.test(l)) continue
|
||||
if (l.indexOf('browser.js') !== -1) continue
|
||||
if (l.indexOf('node:internal') !== -1) continue
|
||||
if (l.indexOf('node_modules') !== -1) continue
|
||||
// try formats like: at func (file:line:col) or at file:line:col
|
||||
let m = l.match(/\((.*?):(\d+):(\d+)\)/)
|
||||
if (!m) m = l.match(/at\s+(.*?):(\d+):(\d+)/)
|
||||
if (m) {
|
||||
const file = m[1]
|
||||
const line = m[2]
|
||||
const col = m[3]
|
||||
return file + ':' + line + ':' + col
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
import { SolanaError, SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH, SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL } from '@solana/errors';
|
||||
|
||||
// src/add-codec-sentinel.ts
|
||||
|
||||
// src/bytes.ts
|
||||
var mergeBytes = (byteArrays) => {
|
||||
const nonEmptyByteArrays = byteArrays.filter((arr) => arr.length);
|
||||
if (nonEmptyByteArrays.length === 0) {
|
||||
return byteArrays.length ? byteArrays[0] : new Uint8Array();
|
||||
}
|
||||
if (nonEmptyByteArrays.length === 1) {
|
||||
return nonEmptyByteArrays[0];
|
||||
}
|
||||
const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);
|
||||
const result = new Uint8Array(totalLength);
|
||||
let offset = 0;
|
||||
nonEmptyByteArrays.forEach((arr) => {
|
||||
result.set(arr, offset);
|
||||
offset += arr.length;
|
||||
});
|
||||
return result;
|
||||
};
|
||||
var padBytes = (bytes, length) => {
|
||||
if (bytes.length >= length) return bytes;
|
||||
const paddedBytes = new Uint8Array(length).fill(0);
|
||||
paddedBytes.set(bytes);
|
||||
return paddedBytes;
|
||||
};
|
||||
var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);
|
||||
function containsBytes(data, bytes, offset) {
|
||||
const slice = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length);
|
||||
if (slice.length !== bytes.length) return false;
|
||||
return bytes.every((b, i) => b === slice[i]);
|
||||
}
|
||||
function getEncodedSize(value, encoder) {
|
||||
return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
|
||||
}
|
||||
function createEncoder(encoder) {
|
||||
return Object.freeze({
|
||||
...encoder,
|
||||
encode: (value) => {
|
||||
const bytes = new Uint8Array(getEncodedSize(value, encoder));
|
||||
encoder.write(value, bytes, 0);
|
||||
return bytes;
|
||||
}
|
||||
});
|
||||
}
|
||||
function createDecoder(decoder) {
|
||||
return Object.freeze({
|
||||
...decoder,
|
||||
decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
|
||||
});
|
||||
}
|
||||
function createCodec(codec) {
|
||||
return Object.freeze({
|
||||
...codec,
|
||||
decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],
|
||||
encode: (value) => {
|
||||
const bytes = new Uint8Array(getEncodedSize(value, codec));
|
||||
codec.write(value, bytes, 0);
|
||||
return bytes;
|
||||
}
|
||||
});
|
||||
}
|
||||
function isFixedSize(codec) {
|
||||
return "fixedSize" in codec && typeof codec.fixedSize === "number";
|
||||
}
|
||||
function assertIsFixedSize(codec) {
|
||||
if (!isFixedSize(codec)) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);
|
||||
}
|
||||
}
|
||||
function isVariableSize(codec) {
|
||||
return !isFixedSize(codec);
|
||||
}
|
||||
function assertIsVariableSize(codec) {
|
||||
if (!isVariableSize(codec)) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);
|
||||
}
|
||||
}
|
||||
function combineCodec(encoder, decoder) {
|
||||
if (isFixedSize(encoder) !== isFixedSize(decoder)) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH);
|
||||
}
|
||||
if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, {
|
||||
decoderFixedSize: decoder.fixedSize,
|
||||
encoderFixedSize: encoder.fixedSize
|
||||
});
|
||||
}
|
||||
if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, {
|
||||
decoderMaxSize: decoder.maxSize,
|
||||
encoderMaxSize: encoder.maxSize
|
||||
});
|
||||
}
|
||||
return {
|
||||
...decoder,
|
||||
...encoder,
|
||||
decode: decoder.decode,
|
||||
encode: encoder.encode,
|
||||
read: decoder.read,
|
||||
write: encoder.write
|
||||
};
|
||||
}
|
||||
|
||||
// src/add-codec-sentinel.ts
|
||||
function addEncoderSentinel(encoder, sentinel) {
|
||||
const write = (value, bytes, offset) => {
|
||||
const encoderBytes = encoder.encode(value);
|
||||
if (findSentinelIndex(encoderBytes, sentinel) >= 0) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, {
|
||||
encodedBytes: encoderBytes,
|
||||
hexEncodedBytes: hexBytes(encoderBytes),
|
||||
hexSentinel: hexBytes(sentinel),
|
||||
sentinel
|
||||
});
|
||||
}
|
||||
bytes.set(encoderBytes, offset);
|
||||
offset += encoderBytes.length;
|
||||
bytes.set(sentinel, offset);
|
||||
offset += sentinel.length;
|
||||
return offset;
|
||||
};
|
||||
if (isFixedSize(encoder)) {
|
||||
return createEncoder({ ...encoder, fixedSize: encoder.fixedSize + sentinel.length, write });
|
||||
}
|
||||
return createEncoder({
|
||||
...encoder,
|
||||
...encoder.maxSize != null ? { maxSize: encoder.maxSize + sentinel.length } : {},
|
||||
getSizeFromValue: (value) => encoder.getSizeFromValue(value) + sentinel.length,
|
||||
write
|
||||
});
|
||||
}
|
||||
function addDecoderSentinel(decoder, sentinel) {
|
||||
const read = (bytes, offset) => {
|
||||
const candidateBytes = offset === 0 ? bytes : bytes.slice(offset);
|
||||
const sentinelIndex = findSentinelIndex(candidateBytes, sentinel);
|
||||
if (sentinelIndex === -1) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, {
|
||||
decodedBytes: candidateBytes,
|
||||
hexDecodedBytes: hexBytes(candidateBytes),
|
||||
hexSentinel: hexBytes(sentinel),
|
||||
sentinel
|
||||
});
|
||||
}
|
||||
const preSentinelBytes = candidateBytes.slice(0, sentinelIndex);
|
||||
return [decoder.decode(preSentinelBytes), offset + preSentinelBytes.length + sentinel.length];
|
||||
};
|
||||
if (isFixedSize(decoder)) {
|
||||
return createDecoder({ ...decoder, fixedSize: decoder.fixedSize + sentinel.length, read });
|
||||
}
|
||||
return createDecoder({
|
||||
...decoder,
|
||||
...decoder.maxSize != null ? { maxSize: decoder.maxSize + sentinel.length } : {},
|
||||
read
|
||||
});
|
||||
}
|
||||
function addCodecSentinel(codec, sentinel) {
|
||||
return combineCodec(addEncoderSentinel(codec, sentinel), addDecoderSentinel(codec, sentinel));
|
||||
}
|
||||
function findSentinelIndex(bytes, sentinel) {
|
||||
return bytes.findIndex((byte, index, arr) => {
|
||||
if (sentinel.length === 1) return byte === sentinel[0];
|
||||
return containsBytes(arr, sentinel, index);
|
||||
});
|
||||
}
|
||||
function hexBytes(bytes) {
|
||||
return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
|
||||
}
|
||||
function assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {
|
||||
if (bytes.length - offset <= 0) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, {
|
||||
codecDescription
|
||||
});
|
||||
}
|
||||
}
|
||||
function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {
|
||||
const bytesLength = bytes.length - offset;
|
||||
if (bytesLength < expected) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {
|
||||
bytesLength,
|
||||
codecDescription,
|
||||
expected
|
||||
});
|
||||
}
|
||||
}
|
||||
function assertByteArrayOffsetIsNotOutOfRange(codecDescription, offset, bytesLength) {
|
||||
if (offset < 0 || offset > bytesLength) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, {
|
||||
bytesLength,
|
||||
codecDescription,
|
||||
offset
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// src/add-codec-size-prefix.ts
|
||||
function addEncoderSizePrefix(encoder, prefix) {
|
||||
const write = (value, bytes, offset) => {
|
||||
const encoderBytes = encoder.encode(value);
|
||||
offset = prefix.write(encoderBytes.length, bytes, offset);
|
||||
bytes.set(encoderBytes, offset);
|
||||
return offset + encoderBytes.length;
|
||||
};
|
||||
if (isFixedSize(prefix) && isFixedSize(encoder)) {
|
||||
return createEncoder({ ...encoder, fixedSize: prefix.fixedSize + encoder.fixedSize, write });
|
||||
}
|
||||
const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
|
||||
const encoderMaxSize = isFixedSize(encoder) ? encoder.fixedSize : encoder.maxSize ?? null;
|
||||
const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;
|
||||
return createEncoder({
|
||||
...encoder,
|
||||
...maxSize !== null ? { maxSize } : {},
|
||||
getSizeFromValue: (value) => {
|
||||
const encoderSize = getEncodedSize(value, encoder);
|
||||
return getEncodedSize(encoderSize, prefix) + encoderSize;
|
||||
},
|
||||
write
|
||||
});
|
||||
}
|
||||
function addDecoderSizePrefix(decoder, prefix) {
|
||||
const read = (bytes, offset) => {
|
||||
const [bigintSize, decoderOffset] = prefix.read(bytes, offset);
|
||||
const size = Number(bigintSize);
|
||||
offset = decoderOffset;
|
||||
if (offset > 0 || bytes.length > size) {
|
||||
bytes = bytes.slice(offset, offset + size);
|
||||
}
|
||||
assertByteArrayHasEnoughBytesForCodec("addDecoderSizePrefix", size, bytes);
|
||||
return [decoder.decode(bytes), offset + size];
|
||||
};
|
||||
if (isFixedSize(prefix) && isFixedSize(decoder)) {
|
||||
return createDecoder({ ...decoder, fixedSize: prefix.fixedSize + decoder.fixedSize, read });
|
||||
}
|
||||
const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
|
||||
const decoderMaxSize = isFixedSize(decoder) ? decoder.fixedSize : decoder.maxSize ?? null;
|
||||
const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;
|
||||
return createDecoder({ ...decoder, ...maxSize !== null ? { maxSize } : {}, read });
|
||||
}
|
||||
function addCodecSizePrefix(codec, prefix) {
|
||||
return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));
|
||||
}
|
||||
|
||||
// src/fix-codec-size.ts
|
||||
function fixEncoderSize(encoder, fixedBytes) {
|
||||
return createEncoder({
|
||||
fixedSize: fixedBytes,
|
||||
write: (value, bytes, offset) => {
|
||||
const variableByteArray = encoder.encode(value);
|
||||
const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;
|
||||
bytes.set(fixedByteArray, offset);
|
||||
return offset + fixedBytes;
|
||||
}
|
||||
});
|
||||
}
|
||||
function fixDecoderSize(decoder, fixedBytes) {
|
||||
return createDecoder({
|
||||
fixedSize: fixedBytes,
|
||||
read: (bytes, offset) => {
|
||||
assertByteArrayHasEnoughBytesForCodec("fixCodecSize", fixedBytes, bytes, offset);
|
||||
if (offset > 0 || bytes.length > fixedBytes) {
|
||||
bytes = bytes.slice(offset, offset + fixedBytes);
|
||||
}
|
||||
if (isFixedSize(decoder)) {
|
||||
bytes = fixBytes(bytes, decoder.fixedSize);
|
||||
}
|
||||
const [value] = decoder.read(bytes, 0);
|
||||
return [value, offset + fixedBytes];
|
||||
}
|
||||
});
|
||||
}
|
||||
function fixCodecSize(codec, fixedBytes) {
|
||||
return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(codec, fixedBytes));
|
||||
}
|
||||
|
||||
// src/offset-codec.ts
|
||||
function offsetEncoder(encoder, config) {
|
||||
return createEncoder({
|
||||
...encoder,
|
||||
write: (value, bytes, preOffset) => {
|
||||
const wrapBytes = (offset) => modulo(offset, bytes.length);
|
||||
const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;
|
||||
assertByteArrayOffsetIsNotOutOfRange("offsetEncoder", newPreOffset, bytes.length);
|
||||
const postOffset = encoder.write(value, bytes, newPreOffset);
|
||||
const newPostOffset = config.postOffset ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes }) : postOffset;
|
||||
assertByteArrayOffsetIsNotOutOfRange("offsetEncoder", newPostOffset, bytes.length);
|
||||
return newPostOffset;
|
||||
}
|
||||
});
|
||||
}
|
||||
function offsetDecoder(decoder, config) {
|
||||
return createDecoder({
|
||||
...decoder,
|
||||
read: (bytes, preOffset) => {
|
||||
const wrapBytes = (offset) => modulo(offset, bytes.length);
|
||||
const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;
|
||||
assertByteArrayOffsetIsNotOutOfRange("offsetDecoder", newPreOffset, bytes.length);
|
||||
const [value, postOffset] = decoder.read(bytes, newPreOffset);
|
||||
const newPostOffset = config.postOffset ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes }) : postOffset;
|
||||
assertByteArrayOffsetIsNotOutOfRange("offsetDecoder", newPostOffset, bytes.length);
|
||||
return [value, newPostOffset];
|
||||
}
|
||||
});
|
||||
}
|
||||
function offsetCodec(codec, config) {
|
||||
return combineCodec(offsetEncoder(codec, config), offsetDecoder(codec, config));
|
||||
}
|
||||
function modulo(dividend, divisor) {
|
||||
if (divisor === 0) return 0;
|
||||
return (dividend % divisor + divisor) % divisor;
|
||||
}
|
||||
function resizeEncoder(encoder, resize) {
|
||||
if (isFixedSize(encoder)) {
|
||||
const fixedSize = resize(encoder.fixedSize);
|
||||
if (fixedSize < 0) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {
|
||||
bytesLength: fixedSize,
|
||||
codecDescription: "resizeEncoder"
|
||||
});
|
||||
}
|
||||
return createEncoder({ ...encoder, fixedSize });
|
||||
}
|
||||
return createEncoder({
|
||||
...encoder,
|
||||
getSizeFromValue: (value) => {
|
||||
const newSize = resize(encoder.getSizeFromValue(value));
|
||||
if (newSize < 0) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {
|
||||
bytesLength: newSize,
|
||||
codecDescription: "resizeEncoder"
|
||||
});
|
||||
}
|
||||
return newSize;
|
||||
}
|
||||
});
|
||||
}
|
||||
function resizeDecoder(decoder, resize) {
|
||||
if (isFixedSize(decoder)) {
|
||||
const fixedSize = resize(decoder.fixedSize);
|
||||
if (fixedSize < 0) {
|
||||
throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {
|
||||
bytesLength: fixedSize,
|
||||
codecDescription: "resizeDecoder"
|
||||
});
|
||||
}
|
||||
return createDecoder({ ...decoder, fixedSize });
|
||||
}
|
||||
return decoder;
|
||||
}
|
||||
function resizeCodec(codec, resize) {
|
||||
return combineCodec(resizeEncoder(codec, resize), resizeDecoder(codec, resize));
|
||||
}
|
||||
|
||||
// src/pad-codec.ts
|
||||
function padLeftEncoder(encoder, offset) {
|
||||
return offsetEncoder(
|
||||
resizeEncoder(encoder, (size) => size + offset),
|
||||
{ preOffset: ({ preOffset }) => preOffset + offset }
|
||||
);
|
||||
}
|
||||
function padRightEncoder(encoder, offset) {
|
||||
return offsetEncoder(
|
||||
resizeEncoder(encoder, (size) => size + offset),
|
||||
{ postOffset: ({ postOffset }) => postOffset + offset }
|
||||
);
|
||||
}
|
||||
function padLeftDecoder(decoder, offset) {
|
||||
return offsetDecoder(
|
||||
resizeDecoder(decoder, (size) => size + offset),
|
||||
{ preOffset: ({ preOffset }) => preOffset + offset }
|
||||
);
|
||||
}
|
||||
function padRightDecoder(decoder, offset) {
|
||||
return offsetDecoder(
|
||||
resizeDecoder(decoder, (size) => size + offset),
|
||||
{ postOffset: ({ postOffset }) => postOffset + offset }
|
||||
);
|
||||
}
|
||||
function padLeftCodec(codec, offset) {
|
||||
return combineCodec(padLeftEncoder(codec, offset), padLeftDecoder(codec, offset));
|
||||
}
|
||||
function padRightCodec(codec, offset) {
|
||||
return combineCodec(padRightEncoder(codec, offset), padRightDecoder(codec, offset));
|
||||
}
|
||||
|
||||
// src/reverse-codec.ts
|
||||
function copySourceToTargetInReverse(source, target_WILL_MUTATE, sourceOffset, sourceLength, targetOffset = 0) {
|
||||
while (sourceOffset < --sourceLength) {
|
||||
const leftValue = source[sourceOffset];
|
||||
target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceLength];
|
||||
target_WILL_MUTATE[sourceLength + targetOffset] = leftValue;
|
||||
sourceOffset++;
|
||||
}
|
||||
if (sourceOffset === sourceLength) {
|
||||
target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceOffset];
|
||||
}
|
||||
}
|
||||
function reverseEncoder(encoder) {
|
||||
assertIsFixedSize(encoder);
|
||||
return createEncoder({
|
||||
...encoder,
|
||||
write: (value, bytes, offset) => {
|
||||
const newOffset = encoder.write(value, bytes, offset);
|
||||
copySourceToTargetInReverse(
|
||||
bytes,
|
||||
bytes,
|
||||
offset,
|
||||
offset + encoder.fixedSize
|
||||
);
|
||||
return newOffset;
|
||||
}
|
||||
});
|
||||
}
|
||||
function reverseDecoder(decoder) {
|
||||
assertIsFixedSize(decoder);
|
||||
return createDecoder({
|
||||
...decoder,
|
||||
read: (bytes, offset) => {
|
||||
const reversedBytes = bytes.slice();
|
||||
copySourceToTargetInReverse(
|
||||
bytes,
|
||||
reversedBytes,
|
||||
offset,
|
||||
offset + decoder.fixedSize
|
||||
);
|
||||
return decoder.read(reversedBytes, offset);
|
||||
}
|
||||
});
|
||||
}
|
||||
function reverseCodec(codec) {
|
||||
return combineCodec(reverseEncoder(codec), reverseDecoder(codec));
|
||||
}
|
||||
|
||||
// src/transform-codec.ts
|
||||
function transformEncoder(encoder, unmap) {
|
||||
return createEncoder({
|
||||
...isVariableSize(encoder) ? { ...encoder, getSizeFromValue: (value) => encoder.getSizeFromValue(unmap(value)) } : encoder,
|
||||
write: (value, bytes, offset) => encoder.write(unmap(value), bytes, offset)
|
||||
});
|
||||
}
|
||||
function transformDecoder(decoder, map) {
|
||||
return createDecoder({
|
||||
...decoder,
|
||||
read: (bytes, offset) => {
|
||||
const [value, newOffset] = decoder.read(bytes, offset);
|
||||
return [map(value, bytes, offset), newOffset];
|
||||
}
|
||||
});
|
||||
}
|
||||
function transformCodec(codec, unmap, map) {
|
||||
return createCodec({
|
||||
...transformEncoder(codec, unmap),
|
||||
read: map ? transformDecoder(codec, map).read : codec.read
|
||||
});
|
||||
}
|
||||
|
||||
export { addCodecSentinel, addCodecSizePrefix, addDecoderSentinel, addDecoderSizePrefix, addEncoderSentinel, addEncoderSizePrefix, assertByteArrayHasEnoughBytesForCodec, assertByteArrayIsNotEmptyForCodec, assertByteArrayOffsetIsNotOutOfRange, assertIsFixedSize, assertIsVariableSize, combineCodec, containsBytes, createCodec, createDecoder, createEncoder, fixBytes, fixCodecSize, fixDecoderSize, fixEncoderSize, getEncodedSize, isFixedSize, isVariableSize, mergeBytes, offsetCodec, offsetDecoder, offsetEncoder, padBytes, padLeftCodec, padLeftDecoder, padLeftEncoder, padRightCodec, padRightDecoder, padRightEncoder, resizeCodec, resizeDecoder, resizeEncoder, reverseCodec, reverseDecoder, reverseEncoder, transformCodec, transformDecoder, transformEncoder };
|
||||
//# sourceMappingURL=index.browser.mjs.map
|
||||
//# sourceMappingURL=index.browser.mjs.map
|
||||
@@ -0,0 +1,4 @@
|
||||
function _nonIterableSpread() {
|
||||
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
||||
}
|
||||
export { _nonIterableSpread as default };
|
||||
@@ -0,0 +1,27 @@
|
||||
type VisitorKeys$1 = {
|
||||
readonly [type: string]: readonly string[];
|
||||
};
|
||||
/**
|
||||
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
|
||||
*/
|
||||
/**
|
||||
* @type {VisitorKeys}
|
||||
*/
|
||||
declare const KEYS: VisitorKeys$1;
|
||||
|
||||
/**
|
||||
* Get visitor keys of a given node.
|
||||
* @param {object} node The AST node to get keys.
|
||||
* @returns {readonly string[]} Visitor keys of the node.
|
||||
*/
|
||||
declare function getKeys(node: object): readonly string[];
|
||||
/**
|
||||
* Make the union set with `KEYS` and given keys.
|
||||
* @param {VisitorKeys} additionalKeys The additional keys.
|
||||
* @returns {VisitorKeys} The union set.
|
||||
*/
|
||||
declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys;
|
||||
|
||||
type VisitorKeys = VisitorKeys$1;
|
||||
|
||||
export { KEYS, VisitorKeys, getKeys, unionWith };
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"sha3.d.ts","sourceRoot":"","sources":["../src/sha3.ts"],"names":[],"mappings":"AAaA,OAAO,EAE6B,IAAI,EAGtC,KAAK,KAAK,EAAE,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,KAAK,EACnD,MAAM,YAAY,CAAC;AAoCpB,kFAAkF;AAClF,wBAAgB,OAAO,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,GAAE,MAAW,GAAG,IAAI,CAyCjE;AAED,8BAA8B;AAC9B,qBAAa,MAAO,SAAQ,IAAI,CAAC,MAAM,CAAE,YAAW,OAAO,CAAC,MAAM,CAAC;IACjE,SAAS,CAAC,KAAK,EAAE,UAAU,CAAC;IAC5B,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,OAAO,EAAE,WAAW,CAAC;IAC/B,SAAS,CAAC,SAAS,UAAS;IAErB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,SAAS,UAAS;IAC5B,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;gBAIvB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,SAAS,UAAQ,EACjB,MAAM,GAAE,MAAW;IAiBrB,KAAK,IAAI,MAAM;IAGf,SAAS,CAAC,MAAM,IAAI,IAAI;IAOxB,MAAM,CAAC,IAAI,EAAE,KAAK,GAAG,IAAI;IAazB,SAAS,CAAC,MAAM,IAAI,IAAI;IAUxB,SAAS,CAAC,SAAS,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU;IAehD,OAAO,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU;IAKpC,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU;IAI9B,UAAU,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU;IAOvC,MAAM,IAAI,UAAU;IAGpB,OAAO,IAAI,IAAI;IAIf,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM;CAehC;AAKD,8BAA8B;AAC9B,eAAO,MAAM,QAAQ,EAAE,KAAyD,CAAC;AACjF,yDAAyD;AACzD,eAAO,MAAM,QAAQ,EAAE,KAAyD,CAAC;AACjF,8BAA8B;AAC9B,eAAO,MAAM,QAAQ,EAAE,KAAyD,CAAC;AACjF,8BAA8B;AAC9B,eAAO,MAAM,QAAQ,EAAE,KAAwD,CAAC;AAEhF,gCAAgC;AAChC,eAAO,MAAM,UAAU,EAAE,KAAyD,CAAC;AACnF,yDAAyD;AACzD,eAAO,MAAM,UAAU,EAAE,KAAyD,CAAC;AACnF,gCAAgC;AAChC,eAAO,MAAM,UAAU,EAAE,KAAyD,CAAC;AACnF,gCAAgC;AAChC,eAAO,MAAM,UAAU,EAAE,KAAwD,CAAC;AAElF,MAAM,MAAM,SAAS,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAQ3C,0CAA0C;AAC1C,eAAO,MAAM,QAAQ,EAAE,OAAgE,CAAC;AACxF,0CAA0C;AAC1C,eAAO,MAAM,QAAQ,EAAE,OAAgE,CAAC"}
|
||||
@@ -0,0 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
function _non_iterable_spread() {
|
||||
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
||||
}
|
||||
exports._ = _non_iterable_spread;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"jsxEmit.enum.js","sourceRoot":"","sources":["../../src/enums/jsxEmit.enum.ts"],"names":[],"mappings":"AAAA,sGAAsG;AAEtG,MAAM,CAAN,IAAY,OAOX;AAPD,WAAY,OAAO;IACf,qCAAQ,CAAA;IACR,6CAAY,CAAA;IACZ,mDAAe,CAAA;IACf,uCAAS,CAAA;IACT,6CAAY,CAAA;IACZ,mDAAe,CAAA;AACnB,CAAC,EAPW,OAAO,KAAP,OAAO,QAOlB"}
|
||||
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.escape = void 0;
|
||||
/**
|
||||
* Escape all magic characters in a glob pattern.
|
||||
*
|
||||
* If the {@link MinimatchOptions.windowsPathsNoEscape}
|
||||
* option is used, then characters are escaped by wrapping in `[]`, because
|
||||
* a magic character wrapped in a character class can only be satisfied by
|
||||
* that exact character. In this mode, `\` is _not_ escaped, because it is
|
||||
* not interpreted as a magic character, but instead as a path separator.
|
||||
*
|
||||
* If the {@link MinimatchOptions.magicalBraces} option is used,
|
||||
* then braces (`{` and `}`) will be escaped.
|
||||
*/
|
||||
const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
|
||||
// don't need to escape +@! because we escape the parens
|
||||
// that make those magic, and escaping ! as [!] isn't valid,
|
||||
// because [!]] is a valid glob class meaning not ']'.
|
||||
if (magicalBraces) {
|
||||
return windowsPathsNoEscape ?
|
||||
s.replace(/[?*()[\]{}]/g, '[$&]')
|
||||
: s.replace(/[?*()[\]\\{}]/g, '\\$&');
|
||||
}
|
||||
return windowsPathsNoEscape ?
|
||||
s.replace(/[?*()[\]]/g, '[$&]')
|
||||
: s.replace(/[?*()[\]\\]/g, '\\$&');
|
||||
};
|
||||
exports.escape = escape;
|
||||
//# sourceMappingURL=escape.js.map
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_non_iterable_rest.cjs",
|
||||
"module": "../../esm/_non_iterable_rest.js"
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "delay",
|
||||
"version": "5.0.0",
|
||||
"description": "Delay a promise a specified amount of time",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/delay",
|
||||
"funding": "https://github.com/sponsors/sindresorhus",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "https://sindresorhus.com"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && ava && tsd"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts"
|
||||
],
|
||||
"keywords": [
|
||||
"promise",
|
||||
"resolve",
|
||||
"delay",
|
||||
"defer",
|
||||
"wait",
|
||||
"stall",
|
||||
"timeout",
|
||||
"settimeout",
|
||||
"event",
|
||||
"loop",
|
||||
"next",
|
||||
"tick",
|
||||
"delay",
|
||||
"async",
|
||||
"await",
|
||||
"promises",
|
||||
"bluebird",
|
||||
"threshold",
|
||||
"range",
|
||||
"random"
|
||||
],
|
||||
"devDependencies": {
|
||||
"abort-controller": "^3.0.0",
|
||||
"ava": "1.4.1",
|
||||
"currently-unhandled": "^0.4.1",
|
||||
"in-range": "^1.0.0",
|
||||
"time-span": "^3.0.0",
|
||||
"tsd": "^0.7.1",
|
||||
"xo": "^0.24.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "yocto-queue",
|
||||
"version": "0.1.0",
|
||||
"description": "Tiny queue data structure",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/yocto-queue",
|
||||
"funding": "https://github.com/sponsors/sindresorhus",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "https://sindresorhus.com"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && ava && tsd"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts"
|
||||
],
|
||||
"keywords": [
|
||||
"queue",
|
||||
"data",
|
||||
"structure",
|
||||
"algorithm",
|
||||
"queues",
|
||||
"queuing",
|
||||
"list",
|
||||
"array",
|
||||
"linkedlist",
|
||||
"fifo",
|
||||
"enqueue",
|
||||
"dequeue",
|
||||
"data-structure"
|
||||
],
|
||||
"devDependencies": {
|
||||
"ava": "^2.4.0",
|
||||
"tsd": "^0.13.1",
|
||||
"xo": "^0.35.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// ESM wrapper for pg-connection-string
|
||||
import connectionString from '../index.js'
|
||||
|
||||
// Re-export the parse function
|
||||
export default connectionString.parse
|
||||
export const parse = connectionString.parse
|
||||
export const toClientConfig = connectionString.toClientConfig
|
||||
export const parseIntoClientConfig = connectionString.parseIntoClientConfig
|
||||
@@ -0,0 +1,2 @@
|
||||
declare function version(uuid: string): number;
|
||||
export default version;
|
||||
@@ -0,0 +1,695 @@
|
||||
/**
|
||||
* @fileoverview Object to handle access and retrieval of tokens.
|
||||
* @author Brandon Mills
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const { isCommentToken } = require("@eslint-community/eslint-utils");
|
||||
const assert = require("../../../../shared/assert");
|
||||
const cursors = require("./cursors");
|
||||
const ForwardTokenCursor = require("./forward-token-cursor");
|
||||
const PaddedTokenCursor = require("./padded-token-cursor");
|
||||
const utils = require("./utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const TOKENS = Symbol("tokens");
|
||||
const COMMENTS = Symbol("comments");
|
||||
const INDEX_MAP = Symbol("indexMap");
|
||||
|
||||
/**
|
||||
* Creates the map from locations to indices in `tokens`.
|
||||
*
|
||||
* The first/last location of tokens is mapped to the index of the token.
|
||||
* The first/last location of comments is mapped to the index of the next token of each comment.
|
||||
* @param {Token[]} tokens The array of tokens.
|
||||
* @param {Comment[]} comments The array of comments.
|
||||
* @returns {Object} The map from locations to indices in `tokens`.
|
||||
* @private
|
||||
*/
|
||||
function createIndexMap(tokens, comments) {
|
||||
const map = Object.create(null);
|
||||
let tokenIndex = 0;
|
||||
let commentIndex = 0;
|
||||
let nextStart;
|
||||
let range;
|
||||
|
||||
while (tokenIndex < tokens.length || commentIndex < comments.length) {
|
||||
nextStart =
|
||||
commentIndex < comments.length
|
||||
? comments[commentIndex].range[0]
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
while (
|
||||
tokenIndex < tokens.length &&
|
||||
(range = tokens[tokenIndex].range)[0] < nextStart
|
||||
) {
|
||||
map[range[0]] = tokenIndex;
|
||||
map[range[1] - 1] = tokenIndex;
|
||||
tokenIndex += 1;
|
||||
}
|
||||
|
||||
nextStart =
|
||||
tokenIndex < tokens.length
|
||||
? tokens[tokenIndex].range[0]
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
while (
|
||||
commentIndex < comments.length &&
|
||||
(range = comments[commentIndex].range)[0] < nextStart
|
||||
) {
|
||||
map[range[0]] = tokenIndex;
|
||||
map[range[1] - 1] = tokenIndex;
|
||||
commentIndex += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the cursor iterates tokens with options.
|
||||
* @param {CursorFactory} factory The cursor factory to initialize cursor.
|
||||
* @param {Token[]} tokens The array of tokens.
|
||||
* @param {Comment[]} comments The array of comments.
|
||||
* @param {Object} indexMap The map from locations to indices in `tokens`.
|
||||
* @param {number} startLoc The start location of the iteration range.
|
||||
* @param {number} endLoc The end location of the iteration range.
|
||||
* @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.skip`. If this is a function then it's `opts.filter`.
|
||||
* @param {boolean} [opts.includeComments=false] The flag to iterate comments as well.
|
||||
* @param {Function|null} [opts.filter=null] The predicate function to choose tokens.
|
||||
* @param {number} [opts.skip=0] The count of tokens the cursor skips.
|
||||
* @returns {Cursor} The created cursor.
|
||||
* @private
|
||||
*/
|
||||
function createCursorWithSkip(
|
||||
factory,
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
opts,
|
||||
) {
|
||||
let includeComments = false;
|
||||
let skip = 0;
|
||||
let filter = null;
|
||||
|
||||
if (typeof opts === "number") {
|
||||
skip = opts | 0;
|
||||
} else if (typeof opts === "function") {
|
||||
filter = opts;
|
||||
} else if (opts) {
|
||||
includeComments = !!opts.includeComments;
|
||||
skip = opts.skip | 0;
|
||||
filter = opts.filter || null;
|
||||
}
|
||||
assert(skip >= 0, "options.skip should be zero or a positive integer.");
|
||||
assert(
|
||||
!filter || typeof filter === "function",
|
||||
"options.filter should be a function.",
|
||||
);
|
||||
|
||||
return factory.createCursor(
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
includeComments,
|
||||
filter,
|
||||
skip,
|
||||
-1,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the cursor iterates tokens with options.
|
||||
* @param {CursorFactory} factory The cursor factory to initialize cursor.
|
||||
* @param {Token[]} tokens The array of tokens.
|
||||
* @param {Comment[]} comments The array of comments.
|
||||
* @param {Object} indexMap The map from locations to indices in `tokens`.
|
||||
* @param {number} startLoc The start location of the iteration range.
|
||||
* @param {number} endLoc The end location of the iteration range.
|
||||
* @param {number|Function|Object} [opts=0] The option object. If this is a number then it's `opts.count`. If this is a function then it's `opts.filter`.
|
||||
* @param {boolean} [opts.includeComments] The flag to iterate comments as well.
|
||||
* @param {Function|null} [opts.filter=null] The predicate function to choose tokens.
|
||||
* @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility.
|
||||
* @returns {Cursor} The created cursor.
|
||||
* @private
|
||||
*/
|
||||
function createCursorWithCount(
|
||||
factory,
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
opts,
|
||||
) {
|
||||
let includeComments = false;
|
||||
let count = 0;
|
||||
let countExists = false;
|
||||
let filter = null;
|
||||
|
||||
if (typeof opts === "number") {
|
||||
count = opts | 0;
|
||||
countExists = true;
|
||||
} else if (typeof opts === "function") {
|
||||
filter = opts;
|
||||
} else if (opts) {
|
||||
includeComments = !!opts.includeComments;
|
||||
count = opts.count | 0;
|
||||
countExists = typeof opts.count === "number";
|
||||
filter = opts.filter || null;
|
||||
}
|
||||
assert(count >= 0, "options.count should be zero or a positive integer.");
|
||||
assert(
|
||||
!filter || typeof filter === "function",
|
||||
"options.filter should be a function.",
|
||||
);
|
||||
|
||||
return factory.createCursor(
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
includeComments,
|
||||
filter,
|
||||
0,
|
||||
countExists ? count : -1,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the cursor iterates tokens with options.
|
||||
* This is overload function of the below.
|
||||
* @param {Token[]} tokens The array of tokens.
|
||||
* @param {Comment[]} comments The array of comments.
|
||||
* @param {Object} indexMap The map from locations to indices in `tokens`.
|
||||
* @param {number} startLoc The start location of the iteration range.
|
||||
* @param {number} endLoc The end location of the iteration range.
|
||||
* @param {Function|Object} opts The option object. If this is a function then it's `opts.filter`.
|
||||
* @param {boolean} [opts.includeComments] The flag to iterate comments as well.
|
||||
* @param {Function|null} [opts.filter=null] The predicate function to choose tokens.
|
||||
* @param {number} [opts.count=0] The maximum count of tokens the cursor iterates. Zero is no iteration for backward compatibility.
|
||||
* @returns {Cursor} The created cursor.
|
||||
* @private
|
||||
*/
|
||||
/**
|
||||
* Creates the cursor iterates tokens with options.
|
||||
* @param {Token[]} tokens The array of tokens.
|
||||
* @param {Comment[]} comments The array of comments.
|
||||
* @param {Object} indexMap The map from locations to indices in `tokens`.
|
||||
* @param {number} startLoc The start location of the iteration range.
|
||||
* @param {number} endLoc The end location of the iteration range.
|
||||
* @param {number} [beforeCount=0] The number of tokens before the node to retrieve.
|
||||
* @param {boolean} [afterCount=0] The number of tokens after the node to retrieve.
|
||||
* @returns {Cursor} The created cursor.
|
||||
* @private
|
||||
*/
|
||||
function createCursorWithPadding(
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
beforeCount,
|
||||
afterCount,
|
||||
) {
|
||||
if (
|
||||
typeof beforeCount === "undefined" &&
|
||||
typeof afterCount === "undefined"
|
||||
) {
|
||||
return new ForwardTokenCursor(
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
);
|
||||
}
|
||||
if (typeof beforeCount === "number" || typeof beforeCount === "undefined") {
|
||||
return new PaddedTokenCursor(
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
beforeCount | 0,
|
||||
afterCount | 0,
|
||||
);
|
||||
}
|
||||
return createCursorWithCount(
|
||||
cursors.forward,
|
||||
tokens,
|
||||
comments,
|
||||
indexMap,
|
||||
startLoc,
|
||||
endLoc,
|
||||
beforeCount,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets comment tokens that are adjacent to the current cursor position.
|
||||
* @param {Cursor} cursor A cursor instance.
|
||||
* @returns {Array} An array of comment tokens adjacent to the current cursor position.
|
||||
* @private
|
||||
*/
|
||||
function getAdjacentCommentTokensFromCursor(cursor) {
|
||||
const tokens = [];
|
||||
let currentToken = cursor.getOneToken();
|
||||
|
||||
while (currentToken && isCommentToken(currentToken)) {
|
||||
tokens.push(currentToken);
|
||||
currentToken = cursor.getOneToken();
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Exports
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The token store.
|
||||
*
|
||||
* This class provides methods to get tokens by locations as fast as possible.
|
||||
* The methods are a part of public API, so we should be careful if it changes this class.
|
||||
*
|
||||
* People can get tokens in O(1) by the hash map which is mapping from the location of tokens/comments to tokens.
|
||||
* Also people can get a mix of tokens and comments in O(log k), the k is the number of comments.
|
||||
* Assuming that comments to be much fewer than tokens, this does not make hash map from token's locations to comments to reduce memory cost.
|
||||
* This uses binary-searching instead for comments.
|
||||
*/
|
||||
module.exports = class TokenStore {
|
||||
/**
|
||||
* Initializes this token store.
|
||||
* @param {Token[]} tokens The array of tokens.
|
||||
* @param {Comment[]} comments The array of comments.
|
||||
*/
|
||||
constructor(tokens, comments) {
|
||||
this[TOKENS] = tokens;
|
||||
this[COMMENTS] = comments;
|
||||
this[INDEX_MAP] = createIndexMap(tokens, comments);
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Gets single token.
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Gets the token starting at the specified index.
|
||||
* @param {number} offset Index of the start of the token's range.
|
||||
* @param {Object} [options=0] The option object.
|
||||
* @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
|
||||
* @returns {Token|null} The token starting at index, or null if no such token.
|
||||
*/
|
||||
getTokenByRangeStart(offset, options) {
|
||||
const includeComments = options && options.includeComments;
|
||||
const token = cursors.forward
|
||||
.createBaseCursor(
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
offset,
|
||||
-1,
|
||||
includeComments,
|
||||
)
|
||||
.getOneToken();
|
||||
|
||||
if (token && token.range[0] === offset) {
|
||||
return token;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the first token of the given node.
|
||||
* @param {ASTNode} node The AST node.
|
||||
* @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.skip`. If this is a function then it's `options.filter`.
|
||||
* @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
|
||||
* @param {Function|null} [options.filter=null] The predicate function to choose tokens.
|
||||
* @param {number} [options.skip=0] The count of tokens the cursor skips.
|
||||
* @returns {Token|null} An object representing the token.
|
||||
*/
|
||||
getFirstToken(node, options) {
|
||||
return createCursorWithSkip(
|
||||
cursors.forward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
node.range[0],
|
||||
node.range[1],
|
||||
options,
|
||||
).getOneToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the last token of the given node.
|
||||
* @param {ASTNode} node The AST node.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
|
||||
* @returns {Token|null} An object representing the token.
|
||||
*/
|
||||
getLastToken(node, options) {
|
||||
return createCursorWithSkip(
|
||||
cursors.backward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
node.range[0],
|
||||
node.range[1],
|
||||
options,
|
||||
).getOneToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the token that precedes a given node or token.
|
||||
* @param {ASTNode|Token|Comment} node The AST node or token.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
|
||||
* @returns {Token|null} An object representing the token.
|
||||
*/
|
||||
getTokenBefore(node, options) {
|
||||
return createCursorWithSkip(
|
||||
cursors.backward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
-1,
|
||||
node.range[0],
|
||||
options,
|
||||
).getOneToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the token that follows a given node or token.
|
||||
* @param {ASTNode|Token|Comment} node The AST node or token.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
|
||||
* @returns {Token|null} An object representing the token.
|
||||
*/
|
||||
getTokenAfter(node, options) {
|
||||
return createCursorWithSkip(
|
||||
cursors.forward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
node.range[1],
|
||||
-1,
|
||||
options,
|
||||
).getOneToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the first token between two non-overlapping nodes.
|
||||
* @param {ASTNode|Token|Comment} left Node before the desired token range.
|
||||
* @param {ASTNode|Token|Comment} right Node after the desired token range.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
|
||||
* @returns {Token|null} An object representing the token.
|
||||
*/
|
||||
getFirstTokenBetween(left, right, options) {
|
||||
return createCursorWithSkip(
|
||||
cursors.forward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
left.range[1],
|
||||
right.range[0],
|
||||
options,
|
||||
).getOneToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the last token between two non-overlapping nodes.
|
||||
* @param {ASTNode|Token|Comment} left Node before the desired token range.
|
||||
* @param {ASTNode|Token|Comment} right Node after the desired token range.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstToken()
|
||||
* @returns {Token|null} An object representing the token.
|
||||
*/
|
||||
getLastTokenBetween(left, right, options) {
|
||||
return createCursorWithSkip(
|
||||
cursors.backward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
left.range[1],
|
||||
right.range[0],
|
||||
options,
|
||||
).getOneToken();
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Gets multiple tokens.
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Gets the first `count` tokens of the given node.
|
||||
* @param {ASTNode} node The AST node.
|
||||
* @param {number|Function|Object} [options=0] The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`.
|
||||
* @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
|
||||
* @param {Function|null} [options.filter=null] The predicate function to choose tokens.
|
||||
* @param {number} [options.count=0] The maximum count of tokens the cursor iterates.
|
||||
* @returns {Token[]} Tokens.
|
||||
*/
|
||||
getFirstTokens(node, options) {
|
||||
return createCursorWithCount(
|
||||
cursors.forward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
node.range[0],
|
||||
node.range[1],
|
||||
options,
|
||||
).getAllTokens();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the last `count` tokens of the given node.
|
||||
* @param {ASTNode} node The AST node.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
|
||||
* @returns {Token[]} Tokens.
|
||||
*/
|
||||
getLastTokens(node, options) {
|
||||
return createCursorWithCount(
|
||||
cursors.backward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
node.range[0],
|
||||
node.range[1],
|
||||
options,
|
||||
)
|
||||
.getAllTokens()
|
||||
.reverse();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the `count` tokens that precedes a given node or token.
|
||||
* @param {ASTNode|Token|Comment} node The AST node or token.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
|
||||
* @returns {Token[]} Tokens.
|
||||
*/
|
||||
getTokensBefore(node, options) {
|
||||
return createCursorWithCount(
|
||||
cursors.backward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
-1,
|
||||
node.range[0],
|
||||
options,
|
||||
)
|
||||
.getAllTokens()
|
||||
.reverse();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the `count` tokens that follows a given node or token.
|
||||
* @param {ASTNode|Token|Comment} node The AST node or token.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
|
||||
* @returns {Token[]} Tokens.
|
||||
*/
|
||||
getTokensAfter(node, options) {
|
||||
return createCursorWithCount(
|
||||
cursors.forward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
node.range[1],
|
||||
-1,
|
||||
options,
|
||||
).getAllTokens();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the first `count` tokens between two non-overlapping nodes.
|
||||
* @param {ASTNode|Token|Comment} left Node before the desired token range.
|
||||
* @param {ASTNode|Token|Comment} right Node after the desired token range.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
|
||||
* @returns {Token[]} Tokens between left and right.
|
||||
*/
|
||||
getFirstTokensBetween(left, right, options) {
|
||||
return createCursorWithCount(
|
||||
cursors.forward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
left.range[1],
|
||||
right.range[0],
|
||||
options,
|
||||
).getAllTokens();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the last `count` tokens between two non-overlapping nodes.
|
||||
* @param {ASTNode|Token|Comment} left Node before the desired token range.
|
||||
* @param {ASTNode|Token|Comment} right Node after the desired token range.
|
||||
* @param {number|Function|Object} [options=0] The option object. Same options as getFirstTokens()
|
||||
* @returns {Token[]} Tokens between left and right.
|
||||
*/
|
||||
getLastTokensBetween(left, right, options) {
|
||||
return createCursorWithCount(
|
||||
cursors.backward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
left.range[1],
|
||||
right.range[0],
|
||||
options,
|
||||
)
|
||||
.getAllTokens()
|
||||
.reverse();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all tokens that are related to the given node.
|
||||
* @param {ASTNode} node The AST node.
|
||||
* @param {Function|Object} options The option object. If this is a function then it's `options.filter`.
|
||||
* @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
|
||||
* @param {Function|null} [options.filter=null] The predicate function to choose tokens.
|
||||
* @param {number} [options.count=0] The maximum count of tokens the cursor iterates.
|
||||
* @returns {Token[]} Array of objects representing tokens.
|
||||
*/
|
||||
/**
|
||||
* Gets all tokens that are related to the given node.
|
||||
* @param {ASTNode} node The AST node.
|
||||
* @param {number} [beforeCount=0] The number of tokens before the node to retrieve.
|
||||
* @param {number} [afterCount=0] The number of tokens after the node to retrieve.
|
||||
* @returns {Token[]} Array of objects representing tokens.
|
||||
*/
|
||||
getTokens(node, beforeCount, afterCount) {
|
||||
return createCursorWithPadding(
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
node.range[0],
|
||||
node.range[1],
|
||||
beforeCount,
|
||||
afterCount,
|
||||
).getAllTokens();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all of the tokens between two non-overlapping nodes.
|
||||
* @param {ASTNode|Token|Comment} left Node before the desired token range.
|
||||
* @param {ASTNode|Token|Comment} right Node after the desired token range.
|
||||
* @param {Function|Object} options The option object. If this is a function then it's `options.filter`.
|
||||
* @param {boolean} [options.includeComments=false] The flag to iterate comments as well.
|
||||
* @param {Function|null} [options.filter=null] The predicate function to choose tokens.
|
||||
* @param {number} [options.count=0] The maximum count of tokens the cursor iterates.
|
||||
* @returns {Token[]} Tokens between left and right.
|
||||
*/
|
||||
/**
|
||||
* Gets all of the tokens between two non-overlapping nodes.
|
||||
* @param {ASTNode|Token|Comment} left Node before the desired token range.
|
||||
* @param {ASTNode|Token|Comment} right Node after the desired token range.
|
||||
* @param {number} [padding=0] Number of extra tokens on either side of center.
|
||||
* @returns {Token[]} Tokens between left and right.
|
||||
*/
|
||||
getTokensBetween(left, right, padding) {
|
||||
return createCursorWithPadding(
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
left.range[1],
|
||||
right.range[0],
|
||||
padding,
|
||||
padding,
|
||||
).getAllTokens();
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Others.
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Checks whether any comments exist or not between the given 2 nodes.
|
||||
* @param {ASTNode} left The node to check.
|
||||
* @param {ASTNode} right The node to check.
|
||||
* @returns {boolean} `true` if one or more comments exist.
|
||||
*/
|
||||
commentsExistBetween(left, right) {
|
||||
const index = utils.search(this[COMMENTS], left.range[1]);
|
||||
|
||||
return (
|
||||
index < this[COMMENTS].length &&
|
||||
this[COMMENTS][index].range[1] <= right.range[0]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all comment tokens directly before the given node or token.
|
||||
* @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens.
|
||||
* @returns {Array} An array of comments in occurrence order.
|
||||
*/
|
||||
getCommentsBefore(nodeOrToken) {
|
||||
const cursor = createCursorWithCount(
|
||||
cursors.backward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
-1,
|
||||
nodeOrToken.range[0],
|
||||
{ includeComments: true },
|
||||
);
|
||||
|
||||
return getAdjacentCommentTokensFromCursor(cursor).reverse();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all comment tokens directly after the given node or token.
|
||||
* @param {ASTNode|token} nodeOrToken The AST node or token to check for adjacent comment tokens.
|
||||
* @returns {Array} An array of comments in occurrence order.
|
||||
*/
|
||||
getCommentsAfter(nodeOrToken) {
|
||||
const cursor = createCursorWithCount(
|
||||
cursors.forward,
|
||||
this[TOKENS],
|
||||
this[COMMENTS],
|
||||
this[INDEX_MAP],
|
||||
nodeOrToken.range[1],
|
||||
-1,
|
||||
{ includeComments: true },
|
||||
);
|
||||
|
||||
return getAdjacentCommentTokensFromCursor(cursor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all comment tokens inside the given node.
|
||||
* @param {ASTNode} node The AST node to get the comments for.
|
||||
* @returns {Array} An array of comments in occurrence order.
|
||||
*/
|
||||
getCommentsInside(node) {
|
||||
return this.getTokens(node, {
|
||||
includeComments: true,
|
||||
filter: isCommentToken,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
|
||||
function _class_apply_descriptor_set(receiver, descriptor, value) {
|
||||
if (descriptor.set) descriptor.set.call(receiver, value);
|
||||
else {
|
||||
if (!descriptor.writable) {
|
||||
// This should only throw in strict mode, but class bodies are
|
||||
// always strict and private fields can only be used inside
|
||||
// class bodies.
|
||||
throw new TypeError("attempted to set read only private field");
|
||||
}
|
||||
descriptor.value = value;
|
||||
}
|
||||
}
|
||||
exports._ = _class_apply_descriptor_set;
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* @fileoverview Rule to define spacing before/after arrow function's arrow.
|
||||
* @author Jxck
|
||||
* @deprecated in ESLint v8.53.0
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
const astUtils = require("./utils/ast-utils");
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// Rule Definition
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
/** @type {import('../types').Rule.RuleModule} */
|
||||
module.exports = {
|
||||
meta: {
|
||||
deprecated: {
|
||||
message: "Formatting rules are being moved out of ESLint core.",
|
||||
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
|
||||
deprecatedSince: "8.53.0",
|
||||
availableUntil: "11.0.0",
|
||||
replacedBy: [
|
||||
{
|
||||
message:
|
||||
"ESLint Stylistic now maintains deprecated stylistic core rules.",
|
||||
url: "https://eslint.style/guide/migration",
|
||||
plugin: {
|
||||
name: "@stylistic/eslint-plugin",
|
||||
url: "https://eslint.style",
|
||||
},
|
||||
rule: {
|
||||
name: "arrow-spacing",
|
||||
url: "https://eslint.style/rules/arrow-spacing",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
type: "layout",
|
||||
|
||||
docs: {
|
||||
description:
|
||||
"Enforce consistent spacing before and after the arrow in arrow functions",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/arrow-spacing",
|
||||
},
|
||||
|
||||
fixable: "whitespace",
|
||||
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
before: {
|
||||
type: "boolean",
|
||||
default: true,
|
||||
},
|
||||
after: {
|
||||
type: "boolean",
|
||||
default: true,
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
|
||||
messages: {
|
||||
expectedBefore: "Missing space before =>.",
|
||||
unexpectedBefore: "Unexpected space before =>.",
|
||||
|
||||
expectedAfter: "Missing space after =>.",
|
||||
unexpectedAfter: "Unexpected space after =>.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
// merge rules with default
|
||||
const rule = Object.assign({}, context.options[0]);
|
||||
|
||||
rule.before = rule.before !== false;
|
||||
rule.after = rule.after !== false;
|
||||
|
||||
const sourceCode = context.sourceCode;
|
||||
|
||||
/**
|
||||
* Get tokens of arrow(`=>`) and before/after arrow.
|
||||
* @param {ASTNode} node The arrow function node.
|
||||
* @returns {Object} Tokens of arrow and before/after arrow.
|
||||
*/
|
||||
function getTokens(node) {
|
||||
const arrow = sourceCode.getTokenBefore(
|
||||
node.body,
|
||||
astUtils.isArrowToken,
|
||||
);
|
||||
|
||||
return {
|
||||
before: sourceCode.getTokenBefore(arrow),
|
||||
arrow,
|
||||
after: sourceCode.getTokenAfter(arrow),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Count spaces before/after arrow(`=>`) token.
|
||||
* @param {Object} tokens Tokens before/after arrow.
|
||||
* @returns {Object} count of space before/after arrow.
|
||||
*/
|
||||
function countSpaces(tokens) {
|
||||
const before = tokens.arrow.range[0] - tokens.before.range[1];
|
||||
const after = tokens.after.range[0] - tokens.arrow.range[1];
|
||||
|
||||
return { before, after };
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether space(s) before after arrow(`=>`) is satisfy rule.
|
||||
* if before/after value is `true`, there should be space(s).
|
||||
* if before/after value is `false`, there should be no space.
|
||||
* @param {ASTNode} node The arrow function node.
|
||||
* @returns {void}
|
||||
*/
|
||||
function spaces(node) {
|
||||
const tokens = getTokens(node);
|
||||
const countSpace = countSpaces(tokens);
|
||||
|
||||
if (rule.before) {
|
||||
// should be space(s) before arrow
|
||||
if (countSpace.before === 0) {
|
||||
context.report({
|
||||
node: tokens.before,
|
||||
messageId: "expectedBefore",
|
||||
fix(fixer) {
|
||||
return fixer.insertTextBefore(tokens.arrow, " ");
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// should be no space before arrow
|
||||
if (countSpace.before > 0) {
|
||||
context.report({
|
||||
node: tokens.before,
|
||||
messageId: "unexpectedBefore",
|
||||
fix(fixer) {
|
||||
return fixer.removeRange([
|
||||
tokens.before.range[1],
|
||||
tokens.arrow.range[0],
|
||||
]);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (rule.after) {
|
||||
// should be space(s) after arrow
|
||||
if (countSpace.after === 0) {
|
||||
context.report({
|
||||
node: tokens.after,
|
||||
messageId: "expectedAfter",
|
||||
fix(fixer) {
|
||||
return fixer.insertTextAfter(tokens.arrow, " ");
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// should be no space after arrow
|
||||
if (countSpace.after > 0) {
|
||||
context.report({
|
||||
node: tokens.after,
|
||||
messageId: "unexpectedAfter",
|
||||
fix(fixer) {
|
||||
return fixer.removeRange([
|
||||
tokens.arrow.range[1],
|
||||
tokens.after.range[0],
|
||||
]);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ArrowFunctionExpression: spaces,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_jsx.cjs",
|
||||
"module": "../../esm/_jsx.js"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
function _taggedTemplateLiteralLoose(e, t) {
|
||||
return t || (t = e.slice(0)), e.raw = t, e;
|
||||
}
|
||||
module.exports = _taggedTemplateLiteralLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
|
||||
@@ -0,0 +1 @@
|
||||
export { _ as default } from "../esm/_is_native_reflect_construct.js";
|
||||
@@ -0,0 +1,2 @@
|
||||
import * as ts from 'typescript';
|
||||
export declare function isTypeBrandedLiteralLike(type: ts.Type): boolean;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
import type { LibDefinition } from '../variable';
|
||||
export declare const es2025_intl: LibDefinition;
|
||||
@@ -0,0 +1,55 @@
|
||||
declare module 'wasi' {
|
||||
interface WASIOptions {
|
||||
/**
|
||||
* An array of strings that the WebAssembly application will
|
||||
* see as command line arguments. The first argument is the virtual path to the
|
||||
* WASI command itself.
|
||||
*/
|
||||
args?: string[] | undefined;
|
||||
|
||||
/**
|
||||
* An object similar to `process.env` that the WebAssembly
|
||||
* application will see as its environment.
|
||||
*/
|
||||
env?: object | undefined;
|
||||
|
||||
/**
|
||||
* This object represents the WebAssembly application's
|
||||
* sandbox directory structure. The string keys of `preopens` are treated as
|
||||
* directories within the sandbox. The corresponding values in `preopens` are
|
||||
* the real paths to those directories on the host machine.
|
||||
*/
|
||||
preopens?: NodeJS.Dict<string> | undefined;
|
||||
|
||||
/**
|
||||
* By default, WASI applications terminate the Node.js
|
||||
* process via the `__wasi_proc_exit()` function. Setting this option to `true`
|
||||
* causes `wasi.start()` to return the exit code rather than terminate the
|
||||
* process.
|
||||
* @default false
|
||||
*/
|
||||
returnOnExit?: boolean | undefined;
|
||||
}
|
||||
|
||||
class WASI {
|
||||
constructor(options?: WASIOptions);
|
||||
/**
|
||||
*
|
||||
* Attempt to begin execution of `instance` by invoking its `_start()` export.
|
||||
* If `instance` does not contain a `_start()` export, then `start()` attempts to
|
||||
* invoke the `__wasi_unstable_reactor_start()` export. If neither of those exports
|
||||
* is present on `instance`, then `start()` does nothing.
|
||||
*
|
||||
* `start()` requires that `instance` exports a [`WebAssembly.Memory`][] named
|
||||
* `memory`. If `instance` does not have a `memory` export an exception is thrown.
|
||||
*/
|
||||
start(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib.
|
||||
|
||||
/**
|
||||
* Is an object that implements the WASI system call API. This object
|
||||
* should be passed as the `wasi_snapshot_preview1` import during the instantiation of a
|
||||
* [`WebAssembly.Instance`][].
|
||||
*/
|
||||
readonly wasiImport: NodeJS.Dict<any>; // TODO: Narrow to DOM types
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import * as ts from 'typescript';
|
||||
export declare function getScriptKind(filePath: string, jsx: boolean): ts.ScriptKind;
|
||||
export declare function getLanguageVariant(scriptKind: ts.ScriptKind): ts.LanguageVariant;
|
||||
@@ -0,0 +1,48 @@
|
||||
const BROWSER_MAPPING = {
|
||||
and_chr: 'chrome',
|
||||
and_ff: 'firefox',
|
||||
ie_mob: 'ie',
|
||||
op_mob: 'opera',
|
||||
and_qq: null,
|
||||
and_uc: null,
|
||||
baidu: null,
|
||||
bb: null,
|
||||
kaios: null,
|
||||
op_mini: null,
|
||||
};
|
||||
|
||||
function browserslistToTargets(browserslist) {
|
||||
let targets = {};
|
||||
for (let browser of browserslist) {
|
||||
let [name, v] = browser.split(' ');
|
||||
if (BROWSER_MAPPING[name] === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let version = parseVersion(v);
|
||||
if (version == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (targets[name] == null || version < targets[name]) {
|
||||
targets[name] = version;
|
||||
}
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
function parseVersion(version) {
|
||||
let [major, minor = 0, patch = 0] = version
|
||||
.split('-')[0]
|
||||
.split('.')
|
||||
.map(v => parseInt(v, 10));
|
||||
|
||||
if (isNaN(major) || isNaN(minor) || isNaN(patch)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (major << 16) | (minor << 8) | patch;
|
||||
}
|
||||
|
||||
module.exports = browserslistToTargets;
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"cryptoNode.js","sourceRoot":"","sources":["src/cryptoNode.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,aAAa;AACb,kCAAkC;AACrB,QAAA,MAAM,GACjB,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,WAAW,IAAI,EAAE;IAC/C,CAAC,CAAE,EAAE,CAAC,SAAiB;IACvB,CAAC,CAAC,EAAE,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,aAAa,IAAI,EAAE;QACnD,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,SAAS,CAAC"}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_array_like_to_array.cjs",
|
||||
"module": "../../esm/_array_like_to_array.js"
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2017, Jon Schlinkert.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,273 @@
|
||||
import { expect, expectTypeOf, test } from "vitest";
|
||||
|
||||
import * as z from "zod/v4";
|
||||
|
||||
test("function parsing", () => {
|
||||
const schema = z.union([z.string().refine(() => false), z.number().refine(() => false)]);
|
||||
const result = schema.safeParse("asdf");
|
||||
expect(result.success).toEqual(false);
|
||||
});
|
||||
|
||||
test("union 2", () => {
|
||||
const result = z.union([z.number(), z.string().refine(() => false)]).safeParse("a");
|
||||
expect(result.success).toEqual(false);
|
||||
});
|
||||
|
||||
test("return valid over invalid", () => {
|
||||
const schema = z.union([
|
||||
z.object({
|
||||
email: z.string().email(),
|
||||
}),
|
||||
z.string(),
|
||||
]);
|
||||
expect(schema.parse("asdf")).toEqual("asdf");
|
||||
expect(schema.parse({ email: "asdlkjf@lkajsdf.com" })).toEqual({
|
||||
email: "asdlkjf@lkajsdf.com",
|
||||
});
|
||||
});
|
||||
|
||||
test("return errors from both union arms", () => {
|
||||
const result = z.union([z.number(), z.boolean()]).safeParse("a");
|
||||
expect(result.success).toEqual(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "invalid_union",
|
||||
"errors": [
|
||||
[
|
||||
{
|
||||
"code": "invalid_type",
|
||||
"expected": "number",
|
||||
"message": "Invalid input: expected number, received string",
|
||||
"path": [],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
"code": "invalid_type",
|
||||
"expected": "boolean",
|
||||
"message": "Invalid input: expected boolean, received string",
|
||||
"path": [],
|
||||
},
|
||||
],
|
||||
],
|
||||
"message": "Invalid input",
|
||||
"path": [],
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
});
|
||||
|
||||
test("options getter", async () => {
|
||||
const union = z.union([z.string(), z.number()]);
|
||||
union.options[0].parse("asdf");
|
||||
union.options[1].parse(1234);
|
||||
await union.options[0].parseAsync("asdf");
|
||||
await union.options[1].parseAsync(1234);
|
||||
});
|
||||
|
||||
test("readonly union", async () => {
|
||||
const options = [z.string(), z.number()] as const;
|
||||
const union = z.union(options);
|
||||
union.parse("asdf");
|
||||
union.parse(12);
|
||||
});
|
||||
|
||||
test("union inferred types", () => {
|
||||
const test = z.object({}).or(z.array(z.object({})));
|
||||
|
||||
type Test = z.output<typeof test>; // <— any
|
||||
expectTypeOf<Test>().toEqualTypeOf<Record<string, never> | Array<Record<string, never>>>();
|
||||
});
|
||||
|
||||
test("union values", () => {
|
||||
const schema = z.union([z.literal("a"), z.literal("b"), z.literal("c")]);
|
||||
|
||||
expect(schema._zod.values).toMatchInlineSnapshot(`
|
||||
Set {
|
||||
"a",
|
||||
"b",
|
||||
"c",
|
||||
}
|
||||
`);
|
||||
});
|
||||
|
||||
test("non-aborted errors", () => {
|
||||
const zItemTest = z.union([
|
||||
z.object({
|
||||
date: z.number(),
|
||||
startDate: z.optional(z.null()),
|
||||
endDate: z.optional(z.null()),
|
||||
}),
|
||||
z
|
||||
.object({
|
||||
date: z.optional(z.null()),
|
||||
startDate: z.number(),
|
||||
endDate: z.number(),
|
||||
})
|
||||
.refine((data) => data.startDate !== data.endDate, {
|
||||
error: "startDate and endDate must be different",
|
||||
path: ["endDate"],
|
||||
}),
|
||||
]);
|
||||
|
||||
const res = zItemTest.safeParse({
|
||||
date: null,
|
||||
startDate: 1,
|
||||
endDate: 1,
|
||||
});
|
||||
|
||||
expect(res).toMatchInlineSnapshot(`
|
||||
{
|
||||
"error": [ZodError: [
|
||||
{
|
||||
"code": "custom",
|
||||
"path": [
|
||||
"endDate"
|
||||
],
|
||||
"message": "startDate and endDate must be different"
|
||||
}
|
||||
]],
|
||||
"success": false,
|
||||
}
|
||||
`);
|
||||
});
|
||||
|
||||
test("surface continuable errors only if they exist", () => {
|
||||
const schema = z.union([z.boolean(), z.uuid(), z.jwt()]);
|
||||
|
||||
expect(schema.safeParse("asdf")).toMatchInlineSnapshot(`
|
||||
{
|
||||
"error": [ZodError: [
|
||||
{
|
||||
"code": "invalid_union",
|
||||
"errors": [
|
||||
[
|
||||
{
|
||||
"expected": "boolean",
|
||||
"code": "invalid_type",
|
||||
"path": [],
|
||||
"message": "Invalid input: expected boolean, received string"
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"origin": "string",
|
||||
"code": "invalid_format",
|
||||
"format": "uuid",
|
||||
"pattern": "/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/",
|
||||
"path": [],
|
||||
"message": "Invalid UUID"
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"code": "invalid_format",
|
||||
"format": "jwt",
|
||||
"path": [],
|
||||
"message": "Invalid JWT"
|
||||
}
|
||||
]
|
||||
],
|
||||
"path": [],
|
||||
"message": "Invalid input"
|
||||
}
|
||||
]],
|
||||
"success": false,
|
||||
}
|
||||
`);
|
||||
});
|
||||
|
||||
// z.xor() tests
|
||||
test("z.xor() - exactly one match succeeds", () => {
|
||||
const schema = z.xor([z.string(), z.number()]);
|
||||
expect(schema.parse("hello")).toBe("hello");
|
||||
expect(schema.parse(42)).toBe(42);
|
||||
});
|
||||
|
||||
test("z.xor() - zero matches fails", () => {
|
||||
const schema = z.xor([z.string(), z.number()]);
|
||||
const result = schema.safeParse(true);
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
test("z.xor() - multiple matches fails", () => {
|
||||
const schema = z.xor([z.string(), z.any()]);
|
||||
const result = schema.safeParse("hello");
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0].code).toBe("invalid_union");
|
||||
expect((result.error.issues[0] as any).inclusive).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("z.xor() with custom error message", () => {
|
||||
const schema = z.xor([z.string(), z.number()], "Expected exactly one of string or number");
|
||||
const result = schema.safeParse(true);
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues[0].message).toBe("Expected exactly one of string or number");
|
||||
}
|
||||
});
|
||||
|
||||
test("z.xor() type inference", () => {
|
||||
const schema = z.xor([z.string(), z.number(), z.boolean()]);
|
||||
type Result = z.infer<typeof schema>;
|
||||
expectTypeOf<Result>().toEqualTypeOf<string | number | boolean>();
|
||||
});
|
||||
|
||||
test("z.union([]) constructs and rejects all input", () => {
|
||||
const schema = z.union([]);
|
||||
expectTypeOf<z.infer<typeof schema>>().toEqualTypeOf<never>();
|
||||
const result = schema.safeParse("anything");
|
||||
expect(result.success).toEqual(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "invalid_union",
|
||||
"errors": [],
|
||||
"message": "Invalid input",
|
||||
"path": [],
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
});
|
||||
|
||||
test("z.xor([]) constructs and rejects all input", () => {
|
||||
const schema = z.xor([]);
|
||||
expectTypeOf<z.infer<typeof schema>>().toEqualTypeOf<never>();
|
||||
const result = schema.safeParse("anything");
|
||||
expect(result.success).toEqual(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues).toMatchInlineSnapshot(`
|
||||
[
|
||||
{
|
||||
"code": "invalid_union",
|
||||
"errors": [],
|
||||
"message": "Invalid input",
|
||||
"path": [],
|
||||
},
|
||||
]
|
||||
`);
|
||||
}
|
||||
});
|
||||
|
||||
test("z.discriminatedUnion with empty options constructs and rejects", () => {
|
||||
const schema = z.discriminatedUnion("type", [] as any);
|
||||
const nonObject = schema.safeParse("nope");
|
||||
expect(nonObject.success).toEqual(false);
|
||||
if (!nonObject.success) {
|
||||
expect(nonObject.error.issues[0].code).toBe("invalid_type");
|
||||
}
|
||||
const obj = schema.safeParse({ type: "x" });
|
||||
expect(obj.success).toEqual(false);
|
||||
if (!obj.success) {
|
||||
expect(obj.error.issues[0].code).toBe("invalid_union");
|
||||
expect((obj.error.issues[0] as any).errors).toEqual([]);
|
||||
expect((obj.error.issues[0] as any).options).toEqual([]);
|
||||
}
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,108 @@
|
||||
// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT)
|
||||
/// <reference types="node" />
|
||||
|
||||
import { File } from 'node:buffer'
|
||||
import { SpecIterableIterator } from './fetch'
|
||||
|
||||
/**
|
||||
* A `string` or `File` that represents a single value from a set of `FormData` key-value pairs.
|
||||
*/
|
||||
declare type FormDataEntryValue = string | File
|
||||
|
||||
/**
|
||||
* Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch().
|
||||
*/
|
||||
export declare class FormData {
|
||||
/**
|
||||
* Appends a new value onto an existing key inside a FormData object,
|
||||
* or adds the key if it does not already exist.
|
||||
*
|
||||
* The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.
|
||||
*
|
||||
* @param name The name of the field whose data is contained in `value`.
|
||||
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
|
||||
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
|
||||
* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
|
||||
*/
|
||||
append (name: string, value: unknown, fileName?: string): void
|
||||
|
||||
/**
|
||||
* Set a new value for an existing key inside FormData,
|
||||
* or add the new field if it does not already exist.
|
||||
*
|
||||
* @param name The name of the field whose data is contained in `value`.
|
||||
* @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
|
||||
or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
|
||||
* @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
|
||||
*
|
||||
*/
|
||||
set (name: string, value: unknown, fileName?: string): void
|
||||
|
||||
/**
|
||||
* Returns the first value associated with a given key from within a `FormData` object.
|
||||
* If you expect multiple values and want all of them, use the `getAll()` method instead.
|
||||
*
|
||||
* @param {string} name A name of the value you want to retrieve.
|
||||
*
|
||||
* @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null.
|
||||
*/
|
||||
get (name: string): FormDataEntryValue | null
|
||||
|
||||
/**
|
||||
* Returns all the values associated with a given key from within a `FormData` object.
|
||||
*
|
||||
* @param {string} name A name of the value you want to retrieve.
|
||||
*
|
||||
* @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list.
|
||||
*/
|
||||
getAll (name: string): FormDataEntryValue[]
|
||||
|
||||
/**
|
||||
* Returns a boolean stating whether a `FormData` object contains a certain key.
|
||||
*
|
||||
* @param name A string representing the name of the key you want to test for.
|
||||
*
|
||||
* @return A boolean value.
|
||||
*/
|
||||
has (name: string): boolean
|
||||
|
||||
/**
|
||||
* Deletes a key and its value(s) from a `FormData` object.
|
||||
*
|
||||
* @param name The name of the key you want to delete.
|
||||
*/
|
||||
delete (name: string): void
|
||||
|
||||
/**
|
||||
* Executes given callback function for each field of the FormData instance
|
||||
*/
|
||||
forEach: (
|
||||
callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void,
|
||||
thisArg?: unknown
|
||||
) => void
|
||||
|
||||
/**
|
||||
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.
|
||||
* Each key is a `string`.
|
||||
*/
|
||||
keys: () => SpecIterableIterator<string>
|
||||
|
||||
/**
|
||||
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.
|
||||
* Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
|
||||
*/
|
||||
values: () => SpecIterableIterator<FormDataEntryValue>
|
||||
|
||||
/**
|
||||
* Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs.
|
||||
* The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
|
||||
*/
|
||||
entries: () => SpecIterableIterator<[string, FormDataEntryValue]>
|
||||
|
||||
/**
|
||||
* An alias for FormData#entries()
|
||||
*/
|
||||
[Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]>
|
||||
|
||||
readonly [Symbol.toStringTag]: string
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"completionItemKind.enum.js","sourceRoot":"","sources":["../../src/enums/completionItemKind.enum.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAE3G,MAAM,CAAN,IAAY,kBA0BX;AA1BD,WAAY,kBAAkB;IAC1B,2DAAQ,CAAA;IACR,+DAAU,CAAA;IACV,mEAAY,CAAA;IACZ,yEAAe,CAAA;IACf,6DAAS,CAAA;IACT,mEAAY,CAAA;IACZ,6DAAS,CAAA;IACT,qEAAa,CAAA;IACb,+DAAU,CAAA;IACV,oEAAa,CAAA;IACb,4DAAS,CAAA;IACT,8DAAU,CAAA;IACV,4DAAS,CAAA;IACT,kEAAY,CAAA;IACZ,kEAAY,CAAA;IACZ,8DAAU,CAAA;IACV,4DAAS,CAAA;IACT,sEAAc,CAAA;IACd,gEAAW,CAAA;IACX,wEAAe,CAAA;IACf,oEAAa,CAAA;IACb,gEAAW,CAAA;IACX,8DAAU,CAAA;IACV,oEAAa,CAAA;IACb,8EAAkB,CAAA;AACtB,CAAC,EA1BW,kBAAkB,KAAlB,kBAAkB,QA0B7B"}
|
||||
Reference in New Issue
Block a user