WIP: bootstrap and partial real Solana watcher implementation
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
function _isNativeFunction(t) {
|
||||
try {
|
||||
return -1 !== Function.toString.call(t).indexOf("[native code]");
|
||||
} catch (n) {
|
||||
return "function" == typeof t;
|
||||
}
|
||||
}
|
||||
export { _isNativeFunction as default };
|
||||
@@ -0,0 +1,21 @@
|
||||
/// <reference types="node" />
|
||||
|
||||
interface MIMEType {
|
||||
type: string
|
||||
subtype: string
|
||||
parameters: Map<string, string>
|
||||
essence: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a string to a {@link MIMEType} object. Returns `failure` if the string
|
||||
* couldn't be parsed.
|
||||
* @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type
|
||||
*/
|
||||
export function parseMIMEType (input: string): 'failure' | MIMEType
|
||||
|
||||
/**
|
||||
* Convert a MIMEType object to a string.
|
||||
* @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
|
||||
*/
|
||||
export function serializeAMimeType (mimeType: MIMEType): string
|
||||
@@ -0,0 +1,6 @@
|
||||
import { ESLintUtils } from '@typescript-eslint/utils';
|
||||
export type MessageIds = 'unusedPrivateClassMember';
|
||||
declare const _default: ESLintUtils.RuleModule<"unusedPrivateClassMember", [], import("../../rules").ESLintPluginDocs, ESLintUtils.RuleListener> & {
|
||||
name: string;
|
||||
};
|
||||
export default _default;
|
||||
@@ -0,0 +1,729 @@
|
||||
'use strict'
|
||||
|
||||
const test = require('node:test')
|
||||
const assert = require('node:assert')
|
||||
const { readFileSync } = require('node:fs')
|
||||
const { join } = require('node:path')
|
||||
const proxyquire = require('proxyquire')
|
||||
const strip = require('strip-ansi')
|
||||
const tspl = require('@matteo.collina/tspl')
|
||||
|
||||
const writeStream = require('flush-write-stream')
|
||||
const pino = require('../')
|
||||
const multistream = pino.multistream
|
||||
const { file, sink } = require('./helper')
|
||||
|
||||
test('sends to multiple streams using string levels', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const streams = [
|
||||
{ stream },
|
||||
{ level: 'debug', stream },
|
||||
{ level: 'trace', stream },
|
||||
{ level: 'fatal', stream },
|
||||
{ level: 'silent', stream }
|
||||
]
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multistream(streams))
|
||||
log.info('info stream')
|
||||
log.debug('debug stream')
|
||||
log.fatal('fatal stream')
|
||||
assert.equal(messageCount, 9)
|
||||
})
|
||||
|
||||
test('sends to multiple streams using custom levels', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const streams = [
|
||||
{ stream },
|
||||
{ level: 'debug', stream },
|
||||
{ level: 'trace', stream },
|
||||
{ level: 'fatal', stream },
|
||||
{ level: 'silent', stream }
|
||||
]
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multistream(streams))
|
||||
log.info('info stream')
|
||||
log.debug('debug stream')
|
||||
log.fatal('fatal stream')
|
||||
assert.equal(messageCount, 9)
|
||||
})
|
||||
|
||||
test('sends to multiple streams using optionally predefined levels', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const opts = {
|
||||
levels: {
|
||||
silent: Infinity,
|
||||
fatal: 60,
|
||||
error: 50,
|
||||
warn: 50,
|
||||
info: 30,
|
||||
debug: 20,
|
||||
trace: 10
|
||||
}
|
||||
}
|
||||
const streams = [
|
||||
{ stream },
|
||||
{ level: 'trace', stream },
|
||||
{ level: 'debug', stream },
|
||||
{ level: 'info', stream },
|
||||
{ level: 'warn', stream },
|
||||
{ level: 'error', stream },
|
||||
{ level: 'fatal', stream },
|
||||
{ level: 'silent', stream }
|
||||
]
|
||||
const mstream = multistream(streams, opts)
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, mstream)
|
||||
log.trace('trace stream')
|
||||
log.debug('debug stream')
|
||||
log.info('info stream')
|
||||
log.warn('warn stream')
|
||||
log.error('error stream')
|
||||
log.fatal('fatal stream')
|
||||
log.silent('silent stream')
|
||||
assert.equal(messageCount, 24)
|
||||
})
|
||||
|
||||
test('sends to multiple streams using number levels', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const streams = [
|
||||
{ stream },
|
||||
{ level: 20, stream },
|
||||
{ level: 60, stream }
|
||||
]
|
||||
const log = pino({
|
||||
level: 'debug'
|
||||
}, multistream(streams))
|
||||
log.info('info stream')
|
||||
log.debug('debug stream')
|
||||
log.fatal('fatal stream')
|
||||
assert.equal(messageCount, 6)
|
||||
})
|
||||
|
||||
test('level include higher levels', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const log = pino({}, multistream([{ level: 'info', stream }]))
|
||||
log.fatal('message')
|
||||
assert.equal(messageCount, 1)
|
||||
})
|
||||
|
||||
test('supports multiple arguments', async (t) => {
|
||||
const plan = tspl(t, { plan: 2 })
|
||||
const messages = []
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messages.push(JSON.parse(data))
|
||||
if (messages.length === 2) {
|
||||
const msg1 = messages[0]
|
||||
plan.equal(msg1.msg, 'foo bar baz foobar')
|
||||
|
||||
const msg2 = messages[1]
|
||||
plan.equal(msg2.msg, 'foo bar baz foobar barfoo foofoo')
|
||||
}
|
||||
cb()
|
||||
})
|
||||
const log = pino({}, multistream({ stream }))
|
||||
log.info('%s %s %s %s', 'foo', 'bar', 'baz', 'foobar') // apply not invoked
|
||||
log.info('%s %s %s %s %s %s', 'foo', 'bar', 'baz', 'foobar', 'barfoo', 'foofoo') // apply invoked
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('supports children', async (t) => {
|
||||
const plan = tspl(t, { plan: 2 })
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
const input = JSON.parse(data)
|
||||
plan.equal(input.msg, 'child stream')
|
||||
plan.equal(input.child, 'one')
|
||||
cb()
|
||||
})
|
||||
const streams = [
|
||||
{ stream }
|
||||
]
|
||||
const log = pino({}, multistream(streams)).child({ child: 'one' })
|
||||
log.info('child stream')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('supports grandchildren', async (t) => {
|
||||
const plan = tspl(t, { plan: 9 })
|
||||
const messages = []
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messages.push(JSON.parse(data))
|
||||
if (messages.length === 3) {
|
||||
const msg1 = messages[0]
|
||||
plan.equal(msg1.msg, 'grandchild stream')
|
||||
plan.equal(msg1.child, 'one')
|
||||
plan.equal(msg1.grandchild, 'two')
|
||||
|
||||
const msg2 = messages[1]
|
||||
plan.equal(msg2.msg, 'grandchild stream')
|
||||
plan.equal(msg2.child, 'one')
|
||||
plan.equal(msg2.grandchild, 'two')
|
||||
|
||||
const msg3 = messages[2]
|
||||
plan.equal(msg3.msg, 'debug grandchild')
|
||||
plan.equal(msg3.child, 'one')
|
||||
plan.equal(msg3.grandchild, 'two')
|
||||
}
|
||||
cb()
|
||||
})
|
||||
const streams = [
|
||||
{ stream },
|
||||
{ level: 'debug', stream }
|
||||
]
|
||||
const log = pino({
|
||||
level: 'debug'
|
||||
}, multistream(streams)).child({ child: 'one' }).child({ grandchild: 'two' })
|
||||
log.info('grandchild stream')
|
||||
log.debug('debug grandchild')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('supports custom levels', (t, end) => {
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
assert.equal(JSON.parse(data).msg, 'bar')
|
||||
end()
|
||||
})
|
||||
const log = pino({
|
||||
customLevels: {
|
||||
foo: 35
|
||||
}
|
||||
}, multistream([{ level: 35, stream }]))
|
||||
log.foo('bar')
|
||||
})
|
||||
|
||||
test('supports pretty print', async (t) => {
|
||||
const plan = tspl(t, { plan: 2 })
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
plan.equal(strip(data.toString()).match(/INFO.*: pretty print/) != null, true)
|
||||
cb()
|
||||
})
|
||||
|
||||
const safeBoom = proxyquire('pino-pretty/lib/utils/build-safe-sonic-boom.js', {
|
||||
'sonic-boom': function () {
|
||||
plan.ok('sonic created')
|
||||
stream.flushSync = () => {}
|
||||
stream.flush = () => {}
|
||||
return stream
|
||||
}
|
||||
})
|
||||
const nested = proxyquire('pino-pretty/lib/utils/index.js', {
|
||||
'./build-safe-sonic-boom.js': safeBoom
|
||||
})
|
||||
const pretty = proxyquire('pino-pretty', {
|
||||
'./lib/utils/index.js': nested
|
||||
})
|
||||
|
||||
const log = pino({
|
||||
level: 'debug',
|
||||
name: 'helloName'
|
||||
}, multistream([
|
||||
{ stream: pretty() }
|
||||
]))
|
||||
|
||||
log.info('pretty print')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('emit propagates events to each stream', async (t) => {
|
||||
const plan = tspl(t, { plan: 3 })
|
||||
const handler = function (data) {
|
||||
plan.equal(data.msg, 'world')
|
||||
}
|
||||
const streams = [sink(), sink(), sink()]
|
||||
streams.forEach(function (s) {
|
||||
s.once('hello', handler)
|
||||
})
|
||||
const stream = multistream(streams)
|
||||
stream.emit('hello', { msg: 'world' })
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('children support custom levels', async (t) => {
|
||||
const plan = tspl(t, { plan: 1 })
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
plan.equal(JSON.parse(data).msg, 'bar')
|
||||
})
|
||||
const parent = pino({
|
||||
customLevels: {
|
||||
foo: 35
|
||||
}
|
||||
}, multistream([{ level: 35, stream }]))
|
||||
const child = parent.child({ child: 'yes' })
|
||||
child.foo('bar')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('levelVal overrides level', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const streams = [
|
||||
{ stream },
|
||||
{ level: 'blabla', levelVal: 15, stream },
|
||||
{ level: 60, stream }
|
||||
]
|
||||
const log = pino({
|
||||
level: 'debug'
|
||||
}, multistream(streams))
|
||||
log.info('info stream')
|
||||
log.debug('debug stream')
|
||||
log.fatal('fatal stream')
|
||||
assert.equal(messageCount, 6)
|
||||
})
|
||||
|
||||
test('forwards metadata', async (t) => {
|
||||
const plan = tspl(t, { plan: 4 })
|
||||
const streams = [
|
||||
{
|
||||
stream: {
|
||||
[Symbol.for('pino.metadata')]: true,
|
||||
write (chunk) {
|
||||
plan.equal(log, this.lastLogger)
|
||||
plan.equal(30, this.lastLevel)
|
||||
plan.deepEqual({ hello: 'world' }, this.lastObj)
|
||||
plan.deepEqual('a msg', this.lastMsg)
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
const log = pino({
|
||||
level: 'debug'
|
||||
}, multistream(streams))
|
||||
|
||||
log.info({ hello: 'world' }, 'a msg')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('forward name', async (t) => {
|
||||
const plan = tspl(t, { plan: 2 })
|
||||
const streams = [
|
||||
{
|
||||
stream: {
|
||||
[Symbol.for('pino.metadata')]: true,
|
||||
write (chunk) {
|
||||
const line = JSON.parse(chunk)
|
||||
plan.equal(line.name, 'helloName')
|
||||
plan.equal(line.hello, 'world')
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
const log = pino({
|
||||
level: 'debug',
|
||||
name: 'helloName'
|
||||
}, multistream(streams))
|
||||
|
||||
log.info({ hello: 'world' }, 'a msg')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('forward name with child', async (t) => {
|
||||
const plan = tspl(t, { plan: 3 })
|
||||
const streams = [
|
||||
{
|
||||
stream: {
|
||||
write (chunk) {
|
||||
const line = JSON.parse(chunk)
|
||||
plan.equal(line.name, 'helloName')
|
||||
plan.equal(line.hello, 'world')
|
||||
plan.equal(line.component, 'aComponent')
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
const log = pino({
|
||||
level: 'debug',
|
||||
name: 'helloName'
|
||||
}, multistream(streams)).child({ component: 'aComponent' })
|
||||
|
||||
log.info({ hello: 'world' }, 'a msg')
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('clone generates a new multistream with all stream at the same level', async (t) => {
|
||||
const plan = tspl(t, { plan: 14 })
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const streams = [
|
||||
{ stream },
|
||||
{ level: 'debug', stream },
|
||||
{ level: 'trace', stream },
|
||||
{ level: 'fatal', stream }
|
||||
]
|
||||
const ms = multistream(streams)
|
||||
const clone = ms.clone(30)
|
||||
|
||||
// eslint-disable-next-line eqeqeq
|
||||
plan.equal(clone != ms, true)
|
||||
|
||||
clone.streams.forEach((s, i) => {
|
||||
// eslint-disable-next-line eqeqeq
|
||||
plan.equal(s != streams[i], true)
|
||||
plan.equal(s.stream, streams[i].stream)
|
||||
plan.equal(s.level, 30)
|
||||
})
|
||||
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, clone)
|
||||
|
||||
log.info('info stream')
|
||||
log.debug('debug message not counted')
|
||||
log.fatal('fatal stream')
|
||||
plan.equal(messageCount, 8)
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('one stream', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multistream({ stream, level: 'fatal' }))
|
||||
log.info('info stream')
|
||||
log.debug('debug stream')
|
||||
log.fatal('fatal stream')
|
||||
assert.equal(messageCount, 1)
|
||||
})
|
||||
|
||||
test('dedupe', async () => {
|
||||
let messageCount = 0
|
||||
const stream1 = writeStream(function (data, enc, cb) {
|
||||
messageCount -= 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const stream2 = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const streams = [
|
||||
{
|
||||
stream: stream1,
|
||||
level: 'info'
|
||||
},
|
||||
{
|
||||
stream: stream2,
|
||||
level: 'fatal'
|
||||
}
|
||||
]
|
||||
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multistream(streams, { dedupe: true }))
|
||||
log.info('info stream')
|
||||
log.fatal('fatal stream')
|
||||
log.fatal('fatal stream')
|
||||
assert.equal(messageCount, 1)
|
||||
})
|
||||
|
||||
test('dedupe when logs have different levels', async () => {
|
||||
let messageCount = 0
|
||||
const stream1 = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const stream2 = writeStream(function (data, enc, cb) {
|
||||
messageCount += 2
|
||||
cb()
|
||||
})
|
||||
|
||||
const streams = [
|
||||
{
|
||||
stream: stream1,
|
||||
level: 'info'
|
||||
},
|
||||
{
|
||||
stream: stream2,
|
||||
level: 'error'
|
||||
}
|
||||
]
|
||||
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multistream(streams, { dedupe: true }))
|
||||
|
||||
log.info('info stream')
|
||||
log.warn('warn stream')
|
||||
log.error('error streams')
|
||||
log.fatal('fatal streams')
|
||||
assert.equal(messageCount, 6)
|
||||
})
|
||||
|
||||
test('dedupe when some streams has the same level', async () => {
|
||||
let messageCount = 0
|
||||
const stream1 = writeStream(function (data, enc, cb) {
|
||||
messageCount -= 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const stream2 = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const stream3 = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const streams = [
|
||||
{
|
||||
stream: stream1,
|
||||
level: 'info'
|
||||
},
|
||||
{
|
||||
stream: stream2,
|
||||
level: 'fatal'
|
||||
},
|
||||
{
|
||||
stream: stream3,
|
||||
level: 'fatal'
|
||||
}
|
||||
]
|
||||
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multistream(streams, { dedupe: true }))
|
||||
log.info('info stream')
|
||||
log.fatal('fatal streams')
|
||||
log.fatal('fatal streams')
|
||||
assert.equal(messageCount, 3)
|
||||
})
|
||||
|
||||
test('no stream', async () => {
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multistream())
|
||||
log.info('info stream')
|
||||
log.debug('debug stream')
|
||||
log.fatal('fatal stream')
|
||||
})
|
||||
|
||||
test('one stream', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multistream(stream))
|
||||
log.info('info stream')
|
||||
log.debug('debug stream')
|
||||
log.fatal('fatal stream')
|
||||
assert.equal(messageCount, 2)
|
||||
})
|
||||
|
||||
test('add a stream', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multistream().add(stream))
|
||||
log.info('info stream')
|
||||
log.debug('debug stream')
|
||||
log.fatal('fatal stream')
|
||||
assert.equal(messageCount, 2)
|
||||
})
|
||||
|
||||
test('remove a stream', async () => {
|
||||
let messageCount1 = 0
|
||||
let messageCount2 = 0
|
||||
let messageCount3 = 0
|
||||
|
||||
const stream1 = writeStream(function (data, enc, cb) {
|
||||
messageCount1 += 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const stream2 = writeStream(function (data, enc, cb) {
|
||||
messageCount2 += 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const stream3 = writeStream(function (data, enc, cb) {
|
||||
messageCount3 += 1
|
||||
cb()
|
||||
})
|
||||
|
||||
const multi = multistream()
|
||||
const log = pino({ level: 'trace', sync: true }, multi)
|
||||
|
||||
multi.add(stream1)
|
||||
const id1 = multi.lastId
|
||||
|
||||
multi.add(stream2)
|
||||
const id2 = multi.lastId
|
||||
|
||||
multi.add(stream3)
|
||||
const id3 = multi.lastId
|
||||
|
||||
log.info('line')
|
||||
multi.remove(id1)
|
||||
|
||||
log.info('line')
|
||||
multi.remove(id2)
|
||||
|
||||
log.info('line')
|
||||
multi.remove(id3)
|
||||
|
||||
log.info('line')
|
||||
multi.remove(Math.floor(Math.random() * 1000)) // non-existing id
|
||||
|
||||
assert.equal(messageCount1, 1)
|
||||
assert.equal(messageCount2, 2)
|
||||
assert.equal(messageCount3, 3)
|
||||
})
|
||||
|
||||
test('multistream.add throws if not a stream', async () => {
|
||||
try {
|
||||
pino({
|
||||
level: 'trace'
|
||||
}, multistream().add({}))
|
||||
} catch (_) {
|
||||
}
|
||||
})
|
||||
|
||||
test('multistream throws if not a stream', async () => {
|
||||
try {
|
||||
pino({
|
||||
level: 'trace'
|
||||
}, multistream({}))
|
||||
} catch (_) {
|
||||
}
|
||||
})
|
||||
|
||||
test('multistream.write should not throw if one stream fails', async () => {
|
||||
let messageCount = 0
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
messageCount += 1
|
||||
cb()
|
||||
})
|
||||
const noopStream = pino.transport({
|
||||
target: join(__dirname, 'fixtures', 'noop-transport.js')
|
||||
})
|
||||
// eslint-disable-next-line
|
||||
noopStream.on('error', function (err) {
|
||||
// something went wrong while writing to noop stream, ignoring!
|
||||
})
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
},
|
||||
multistream([
|
||||
{
|
||||
level: 'trace',
|
||||
stream
|
||||
},
|
||||
{
|
||||
level: 'debug',
|
||||
stream: noopStream
|
||||
}
|
||||
])
|
||||
)
|
||||
log.debug('0')
|
||||
noopStream.end()
|
||||
// noop stream is ending, should emit an error but not throw
|
||||
log.debug('1')
|
||||
log.debug('2')
|
||||
assert.equal(messageCount, 3)
|
||||
})
|
||||
|
||||
test('flushSync', async (t) => {
|
||||
const plan = tspl(t, { plan: 2 })
|
||||
const tmp = file()
|
||||
const destination = pino.destination({ dest: tmp, sync: false, minLength: 4096 })
|
||||
const stream = multistream([{ level: 'info', stream: destination }])
|
||||
const log = pino({ level: 'info' }, stream)
|
||||
destination.on('ready', () => {
|
||||
log.info('foo')
|
||||
log.info('bar')
|
||||
stream.flushSync()
|
||||
plan.equal(readFileSync(tmp, { encoding: 'utf-8' }).split('\n').length - 1, 2)
|
||||
log.info('biz')
|
||||
stream.flushSync()
|
||||
plan.equal(readFileSync(tmp, { encoding: 'utf-8' }).split('\n').length - 1, 3)
|
||||
})
|
||||
|
||||
await plan
|
||||
})
|
||||
|
||||
test('ends all streams', async (t) => {
|
||||
const plan = tspl(t, { plan: 7 })
|
||||
const stream = writeStream(function (data, enc, cb) {
|
||||
plan.ok('message')
|
||||
cb()
|
||||
})
|
||||
stream.flushSync = function () {
|
||||
plan.ok('flushSync')
|
||||
}
|
||||
// stream2 has no flushSync
|
||||
const stream2 = writeStream(function (data, enc, cb) {
|
||||
plan.ok('message2')
|
||||
cb()
|
||||
})
|
||||
const streams = [
|
||||
{ stream },
|
||||
{ level: 'debug', stream },
|
||||
{ level: 'trace', stream: stream2 },
|
||||
{ level: 'fatal', stream },
|
||||
{ level: 'silent', stream }
|
||||
]
|
||||
const multi = multistream(streams)
|
||||
const log = pino({
|
||||
level: 'trace'
|
||||
}, multi)
|
||||
log.info('info stream')
|
||||
multi.end()
|
||||
|
||||
await plan
|
||||
})
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"main": "../../cjs/_to_property_key.cjs",
|
||||
"module": "../../esm/_to_property_key.js"
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { Disposable } from './disposable';
|
||||
import type { ContentTypeEncoder, ContentTypeDecoder } from './encoding';
|
||||
interface _MessageBuffer {
|
||||
readonly encoding: RAL.MessageBufferEncoding;
|
||||
/**
|
||||
* Append data to the message buffer.
|
||||
*
|
||||
* @param chunk the data to append.
|
||||
*/
|
||||
append(chunk: Uint8Array | string): void;
|
||||
/**
|
||||
* Tries to read the headers from the buffer
|
||||
*
|
||||
* @param lowerCaseKeys Whether the keys should be stored lower case. Doing
|
||||
* so is recommended since HTTP headers are case insensitive.
|
||||
*
|
||||
* @returns the header properties or undefined in not enough data can be read.
|
||||
*/
|
||||
tryReadHeaders(lowerCaseKeys?: boolean): Map<string, string> | undefined;
|
||||
/**
|
||||
* Tries to read the body of the given length.
|
||||
*
|
||||
* @param length the amount of bytes to read.
|
||||
* @returns the data or undefined int less data is available.
|
||||
*/
|
||||
tryReadBody(length: number): Uint8Array | undefined;
|
||||
}
|
||||
type _MessageBufferEncoding = 'ascii' | 'utf-8';
|
||||
interface _ReadableStream {
|
||||
onData(listener: (data: Uint8Array) => void): Disposable;
|
||||
onClose(listener: () => void): Disposable;
|
||||
onError(listener: (error: any) => void): Disposable;
|
||||
onEnd(listener: () => void): Disposable;
|
||||
}
|
||||
interface _WritableStream {
|
||||
onClose(listener: () => void): Disposable;
|
||||
onError(listener: (error: any) => void): Disposable;
|
||||
onEnd(listener: () => void): Disposable;
|
||||
write(data: Uint8Array): Promise<void>;
|
||||
write(data: string, encoding: _MessageBufferEncoding): Promise<void>;
|
||||
end(): void;
|
||||
}
|
||||
interface _DuplexStream extends _ReadableStream, _WritableStream {
|
||||
}
|
||||
interface RAL {
|
||||
readonly applicationJson: {
|
||||
readonly encoder: ContentTypeEncoder;
|
||||
readonly decoder: ContentTypeDecoder;
|
||||
};
|
||||
readonly messageBuffer: {
|
||||
create(encoding: RAL.MessageBufferEncoding): RAL.MessageBuffer;
|
||||
};
|
||||
readonly console: {
|
||||
info(message?: any, ...optionalParams: any[]): void;
|
||||
log(message?: any, ...optionalParams: any[]): void;
|
||||
warn(message?: any, ...optionalParams: any[]): void;
|
||||
error(message?: any, ...optionalParams: any[]): void;
|
||||
};
|
||||
readonly timer: {
|
||||
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable;
|
||||
setImmediate(callback: (...args: any[]) => void, ...args: any[]): Disposable;
|
||||
setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): Disposable;
|
||||
};
|
||||
}
|
||||
declare function RAL(): RAL;
|
||||
declare namespace RAL {
|
||||
type MessageBuffer = _MessageBuffer;
|
||||
type MessageBufferEncoding = _MessageBufferEncoding;
|
||||
type ReadableStream = _ReadableStream;
|
||||
type WritableStream = _WritableStream;
|
||||
type DuplexStream = _DuplexStream;
|
||||
function install(ral: RAL): void;
|
||||
}
|
||||
export default RAL;
|
||||
@@ -0,0 +1,62 @@
|
||||
import { ReadonlyUint8Array } from './readonly-uint8array';
|
||||
/**
|
||||
* Asserts that a given byte array is not empty (after the optional provided offset).
|
||||
*
|
||||
* Returns void if the byte array is not empty but throws a {@link SolanaError} otherwise.
|
||||
*
|
||||
* @param codecDescription - A description of the codec used by the assertion error.
|
||||
* @param bytes - The byte array to check.
|
||||
* @param offset - The offset from which to start checking the byte array.
|
||||
* If provided, the byte array is considered empty if it has no bytes after the offset.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const bytes = new Uint8Array([0x01, 0x02, 0x03]);
|
||||
* assertByteArrayIsNotEmptyForCodec('myCodec', bytes); // OK
|
||||
* assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 1); // OK
|
||||
* assertByteArrayIsNotEmptyForCodec('myCodec', bytes, 3); // Throws
|
||||
* ```
|
||||
*/
|
||||
export declare function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: ReadonlyUint8Array | Uint8Array, offset?: number): void;
|
||||
/**
|
||||
* Asserts that a given byte array has enough bytes to decode
|
||||
* (after the optional provided offset).
|
||||
*
|
||||
* Returns void if the byte array has at least the expected number
|
||||
* of bytes but throws a {@link SolanaError} otherwise.
|
||||
*
|
||||
* @param codecDescription - A description of the codec used by the assertion error.
|
||||
* @param expected - The minimum number of bytes expected in the byte array.
|
||||
* @param bytes - The byte array to check.
|
||||
* @param offset - The offset from which to start checking the byte array.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const bytes = new Uint8Array([0x01, 0x02, 0x03]);
|
||||
* assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes); // OK
|
||||
* assertByteArrayHasEnoughBytesForCodec('myCodec', 4, bytes); // Throws
|
||||
* assertByteArrayHasEnoughBytesForCodec('myCodec', 2, bytes, 1); // OK
|
||||
* assertByteArrayHasEnoughBytesForCodec('myCodec', 3, bytes, 1); // Throws
|
||||
* ```
|
||||
*/
|
||||
export declare function assertByteArrayHasEnoughBytesForCodec(codecDescription: string, expected: number, bytes: ReadonlyUint8Array | Uint8Array, offset?: number): void;
|
||||
/**
|
||||
* Asserts that a given offset is within the byte array bounds.
|
||||
* This range is between 0 and the byte array length and is inclusive.
|
||||
* An offset equals to the byte array length is considered a valid offset
|
||||
* as it allows the post-offset of codecs to signal the end of the byte array.
|
||||
*
|
||||
* @param codecDescription - A description of the codec used by the assertion error.
|
||||
* @param offset - The offset to check.
|
||||
* @param bytesLength - The length of the byte array from which the offset should be within bounds.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const bytes = new Uint8Array([0x01, 0x02, 0x03]);
|
||||
* assertByteArrayOffsetIsNotOutOfRange('myCodec', 0, bytes.length); // OK
|
||||
* assertByteArrayOffsetIsNotOutOfRange('myCodec', 3, bytes.length); // OK
|
||||
* assertByteArrayOffsetIsNotOutOfRange('myCodec', 4, bytes.length); // Throws
|
||||
* ```
|
||||
*/
|
||||
export declare function assertByteArrayOffsetIsNotOutOfRange(codecDescription: string, offset: number, bytesLength: number): void;
|
||||
//# sourceMappingURL=assertions.d.ts.map
|
||||
@@ -0,0 +1,3 @@
|
||||
import {expect} from './index.js';
|
||||
|
||||
globalThis.expect = expect;
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
var spawn = require('child_process').spawn
|
||||
var path = require('path')
|
||||
|
||||
var prog = path.resolve(process.argv[2])
|
||||
var progArgs = process.argv.slice(3)
|
||||
|
||||
console.log('probing program', prog)
|
||||
|
||||
var nodeArgs = [
|
||||
'-r',
|
||||
path.join(__dirname, 'include.js')
|
||||
]
|
||||
var nodeOpts = { stdio: 'inherit' }
|
||||
var child = spawn('node', nodeArgs.concat(prog).concat(progArgs), nodeOpts)
|
||||
|
||||
console.log('kill -SIGUSR1', child.pid, 'for logging')
|
||||
@@ -0,0 +1,448 @@
|
||||
import { globalRegistry } from "./registries.js";
|
||||
// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {
|
||||
// return {
|
||||
// processor: inputs.processor,
|
||||
// metadataRegistry: inputs.metadata ?? globalRegistry,
|
||||
// target: inputs.target ?? "draft-2020-12",
|
||||
// unrepresentable: inputs.unrepresentable ?? "throw",
|
||||
// };
|
||||
// }
|
||||
export function initializeContext(params) {
|
||||
// Normalize target: convert old non-hyphenated versions to hyphenated versions
|
||||
let target = params?.target ?? "draft-2020-12";
|
||||
if (target === "draft-4")
|
||||
target = "draft-04";
|
||||
if (target === "draft-7")
|
||||
target = "draft-07";
|
||||
return {
|
||||
processors: params.processors ?? {},
|
||||
metadataRegistry: params?.metadata ?? globalRegistry,
|
||||
target,
|
||||
unrepresentable: params?.unrepresentable ?? "throw",
|
||||
override: params?.override ?? (() => { }),
|
||||
io: params?.io ?? "output",
|
||||
counter: 0,
|
||||
seen: new Map(),
|
||||
cycles: params?.cycles ?? "ref",
|
||||
reused: params?.reused ?? "inline",
|
||||
external: params?.external ?? undefined,
|
||||
};
|
||||
}
|
||||
export function process(schema, ctx, _params = { path: [], schemaPath: [] }) {
|
||||
var _a;
|
||||
const def = schema._zod.def;
|
||||
// check for schema in seens
|
||||
const seen = ctx.seen.get(schema);
|
||||
if (seen) {
|
||||
seen.count++;
|
||||
// check if cycle
|
||||
const isCycle = _params.schemaPath.includes(schema);
|
||||
if (isCycle) {
|
||||
seen.cycle = _params.path;
|
||||
}
|
||||
return seen.schema;
|
||||
}
|
||||
// initialize
|
||||
const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
|
||||
ctx.seen.set(schema, result);
|
||||
// custom method overrides default behavior
|
||||
const overrideSchema = schema._zod.toJSONSchema?.();
|
||||
if (overrideSchema) {
|
||||
result.schema = overrideSchema;
|
||||
}
|
||||
else {
|
||||
const params = {
|
||||
..._params,
|
||||
schemaPath: [..._params.schemaPath, schema],
|
||||
path: _params.path,
|
||||
};
|
||||
if (schema._zod.processJSONSchema) {
|
||||
schema._zod.processJSONSchema(ctx, result.schema, params);
|
||||
}
|
||||
else {
|
||||
const _json = result.schema;
|
||||
const processor = ctx.processors[def.type];
|
||||
if (!processor) {
|
||||
throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
|
||||
}
|
||||
processor(schema, ctx, _json, params);
|
||||
}
|
||||
const parent = schema._zod.parent;
|
||||
if (parent) {
|
||||
// Also set ref if processor didn't (for inheritance)
|
||||
if (!result.ref)
|
||||
result.ref = parent;
|
||||
process(parent, ctx, params);
|
||||
ctx.seen.get(parent).isParent = true;
|
||||
}
|
||||
}
|
||||
// metadata
|
||||
const meta = ctx.metadataRegistry.get(schema);
|
||||
if (meta)
|
||||
Object.assign(result.schema, meta);
|
||||
if (ctx.io === "input" && isTransforming(schema)) {
|
||||
// examples/defaults only apply to output type of pipe
|
||||
delete result.schema.examples;
|
||||
delete result.schema.default;
|
||||
}
|
||||
// set prefault as default
|
||||
if (ctx.io === "input" && "_prefault" in result.schema)
|
||||
(_a = result.schema).default ?? (_a.default = result.schema._prefault);
|
||||
delete result.schema._prefault;
|
||||
// pulling fresh from ctx.seen in case it was overwritten
|
||||
const _result = ctx.seen.get(schema);
|
||||
return _result.schema;
|
||||
}
|
||||
export function extractDefs(ctx, schema
|
||||
// params: EmitParams
|
||||
) {
|
||||
// iterate over seen map;
|
||||
const root = ctx.seen.get(schema);
|
||||
if (!root)
|
||||
throw new Error("Unprocessed schema. This is a bug in Zod.");
|
||||
// Track ids to detect duplicates across different schemas
|
||||
const idToSchema = new Map();
|
||||
for (const entry of ctx.seen.entries()) {
|
||||
const id = ctx.metadataRegistry.get(entry[0])?.id;
|
||||
if (id) {
|
||||
const existing = idToSchema.get(id);
|
||||
if (existing && existing !== entry[0]) {
|
||||
throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
|
||||
}
|
||||
idToSchema.set(id, entry[0]);
|
||||
}
|
||||
}
|
||||
// returns a ref to the schema
|
||||
// defId will be empty if the ref points to an external schema (or #)
|
||||
const makeURI = (entry) => {
|
||||
// comparing the seen objects because sometimes
|
||||
// multiple schemas map to the same seen object.
|
||||
// e.g. lazy
|
||||
// external is configured
|
||||
const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
|
||||
if (ctx.external) {
|
||||
const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`;
|
||||
// check if schema is in the external registry
|
||||
const uriGenerator = ctx.external.uri ?? ((id) => id);
|
||||
if (externalId) {
|
||||
return { ref: uriGenerator(externalId) };
|
||||
}
|
||||
// otherwise, add to __shared
|
||||
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
|
||||
entry[1].defId = id; // set defId so it will be reused if needed
|
||||
return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
|
||||
}
|
||||
if (entry[1] === root) {
|
||||
return { ref: "#" };
|
||||
}
|
||||
// self-contained schema
|
||||
const uriPrefix = `#`;
|
||||
const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
|
||||
const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
|
||||
return { defId, ref: defUriPrefix + defId };
|
||||
};
|
||||
// stored cached version in `def` property
|
||||
// remove all properties, set $ref
|
||||
const extractToDef = (entry) => {
|
||||
// if the schema is already a reference, do not extract it
|
||||
if (entry[1].schema.$ref) {
|
||||
return;
|
||||
}
|
||||
const seen = entry[1];
|
||||
const { ref, defId } = makeURI(entry);
|
||||
seen.def = { ...seen.schema };
|
||||
// defId won't be set if the schema is a reference to an external schema
|
||||
// or if the schema is the root schema
|
||||
if (defId)
|
||||
seen.defId = defId;
|
||||
// wipe away all properties except $ref
|
||||
const schema = seen.schema;
|
||||
for (const key in schema) {
|
||||
delete schema[key];
|
||||
}
|
||||
schema.$ref = ref;
|
||||
};
|
||||
// throw on cycles
|
||||
// break cycles
|
||||
if (ctx.cycles === "throw") {
|
||||
for (const entry of ctx.seen.entries()) {
|
||||
const seen = entry[1];
|
||||
if (seen.cycle) {
|
||||
throw new Error("Cycle detected: " +
|
||||
`#/${seen.cycle?.join("/")}/<root>` +
|
||||
'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
|
||||
}
|
||||
}
|
||||
}
|
||||
// extract schemas into $defs
|
||||
for (const entry of ctx.seen.entries()) {
|
||||
const seen = entry[1];
|
||||
// convert root schema to # $ref
|
||||
if (schema === entry[0]) {
|
||||
extractToDef(entry); // this has special handling for the root schema
|
||||
continue;
|
||||
}
|
||||
// extract schemas that are in the external registry
|
||||
if (ctx.external) {
|
||||
const ext = ctx.external.registry.get(entry[0])?.id;
|
||||
if (schema !== entry[0] && ext) {
|
||||
extractToDef(entry);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// extract schemas with `id` meta
|
||||
const id = ctx.metadataRegistry.get(entry[0])?.id;
|
||||
if (id) {
|
||||
extractToDef(entry);
|
||||
continue;
|
||||
}
|
||||
// break cycles
|
||||
if (seen.cycle) {
|
||||
// any
|
||||
extractToDef(entry);
|
||||
continue;
|
||||
}
|
||||
// extract reused schemas
|
||||
if (seen.count > 1) {
|
||||
if (ctx.reused === "ref") {
|
||||
extractToDef(entry);
|
||||
// biome-ignore lint:
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
export function finalize(ctx, schema) {
|
||||
const root = ctx.seen.get(schema);
|
||||
if (!root)
|
||||
throw new Error("Unprocessed schema. This is a bug in Zod.");
|
||||
// flatten refs - inherit properties from parent schemas
|
||||
const flattenRef = (zodSchema) => {
|
||||
const seen = ctx.seen.get(zodSchema);
|
||||
// already processed
|
||||
if (seen.ref === null)
|
||||
return;
|
||||
const schema = seen.def ?? seen.schema;
|
||||
const _cached = { ...schema };
|
||||
const ref = seen.ref;
|
||||
seen.ref = null; // prevent infinite recursion
|
||||
if (ref) {
|
||||
flattenRef(ref);
|
||||
const refSeen = ctx.seen.get(ref);
|
||||
const refSchema = refSeen.schema;
|
||||
// merge referenced schema into current
|
||||
if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
|
||||
// older drafts can't combine $ref with other properties
|
||||
schema.allOf = schema.allOf ?? [];
|
||||
schema.allOf.push(refSchema);
|
||||
}
|
||||
else {
|
||||
Object.assign(schema, refSchema);
|
||||
}
|
||||
// restore child's own properties (child wins)
|
||||
Object.assign(schema, _cached);
|
||||
const isParentRef = zodSchema._zod.parent === ref;
|
||||
// For parent chain, child is a refinement - remove parent-only properties
|
||||
if (isParentRef) {
|
||||
for (const key in schema) {
|
||||
if (key === "$ref" || key === "allOf")
|
||||
continue;
|
||||
if (!(key in _cached)) {
|
||||
delete schema[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
// When ref was extracted to $defs, remove properties that match the definition
|
||||
if (refSchema.$ref && refSeen.def) {
|
||||
for (const key in schema) {
|
||||
if (key === "$ref" || key === "allOf")
|
||||
continue;
|
||||
if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {
|
||||
delete schema[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// If parent was extracted (has $ref), propagate $ref to this schema
|
||||
// This handles cases like: readonly().meta({id}).describe()
|
||||
// where processor sets ref to innerType but parent should be referenced
|
||||
const parent = zodSchema._zod.parent;
|
||||
if (parent && parent !== ref) {
|
||||
// Ensure parent is processed first so its def has inherited properties
|
||||
flattenRef(parent);
|
||||
const parentSeen = ctx.seen.get(parent);
|
||||
if (parentSeen?.schema.$ref) {
|
||||
schema.$ref = parentSeen.schema.$ref;
|
||||
// De-duplicate with parent's definition
|
||||
if (parentSeen.def) {
|
||||
for (const key in schema) {
|
||||
if (key === "$ref" || key === "allOf")
|
||||
continue;
|
||||
if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {
|
||||
delete schema[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// execute overrides
|
||||
ctx.override({
|
||||
zodSchema: zodSchema,
|
||||
jsonSchema: schema,
|
||||
path: seen.path ?? [],
|
||||
});
|
||||
};
|
||||
for (const entry of [...ctx.seen.entries()].reverse()) {
|
||||
flattenRef(entry[0]);
|
||||
}
|
||||
const result = {};
|
||||
if (ctx.target === "draft-2020-12") {
|
||||
result.$schema = "https://json-schema.org/draft/2020-12/schema";
|
||||
}
|
||||
else if (ctx.target === "draft-07") {
|
||||
result.$schema = "http://json-schema.org/draft-07/schema#";
|
||||
}
|
||||
else if (ctx.target === "draft-04") {
|
||||
result.$schema = "http://json-schema.org/draft-04/schema#";
|
||||
}
|
||||
else if (ctx.target === "openapi-3.0") {
|
||||
// OpenAPI 3.0 schema objects should not include a $schema property
|
||||
}
|
||||
else {
|
||||
// Arbitrary string values are allowed but won't have a $schema property set
|
||||
}
|
||||
if (ctx.external?.uri) {
|
||||
const id = ctx.external.registry.get(schema)?.id;
|
||||
if (!id)
|
||||
throw new Error("Schema is missing an `id` property");
|
||||
result.$id = ctx.external.uri(id);
|
||||
}
|
||||
Object.assign(result, root.def ?? root.schema);
|
||||
// The `id` in `.meta()` is a Zod-specific registration tag used to extract
|
||||
// schemas into $defs — it is not user-facing JSON Schema metadata. Strip it
|
||||
// from the output body where it would otherwise leak. The id is preserved
|
||||
// implicitly via the $defs key (and via $ref paths).
|
||||
const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
|
||||
if (rootMetaId !== undefined && result.id === rootMetaId)
|
||||
delete result.id;
|
||||
// build defs object
|
||||
const defs = ctx.external?.defs ?? {};
|
||||
for (const entry of ctx.seen.entries()) {
|
||||
const seen = entry[1];
|
||||
if (seen.def && seen.defId) {
|
||||
if (seen.def.id === seen.defId)
|
||||
delete seen.def.id;
|
||||
defs[seen.defId] = seen.def;
|
||||
}
|
||||
}
|
||||
// set definitions in result
|
||||
if (ctx.external) {
|
||||
}
|
||||
else {
|
||||
if (Object.keys(defs).length > 0) {
|
||||
if (ctx.target === "draft-2020-12") {
|
||||
result.$defs = defs;
|
||||
}
|
||||
else {
|
||||
result.definitions = defs;
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
// this "finalizes" this schema and ensures all cycles are removed
|
||||
// each call to finalize() is functionally independent
|
||||
// though the seen map is shared
|
||||
const finalized = JSON.parse(JSON.stringify(result));
|
||||
Object.defineProperty(finalized, "~standard", {
|
||||
value: {
|
||||
...schema["~standard"],
|
||||
jsonSchema: {
|
||||
input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
|
||||
output: createStandardJSONSchemaMethod(schema, "output", ctx.processors),
|
||||
},
|
||||
},
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
});
|
||||
return finalized;
|
||||
}
|
||||
catch (_err) {
|
||||
throw new Error("Error converting schema to JSON.");
|
||||
}
|
||||
}
|
||||
function isTransforming(_schema, _ctx) {
|
||||
const ctx = _ctx ?? { seen: new Set() };
|
||||
if (ctx.seen.has(_schema))
|
||||
return false;
|
||||
ctx.seen.add(_schema);
|
||||
const def = _schema._zod.def;
|
||||
if (def.type === "transform")
|
||||
return true;
|
||||
if (def.type === "array")
|
||||
return isTransforming(def.element, ctx);
|
||||
if (def.type === "set")
|
||||
return isTransforming(def.valueType, ctx);
|
||||
if (def.type === "lazy")
|
||||
return isTransforming(def.getter(), ctx);
|
||||
if (def.type === "promise" ||
|
||||
def.type === "optional" ||
|
||||
def.type === "nonoptional" ||
|
||||
def.type === "nullable" ||
|
||||
def.type === "readonly" ||
|
||||
def.type === "default" ||
|
||||
def.type === "prefault") {
|
||||
return isTransforming(def.innerType, ctx);
|
||||
}
|
||||
if (def.type === "intersection") {
|
||||
return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
|
||||
}
|
||||
if (def.type === "record" || def.type === "map") {
|
||||
return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
|
||||
}
|
||||
if (def.type === "pipe") {
|
||||
if (_schema._zod.traits.has("$ZodCodec"))
|
||||
return true;
|
||||
return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
|
||||
}
|
||||
if (def.type === "object") {
|
||||
for (const key in def.shape) {
|
||||
if (isTransforming(def.shape[key], ctx))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (def.type === "union") {
|
||||
for (const option of def.options) {
|
||||
if (isTransforming(option, ctx))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (def.type === "tuple") {
|
||||
for (const item of def.items) {
|
||||
if (isTransforming(item, ctx))
|
||||
return true;
|
||||
}
|
||||
if (def.rest && isTransforming(def.rest, ctx))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Creates a toJSONSchema method for a schema instance.
|
||||
* This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.
|
||||
*/
|
||||
export const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
|
||||
const ctx = initializeContext({ ...params, processors });
|
||||
process(schema, ctx);
|
||||
extractDefs(ctx, schema);
|
||||
return finalize(ctx, schema);
|
||||
};
|
||||
export const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
|
||||
const { libraryOptions, target } = params ?? {};
|
||||
const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });
|
||||
process(schema, ctx);
|
||||
extractDefs(ctx, schema);
|
||||
return finalize(ctx, schema);
|
||||
};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
|
||||
import type { NonSharedArrayBuffer } from './types.js';
|
||||
export default function v1ToV6(uuid: string): string;
|
||||
export default function v1ToV6(uuid: Uint8Array): NonSharedArrayBuffer;
|
||||
@@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
module.exports = function generate_allOf(it, $keyword, $ruleType) {
|
||||
var out = ' ';
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
var $currentBaseId = $it.baseId,
|
||||
$allSchemasEmpty = true;
|
||||
var arr1 = $schema;
|
||||
if (arr1) {
|
||||
var $sch, $i = -1,
|
||||
l1 = arr1.length - 1;
|
||||
while ($i < l1) {
|
||||
$sch = arr1[$i += 1];
|
||||
if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
|
||||
$allSchemasEmpty = false;
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
out += ' ' + (it.validate($it)) + ' ';
|
||||
$it.baseId = $currentBaseId;
|
||||
if ($breakOnError) {
|
||||
out += ' if (' + ($nextValid) + ') { ';
|
||||
$closingBraces += '}';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($breakOnError) {
|
||||
if ($allSchemasEmpty) {
|
||||
out += ' if (true) { ';
|
||||
} else {
|
||||
out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
const file7 = require("./file7.js")
|
||||
|
||||
module.exports = function () {
|
||||
file7()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import * as ts from 'typescript';
|
||||
/*** Indicates whether identifiers require the use of quotation marks when accessing property definitions and dot notation. */
|
||||
export declare function requiresQuoting(name: string, target?: ts.ScriptTarget): boolean;
|
||||
@@ -0,0 +1,46 @@
|
||||
name: CI
|
||||
on:
|
||||
push:
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
- '*.md'
|
||||
pull_request:
|
||||
paths-ignore:
|
||||
- 'docs/**'
|
||||
- '*.md'
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [14, 16, 18, 20]
|
||||
os: [macos-latest, ubuntu-latest, windows-latest]
|
||||
exclude:
|
||||
- node-version: 14
|
||||
os: windows-latest
|
||||
|
||||
steps:
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Use Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Install
|
||||
run: |
|
||||
npm install --ignore-scripts
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
npm run test
|
||||
|
||||
automerge:
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: fastify/github-action-merge-dependabot@v3.9
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,105 @@
|
||||
pg-connection-string
|
||||
====================
|
||||
|
||||
[](https://nodei.co/npm/pg-connection-string/)
|
||||
|
||||
Functions for dealing with a PostgreSQL connection string
|
||||
|
||||
`parse` method taken from [node-postgres](https://github.com/brianc/node-postgres.git)
|
||||
Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com)
|
||||
MIT License
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const parse = require('pg-connection-string').parse;
|
||||
|
||||
const config = parse('postgres://someuser:somepassword@somehost:381/somedatabase')
|
||||
```
|
||||
|
||||
The resulting config contains a subset of the following properties:
|
||||
|
||||
* `user` - User with which to authenticate to the server
|
||||
* `password` - Corresponding password
|
||||
* `host` - Postgres server hostname or, for UNIX domain sockets, the socket filename
|
||||
* `port` - port on which to connect
|
||||
* `database` - Database name within the server
|
||||
* `client_encoding` - string encoding the client will use
|
||||
* `ssl`, either a boolean or an object with properties
|
||||
* `rejectUnauthorized`
|
||||
* `cert`
|
||||
* `key`
|
||||
* `ca`
|
||||
* any other query parameters (for example, `application_name`) are preserved intact.
|
||||
|
||||
### ClientConfig Compatibility for TypeScript
|
||||
|
||||
The pg-connection-string `ConnectionOptions` interface is not compatible with the `ClientConfig` interface that [pg.Client](https://node-postgres.com/apis/client) expects. To remedy this, use the `parseIntoClientConfig` function instead of `parse`:
|
||||
|
||||
```ts
|
||||
import { ClientConfig } from 'pg';
|
||||
import { parseIntoClientConfig } from 'pg-connection-string';
|
||||
|
||||
const config: ClientConfig = parseIntoClientConfig('postgres://someuser:somepassword@somehost:381/somedatabase')
|
||||
```
|
||||
|
||||
You can also use `toClientConfig` to convert an existing `ConnectionOptions` interface into a `ClientConfig` interface:
|
||||
|
||||
```ts
|
||||
import { ClientConfig } from 'pg';
|
||||
import { parse, toClientConfig } from 'pg-connection-string';
|
||||
|
||||
const config = parse('postgres://someuser:somepassword@somehost:381/somedatabase')
|
||||
const clientConfig: ClientConfig = toClientConfig(config)
|
||||
```
|
||||
|
||||
## Connection Strings
|
||||
|
||||
The short summary of acceptable URLs is:
|
||||
|
||||
* `socket:<path>?<query>` - UNIX domain socket
|
||||
* `postgres://<user>:<password>@<host>:<port>/<database>?<query>` - TCP connection
|
||||
|
||||
But see below for more details.
|
||||
|
||||
### UNIX Domain Sockets
|
||||
|
||||
When user and password are not given, the socket path follows `socket:`, as in `socket:/var/run/pgsql`.
|
||||
This form can be shortened to just a path: `/var/run/pgsql`.
|
||||
|
||||
When user and password are given, they are included in the typical URL positions, with an empty `host`, as in `socket://user:pass@/var/run/pgsql`.
|
||||
|
||||
Query parameters follow a `?` character, including the following special query parameters:
|
||||
|
||||
* `db=<database>` - sets the database name (urlencoded)
|
||||
* `encoding=<encoding>` - sets the `client_encoding` property
|
||||
|
||||
### TCP Connections
|
||||
|
||||
TCP connections to the Postgres server are indicated with `pg:` or `postgres:` schemes (in fact, any scheme but `socket:` is accepted).
|
||||
If username and password are included, they should be urlencoded.
|
||||
The database name, however, should *not* be urlencoded.
|
||||
|
||||
Query parameters follow a `?` character, including the following special query parameters:
|
||||
* `host=<host>` - sets `host` property, overriding the URL's host
|
||||
* `encoding=<encoding>` - sets the `client_encoding` property
|
||||
* `ssl=1`, `ssl=true`, `ssl=0`, `ssl=false` - sets `ssl` to true or false, accordingly
|
||||
* `uselibpqcompat=true` - use libpq semantics
|
||||
* `sslmode=<sslmode>` when `uselibpqcompat=true` is not set
|
||||
* `sslmode=disable` - sets `ssl` to false
|
||||
* `sslmode=no-verify` - sets `ssl` to `{ rejectUnauthorized: false }`
|
||||
* `sslmode=prefer`, `sslmode=require`, `sslmode=verify-ca`, `sslmode=verify-full` - sets `ssl` to true
|
||||
* `sslmode=<sslmode>` when `uselibpqcompat=true`
|
||||
* `sslmode=disable` - sets `ssl` to false
|
||||
* `sslmode=prefer` - sets `ssl` to `{ rejectUnauthorized: false }`
|
||||
* `sslmode=require` - sets `ssl` to `{ rejectUnauthorized: false }` unless `sslrootcert` is specified, in which case it behaves like `verify-ca`
|
||||
* `sslmode=verify-ca` - sets `ssl` to `{ checkServerIdentity: no-op }` (verify CA, but not server identity). This verifies the presented certificate against the effective CA specified in sslrootcert.
|
||||
* `sslmode=verify-full` - sets `ssl` to `{}` (verify CA and server identity)
|
||||
* `sslcert=<filename>` - reads data from the given file and includes the result as `ssl.cert`
|
||||
* `sslkey=<filename>` - reads data from the given file and includes the result as `ssl.key`
|
||||
* `sslrootcert=<filename>` - reads data from the given file and includes the result as `ssl.ca`
|
||||
|
||||
A bare relative URL, such as `salesdata`, will indicate a database name while leaving other properties empty.
|
||||
|
||||
> [!CAUTION]
|
||||
> Choosing an sslmode other than verify-full has serious security implications. Please read https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS to understand the trade-offs.
|
||||
@@ -0,0 +1,33 @@
|
||||
import { CursorOptions, CursorResult, Options, SupportInfo } from "./index.js";
|
||||
|
||||
/**
|
||||
* formatWithCursor both formats the code, and translates a cursor position from unformatted code to formatted code.
|
||||
* This is useful for editor integrations, to prevent the cursor from moving when code is formatted
|
||||
*
|
||||
* The cursorOffset option should be provided, to specify where the cursor is.
|
||||
*
|
||||
* ```js
|
||||
* await prettier.formatWithCursor(" 1", { cursorOffset: 2, parser: "babel" });
|
||||
* ```
|
||||
* `-> { formatted: "1;\n", cursorOffset: 1 }`
|
||||
*/
|
||||
export function formatWithCursor(
|
||||
source: string,
|
||||
options: CursorOptions,
|
||||
): Promise<CursorResult>;
|
||||
|
||||
/**
|
||||
* `format` is used to format text using Prettier. [Options](https://prettier.io/docs/options) may be provided to override the defaults.
|
||||
*/
|
||||
export function format(source: string, options?: Options): Promise<string>;
|
||||
|
||||
/**
|
||||
* `check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`.
|
||||
* This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
|
||||
*/
|
||||
export function check(source: string, options?: Options): Promise<boolean>;
|
||||
|
||||
/**
|
||||
* Returns an object representing the parsers, languages and file types Prettier supports for the current version.
|
||||
*/
|
||||
export function getSupportInfo(): Promise<SupportInfo>;
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* @fileoverview Disallows or enforces spaces inside of array brackets.
|
||||
* @author Jamund Ferguson
|
||||
* @deprecated in ESLint v8.53.0
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
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: "array-bracket-spacing",
|
||||
url: "https://eslint.style/rules/array-bracket-spacing",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
type: "layout",
|
||||
|
||||
docs: {
|
||||
description: "Enforce consistent spacing inside array brackets",
|
||||
recommended: false,
|
||||
url: "https://eslint.org/docs/latest/rules/array-bracket-spacing",
|
||||
},
|
||||
|
||||
fixable: "whitespace",
|
||||
|
||||
schema: [
|
||||
{
|
||||
enum: ["always", "never"],
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
singleValue: {
|
||||
type: "boolean",
|
||||
},
|
||||
objectsInArrays: {
|
||||
type: "boolean",
|
||||
},
|
||||
arraysInArrays: {
|
||||
type: "boolean",
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
|
||||
messages: {
|
||||
unexpectedSpaceAfter:
|
||||
"There should be no space after '{{tokenValue}}'.",
|
||||
unexpectedSpaceBefore:
|
||||
"There should be no space before '{{tokenValue}}'.",
|
||||
missingSpaceAfter: "A space is required after '{{tokenValue}}'.",
|
||||
missingSpaceBefore: "A space is required before '{{tokenValue}}'.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const spaced = context.options[0] === "always",
|
||||
sourceCode = context.sourceCode;
|
||||
|
||||
/**
|
||||
* Determines whether an option is set, relative to the spacing option.
|
||||
* If spaced is "always", then check whether option is set to false.
|
||||
* If spaced is "never", then check whether option is set to true.
|
||||
* @param {Object} option The option to exclude.
|
||||
* @returns {boolean} Whether or not the property is excluded.
|
||||
*/
|
||||
function isOptionSet(option) {
|
||||
return context.options[1]
|
||||
? context.options[1][option] === !spaced
|
||||
: false;
|
||||
}
|
||||
|
||||
const options = {
|
||||
spaced,
|
||||
singleElementException: isOptionSet("singleValue"),
|
||||
objectsInArraysException: isOptionSet("objectsInArrays"),
|
||||
arraysInArraysException: isOptionSet("arraysInArrays"),
|
||||
};
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Helpers
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Reports that there shouldn't be a space after the first token
|
||||
* @param {ASTNode} node The node to report in the event of an error.
|
||||
* @param {Token} token The token to use for the report.
|
||||
* @returns {void}
|
||||
*/
|
||||
function reportNoBeginningSpace(node, token) {
|
||||
const nextToken = sourceCode.getTokenAfter(token);
|
||||
|
||||
context.report({
|
||||
node,
|
||||
loc: { start: token.loc.end, end: nextToken.loc.start },
|
||||
messageId: "unexpectedSpaceAfter",
|
||||
data: {
|
||||
tokenValue: token.value,
|
||||
},
|
||||
fix(fixer) {
|
||||
return fixer.removeRange([
|
||||
token.range[1],
|
||||
nextToken.range[0],
|
||||
]);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports that there shouldn't be a space before the last token
|
||||
* @param {ASTNode} node The node to report in the event of an error.
|
||||
* @param {Token} token The token to use for the report.
|
||||
* @returns {void}
|
||||
*/
|
||||
function reportNoEndingSpace(node, token) {
|
||||
const previousToken = sourceCode.getTokenBefore(token);
|
||||
|
||||
context.report({
|
||||
node,
|
||||
loc: { start: previousToken.loc.end, end: token.loc.start },
|
||||
messageId: "unexpectedSpaceBefore",
|
||||
data: {
|
||||
tokenValue: token.value,
|
||||
},
|
||||
fix(fixer) {
|
||||
return fixer.removeRange([
|
||||
previousToken.range[1],
|
||||
token.range[0],
|
||||
]);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports that there should be a space after the first token
|
||||
* @param {ASTNode} node The node to report in the event of an error.
|
||||
* @param {Token} token The token to use for the report.
|
||||
* @returns {void}
|
||||
*/
|
||||
function reportRequiredBeginningSpace(node, token) {
|
||||
context.report({
|
||||
node,
|
||||
loc: token.loc,
|
||||
messageId: "missingSpaceAfter",
|
||||
data: {
|
||||
tokenValue: token.value,
|
||||
},
|
||||
fix(fixer) {
|
||||
return fixer.insertTextAfter(token, " ");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports that there should be a space before the last token
|
||||
* @param {ASTNode} node The node to report in the event of an error.
|
||||
* @param {Token} token The token to use for the report.
|
||||
* @returns {void}
|
||||
*/
|
||||
function reportRequiredEndingSpace(node, token) {
|
||||
context.report({
|
||||
node,
|
||||
loc: token.loc,
|
||||
messageId: "missingSpaceBefore",
|
||||
data: {
|
||||
tokenValue: token.value,
|
||||
},
|
||||
fix(fixer) {
|
||||
return fixer.insertTextBefore(token, " ");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a node is an object type
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {boolean} Whether or not the node is an object type.
|
||||
*/
|
||||
function isObjectType(node) {
|
||||
return (
|
||||
node &&
|
||||
(node.type === "ObjectExpression" ||
|
||||
node.type === "ObjectPattern")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a node is an array type
|
||||
* @param {ASTNode} node The node to check.
|
||||
* @returns {boolean} Whether or not the node is an array type.
|
||||
*/
|
||||
function isArrayType(node) {
|
||||
return (
|
||||
node &&
|
||||
(node.type === "ArrayExpression" ||
|
||||
node.type === "ArrayPattern")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the spacing around array brackets
|
||||
* @param {ASTNode} node The node we're checking for spacing
|
||||
* @returns {void}
|
||||
*/
|
||||
function validateArraySpacing(node) {
|
||||
if (options.spaced && node.elements.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const first = sourceCode.getFirstToken(node),
|
||||
second = sourceCode.getFirstToken(node, 1),
|
||||
last = node.typeAnnotation
|
||||
? sourceCode.getTokenBefore(node.typeAnnotation)
|
||||
: sourceCode.getLastToken(node),
|
||||
penultimate = sourceCode.getTokenBefore(last),
|
||||
firstElement = node.elements[0],
|
||||
lastElement = node.elements.at(-1);
|
||||
|
||||
const openingBracketMustBeSpaced =
|
||||
(options.objectsInArraysException &&
|
||||
isObjectType(firstElement)) ||
|
||||
(options.arraysInArraysException &&
|
||||
isArrayType(firstElement)) ||
|
||||
(options.singleElementException && node.elements.length === 1)
|
||||
? !options.spaced
|
||||
: options.spaced;
|
||||
|
||||
const closingBracketMustBeSpaced =
|
||||
(options.objectsInArraysException &&
|
||||
isObjectType(lastElement)) ||
|
||||
(options.arraysInArraysException && isArrayType(lastElement)) ||
|
||||
(options.singleElementException && node.elements.length === 1)
|
||||
? !options.spaced
|
||||
: options.spaced;
|
||||
|
||||
if (astUtils.isTokenOnSameLine(first, second)) {
|
||||
if (
|
||||
openingBracketMustBeSpaced &&
|
||||
!sourceCode.isSpaceBetween(first, second)
|
||||
) {
|
||||
reportRequiredBeginningSpace(node, first);
|
||||
}
|
||||
if (
|
||||
!openingBracketMustBeSpaced &&
|
||||
sourceCode.isSpaceBetween(first, second)
|
||||
) {
|
||||
reportNoBeginningSpace(node, first);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
first !== penultimate &&
|
||||
astUtils.isTokenOnSameLine(penultimate, last)
|
||||
) {
|
||||
if (
|
||||
closingBracketMustBeSpaced &&
|
||||
!sourceCode.isSpaceBetween(penultimate, last)
|
||||
) {
|
||||
reportRequiredEndingSpace(node, last);
|
||||
}
|
||||
if (
|
||||
!closingBracketMustBeSpaced &&
|
||||
sourceCode.isSpaceBetween(penultimate, last)
|
||||
) {
|
||||
reportNoEndingSpace(node, last);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
// Public
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
return {
|
||||
ArrayPattern: validateArraySpacing,
|
||||
ArrayExpression: validateArraySpacing,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,680 @@
|
||||
semver(1) -- The semantic versioner for npm
|
||||
===========================================
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm install semver
|
||||
````
|
||||
|
||||
## Usage
|
||||
|
||||
As a node module:
|
||||
|
||||
```js
|
||||
const semver = require('semver')
|
||||
|
||||
semver.valid('1.2.3') // '1.2.3'
|
||||
semver.valid('a.b.c') // null
|
||||
semver.clean(' =v1.2.3 ') // '1.2.3'
|
||||
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
|
||||
semver.gt('1.2.3', '9.8.7') // false
|
||||
semver.lt('1.2.3', '9.8.7') // true
|
||||
semver.minVersion('>=1.0.0') // '1.0.0'
|
||||
semver.valid(semver.coerce('v2')) // '2.0.0'
|
||||
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
|
||||
```
|
||||
|
||||
You can also just load the module for the function that you care about if
|
||||
you'd like to minimize your footprint.
|
||||
|
||||
```js
|
||||
// load the whole API at once in a single object
|
||||
const semver = require('semver')
|
||||
|
||||
// or just load the bits you need
|
||||
// all of them listed here, just pick and choose what you want
|
||||
|
||||
// classes
|
||||
const SemVer = require('semver/classes/semver')
|
||||
const Comparator = require('semver/classes/comparator')
|
||||
const Range = require('semver/classes/range')
|
||||
|
||||
// functions for working with versions
|
||||
const semverParse = require('semver/functions/parse')
|
||||
const semverValid = require('semver/functions/valid')
|
||||
const semverClean = require('semver/functions/clean')
|
||||
const semverInc = require('semver/functions/inc')
|
||||
const semverDiff = require('semver/functions/diff')
|
||||
const semverMajor = require('semver/functions/major')
|
||||
const semverMinor = require('semver/functions/minor')
|
||||
const semverPatch = require('semver/functions/patch')
|
||||
const semverPrerelease = require('semver/functions/prerelease')
|
||||
const semverCompare = require('semver/functions/compare')
|
||||
const semverRcompare = require('semver/functions/rcompare')
|
||||
const semverCompareLoose = require('semver/functions/compare-loose')
|
||||
const semverCompareBuild = require('semver/functions/compare-build')
|
||||
const semverSort = require('semver/functions/sort')
|
||||
const semverRsort = require('semver/functions/rsort')
|
||||
const semverTruncate = require('semver/functions/truncate')
|
||||
|
||||
// low-level comparators between versions
|
||||
const semverGt = require('semver/functions/gt')
|
||||
const semverLt = require('semver/functions/lt')
|
||||
const semverEq = require('semver/functions/eq')
|
||||
const semverNeq = require('semver/functions/neq')
|
||||
const semverGte = require('semver/functions/gte')
|
||||
const semverLte = require('semver/functions/lte')
|
||||
const semverCmp = require('semver/functions/cmp')
|
||||
const semverCoerce = require('semver/functions/coerce')
|
||||
|
||||
// working with ranges
|
||||
const semverSatisfies = require('semver/functions/satisfies')
|
||||
const semverMaxSatisfying = require('semver/ranges/max-satisfying')
|
||||
const semverMinSatisfying = require('semver/ranges/min-satisfying')
|
||||
const semverToComparators = require('semver/ranges/to-comparators')
|
||||
const semverMinVersion = require('semver/ranges/min-version')
|
||||
const semverValidRange = require('semver/ranges/valid')
|
||||
const semverOutside = require('semver/ranges/outside')
|
||||
const semverGtr = require('semver/ranges/gtr')
|
||||
const semverLtr = require('semver/ranges/ltr')
|
||||
const semverIntersects = require('semver/ranges/intersects')
|
||||
const semverSimplifyRange = require('semver/ranges/simplify')
|
||||
const semverRangeSubset = require('semver/ranges/subset')
|
||||
```
|
||||
|
||||
As a command-line utility:
|
||||
|
||||
```
|
||||
$ semver -h
|
||||
|
||||
A JavaScript implementation of the https://semver.org/ specification
|
||||
Copyright Isaac Z. Schlueter
|
||||
|
||||
Usage: semver [options] <version> [<version> [...]]
|
||||
Prints valid versions sorted by SemVer precedence
|
||||
|
||||
Options:
|
||||
-r --range <range>
|
||||
Print versions that match the specified range.
|
||||
|
||||
-i --increment [<level>]
|
||||
Increment a version by the specified level. Level can
|
||||
be one of: major, minor, patch, premajor, preminor,
|
||||
prepatch, prerelease, or release. Default level is 'patch'.
|
||||
Only one version may be specified.
|
||||
|
||||
--preid <identifier>
|
||||
Identifier to be used to prefix premajor, preminor,
|
||||
prepatch or prerelease version increments.
|
||||
|
||||
-l --loose
|
||||
Interpret versions and ranges loosely
|
||||
|
||||
-n <0|1|false>
|
||||
Base number for prerelease identifier (default: 0).
|
||||
Use false to omit the number altogether.
|
||||
|
||||
-p --include-prerelease
|
||||
Always include prerelease versions in range matching
|
||||
|
||||
-c --coerce
|
||||
Coerce a string into SemVer if possible
|
||||
(does not imply --loose)
|
||||
|
||||
--rtl
|
||||
Coerce version strings right to left
|
||||
|
||||
--ltr
|
||||
Coerce version strings left to right (default)
|
||||
|
||||
Program exits successfully if any valid version satisfies
|
||||
all supplied ranges, and prints all satisfying versions.
|
||||
|
||||
If no satisfying versions are found, then exits failure.
|
||||
|
||||
Versions are printed in ascending order, so supplying
|
||||
multiple versions to the utility will just sort them.
|
||||
```
|
||||
|
||||
## Versions
|
||||
|
||||
A "version" is described by the `v2.0.0` specification found at
|
||||
<https://semver.org/>.
|
||||
|
||||
A leading `"="` or `"v"` character is stripped off and ignored.
|
||||
Support for stripping a leading "v" is kept for compatibility with `v1.0.0` of the SemVer
|
||||
specification but should not be used anymore.
|
||||
|
||||
## Ranges
|
||||
|
||||
A `version range` is a set of `comparators` that specify versions
|
||||
that satisfy the range.
|
||||
|
||||
A `comparator` is composed of an `operator` and a `version`. The set
|
||||
of primitive `operators` is:
|
||||
|
||||
* `<` Less than
|
||||
* `<=` Less than or equal to
|
||||
* `>` Greater than
|
||||
* `>=` Greater than or equal to
|
||||
* `=` Equal. If no operator is specified, then equality is assumed,
|
||||
so this operator is optional but MAY be included.
|
||||
|
||||
For example, the comparator `>=1.2.7` would match the versions
|
||||
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
|
||||
or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and
|
||||
would match the versions `2.0.0` and `3.1.0`, but not the versions
|
||||
`1.0.1` or `1.1.0`.
|
||||
|
||||
Comparators can be joined by whitespace to form a `comparator set`,
|
||||
which is satisfied by the **intersection** of all of the comparators
|
||||
it includes.
|
||||
|
||||
A range is composed of one or more comparator sets, joined by `||`. A
|
||||
version matches a range if and only if every comparator in at least
|
||||
one of the `||`-separated comparator sets is satisfied by the version.
|
||||
|
||||
For example, the range `>=1.2.7 <1.3.0` would match the versions
|
||||
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
|
||||
or `1.1.0`.
|
||||
|
||||
The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
|
||||
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.
|
||||
|
||||
### Prerelease Tags
|
||||
|
||||
If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
|
||||
it will only be allowed to satisfy comparator sets if at least one
|
||||
comparator with the same `[major, minor, patch]` tuple also has a
|
||||
prerelease tag.
|
||||
|
||||
For example, the range `>1.2.3-alpha.3` would be allowed to match the
|
||||
version `1.2.3-alpha.7`, but it would *not* be satisfied by
|
||||
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
|
||||
than" `1.2.3-alpha.3` according to the SemVer sort rules. The version
|
||||
range only accepts prerelease tags on the `1.2.3` version.
|
||||
Version `3.4.5` *would* satisfy the range because it does not have a
|
||||
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.
|
||||
|
||||
The purpose of this behavior is twofold. First, prerelease versions
|
||||
frequently are updated very quickly, and contain many breaking changes
|
||||
that are (by the author's design) not yet fit for public consumption.
|
||||
Therefore, by default, they are excluded from range-matching
|
||||
semantics.
|
||||
|
||||
Second, a user who has opted into using a prerelease version has
|
||||
indicated the intent to use *that specific* set of
|
||||
alpha/beta/rc versions. By including a prerelease tag in the range,
|
||||
the user is indicating that they are aware of the risk. However, it
|
||||
is still not appropriate to assume that they have opted into taking a
|
||||
similar risk on the *next* set of prerelease versions.
|
||||
|
||||
Note that this behavior can be suppressed (treating all prerelease
|
||||
versions as if they were normal versions, for range-matching)
|
||||
by setting the `includePrerelease` flag on the options
|
||||
object to any
|
||||
[functions](https://github.com/npm/node-semver#functions) that do
|
||||
range matching.
|
||||
|
||||
#### Prerelease Identifiers
|
||||
|
||||
The method `.inc` takes an additional `identifier` string argument that
|
||||
will append the value of the string as a prerelease identifier:
|
||||
|
||||
```javascript
|
||||
semver.inc('1.2.3', 'prerelease', 'beta')
|
||||
// '1.2.4-beta.0'
|
||||
```
|
||||
|
||||
command-line example:
|
||||
|
||||
```bash
|
||||
$ semver 1.2.3 -i prerelease --preid beta
|
||||
1.2.4-beta.0
|
||||
```
|
||||
|
||||
Which then can be used to increment further:
|
||||
|
||||
```bash
|
||||
$ semver 1.2.4-beta.0 -i prerelease
|
||||
1.2.4-beta.1
|
||||
```
|
||||
|
||||
To get out of the prerelease phase, use the `release` option:
|
||||
|
||||
```bash
|
||||
$ semver 1.2.4-beta.1 -i release
|
||||
1.2.4
|
||||
```
|
||||
|
||||
#### Prerelease Identifier Base
|
||||
|
||||
The method `.inc` takes an optional parameter 'identifierBase' string
|
||||
that will let you let your prerelease number as zero-based or one-based.
|
||||
Set to `false` to omit the prerelease number altogether.
|
||||
If you do not specify this parameter, it will default to zero-based.
|
||||
|
||||
```javascript
|
||||
semver.inc('1.2.3', 'prerelease', 'beta', '1')
|
||||
// '1.2.4-beta.1'
|
||||
```
|
||||
|
||||
```javascript
|
||||
semver.inc('1.2.3', 'prerelease', 'beta', false)
|
||||
// '1.2.4-beta'
|
||||
```
|
||||
|
||||
command-line example:
|
||||
|
||||
```bash
|
||||
$ semver 1.2.3 -i prerelease --preid beta -n 1
|
||||
1.2.4-beta.1
|
||||
```
|
||||
|
||||
```bash
|
||||
$ semver 1.2.3 -i prerelease --preid beta -n false
|
||||
1.2.4-beta
|
||||
```
|
||||
|
||||
### Advanced Range Syntax
|
||||
|
||||
Advanced range syntax desugars to primitive comparators in
|
||||
deterministic ways.
|
||||
|
||||
Advanced ranges may be combined in the same way as primitive
|
||||
comparators using white space or `||`.
|
||||
|
||||
#### Hyphen Ranges `X.Y.Z - A.B.C`
|
||||
|
||||
Specifies an inclusive set.
|
||||
|
||||
* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`
|
||||
|
||||
If a partial version is provided as the first version in the inclusive
|
||||
range, then the missing pieces are replaced with zeroes.
|
||||
|
||||
* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`
|
||||
|
||||
If a partial version is provided as the second version in the
|
||||
inclusive range, then all versions that start with the supplied parts
|
||||
of the tuple are accepted, but nothing that would be greater than the
|
||||
provided tuple parts.
|
||||
|
||||
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0`
|
||||
* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0`
|
||||
|
||||
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
|
||||
|
||||
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
|
||||
numeric values in the `[major, minor, patch]` tuple.
|
||||
|
||||
* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless
|
||||
`includePrerelease` is specified, in which case any version at all
|
||||
satisfies)
|
||||
* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version)
|
||||
* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions)
|
||||
|
||||
A partial version range is treated as an X-Range, so the special
|
||||
character is in fact optional.
|
||||
|
||||
* `""` (empty string) := `*` := `>=0.0.0`
|
||||
* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0`
|
||||
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0`
|
||||
|
||||
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
|
||||
|
||||
Allows patch-level changes if a minor version is specified on the
|
||||
comparator. Allows minor-level changes if not.
|
||||
|
||||
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0`
|
||||
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`)
|
||||
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`)
|
||||
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0`
|
||||
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`)
|
||||
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`)
|
||||
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in
|
||||
the `1.2.3` version will be allowed, if they are greater than or
|
||||
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
|
||||
`1.2.4-beta.2` would not, because it is a prerelease of a
|
||||
different `[major, minor, patch]` tuple.
|
||||
|
||||
#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`
|
||||
|
||||
Allows changes that do not modify the left-most non-zero element in the
|
||||
`[major, minor, patch]` tuple. In other words, this allows patch and
|
||||
minor updates for versions `1.0.0` and above, patch updates for
|
||||
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.
|
||||
|
||||
Many authors treat a `0.x` version as if the `x` were the major
|
||||
"breaking-change" indicator.
|
||||
|
||||
Caret ranges are ideal when an author may make breaking changes
|
||||
between `0.2.4` and `0.3.0` releases, which is a common practice.
|
||||
However, it presumes that there will *not* be breaking changes between
|
||||
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
|
||||
additive (but non-breaking), according to commonly observed practices.
|
||||
|
||||
* `^1.2.3` := `>=1.2.3 <2.0.0-0`
|
||||
* `^0.2.3` := `>=0.2.3 <0.3.0-0`
|
||||
* `^0.0.3` := `>=0.0.3 <0.0.4-0`
|
||||
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in
|
||||
the `1.2.3` version will be allowed, if they are greater than or
|
||||
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
|
||||
`1.2.4-beta.2` would not, because it is a prerelease of a
|
||||
different `[major, minor, patch]` tuple.
|
||||
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the
|
||||
`0.0.3` version *only* will be allowed, if they are greater than or
|
||||
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
|
||||
|
||||
When parsing caret ranges, a missing `patch` value desugars to the
|
||||
number `0`, but will allow flexibility within that value, even if the
|
||||
major and minor versions are both `0`.
|
||||
|
||||
* `^1.2.x` := `>=1.2.0 <2.0.0-0`
|
||||
* `^0.0.x` := `>=0.0.0 <0.1.0-0`
|
||||
* `^0.0` := `>=0.0.0 <0.1.0-0`
|
||||
|
||||
A missing `minor` and `patch` values will desugar to zero, but also
|
||||
allow flexibility within those values, even if the major version is
|
||||
zero.
|
||||
|
||||
* `^1.x` := `>=1.0.0 <2.0.0-0`
|
||||
* `^0.x` := `>=0.0.0 <1.0.0-0`
|
||||
|
||||
### Range Grammar
|
||||
|
||||
Putting all this together, here is a Backus-Naur grammar for ranges,
|
||||
for the benefit of parser authors:
|
||||
|
||||
```bnf
|
||||
range-set ::= range ( logical-or range ) *
|
||||
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
|
||||
range ::= hyphen | simple ( ' ' simple ) * | ''
|
||||
hyphen ::= partial ' - ' partial
|
||||
simple ::= primitive | partial | tilde | caret
|
||||
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
|
||||
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
|
||||
xr ::= 'x' | 'X' | '*' | nr
|
||||
nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
|
||||
tilde ::= '~' partial
|
||||
caret ::= '^' partial
|
||||
qualifier ::= ( '-' pre )? ( '+' build )?
|
||||
pre ::= prepart ( '.' prepart ) *
|
||||
prepart ::= nr | alphanumid
|
||||
build ::= buildid ( '.' buildid ) *
|
||||
alphanumid ::= ( ['0'-'9'] ) * [-A-Za-z] [-0-9A-Za-z] *
|
||||
buildid ::= [-0-9A-Za-z]+
|
||||
```
|
||||
|
||||
Note: Prerelease identifiers (`pre`) use `nr` for numeric parts, which
|
||||
disallows leading zeros (e.g., `1.2.3-00` is invalid). Build metadata
|
||||
identifiers (`build`) allow any alphanumeric string including leading
|
||||
zeros (e.g., `1.2.3+00` is valid). This matches the
|
||||
[SemVer 2.0.0 specification](https://semver.org/#spec-item-9).
|
||||
|
||||
## Functions
|
||||
|
||||
All methods and classes take a final `options` object argument. All
|
||||
options in this object are `false` by default. The options supported
|
||||
are:
|
||||
|
||||
- `loose`: Be more forgiving about not-quite-valid semver strings.
|
||||
(Any resulting output will always be 100% strict compliant, of
|
||||
course.) For backwards compatibility reasons, if the `options`
|
||||
argument is a boolean value instead of an object, it is interpreted
|
||||
to be the `loose` param.
|
||||
- `includePrerelease`: Set to suppress the [default
|
||||
behavior](https://github.com/npm/node-semver#prerelease-tags) of
|
||||
excluding prerelease tagged versions from ranges unless they are
|
||||
explicitly opted into.
|
||||
|
||||
Strict-mode Comparators and Ranges will be strict about the SemVer
|
||||
strings that they parse.
|
||||
|
||||
* `valid(v)`: Return the parsed version, or null if it's not valid.
|
||||
* `inc(v, releaseType, options, identifier, identifierBase)`:
|
||||
Return the version incremented by the release
|
||||
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
|
||||
`prepatch`, `prerelease`, or `release`), or null if it's not valid
|
||||
* `premajor` in one call will bump the version up to the next major
|
||||
version and down to a prerelease of that major version.
|
||||
`preminor`, and `prepatch` work the same way.
|
||||
* If called from a non-prerelease version, `prerelease` will work the
|
||||
same as `prepatch`. It increments the patch version and then makes a
|
||||
prerelease. If the input version is already a prerelease it simply
|
||||
increments it.
|
||||
* `release` will remove any prerelease part of the version.
|
||||
* `identifier` can be used to prefix `premajor`, `preminor`,
|
||||
`prepatch`, or `prerelease` version increments. `identifierBase`
|
||||
is the base to be used for the `prerelease` identifier.
|
||||
* `prerelease(v)`: Returns an array of prerelease components, or null
|
||||
if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
|
||||
* `major(v)`: Return the major version number.
|
||||
* `minor(v)`: Return the minor version number.
|
||||
* `patch(v)`: Return the patch version number.
|
||||
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
|
||||
or comparators intersect.
|
||||
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
|
||||
a `SemVer` object or `null`.
|
||||
* `truncate(v, releaseType)`: Return the version with components _lower_
|
||||
than `releaseType` dropped off, e.g.:
|
||||
* `major` removes build & prerelease info and sets minor & patch to 0.
|
||||
* `minor` removes build & prerelease info, and sets patch to 0
|
||||
* `patch` removes build & prerelease info
|
||||
* All prerelease types remove build info only
|
||||
|
||||
### Comparison
|
||||
|
||||
* `gt(v1, v2)`: `v1 > v2`
|
||||
* `gte(v1, v2)`: `v1 >= v2`
|
||||
* `lt(v1, v2)`: `v1 < v2`
|
||||
* `lte(v1, v2)`: `v1 <= v2`
|
||||
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
|
||||
even if they're not the same string. You already know how to
|
||||
compare strings.
|
||||
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
|
||||
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
|
||||
the corresponding function above. `"==="` and `"!=="` do simple
|
||||
string comparison, but are included for completeness. Throws if an
|
||||
invalid comparison string is provided.
|
||||
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
|
||||
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
|
||||
* `rcompare(v1, v2)`: The reverse of `compare`. Sorts an array of versions
|
||||
in descending order when passed to `Array.sort()`.
|
||||
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
|
||||
are equal. Sorts in ascending order if passed to `Array.sort()`.
|
||||
* `compareLoose(v1, v2)`: Short for `compare(v1, v2, { loose: true })`.
|
||||
* `diff(v1, v2)`: Returns the difference between two versions by the release type
|
||||
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
|
||||
or null if the versions are the same.
|
||||
|
||||
### Sorting
|
||||
|
||||
* `sort(versions)`: Returns a sorted array of versions based on the `compareBuild`
|
||||
function.
|
||||
* `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on
|
||||
the `compareBuild` function in descending order.
|
||||
|
||||
### Comparators
|
||||
|
||||
* `intersects(comparator)`: Return true if the comparators intersect
|
||||
|
||||
### Ranges
|
||||
|
||||
* `validRange(range)`: Return the valid range or null if it's not valid.
|
||||
* `satisfies(version, range)`: Return true if the version satisfies the
|
||||
range.
|
||||
* `maxSatisfying(versions, range)`: Return the highest version in the list
|
||||
that satisfies the range, or `null` if none of them do.
|
||||
* `minSatisfying(versions, range)`: Return the lowest version in the list
|
||||
that satisfies the range, or `null` if none of them do.
|
||||
* `minVersion(range)`: Return the lowest version that can match
|
||||
the given range.
|
||||
* `gtr(version, range)`: Return `true` if the version is greater than all the
|
||||
versions possible in the range.
|
||||
* `ltr(version, range)`: Return `true` if the version is less than all the
|
||||
versions possible in the range.
|
||||
* `outside(version, range, hilo)`: Return true if the version is outside
|
||||
the bounds of the range in either the high or low direction. The
|
||||
`hilo` argument must be either the string `'>'` or `'<'`. (This is
|
||||
the function called by `gtr` and `ltr`.)
|
||||
* `intersects(range)`: Return true if any of the range comparators intersect.
|
||||
* `simplifyRange(versions, range)`: Return a "simplified" range that
|
||||
matches the same items in the `versions` list as the range specified. Note
|
||||
that it does *not* guarantee that it would match the same versions in all
|
||||
cases, only for the set of versions provided. This is useful when
|
||||
generating ranges by joining together multiple versions with `||`
|
||||
programmatically, to provide the user with something a bit more
|
||||
ergonomic. If the provided range is shorter in string-length than the
|
||||
generated range, then that is returned.
|
||||
* `subset(subRange, superRange)`: Return `true` if the `subRange` range is
|
||||
entirely contained by the `superRange` range.
|
||||
|
||||
Note that, since ranges may be non-contiguous, a version might not be
|
||||
greater than a range, less than a range, *or* satisfy a range! For
|
||||
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
|
||||
until `2.0.0`, so version `1.2.10` would not be greater than the
|
||||
range (because `2.0.1` satisfies, which is higher), nor less than the
|
||||
range (since `1.2.8` satisfies, which is lower), and it also does not
|
||||
satisfy the range.
|
||||
|
||||
If you want to know if a version satisfies or does not satisfy a
|
||||
range, use the `satisfies(version, range)` function.
|
||||
|
||||
### Coercion
|
||||
|
||||
* `coerce(version, options)`: Coerces a string to semver if possible
|
||||
|
||||
This aims to provide a very forgiving translation of a non-semver string to
|
||||
semver. It looks for the first digit in a string and consumes all
|
||||
remaining characters which satisfy at least a partial semver (e.g., `1`,
|
||||
`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer
|
||||
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All
|
||||
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
|
||||
`3.4.0`). Only text which lacks digits will fail coercion (`version one`
|
||||
is not valid). The maximum length for any semver component considered for
|
||||
coercion is 16 characters; longer components will be ignored
|
||||
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
|
||||
semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
|
||||
components are invalid (`9999999999999999.4.7.4` is likely invalid).
|
||||
|
||||
If the `options.rtl` flag is set, then `coerce` will return the right-most
|
||||
coercible tuple that does not share an ending index with a longer coercible
|
||||
tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
|
||||
`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
|
||||
any other overlapping SemVer tuple.
|
||||
|
||||
If the `options.includePrerelease` flag is set, then the `coerce` result will contain
|
||||
prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2`
|
||||
will preserve prerelease `rc.1` and build `rev.2` in the result.
|
||||
|
||||
### Clean
|
||||
|
||||
* `clean(version)`: Clean a string to be a valid semver if possible
|
||||
|
||||
This will return a cleaned and trimmed semver version. If the provided
|
||||
version is not valid a null will be returned. This does not work for
|
||||
ranges.
|
||||
|
||||
ex.
|
||||
* `s.clean(' = v 2.1.5foo')`: `null`
|
||||
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
|
||||
* `s.clean(' = v 2.1.5-foo')`: `null`
|
||||
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
|
||||
* `s.clean('=v2.1.5')`: `'2.1.5'`
|
||||
* `s.clean(' =v2.1.5')`: `'2.1.5'`
|
||||
* `s.clean(' 2.1.5 ')`: `'2.1.5'`
|
||||
* `s.clean('~1.0.0')`: `null`
|
||||
|
||||
## Constants
|
||||
|
||||
As a convenience, helper constants are exported to provide information about what `node-semver` supports:
|
||||
|
||||
### `RELEASE_TYPES`
|
||||
|
||||
- major
|
||||
- premajor
|
||||
- minor
|
||||
- preminor
|
||||
- patch
|
||||
- prepatch
|
||||
- prerelease
|
||||
|
||||
```
|
||||
const semver = require('semver');
|
||||
|
||||
if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) {
|
||||
console.log('This is a valid release type!');
|
||||
} else {
|
||||
console.warn('This is NOT a valid release type!');
|
||||
}
|
||||
```
|
||||
|
||||
### `SEMVER_SPEC_VERSION`
|
||||
|
||||
2.0.0
|
||||
|
||||
```
|
||||
const semver = require('semver');
|
||||
|
||||
console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION);
|
||||
```
|
||||
|
||||
## Exported Modules
|
||||
|
||||
<!--
|
||||
TODO: Make sure that all of these items are documented (classes aren't,
|
||||
eg), and then pull the module name into the documentation for that specific
|
||||
thing.
|
||||
-->
|
||||
|
||||
You may pull in just the part of this semver utility that you need if you
|
||||
are sensitive to packing and tree-shaking concerns. The main
|
||||
`require('semver')` export uses getter functions to lazily load the parts
|
||||
of the API that are used.
|
||||
|
||||
The following modules are available:
|
||||
|
||||
* `require('semver')`
|
||||
* `require('semver/classes')`
|
||||
* `require('semver/classes/comparator')`
|
||||
* `require('semver/classes/range')`
|
||||
* `require('semver/classes/semver')`
|
||||
* `require('semver/functions/clean')`
|
||||
* `require('semver/functions/cmp')`
|
||||
* `require('semver/functions/coerce')`
|
||||
* `require('semver/functions/compare')`
|
||||
* `require('semver/functions/compare-build')`
|
||||
* `require('semver/functions/compare-loose')`
|
||||
* `require('semver/functions/diff')`
|
||||
* `require('semver/functions/eq')`
|
||||
* `require('semver/functions/gt')`
|
||||
* `require('semver/functions/gte')`
|
||||
* `require('semver/functions/inc')`
|
||||
* `require('semver/functions/lt')`
|
||||
* `require('semver/functions/lte')`
|
||||
* `require('semver/functions/major')`
|
||||
* `require('semver/functions/minor')`
|
||||
* `require('semver/functions/neq')`
|
||||
* `require('semver/functions/parse')`
|
||||
* `require('semver/functions/patch')`
|
||||
* `require('semver/functions/prerelease')`
|
||||
* `require('semver/functions/rcompare')`
|
||||
* `require('semver/functions/rsort')`
|
||||
* `require('semver/functions/satisfies')`
|
||||
* `require('semver/functions/sort')`
|
||||
* `require('semver/functions/truncate')`
|
||||
* `require('semver/functions/valid')`
|
||||
* `require('semver/ranges/gtr')`
|
||||
* `require('semver/ranges/intersects')`
|
||||
* `require('semver/ranges/ltr')`
|
||||
* `require('semver/ranges/max-satisfying')`
|
||||
* `require('semver/ranges/min-satisfying')`
|
||||
* `require('semver/ranges/min-version')`
|
||||
* `require('semver/ranges/outside')`
|
||||
* `require('semver/ranges/simplify')`
|
||||
* `require('semver/ranges/subset')`
|
||||
* `require('semver/ranges/to-comparators')`
|
||||
* `require('semver/ranges/valid')`
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/*! *****************************************************************************
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
||||
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
||||
MERCHANTABLITY OR NON-INFRINGEMENT.
|
||||
|
||||
See the Apache Version 2.0 License for specific language governing permissions
|
||||
and limitations under the License.
|
||||
***************************************************************************** */
|
||||
|
||||
|
||||
/// <reference no-default-lib="true"/>
|
||||
|
||||
/// <reference lib="es5" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="webworker.importscripts" />
|
||||
/// <reference lib="scripthost" />
|
||||
@@ -0,0 +1,25 @@
|
||||
// Code generated by Herebyfile.mjs generate:enums from internal/ast/symbol.go. DO NOT EDIT.
|
||||
export var InternalSymbolName;
|
||||
(function (InternalSymbolName) {
|
||||
InternalSymbolName["Call"] = "__call";
|
||||
InternalSymbolName["Constructor"] = "__constructor";
|
||||
InternalSymbolName["New"] = "__new";
|
||||
InternalSymbolName["Index"] = "__index";
|
||||
InternalSymbolName["ExportStar"] = "__export";
|
||||
InternalSymbolName["Global"] = "__global";
|
||||
InternalSymbolName["Missing"] = "__missing";
|
||||
InternalSymbolName["Type"] = "__type";
|
||||
InternalSymbolName["Object"] = "__object";
|
||||
InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
|
||||
InternalSymbolName["Class"] = "__class";
|
||||
InternalSymbolName["Function"] = "__function";
|
||||
InternalSymbolName["Computed"] = "__computed";
|
||||
InternalSymbolName["AssignmentDeclaration"] = "__assignment";
|
||||
InternalSymbolName["InstantiationExpression"] = "__instantiationExpression";
|
||||
InternalSymbolName["ImportAttributes"] = "__importAttributes";
|
||||
InternalSymbolName["ExportEquals"] = "export=";
|
||||
InternalSymbolName["Default"] = "default";
|
||||
InternalSymbolName["This"] = "this";
|
||||
InternalSymbolName["ModuleExports"] = "module.exports";
|
||||
})(InternalSymbolName || (InternalSymbolName = {}));
|
||||
//# sourceMappingURL=internalSymbolName.enum.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,MAAM,EAAE,GACqE,CAAC"}
|
||||
@@ -0,0 +1 @@
|
||||
export { __param as _ } from "tslib";
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "humanize-ms",
|
||||
"version": "1.2.1",
|
||||
"description": "transform humanize time to ms",
|
||||
"main": "index.js",
|
||||
"files": [
|
||||
"index.js"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "make test"
|
||||
},
|
||||
"keywords": [
|
||||
"humanize",
|
||||
"ms"
|
||||
],
|
||||
"author": {
|
||||
"name": "dead-horse",
|
||||
"email": "dead_horse@qq.com",
|
||||
"url": "http://deadhorse.me"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/node-modules/humanize-ms"
|
||||
},
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"autod": "*",
|
||||
"beautify-benchmark": "~0.2.4",
|
||||
"benchmark": "~1.0.0",
|
||||
"istanbul": "*",
|
||||
"mocha": "*",
|
||||
"should": "*"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,478 @@
|
||||
import AtRule from './at-rule.js'
|
||||
import Comment from './comment.js'
|
||||
import Declaration from './declaration.js'
|
||||
import Node, { ChildNode, ChildProps, NodeProps } from './node.js'
|
||||
import { Root } from './postcss.js'
|
||||
import Rule from './rule.js'
|
||||
|
||||
declare namespace Container {
|
||||
export type ContainerWithChildren<Child extends Node = ChildNode> = {
|
||||
nodes: Child[]
|
||||
} & (AtRule | Root | Rule)
|
||||
|
||||
export interface ValueOptions {
|
||||
/**
|
||||
* String that’s used to narrow down values and speed up the regexp search.
|
||||
*/
|
||||
fast?: string
|
||||
|
||||
/**
|
||||
* An array of property names.
|
||||
*/
|
||||
props?: readonly string[]
|
||||
}
|
||||
|
||||
export interface ContainerProps extends NodeProps {
|
||||
nodes?: readonly (ChildProps | Node)[]
|
||||
}
|
||||
|
||||
/**
|
||||
* All types that can be passed into container methods to create or add a new
|
||||
* child node.
|
||||
*/
|
||||
export type NewChild =
|
||||
| ChildProps
|
||||
| Node
|
||||
| readonly ChildProps[]
|
||||
| readonly Node[]
|
||||
| readonly string[]
|
||||
| string
|
||||
| undefined
|
||||
|
||||
export { Container_ as default }
|
||||
}
|
||||
|
||||
/**
|
||||
* The `Root`, `AtRule`, and `Rule` container nodes
|
||||
* inherit some common methods to help work with their children.
|
||||
*
|
||||
* Note that all containers can store any content. If you write a rule inside
|
||||
* a rule, PostCSS will parse it.
|
||||
*/
|
||||
declare abstract class Container_<Child extends Node = ChildNode> extends Node {
|
||||
/**
|
||||
* An array containing the container’s children.
|
||||
*
|
||||
* ```js
|
||||
* const root = postcss.parse('a { color: black }')
|
||||
* root.nodes.length //=> 1
|
||||
* root.nodes[0].selector //=> 'a'
|
||||
* root.nodes[0].nodes[0].prop //=> 'color'
|
||||
* ```
|
||||
*/
|
||||
nodes: Child[] | undefined
|
||||
|
||||
/**
|
||||
* The container’s first child.
|
||||
*
|
||||
* ```js
|
||||
* rule.first === rules.nodes[0]
|
||||
* ```
|
||||
*/
|
||||
get first(): Child | undefined
|
||||
|
||||
/**
|
||||
* The container’s last child.
|
||||
*
|
||||
* ```js
|
||||
* rule.last === rule.nodes[rule.nodes.length - 1]
|
||||
* ```
|
||||
*/
|
||||
get last(): Child | undefined
|
||||
/**
|
||||
* Inserts new nodes to the end of the container.
|
||||
*
|
||||
* ```js
|
||||
* const decl1 = new Declaration({ prop: 'color', value: 'black' })
|
||||
* const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
|
||||
* rule.append(decl1, decl2)
|
||||
*
|
||||
* root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
|
||||
* root.append({ selector: 'a' }) // rule
|
||||
* rule.append({ prop: 'color', value: 'black' }) // declaration
|
||||
* rule.append({ text: 'Comment' }) // comment
|
||||
*
|
||||
* root.append('a {}')
|
||||
* root.first.append('color: black; z-index: 1')
|
||||
* ```
|
||||
*
|
||||
* @param nodes New nodes.
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
append(...nodes: Container.NewChild[]): this
|
||||
assign(overrides: Container.ContainerProps | object): this
|
||||
clone(overrides?: Partial<Container.ContainerProps>): this
|
||||
|
||||
cloneAfter(overrides?: Partial<Container.ContainerProps>): this
|
||||
|
||||
cloneBefore(overrides?: Partial<Container.ContainerProps>): this
|
||||
/**
|
||||
* Iterates through the container’s immediate children,
|
||||
* calling `callback` for each child.
|
||||
*
|
||||
* Returning `false` in the callback will break iteration.
|
||||
*
|
||||
* This method only iterates through the container’s immediate children.
|
||||
* If you need to recursively iterate through all the container’s descendant
|
||||
* nodes, use `Container#walk`.
|
||||
*
|
||||
* Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
|
||||
* if you are mutating the array of child nodes during iteration.
|
||||
* PostCSS will adjust the current index to match the mutations.
|
||||
*
|
||||
* ```js
|
||||
* const root = postcss.parse('a { color: black; z-index: 1 }')
|
||||
* const rule = root.first
|
||||
*
|
||||
* for (const decl of rule.nodes) {
|
||||
* decl.cloneBefore({ prop: '-webkit-' + decl.prop })
|
||||
* // Cycle will be infinite, because cloneBefore moves the current node
|
||||
* // to the next index
|
||||
* }
|
||||
*
|
||||
* rule.each(decl => {
|
||||
* decl.cloneBefore({ prop: '-webkit-' + decl.prop })
|
||||
* // Will be executed only for color and z-index
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @param callback Iterator receives each node and index.
|
||||
* @return Returns `false` if iteration was broke.
|
||||
*/
|
||||
each(
|
||||
callback: (node: Child, index: number) => false | void
|
||||
): false | undefined
|
||||
|
||||
/**
|
||||
* Returns `true` if callback returns `true`
|
||||
* for all of the container’s children.
|
||||
*
|
||||
* ```js
|
||||
* const noPrefixes = rule.every(i => i.prop[0] !== '-')
|
||||
* ```
|
||||
*
|
||||
* @param condition Iterator returns true or false.
|
||||
* @return Is every child pass condition.
|
||||
*/
|
||||
every(
|
||||
condition: (node: Child, index: number, nodes: Child[]) => boolean
|
||||
): boolean
|
||||
/**
|
||||
* Returns a `child`’s index within the `Container#nodes` array.
|
||||
*
|
||||
* ```js
|
||||
* rule.index( rule.nodes[2] ) //=> 2
|
||||
* ```
|
||||
*
|
||||
* @param child Child of the current container.
|
||||
* @return Child index.
|
||||
*/
|
||||
index(child: Child | number): number
|
||||
|
||||
/**
|
||||
* Insert new node after old node within the container.
|
||||
*
|
||||
* @param oldNode Child or child’s index.
|
||||
* @param newNode New node.
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
insertAfter(oldNode: Child | number, newNode: Container.NewChild): this
|
||||
|
||||
/**
|
||||
* Traverses the container’s descendant nodes, calling callback
|
||||
* for each comment node.
|
||||
*
|
||||
* Like `Container#each`, this method is safe
|
||||
* to use if you are mutating arrays during iteration.
|
||||
*
|
||||
* ```js
|
||||
* root.walkComments(comment => {
|
||||
* comment.remove()
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @param callback Iterator receives each node and index.
|
||||
* @return Returns `false` if iteration was broke.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Insert new node before old node within the container.
|
||||
*
|
||||
* ```js
|
||||
* rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
|
||||
* ```
|
||||
*
|
||||
* @param oldNode Child or child’s index.
|
||||
* @param newNode New node.
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
insertBefore(oldNode: Child | number, newNode: Container.NewChild): this
|
||||
/**
|
||||
* Inserts new nodes to the start of the container.
|
||||
*
|
||||
* ```js
|
||||
* const decl1 = new Declaration({ prop: 'color', value: 'black' })
|
||||
* const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
|
||||
* rule.prepend(decl1, decl2)
|
||||
*
|
||||
* root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
|
||||
* root.append({ selector: 'a' }) // rule
|
||||
* rule.append({ prop: 'color', value: 'black' }) // declaration
|
||||
* rule.append({ text: 'Comment' }) // comment
|
||||
*
|
||||
* root.append('a {}')
|
||||
* root.first.append('color: black; z-index: 1')
|
||||
* ```
|
||||
*
|
||||
* @param nodes New nodes.
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
prepend(...nodes: Container.NewChild[]): this
|
||||
|
||||
/**
|
||||
* Add child to the end of the node.
|
||||
*
|
||||
* ```js
|
||||
* rule.push(new Declaration({ prop: 'color', value: 'black' }))
|
||||
* ```
|
||||
*
|
||||
* @param child New node.
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
push(child: Child): this
|
||||
|
||||
/**
|
||||
* Removes all children from the container
|
||||
* and cleans their parent properties.
|
||||
*
|
||||
* ```js
|
||||
* rule.removeAll()
|
||||
* rule.nodes.length //=> 0
|
||||
* ```
|
||||
*
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
removeAll(): this
|
||||
|
||||
/**
|
||||
* Removes node from the container and cleans the parent properties
|
||||
* from the node and its children.
|
||||
*
|
||||
* ```js
|
||||
* rule.nodes.length //=> 5
|
||||
* rule.removeChild(decl)
|
||||
* rule.nodes.length //=> 4
|
||||
* decl.parent //=> undefined
|
||||
* ```
|
||||
*
|
||||
* @param child Child or child’s index.
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
removeChild(child: Child | number): this
|
||||
|
||||
replaceValues(
|
||||
pattern: RegExp | string,
|
||||
replaced: { (substring: string, ...args: any[]): string } | string
|
||||
): this
|
||||
/**
|
||||
* Passes all declaration values within the container that match pattern
|
||||
* through callback, replacing those values with the returned result
|
||||
* of callback.
|
||||
*
|
||||
* This method is useful if you are using a custom unit or function
|
||||
* and need to iterate through all values.
|
||||
*
|
||||
* ```js
|
||||
* root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
|
||||
* return 15 * parseInt(string) + 'px'
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @param pattern Replace pattern.
|
||||
* @param {object} options Options to speed up the search.
|
||||
* @param replaced String to replace pattern or callback
|
||||
* that returns a new value. The callback
|
||||
* will receive the same arguments
|
||||
* as those passed to a function parameter
|
||||
* of `String#replace`.
|
||||
* @return This node for methods chain.
|
||||
*/
|
||||
replaceValues(
|
||||
pattern: RegExp | string,
|
||||
options: Container.ValueOptions,
|
||||
replaced: { (substring: string, ...args: any[]): string } | string
|
||||
): this
|
||||
|
||||
/**
|
||||
* Returns `true` if callback returns `true` for (at least) one
|
||||
* of the container’s children.
|
||||
*
|
||||
* ```js
|
||||
* const hasPrefix = rule.some(i => i.prop[0] === '-')
|
||||
* ```
|
||||
*
|
||||
* @param condition Iterator returns true or false.
|
||||
* @return Is some child pass condition.
|
||||
*/
|
||||
some(
|
||||
condition: (node: Child, index: number, nodes: Child[]) => boolean
|
||||
): boolean
|
||||
|
||||
/**
|
||||
* Traverses the container’s descendant nodes, calling callback
|
||||
* for each node.
|
||||
*
|
||||
* Like container.each(), this method is safe to use
|
||||
* if you are mutating arrays during iteration.
|
||||
*
|
||||
* If you only need to iterate through the container’s immediate children,
|
||||
* use `Container#each`.
|
||||
*
|
||||
* ```js
|
||||
* root.walk(node => {
|
||||
* // Traverses all descendant nodes.
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @param callback Iterator receives each node and index.
|
||||
* @return Returns `false` if iteration was broke.
|
||||
*/
|
||||
walk(
|
||||
callback: (node: ChildNode, index: number) => false | void
|
||||
): false | undefined
|
||||
|
||||
/**
|
||||
* Traverses the container’s descendant nodes, calling callback
|
||||
* for each at-rule node.
|
||||
*
|
||||
* If you pass a filter, iteration will only happen over at-rules
|
||||
* that have matching names.
|
||||
*
|
||||
* Like `Container#each`, this method is safe
|
||||
* to use if you are mutating arrays during iteration.
|
||||
*
|
||||
* ```js
|
||||
* root.walkAtRules(rule => {
|
||||
* if (isOld(rule.name)) rule.remove()
|
||||
* })
|
||||
*
|
||||
* let first = false
|
||||
* root.walkAtRules('charset', rule => {
|
||||
* if (!first) {
|
||||
* first = true
|
||||
* } else {
|
||||
* rule.remove()
|
||||
* }
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* @param name String or regular expression to filter at-rules by name.
|
||||
* @param callback Iterator receives each node and index.
|
||||
* @return Returns `false` if iteration was broke.
|
||||
*/
|
||||
walkAtRules(
|
||||
nameFilter: RegExp | string,
|
||||
callback: (atRule: AtRule, index: number) => false | void
|
||||
): false | undefined
|
||||
walkAtRules(
|
||||
callback: (atRule: AtRule, index: number) => false | void
|
||||
): false | undefined
|
||||
|
||||
walkComments(
|
||||
callback: (comment: Comment, indexed: number) => false | void
|
||||
): false | undefined
|
||||
walkComments(
|
||||
callback: (comment: Comment, indexed: number) => false | void
|
||||
): false | undefined
|
||||
|
||||
/**
|
||||
* Traverses the container’s descendant nodes, calling callback
|
||||
* for each declaration node.
|
||||
*
|
||||
* If you pass a filter, iteration will only happen over declarations
|
||||
* with matching properties.
|
||||
*
|
||||
* ```js
|
||||
* root.walkDecls(decl => {
|
||||
* checkPropertySupport(decl.prop)
|
||||
* })
|
||||
*
|
||||
* root.walkDecls('border-radius', decl => {
|
||||
* decl.remove()
|
||||
* })
|
||||
*
|
||||
* root.walkDecls(/^background/, decl => {
|
||||
* decl.value = takeFirstColorFromGradient(decl.value)
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* Like `Container#each`, this method is safe
|
||||
* to use if you are mutating arrays during iteration.
|
||||
*
|
||||
* @param prop String or regular expression to filter declarations
|
||||
* by property name.
|
||||
* @param callback Iterator receives each node and index.
|
||||
* @return Returns `false` if iteration was broke.
|
||||
*/
|
||||
walkDecls(
|
||||
propFilter: RegExp | string,
|
||||
callback: (decl: Declaration, index: number) => false | void
|
||||
): false | undefined
|
||||
walkDecls(
|
||||
callback: (decl: Declaration, index: number) => false | void
|
||||
): false | undefined
|
||||
/**
|
||||
* Traverses the container’s descendant nodes, calling callback
|
||||
* for each rule node.
|
||||
*
|
||||
* If you pass a filter, iteration will only happen over rules
|
||||
* with matching selectors.
|
||||
*
|
||||
* Like `Container#each`, this method is safe
|
||||
* to use if you are mutating arrays during iteration.
|
||||
*
|
||||
* ```js
|
||||
* const selectors = []
|
||||
* root.walkRules(rule => {
|
||||
* selectors.push(rule.selector)
|
||||
* })
|
||||
* console.log(`Your CSS uses ${ selectors.length } selectors`)
|
||||
* ```
|
||||
*
|
||||
* @param selector String or regular expression to filter rules by selector.
|
||||
* @param callback Iterator receives each node and index.
|
||||
* @return Returns `false` if iteration was broke.
|
||||
*/
|
||||
walkRules(
|
||||
selectorFilter: RegExp | string,
|
||||
callback: (rule: Rule, index: number) => false | void
|
||||
): false | undefined
|
||||
walkRules(
|
||||
callback: (rule: Rule, index: number) => false | void
|
||||
): false | undefined
|
||||
/**
|
||||
* An internal method that converts a {@link NewChild} into a list of actual
|
||||
* child nodes that can then be added to this container.
|
||||
*
|
||||
* This ensures that the nodes' parent is set to this container, that they use
|
||||
* the correct prototype chain, and that they're marked as dirty.
|
||||
*
|
||||
* @param mnodes The new node or nodes to add.
|
||||
* @param sample A node from whose raws the new node's `before` raw should be
|
||||
* taken.
|
||||
* @param type This should be set to `'prepend'` if the new nodes will be
|
||||
* inserted at the beginning of the container.
|
||||
* @hidden
|
||||
*/
|
||||
protected normalize(
|
||||
nodes: Container.NewChild,
|
||||
sample: Node | undefined,
|
||||
type?: 'prepend' | false
|
||||
): Child[]
|
||||
}
|
||||
|
||||
declare class Container<
|
||||
Child extends Node = ChildNode
|
||||
> extends Container_<Child> {}
|
||||
|
||||
export = Container
|
||||
@@ -0,0 +1,11 @@
|
||||
// ESM wrapper for pg-protocol
|
||||
import * as protocol from '../dist/index.js'
|
||||
|
||||
// Re-export all the properties
|
||||
export const DatabaseError = protocol.DatabaseError
|
||||
export const SASL = protocol.SASL
|
||||
export const serialize = protocol.serialize
|
||||
export const parse = protocol.parse
|
||||
|
||||
// Re-export the default
|
||||
export default protocol
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"secp256k1.d.ts","sourceRoot":"","sources":["../src/secp256k1.ts"],"names":[],"mappings":"AAUA,OAAO,EAAe,KAAK,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAEL,KAAK,SAAS,EACd,KAAK,SAAS,EAEf,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAyB,GAAG,EAAQ,MAAM,uBAAuB,CAAC;AACzE,OAAO,EAIL,KAAK,gBAAgB,IAAI,SAAS,EAElC,KAAK,oBAAoB,EAC1B,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EACL,eAAe,EAIf,eAAe,EAEhB,MAAM,YAAY,CAAC;AAyDpB;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,SAAS,EAAE,iBAGvB,CAAC;AAMF,iBAAS,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,UAAU,EAAE,GAAG,UAAU,CAQtE;AAeD;;;GAGG;AACH,iBAAS,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAY5C;AASD;;GAEG;AACH,iBAAS,mBAAmB,CAAC,SAAS,EAAE,GAAG,GAAG,UAAU,CAEvD;AAED;;;GAGG;AACH,iBAAS,WAAW,CAAC,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAE,GAAqB,GAAG,UAAU,CAgBjG;AAED;;;GAGG;AACH,iBAAS,aAAa,CAAC,SAAS,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,GAAG,OAAO,CAsB5E;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,KAAK;QAAE,SAAS,EAAE,UAAU,CAAC;QAAC,SAAS,EAAE,UAAU,CAAA;KAAE,CAAC;IAChF,YAAY,EAAE,OAAO,mBAAmB,CAAC;IACzC,IAAI,EAAE,OAAO,WAAW,CAAC;IACzB,MAAM,EAAE,OAAO,aAAa,CAAC;IAC7B,KAAK,EAAE,oBAAoB,CAAC,MAAM,CAAC,CAAC;IACpC,KAAK,EAAE;QACL,eAAe,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,KAAK,UAAU,CAAC;QACnD,YAAY,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK,UAAU,CAAC;QACvD,MAAM,EAAE,OAAO,MAAM,CAAC;QACtB,UAAU,EAAE,OAAO,UAAU,CAAC;QAE9B,wCAAwC;QACxC,gBAAgB,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,KAAK,UAAU,CAAC;QACpD,8BAA8B;QAC9B,eAAe,EAAE,OAAO,eAAe,CAAC;QACxC,8BAA8B;QAC9B,eAAe,EAAE,OAAO,eAAe,CAAC;QACxC,gCAAgC;QAChC,GAAG,EAAE,OAAO,GAAG,CAAC;KACjB,CAAC;IACF,OAAO,EAAE,YAAY,CAAC;CACvB,CAAC;AACF;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,OAAO,EAAE,WAsClB,CAAC;AA0CL,wEAAwE;AACxE,eAAO,MAAM,gBAAgB,EAAE,SAAS,CAAC,MAAM,CAgBzC,CAAC;AAEP,uFAAuF;AACvF,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CACT,CAAC;AAElC,uFAAuF;AACvF,eAAO,MAAM,aAAa,EAAE,SAAS,CAAC,MAAM,CACT,CAAC"}
|
||||
@@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
|
||||
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.
|
||||
Binary file not shown.
Reference in New Issue
Block a user