id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
2,000
constructor(label: Identifier, body: Statement) { this.type = Syntax.LabeledStatement; this.label = label; this.body = body; }
class Identifier { readonly type: string; readonly name: string; constructor(name) { this.type = Syntax.Identifier; this.name = name; } }
2,001
constructor(meta: Identifier, property: Identifier) { this.type = Syntax.MetaProperty; this.meta = meta; this.property = property; }
class Identifier { readonly type: string; readonly name: string; constructor(name) { this.type = Syntax.Identifier; this.name = name; } }
2,002
constructor(callee: Expression, args: ArgumentListElement[]) { this.type = Syntax.NewExpression; this.callee = callee; this.arguments = args; }
type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression | ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression | RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression | ThisExpression | UnaryExpression | UpdateExpression | YieldExpression;
2,003
constructor(argument: Expression) { this.type = Syntax.SpreadElement; this.argument = argument; }
type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression | ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression | RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression | ThisExpression | UnaryExpression | UpdateExpression | YieldExpression;
2,004
constructor(object: Expression, property: Expression, optional: boolean) { this.type = Syntax.MemberExpression; this.computed = false; this.object = object; this.property = property; this.optional = optional; }
type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression | ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression | RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression | ThisExpression | UnaryExpression | UpdateExpression | YieldExpression;
2,005
constructor(test: Expression, consequent: Statement[]) { this.type = Syntax.SwitchCase; this.test = test; this.consequent = consequent; }
type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression | ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression | RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression | ThisExpression | UnaryExpression | UpdateExpression | YieldExpression;
2,006
constructor(discriminant: Expression, cases: SwitchCase[]) { this.type = Syntax.SwitchStatement; this.discriminant = discriminant; this.cases = cases; }
type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression | ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression | RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression | ThisExpression | UnaryExpression | UpdateExpression | YieldExpression;
2,007
constructor(tag: Expression, quasi: TemplateLiteral) { this.type = Syntax.TaggedTemplateExpression; this.tag = tag; this.quasi = quasi; }
type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression | ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression | RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression | ThisExpression | UnaryExpression | UpdateExpression | YieldExpression;
2,008
constructor(tag: Expression, quasi: TemplateLiteral) { this.type = Syntax.TaggedTemplateExpression; this.tag = tag; this.quasi = quasi; }
class TemplateLiteral { readonly type: string; readonly quasis: TemplateElement[]; readonly expressions: Expression[]; constructor(quasis: TemplateElement[], expressions: Expression[]) { this.type = Syntax.TemplateLiteral; this.quasis = quasis; this.expressions = expressions; } }
2,009
constructor(value: TemplateElementValue, tail: boolean) { this.type = Syntax.TemplateElement; this.value = value; this.tail = tail; }
interface TemplateElementValue { cooked: string | null; raw: string; }
2,010
constructor(argument: Expression) { this.type = Syntax.ThrowStatement; this.argument = argument; }
type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression | ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression | RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression | ThisExpression | UnaryExpression | UpdateExpression | YieldExpression;
2,011
constructor(block: BlockStatement, handler: CatchClause | null, finalizer: BlockStatement | null) { this.type = Syntax.TryStatement; this.block = block; this.handler = handler; this.finalizer = finalizer; }
class BlockStatement { readonly type: string; readonly body: Statement[]; constructor(body) { this.type = Syntax.BlockStatement; this.body = body; } }
2,012
constructor(test: Expression, body: Statement) { this.type = Syntax.WhileStatement; this.test = test; this.body = body; }
type Statement = AsyncFunctionDeclaration | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | Directive | ForStatement | ForInStatement | ForOfStatement | FunctionDeclaration | IfStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration | WhileStatement | WithStatement;
2,013
constructor(test: Expression, body: Statement) { this.type = Syntax.WhileStatement; this.test = test; this.body = body; }
type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression | ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression | RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression | ThisExpression | UnaryExpression | UpdateExpression | YieldExpression;
2,014
constructor(object: Expression, body: Statement) { this.type = Syntax.WithStatement; this.object = object; this.body = body; }
type Statement = AsyncFunctionDeclaration | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | Directive | ForStatement | ForInStatement | ForOfStatement | FunctionDeclaration | IfStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration | WhileStatement | WithStatement;
2,015
constructor(object: Expression, body: Statement) { this.type = Syntax.WithStatement; this.object = object; this.body = body; }
type Expression = ArrayExpression | ArrowFunctionExpression | AssignmentExpression | AsyncArrowFunctionExpression | AsyncFunctionExpression | AwaitExpression | BinaryExpression | CallExpression | ChainExpression | ClassExpression | ComputedMemberExpression | ConditionalExpression | Identifier | FunctionExpression | Literal | NewExpression | ObjectExpression | RegexLiteral | SequenceExpression | StaticMemberExpression | TaggedTemplateExpression | ThisExpression | UnaryExpression | UpdateExpression | YieldExpression;
2,016
parseComplexJSXElement(el: MetaJSXElement): MetaJSXElement { const stack: MetaJSXElement[] = []; while (!this.scanner.eof()) { el.children = el.children.concat(this.parseJSXChildren()); const node = this.createJSXChildNode(); const element = this.parseJSXBoundaryElement(); if (element.type === JSXSyntax.JSXOpeningElement) { const opening = element as JSXNode.JSXOpeningElement; if (opening.selfClosing) { const child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); el.children.push(child); } else { stack.push(el); el = { node, opening, closing: null, children: [] }; } } if (element.type === JSXSyntax.JSXClosingElement) { el.closing = element as JSXNode.JSXClosingElement; const open = getQualifiedElementName((el.opening as JSXNode.JSXOpeningElement).name); const close = getQualifiedElementName((el.closing as JSXNode.JSXClosingElement).name); if (open !== close) { this.tolerateError('Expected corresponding JSX closing tag for %0', open); } if (stack.length > 0) { const child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); el = stack[stack.length - 1]; el.children.push(child); stack.pop(); } else { break; } } if (element.type === JSXSyntax.JSXClosingFragment) { el.closing = element as JSXNode.JSXClosingFragment; if (el.opening.type !== JSXSyntax.JSXOpeningFragment) { this.tolerateError('Expected corresponding JSX closing tag for jsx fragment'); } else { break; } } } return el; }
interface MetaJSXElement { node: Marker; opening: JSXNode.JSXOpeningElement | JSXNode.JSXOpeningFragment; closing: JSXNode.JSXClosingElement | JSXNode.JSXClosingFragment | null; children: JSXNode.JSXChild[]; }
2,017
constructor(name: JSXElementName) { this.type = JSXSyntax.JSXClosingElement; this.name = name; }
type JSXElementName = JSXIdentifier | JSXNamespacedName | JSXMemberExpression;
2,018
constructor(name: JSXAttributeName, value: JSXAttributeValue | null) { this.type = JSXSyntax.JSXAttribute; this.name = name; this.value = value; }
type JSXAttributeName = JSXIdentifier | JSXNamespacedName;
2,019
constructor(namespace: JSXIdentifier, name: JSXIdentifier) { this.type = JSXSyntax.JSXNamespacedName; this.namespace = namespace; this.name = name; }
class JSXIdentifier { readonly type: string; readonly name: string; constructor(name: string) { this.type = JSXSyntax.JSXIdentifier; this.name = name; } }
2,020
constructor(name: JSXElementName, selfClosing: boolean, attributes: JSXElementAttribute[]) { this.type = JSXSyntax.JSXOpeningElement; this.name = name; this.selfClosing = selfClosing; this.attributes = attributes; }
type JSXElementName = JSXIdentifier | JSXNamespacedName | JSXMemberExpression;
2,021
convertToken(token: RawToken): TokenEntry { const t: TokenEntry = { type: TokenName[token.type], value: this.getTokenRaw(token) }; if (this.config.range) { t.range = [token.start, token.end]; } if (this.config.loc) { t.loc = { start: { line: this.startMarker.line, column: this.startMarker.column }, end: { line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart } }; } if (token.type === Token.RegularExpression) { const pattern = token.pattern as string; const flags = token.flags as string; t.regex = { pattern, flags }; } return t; }
interface RawToken { type: Token; value: string | number; pattern?: string; flags?: string; regex?: RegExp | null; octal?: boolean; cooked?: string | null; notEscapeSequenceHead?: NotEscapeSequenceHead | null; head?: boolean; tail?: boolean; lineNumber: number; lineStart: number; start: number; end: number; }
2,022
finalize(marker: Marker, node) { if (this.config.range) { node.range = [marker.index, this.lastMarker.index]; } if (this.config.loc) { node.loc = { start: { line: marker.line, column: marker.column, }, end: { line: this.lastMarker.line, column: this.lastMarker.column } }; if (this.config.source) { node.loc.source = this.config.source; } } if (this.delegate) { const metadata = { start: { line: marker.line, column: marker.column, offset: marker.index }, end: { line: this.lastMarker.line, column: this.lastMarker.column, offset: this.lastMarker.index } }; this.delegate(node, metadata); } return node; }
interface Marker { index: number; line: number; column: number; }
2,023
throwTemplateLiteralEarlyErrors(token: RawToken): never { switch (token.notEscapeSequenceHead) { case 'u': return this.throwUnexpectedToken(token, Messages.InvalidUnicodeEscapeSequence); case 'x': return this.throwUnexpectedToken(token, Messages.InvalidHexEscapeSequence); case '8': case '9': return this.throwUnexpectedToken(token, Messages.TemplateEscape89); default: // For 0-7 return this.throwUnexpectedToken(token, Messages.TemplateOctalLiteral); } }
interface RawToken { type: Token; value: string | number; pattern?: string; flags?: string; regex?: RegExp | null; octal?: boolean; cooked?: string | null; notEscapeSequenceHead?: NotEscapeSequenceHead | null; head?: boolean; tail?: boolean; lineNumber: number; lineStart: number; start: number; end: number; }
2,024
parseTemplateHead(options: ParseTemplateLiteralOptions): Node.TemplateElement { assert(this.lookahead.head as boolean, 'Template literal must start with a template head'); const node = this.createNode(); const token = this.nextToken(); if (!options.isTagged && token.notEscapeSequenceHead !== null) { this.throwTemplateLiteralEarlyErrors(token); } const raw = token.value as string; const cooked = token.cooked as string; return this.finalize(node, new Node.TemplateElement({ raw, cooked }, token.tail as boolean)); }
interface ParseTemplateLiteralOptions { isTagged: boolean; }
2,025
parseTemplateElement(options: ParseTemplateLiteralOptions): Node.TemplateElement { if (this.lookahead.type !== Token.Template) { this.throwUnexpectedToken(); } const node = this.createNode(); const token = this.nextToken(); if (!options.isTagged && token.notEscapeSequenceHead !== null) { this.throwTemplateLiteralEarlyErrors(token); } const raw = token.value as string; const cooked = token.cooked as string; return this.finalize(node, new Node.TemplateElement({ raw, cooked }, token.tail as boolean)); }
interface ParseTemplateLiteralOptions { isTagged: boolean; }
2,026
parseTemplateLiteral(options: ParseTemplateLiteralOptions): Node.TemplateLiteral { const node = this.createNode(); const expressions: Node.Expression[] = []; const quasis: Node.TemplateElement[] = []; let quasi = this.parseTemplateHead(options); quasis.push(quasi); while (!quasi.tail) { expressions.push(this.parseExpression()); quasi = this.parseTemplateElement(options); quasis.push(quasi); } return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); }
interface ParseTemplateLiteralOptions { isTagged: boolean; }
2,027
parseVariableDeclaration(options: DeclarationOptions): Node.VariableDeclarator { const node = this.createNode(); const params = []; const id = this.parsePattern(params, 'var'); if (this.context.strict && id.type === Syntax.Identifier) { if (this.scanner.isRestrictedWord((id as Node.Identifier).name)) { this.tolerateError(Messages.StrictVarName); } } let init = null; if (this.match('=')) { this.nextToken(); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } else if (id.type !== Syntax.Identifier && !options.inFor) { this.expect('='); } return this.finalize(node, new Node.VariableDeclarator(id, init)); }
interface DeclarationOptions { inFor: boolean; }
2,028
recordError(error: Error): void { this.errors.push(error); }
class Error { public name: string; public message: string; public index: number; public lineNumber: number; public column: number; public description: string; constructor(message: string); }
2,029
public restoreState(state: ScannerState): void { this.index = state.index; this.lineNumber = state.lineNumber; this.lineStart = state.lineStart; this.curlyStack = state.curlyStack; }
interface ScannerState { index: number; lineNumber: number; lineStart: number; curlyStack: string[]; }
2,030
onparserinit(parser: Parser) { // @ts-expect-error Accessing private tokenizer here expect(parser.tokenizer).toBeInstanceOf(CustomTokenizer); }
class Parser implements Callbacks { /** The start index of the last event. */ public startIndex = 0; /** The end index of the last event. */ public endIndex = 0; /** * Store the start index of the current open tag, * so we can update the start index for attributes. */ private openTagStart = 0; private tagname = ""; private attribname = ""; private attribvalue = ""; private attribs: null | { [key: string]: string } = null; private readonly stack: string[] = []; private readonly foreignContext: boolean[] = []; private readonly cbs: Partial<Handler>; private readonly lowerCaseTagNames: boolean; private readonly lowerCaseAttributeNames: boolean; private readonly tokenizer: Tokenizer; private readonly buffers: string[] = []; private bufferOffset = 0; /** The index of the last written buffer. Used when resuming after a `pause()`. */ private writeIndex = 0; /** Indicates whether the parser has finished running / `.end` has been called. */ private ended = false; constructor( cbs?: Partial<Handler> | null, private readonly options: ParserOptions = {} ) { this.cbs = cbs ?? {}; this.lowerCaseTagNames = options.lowerCaseTags ?? !options.xmlMode; this.lowerCaseAttributeNames = options.lowerCaseAttributeNames ?? !options.xmlMode; this.tokenizer = new (options.Tokenizer ?? Tokenizer)( this.options, this ); this.cbs.onparserinit?.(this); } // Tokenizer event handlers /** @internal */ ontext(start: number, endIndex: number): void { const data = this.getSlice(start, endIndex); this.endIndex = endIndex - 1; this.cbs.ontext?.(data); this.startIndex = endIndex; } /** @internal */ ontextentity(cp: number): void { /* * Entities can be emitted on the character, or directly after. * We use the section start here to get accurate indices. */ const index = this.tokenizer.getSectionStart(); this.endIndex = index - 1; this.cbs.ontext?.(fromCodePoint(cp)); this.startIndex = index; } protected isVoidElement(name: string): boolean { return !this.options.xmlMode && voidElements.has(name); } /** @internal */ onopentagname(start: number, endIndex: number): void { this.endIndex = endIndex; let name = this.getSlice(start, endIndex); if (this.lowerCaseTagNames) { name = name.toLowerCase(); } this.emitOpenTag(name); } private emitOpenTag(name: string) { this.openTagStart = this.startIndex; this.tagname = name; const impliesClose = !this.options.xmlMode && openImpliesClose.get(name); if (impliesClose) { while ( this.stack.length > 0 && impliesClose.has(this.stack[this.stack.length - 1]) ) { const element = this.stack.pop()!; this.cbs.onclosetag?.(element, true); } } if (!this.isVoidElement(name)) { this.stack.push(name); if (foreignContextElements.has(name)) { this.foreignContext.push(true); } else if (htmlIntegrationElements.has(name)) { this.foreignContext.push(false); } } this.cbs.onopentagname?.(name); if (this.cbs.onopentag) this.attribs = {}; } private endOpenTag(isImplied: boolean) { this.startIndex = this.openTagStart; if (this.attribs) { this.cbs.onopentag?.(this.tagname, this.attribs, isImplied); this.attribs = null; } if (this.cbs.onclosetag && this.isVoidElement(this.tagname)) { this.cbs.onclosetag(this.tagname, true); } this.tagname = ""; } /** @internal */ onopentagend(endIndex: number): void { this.endIndex = endIndex; this.endOpenTag(false); // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ onclosetag(start: number, endIndex: number): void { this.endIndex = endIndex; let name = this.getSlice(start, endIndex); if (this.lowerCaseTagNames) { name = name.toLowerCase(); } if ( foreignContextElements.has(name) || htmlIntegrationElements.has(name) ) { this.foreignContext.pop(); } if (!this.isVoidElement(name)) { const pos = this.stack.lastIndexOf(name); if (pos !== -1) { if (this.cbs.onclosetag) { let count = this.stack.length - pos; while (count--) { // We know the stack has sufficient elements. this.cbs.onclosetag(this.stack.pop()!, count !== 0); } } else this.stack.length = pos; } else if (!this.options.xmlMode && name === "p") { // Implicit open before close this.emitOpenTag("p"); this.closeCurrentTag(true); } } else if (!this.options.xmlMode && name === "br") { // We can't use `emitOpenTag` for implicit open, as `br` would be implicitly closed. this.cbs.onopentagname?.("br"); this.cbs.onopentag?.("br", {}, true); this.cbs.onclosetag?.("br", false); } // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ onselfclosingtag(endIndex: number): void { this.endIndex = endIndex; if ( this.options.xmlMode || this.options.recognizeSelfClosing || this.foreignContext[this.foreignContext.length - 1] ) { this.closeCurrentTag(false); // Set `startIndex` for next node this.startIndex = endIndex + 1; } else { // Ignore the fact that the tag is self-closing. this.onopentagend(endIndex); } } private closeCurrentTag(isOpenImplied: boolean) { const name = this.tagname; this.endOpenTag(isOpenImplied); // Self-closing tags will be on the top of the stack if (this.stack[this.stack.length - 1] === name) { // If the opening tag isn't implied, the closing tag has to be implied. this.cbs.onclosetag?.(name, !isOpenImplied); this.stack.pop(); } } /** @internal */ onattribname(start: number, endIndex: number): void { this.startIndex = start; const name = this.getSlice(start, endIndex); this.attribname = this.lowerCaseAttributeNames ? name.toLowerCase() : name; } /** @internal */ onattribdata(start: number, endIndex: number): void { this.attribvalue += this.getSlice(start, endIndex); } /** @internal */ onattribentity(cp: number): void { this.attribvalue += fromCodePoint(cp); } /** @internal */ onattribend(quote: QuoteType, endIndex: number): void { this.endIndex = endIndex; this.cbs.onattribute?.( this.attribname, this.attribvalue, quote === QuoteType.Double ? '"' : quote === QuoteType.Single ? "'" : quote === QuoteType.NoValue ? undefined : null ); if ( this.attribs && !Object.prototype.hasOwnProperty.call(this.attribs, this.attribname) ) { this.attribs[this.attribname] = this.attribvalue; } this.attribvalue = ""; } private getInstructionName(value: string) { const index = value.search(reNameEnd); let name = index < 0 ? value : value.substr(0, index); if (this.lowerCaseTagNames) { name = name.toLowerCase(); } return name; } /** @internal */ ondeclaration(start: number, endIndex: number): void { this.endIndex = endIndex; const value = this.getSlice(start, endIndex); if (this.cbs.onprocessinginstruction) { const name = this.getInstructionName(value); this.cbs.onprocessinginstruction(`!${name}`, `!${value}`); } // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ onprocessinginstruction(start: number, endIndex: number): void { this.endIndex = endIndex; const value = this.getSlice(start, endIndex); if (this.cbs.onprocessinginstruction) { const name = this.getInstructionName(value); this.cbs.onprocessinginstruction(`?${name}`, `?${value}`); } // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ oncomment(start: number, endIndex: number, offset: number): void { this.endIndex = endIndex; this.cbs.oncomment?.(this.getSlice(start, endIndex - offset)); this.cbs.oncommentend?.(); // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ oncdata(start: number, endIndex: number, offset: number): void { this.endIndex = endIndex; const value = this.getSlice(start, endIndex - offset); if (this.options.xmlMode || this.options.recognizeCDATA) { this.cbs.oncdatastart?.(); this.cbs.ontext?.(value); this.cbs.oncdataend?.(); } else { this.cbs.oncomment?.(`[CDATA[${value}]]`); this.cbs.oncommentend?.(); } // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ onend(): void { if (this.cbs.onclosetag) { // Set the end index for all remaining tags this.endIndex = this.startIndex; for ( let index = this.stack.length; index > 0; this.cbs.onclosetag(this.stack[--index], true) ); } this.cbs.onend?.(); } /** * Resets the parser to a blank state, ready to parse a new HTML document */ public reset(): void { this.cbs.onreset?.(); this.tokenizer.reset(); this.tagname = ""; this.attribname = ""; this.attribs = null; this.stack.length = 0; this.startIndex = 0; this.endIndex = 0; this.cbs.onparserinit?.(this); this.buffers.length = 0; this.bufferOffset = 0; this.writeIndex = 0; this.ended = false; } /** * Resets the parser, then parses a complete document and * pushes it to the handler. * * @param data Document to parse. */ public parseComplete(data: string): void { this.reset(); this.end(data); } private getSlice(start: number, end: number) { while (start - this.bufferOffset >= this.buffers[0].length) { this.shiftBuffer(); } let slice = this.buffers[0].slice( start - this.bufferOffset, end - this.bufferOffset ); while (end - this.bufferOffset > this.buffers[0].length) { this.shiftBuffer(); slice += this.buffers[0].slice(0, end - this.bufferOffset); } return slice; } private shiftBuffer(): void { this.bufferOffset += this.buffers[0].length; this.writeIndex--; this.buffers.shift(); } /** * Parses a chunk of data and calls the corresponding callbacks. * * @param chunk Chunk to parse. */ public write(chunk: string): void { if (this.ended) { this.cbs.onerror?.(new Error(".write() after done!")); return; } this.buffers.push(chunk); if (this.tokenizer.running) { this.tokenizer.write(chunk); this.writeIndex++; } } /** * Parses the end of the buffer and clears the stack, calls onend. * * @param chunk Optional final chunk to parse. */ public end(chunk?: string): void { if (this.ended) { this.cbs.onerror?.(new Error(".end() after done!")); return; } if (chunk) this.write(chunk); this.ended = true; this.tokenizer.end(); } /** * Pauses parsing. The parser won't emit events until `resume` is called. */ public pause(): void { this.tokenizer.pause(); } /** * Resumes parsing after `pause` was called. */ public resume(): void { this.tokenizer.resume(); while ( this.tokenizer.running && this.writeIndex < this.buffers.length ) { this.tokenizer.write(this.buffers[this.writeIndex++]); } if (this.ended) this.tokenizer.end(); } /** * Alias of `write`, for backwards compatibility. * * @param chunk Chunk to parse. * @deprecated */ public parseChunk(chunk: string): void { this.write(chunk); } /** * Alias of `end`, for backwards compatibility. * * @param chunk Optional final chunk to parse. * @deprecated */ public done(chunk?: string): void { this.end(chunk); } }
2,031
onparserinit(parser: Parser): void
class Parser implements Callbacks { /** The start index of the last event. */ public startIndex = 0; /** The end index of the last event. */ public endIndex = 0; /** * Store the start index of the current open tag, * so we can update the start index for attributes. */ private openTagStart = 0; private tagname = ""; private attribname = ""; private attribvalue = ""; private attribs: null | { [key: string]: string } = null; private readonly stack: string[] = []; private readonly foreignContext: boolean[] = []; private readonly cbs: Partial<Handler>; private readonly lowerCaseTagNames: boolean; private readonly lowerCaseAttributeNames: boolean; private readonly tokenizer: Tokenizer; private readonly buffers: string[] = []; private bufferOffset = 0; /** The index of the last written buffer. Used when resuming after a `pause()`. */ private writeIndex = 0; /** Indicates whether the parser has finished running / `.end` has been called. */ private ended = false; constructor( cbs?: Partial<Handler> | null, private readonly options: ParserOptions = {} ) { this.cbs = cbs ?? {}; this.lowerCaseTagNames = options.lowerCaseTags ?? !options.xmlMode; this.lowerCaseAttributeNames = options.lowerCaseAttributeNames ?? !options.xmlMode; this.tokenizer = new (options.Tokenizer ?? Tokenizer)( this.options, this ); this.cbs.onparserinit?.(this); } // Tokenizer event handlers /** @internal */ ontext(start: number, endIndex: number): void { const data = this.getSlice(start, endIndex); this.endIndex = endIndex - 1; this.cbs.ontext?.(data); this.startIndex = endIndex; } /** @internal */ ontextentity(cp: number): void { /* * Entities can be emitted on the character, or directly after. * We use the section start here to get accurate indices. */ const index = this.tokenizer.getSectionStart(); this.endIndex = index - 1; this.cbs.ontext?.(fromCodePoint(cp)); this.startIndex = index; } protected isVoidElement(name: string): boolean { return !this.options.xmlMode && voidElements.has(name); } /** @internal */ onopentagname(start: number, endIndex: number): void { this.endIndex = endIndex; let name = this.getSlice(start, endIndex); if (this.lowerCaseTagNames) { name = name.toLowerCase(); } this.emitOpenTag(name); } private emitOpenTag(name: string) { this.openTagStart = this.startIndex; this.tagname = name; const impliesClose = !this.options.xmlMode && openImpliesClose.get(name); if (impliesClose) { while ( this.stack.length > 0 && impliesClose.has(this.stack[this.stack.length - 1]) ) { const element = this.stack.pop()!; this.cbs.onclosetag?.(element, true); } } if (!this.isVoidElement(name)) { this.stack.push(name); if (foreignContextElements.has(name)) { this.foreignContext.push(true); } else if (htmlIntegrationElements.has(name)) { this.foreignContext.push(false); } } this.cbs.onopentagname?.(name); if (this.cbs.onopentag) this.attribs = {}; } private endOpenTag(isImplied: boolean) { this.startIndex = this.openTagStart; if (this.attribs) { this.cbs.onopentag?.(this.tagname, this.attribs, isImplied); this.attribs = null; } if (this.cbs.onclosetag && this.isVoidElement(this.tagname)) { this.cbs.onclosetag(this.tagname, true); } this.tagname = ""; } /** @internal */ onopentagend(endIndex: number): void { this.endIndex = endIndex; this.endOpenTag(false); // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ onclosetag(start: number, endIndex: number): void { this.endIndex = endIndex; let name = this.getSlice(start, endIndex); if (this.lowerCaseTagNames) { name = name.toLowerCase(); } if ( foreignContextElements.has(name) || htmlIntegrationElements.has(name) ) { this.foreignContext.pop(); } if (!this.isVoidElement(name)) { const pos = this.stack.lastIndexOf(name); if (pos !== -1) { if (this.cbs.onclosetag) { let count = this.stack.length - pos; while (count--) { // We know the stack has sufficient elements. this.cbs.onclosetag(this.stack.pop()!, count !== 0); } } else this.stack.length = pos; } else if (!this.options.xmlMode && name === "p") { // Implicit open before close this.emitOpenTag("p"); this.closeCurrentTag(true); } } else if (!this.options.xmlMode && name === "br") { // We can't use `emitOpenTag` for implicit open, as `br` would be implicitly closed. this.cbs.onopentagname?.("br"); this.cbs.onopentag?.("br", {}, true); this.cbs.onclosetag?.("br", false); } // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ onselfclosingtag(endIndex: number): void { this.endIndex = endIndex; if ( this.options.xmlMode || this.options.recognizeSelfClosing || this.foreignContext[this.foreignContext.length - 1] ) { this.closeCurrentTag(false); // Set `startIndex` for next node this.startIndex = endIndex + 1; } else { // Ignore the fact that the tag is self-closing. this.onopentagend(endIndex); } } private closeCurrentTag(isOpenImplied: boolean) { const name = this.tagname; this.endOpenTag(isOpenImplied); // Self-closing tags will be on the top of the stack if (this.stack[this.stack.length - 1] === name) { // If the opening tag isn't implied, the closing tag has to be implied. this.cbs.onclosetag?.(name, !isOpenImplied); this.stack.pop(); } } /** @internal */ onattribname(start: number, endIndex: number): void { this.startIndex = start; const name = this.getSlice(start, endIndex); this.attribname = this.lowerCaseAttributeNames ? name.toLowerCase() : name; } /** @internal */ onattribdata(start: number, endIndex: number): void { this.attribvalue += this.getSlice(start, endIndex); } /** @internal */ onattribentity(cp: number): void { this.attribvalue += fromCodePoint(cp); } /** @internal */ onattribend(quote: QuoteType, endIndex: number): void { this.endIndex = endIndex; this.cbs.onattribute?.( this.attribname, this.attribvalue, quote === QuoteType.Double ? '"' : quote === QuoteType.Single ? "'" : quote === QuoteType.NoValue ? undefined : null ); if ( this.attribs && !Object.prototype.hasOwnProperty.call(this.attribs, this.attribname) ) { this.attribs[this.attribname] = this.attribvalue; } this.attribvalue = ""; } private getInstructionName(value: string) { const index = value.search(reNameEnd); let name = index < 0 ? value : value.substr(0, index); if (this.lowerCaseTagNames) { name = name.toLowerCase(); } return name; } /** @internal */ ondeclaration(start: number, endIndex: number): void { this.endIndex = endIndex; const value = this.getSlice(start, endIndex); if (this.cbs.onprocessinginstruction) { const name = this.getInstructionName(value); this.cbs.onprocessinginstruction(`!${name}`, `!${value}`); } // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ onprocessinginstruction(start: number, endIndex: number): void { this.endIndex = endIndex; const value = this.getSlice(start, endIndex); if (this.cbs.onprocessinginstruction) { const name = this.getInstructionName(value); this.cbs.onprocessinginstruction(`?${name}`, `?${value}`); } // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ oncomment(start: number, endIndex: number, offset: number): void { this.endIndex = endIndex; this.cbs.oncomment?.(this.getSlice(start, endIndex - offset)); this.cbs.oncommentend?.(); // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ oncdata(start: number, endIndex: number, offset: number): void { this.endIndex = endIndex; const value = this.getSlice(start, endIndex - offset); if (this.options.xmlMode || this.options.recognizeCDATA) { this.cbs.oncdatastart?.(); this.cbs.ontext?.(value); this.cbs.oncdataend?.(); } else { this.cbs.oncomment?.(`[CDATA[${value}]]`); this.cbs.oncommentend?.(); } // Set `startIndex` for next node this.startIndex = endIndex + 1; } /** @internal */ onend(): void { if (this.cbs.onclosetag) { // Set the end index for all remaining tags this.endIndex = this.startIndex; for ( let index = this.stack.length; index > 0; this.cbs.onclosetag(this.stack[--index], true) ); } this.cbs.onend?.(); } /** * Resets the parser to a blank state, ready to parse a new HTML document */ public reset(): void { this.cbs.onreset?.(); this.tokenizer.reset(); this.tagname = ""; this.attribname = ""; this.attribs = null; this.stack.length = 0; this.startIndex = 0; this.endIndex = 0; this.cbs.onparserinit?.(this); this.buffers.length = 0; this.bufferOffset = 0; this.writeIndex = 0; this.ended = false; } /** * Resets the parser, then parses a complete document and * pushes it to the handler. * * @param data Document to parse. */ public parseComplete(data: string): void { this.reset(); this.end(data); } private getSlice(start: number, end: number) { while (start - this.bufferOffset >= this.buffers[0].length) { this.shiftBuffer(); } let slice = this.buffers[0].slice( start - this.bufferOffset, end - this.bufferOffset ); while (end - this.bufferOffset > this.buffers[0].length) { this.shiftBuffer(); slice += this.buffers[0].slice(0, end - this.bufferOffset); } return slice; } private shiftBuffer(): void { this.bufferOffset += this.buffers[0].length; this.writeIndex--; this.buffers.shift(); } /** * Parses a chunk of data and calls the corresponding callbacks. * * @param chunk Chunk to parse. */ public write(chunk: string): void { if (this.ended) { this.cbs.onerror?.(new Error(".write() after done!")); return; } this.buffers.push(chunk); if (this.tokenizer.running) { this.tokenizer.write(chunk); this.writeIndex++; } } /** * Parses the end of the buffer and clears the stack, calls onend. * * @param chunk Optional final chunk to parse. */ public end(chunk?: string): void { if (this.ended) { this.cbs.onerror?.(new Error(".end() after done!")); return; } if (chunk) this.write(chunk); this.ended = true; this.tokenizer.end(); } /** * Pauses parsing. The parser won't emit events until `resume` is called. */ public pause(): void { this.tokenizer.pause(); } /** * Resumes parsing after `pause` was called. */ public resume(): void { this.tokenizer.resume(); while ( this.tokenizer.running && this.writeIndex < this.buffers.length ) { this.tokenizer.write(this.buffers[this.writeIndex++]); } if (this.ended) this.tokenizer.end(); } /** * Alias of `write`, for backwards compatibility. * * @param chunk Chunk to parse. * @deprecated */ public parseChunk(chunk: string): void { this.write(chunk); } /** * Alias of `end`, for backwards compatibility. * * @param chunk Optional final chunk to parse. * @deprecated */ public done(chunk?: string): void { this.end(chunk); } }
2,032
function ui (opts: UIOptions): UI { return cliui(opts, { stringWidth: (str: string) => { return [...str].length }, stripAnsi, wrap }) }
interface UIOptions { width: number; wrap?: boolean; rows?: string[]; }
2,033
function ui (opts: UIOptions) { return cliui(opts, { stringWidth, stripAnsi, wrap }) }
interface UIOptions { width: number; wrap?: boolean; rows?: string[]; }
2,034
constructor (opts: UIOptions) { this.width = opts.width this.wrap = opts.wrap ?? true this.rows = [] }
interface UIOptions { width: number; wrap?: boolean; rows?: string[]; }
2,035
span (...args: ColumnArray) { const cols = this.div(...args) cols.span = true }
interface ColumnArray extends Array<Column> { span: boolean; }
2,036
rowToString (row: ColumnArray, lines: Line[]) { this.rasterize(row).forEach((rrow, r) => { let str = '' rrow.forEach((col: string, c: number) => { const { width } = row[c] // the width with padding. const wrapWidth = this.negatePadding(row[c]) // the width without padding. let ts = col // temporary string used during alignment/padding. if (wrapWidth > mixin.stringWidth(col)) { ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)) } // align the string within its column. if (row[c].align && row[c].align !== 'left' && this.wrap) { const fn = align[(row[c].align as 'right'|'center')] ts = fn(ts, wrapWidth) if (mixin.stringWidth(ts) < wrapWidth) { ts += ' '.repeat((width || 0) - mixin.stringWidth(ts) - 1) } } // apply border and padding to string. const padding = row[c].padding || [0, 0, 0, 0] if (padding[left]) { str += ' '.repeat(padding[left]) } str += addBorder(row[c], ts, '| ') str += ts str += addBorder(row[c], ts, ' |') if (padding[right]) { str += ' '.repeat(padding[right]) } // if prior row is span, try to render the // current row on the prior line. if (r === 0 && lines.length > 0) { str = this.renderInline(str, lines[lines.length - 1]) } }) // remove trailing whitespace. lines.push({ text: str.replace(/ +$/, ''), span: row.span }) }) return lines }
interface ColumnArray extends Array<Column> { span: boolean; }
2,037
private rasterize (row: ColumnArray) { const rrows: string[][] = [] const widths = this.columnWidths(row) let wrapped // word wrap all columns, and create // a data-structure that is easy to rasterize. row.forEach((col, c) => { // leave room for left and right padding. col.width = widths[c] if (this.wrap) { wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n') } else { wrapped = col.text.split('\n') } if (col.border) { wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.') wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'") } // add top and bottom padding. if (col.padding) { wrapped.unshift(...new Array(col.padding[top] || 0).fill('')) wrapped.push(...new Array(col.padding[bottom] || 0).fill('')) } wrapped.forEach((str: string, r: number) => { if (!rrows[r]) { rrows.push([]) } const rrow = rrows[r] for (let i = 0; i < c; i++) { if (rrow[i] === undefined) { rrow.push('') } } rrow.push(str) }) }) return rrows }
interface ColumnArray extends Array<Column> { span: boolean; }
2,038
private negatePadding (col: Column) { let wrapWidth = col.width || 0 if (col.padding) { wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0) } if (col.border) { wrapWidth -= 4 } return wrapWidth }
interface Column { text: string; width?: number; align?: 'right'|'left'|'center', padding: number[], border?: boolean; }
2,039
private columnWidths (row: ColumnArray) { if (!this.wrap) { return row.map(col => { return col.width || mixin.stringWidth(col.text) }) } let unset = row.length let remainingWidth = this.width // column widths can be set in config. const widths = row.map(col => { if (col.width) { unset-- remainingWidth -= col.width return col.width } return undefined }) // any unset widths should be calculated. const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0 return widths.map((w, i) => { if (w === undefined) { return Math.max(unsetWidth, _minWidth(row[i])) } return w }) }
interface ColumnArray extends Array<Column> { span: boolean; }
2,040
function addBorder (col: Column, ts: string, style: string) { if (col.border) { if (/[.']-+[.']/.test(ts)) { return '' } if (ts.trim().length !== 0) { return style } return ' ' } return '' }
interface Column { text: string; width?: number; align?: 'right'|'left'|'center', padding: number[], border?: boolean; }
2,041
function _minWidth (col: Column) { const padding = col.padding || [] const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0) if (col.border) { return minWidth + 4 } return minWidth }
interface Column { text: string; width?: number; align?: 'right'|'left'|'center', padding: number[], border?: boolean; }
2,042
(pathname: Pathname) => boolean
type Pathname = string
2,043
ignores(pathname: Pathname): boolean
type Pathname = string
2,044
test(pathname: Pathname): TestResult
type Pathname = string
2,045
function ignore(options?: Options): Ignore
interface Options { ignorecase?: boolean // For compatibility ignoreCase?: boolean allowRelativePaths?: boolean }
2,046
(node: XastElement, info: PluginInfo) => string
type XastElement = { type: 'element'; name: string; attributes: Record<string, string>; children: Array<XastChild>; };
2,047
(node: XastElement, info: PluginInfo) => string
type PluginInfo = { path?: string; multipassCount: number; };
2,048
(node: Node, parentNode: XastParent) => void | symbol
type XastParent = XastRoot | XastElement;
2,049
(node: Node, parentNode: XastParent) => void
type XastParent = XastRoot | XastElement;
2,050
(node: XastRoot, parentNode: null) => void
type XastRoot = { type: 'root'; children: Array<XastChild>; };
2,051
( root: XastRoot, params: Params, info: PluginInfo ) => null | Visitor
type XastRoot = { type: 'root'; children: Array<XastChild>; };
2,052
( root: XastRoot, params: Params, info: PluginInfo ) => null | Visitor
type PluginInfo = { path?: string; multipassCount: number; };
2,053
(config: BaseConfig): number[] => { return config.columns.map(({truncate}) => { return truncate; }); }
type BaseConfig = { readonly border: BorderConfig, readonly columns: ColumnConfig[], readonly drawVerticalLine: DrawVerticalLine, readonly drawHorizontalLine?: DrawHorizontalLine, readonly spanningCellManager?: SpanningCellManager, };
2,054
(spanningCellConfig: SpanningCellConfig): RangeCoordinate => { const {row, col, colSpan = 1, rowSpan = 1} = spanningCellConfig; return {bottomRight: {col: col + colSpan - 1, row: row + rowSpan - 1}, topLeft: {col, row}}; }
type SpanningCellConfig = CellUserConfig & { readonly row: number, readonly col: number, readonly rowSpan?: number, readonly colSpan?: number, };
2,055
(cell1: CellCoordinates, cell2: CellCoordinates): boolean => { return cell1.row === cell2.row && cell1.col === cell2.col; }
type CellCoordinates = { row: number, col: number, };
2,056
(cell: CellCoordinates, {topLeft, bottomRight}: RangeCoordinate): boolean => { return ( topLeft.row <= cell.row && cell.row <= bottomRight.row && topLeft.col <= cell.col && cell.col <= bottomRight.col ); }
type RangeCoordinate = { topLeft: CellCoordinates, bottomRight: CellCoordinates, };
2,057
(cell: CellCoordinates, {topLeft, bottomRight}: RangeCoordinate): boolean => { return ( topLeft.row <= cell.row && cell.row <= bottomRight.row && topLeft.col <= cell.col && cell.col <= bottomRight.col ); }
type CellCoordinates = { row: number, col: number, };
2,058
(config: StreamUserConfig): StreamConfig => { validateConfig('streamConfig.json', config); if (config.columnDefault.width === undefined) { throw new Error('Must provide config.columnDefault.width when creating a stream.'); } return { drawVerticalLine: () => { return true; }, ...config, border: makeBorderConfig(config.border), columns: makeColumnsConfig(config.columnCount, config.columns, config.columnDefault), }; }
type StreamUserConfig = BaseUserConfig & { /** * The number of columns */ readonly columnCount: number, /** * Default values for all columns. Column specific settings overwrite the default values. */ readonly columnDefault: ColumnUserConfig & { /** * The default width for each column */ readonly width: number, }, };
2,059
(rangeConfig: RangeConfig, rangeWidth: number, context: SpanningCellContext): string[] => { const {topLeft, paddingRight, paddingLeft, truncate, wrapWord, alignment} = rangeConfig; const originalContent = context.rows[topLeft.row][topLeft.col]; const contentWidth = rangeWidth - paddingLeft - paddingRight; return wrapCell(truncateString(originalContent, truncate), contentWidth, wrapWord).map((line) => { const alignedLine = alignString(line, contentWidth, alignment); return padString(alignedLine, paddingLeft, paddingRight); }); }
type SpanningCellContext = SpanningCellParameters & { rowHeights: number[], };
2,060
(rangeConfig: RangeConfig, rangeWidth: number, context: SpanningCellContext): string[] => { const {topLeft, paddingRight, paddingLeft, truncate, wrapWord, alignment} = rangeConfig; const originalContent = context.rows[topLeft.row][topLeft.col]; const contentWidth = rangeWidth - paddingLeft - paddingRight; return wrapCell(truncateString(originalContent, truncate), contentWidth, wrapWord).map((line) => { const alignedLine = alignString(line, contentWidth, alignment); return padString(alignedLine, paddingLeft, paddingRight); }); }
type RangeConfig = RangeCoordinate & Required<CellUserConfig>;
2,061
(range: RangeConfig, content: string[], context: SpanningCellContext) => { const {rows, drawHorizontalLine, rowHeights} = context; const {topLeft, bottomRight, verticalAlignment} = range; // They are empty before calculateRowHeights function run if (rowHeights.length === 0) { return []; } const totalCellHeight = sumArray(rowHeights.slice(topLeft.row, bottomRight.row + 1)); const totalBorderHeight = bottomRight.row - topLeft.row; const hiddenHorizontalBorderCount = sequence(topLeft.row + 1, bottomRight.row).filter((horizontalBorderIndex) => { return !drawHorizontalLine(horizontalBorderIndex, rows.length); }).length; const availableRangeHeight = totalCellHeight + totalBorderHeight - hiddenHorizontalBorderCount; return padCellVertically(content, availableRangeHeight, verticalAlignment).map((line) => { if (line.length === 0) { return ' '.repeat(stringWidth(content[0])); } return line; }); }
type SpanningCellContext = SpanningCellParameters & { rowHeights: number[], };
2,062
(range: RangeConfig, content: string[], context: SpanningCellContext) => { const {rows, drawHorizontalLine, rowHeights} = context; const {topLeft, bottomRight, verticalAlignment} = range; // They are empty before calculateRowHeights function run if (rowHeights.length === 0) { return []; } const totalCellHeight = sumArray(rowHeights.slice(topLeft.row, bottomRight.row + 1)); const totalBorderHeight = bottomRight.row - topLeft.row; const hiddenHorizontalBorderCount = sequence(topLeft.row + 1, bottomRight.row).filter((horizontalBorderIndex) => { return !drawHorizontalLine(horizontalBorderIndex, rows.length); }).length; const availableRangeHeight = totalCellHeight + totalBorderHeight - hiddenHorizontalBorderCount; return padCellVertically(content, availableRangeHeight, verticalAlignment).map((line) => { if (line.length === 0) { return ' '.repeat(stringWidth(content[0])); } return line; }); }
type RangeConfig = RangeCoordinate & Required<CellUserConfig>;
2,063
(row: Row, columnWidths: number[], config: StreamConfig) => { const rows = prepareData([row], config); const body = rows.map((literalRow) => { return drawRow(literalRow, config); }).join(''); let output; output = ''; output += drawBorderTop(columnWidths, config); output += body; output += drawBorderBottom(columnWidths, config); output = output.trimEnd(); process.stdout.write(output); }
type Row = Cell[];
2,064
(row: Row, columnWidths: number[], config: StreamConfig) => { const rows = prepareData([row], config); const body = rows.map((literalRow) => { return drawRow(literalRow, config); }).join(''); let output; output = ''; output += drawBorderTop(columnWidths, config); output += body; output += drawBorderBottom(columnWidths, config); output = output.trimEnd(); process.stdout.write(output); }
type StreamConfig = Required<Omit<StreamUserConfig, 'border' | 'columnDefault' | 'columns'>> & { readonly border: BorderConfig, readonly columns: ColumnConfig[], };
2,065
(row: Row, columnWidths: number[], config: StreamConfig) => { const rows = prepareData([row], config); const body = rows.map((literalRow) => { return drawRow(literalRow, config); }).join(''); let output = ''; const bottom = drawBorderBottom(columnWidths, config); if (bottom !== '\n') { output = '\r\u001B[K'; } output += drawBorderJoin(columnWidths, config); output += body; output += bottom; output = output.trimEnd(); process.stdout.write(output); }
type Row = Cell[];
2,066
(row: Row, columnWidths: number[], config: StreamConfig) => { const rows = prepareData([row], config); const body = rows.map((literalRow) => { return drawRow(literalRow, config); }).join(''); let output = ''; const bottom = drawBorderBottom(columnWidths, config); if (bottom !== '\n') { output = '\r\u001B[K'; } output += drawBorderJoin(columnWidths, config); output += body; output += bottom; output = output.trimEnd(); process.stdout.write(output); }
type StreamConfig = Required<Omit<StreamUserConfig, 'border' | 'columnDefault' | 'columns'>> & { readonly border: BorderConfig, readonly columns: ColumnConfig[], };
2,067
(userConfig: StreamUserConfig): WritableStream => { const config = makeStreamConfig(userConfig); const columnWidths = Object.values(config.columns).map((column) => { return column.width + column.paddingLeft + column.paddingRight; }); let empty = true; return { write: (row: string[]) => { if (row.length !== config.columnCount) { throw new Error('Row cell count does not match the config.columnCount.'); } if (empty) { empty = false; create(row, columnWidths, config); } else { append(row, columnWidths, config); } }, }; }
type StreamUserConfig = BaseUserConfig & { /** * The number of columns */ readonly columnCount: number, /** * Default values for all columns. Column specific settings overwrite the default values. */ readonly columnDefault: ColumnUserConfig & { /** * The default width for each column */ readonly width: number, }, };
2,068
(cell: Cell): number => { return Math.max( ...cell.split('\n').map(stringWidth), ); }
type Cell = string;
2,069
(row: Row, config: DrawRowConfig): string => { const {border, drawVerticalLine, rowIndex, spanningCellManager} = config; return drawContent({ contents: row, drawSeparator: drawVerticalLine, elementType: 'cell', rowIndex, separatorGetter: (index, columnCount) => { if (index === 0) { return border.bodyLeft; } if (index === columnCount) { return border.bodyRight; } return border.bodyJoin; }, spanningCellManager, }) + '\n'; }
type Row = Cell[];
2,070
(row: Row, config: DrawRowConfig): string => { const {border, drawVerticalLine, rowIndex, spanningCellManager} = config; return drawContent({ contents: row, drawSeparator: drawVerticalLine, elementType: 'cell', rowIndex, separatorGetter: (index, columnCount) => { if (index === 0) { return border.bodyLeft; } if (index === columnCount) { return border.bodyRight; } return border.bodyJoin; }, spanningCellManager, }) + '\n'; }
type DrawRowConfig = { border: BodyBorderConfig, drawVerticalLine: DrawVerticalLine, spanningCellManager?: SpanningCellManager, rowIndex?: number, };
2,071
(config: TableConfig): number[] => { return config.columns.map((col) => { return col.paddingLeft + col.width + col.paddingRight; }); }
type TableConfig = Required<Omit<TableUserConfig, 'border' | 'columnDefault' | 'columns' | 'header' | 'spanningCells'>> & { readonly border: BorderConfig, readonly columns: ColumnConfig[], readonly spanningCellManager: SpanningCellManager, };
2,072
(parameters: DrawContentParameters): string => { const {contents, separatorGetter, drawSeparator, spanningCellManager, rowIndex, elementType} = parameters; const contentSize = contents.length; const result: string[] = []; if (drawSeparator(0, contentSize)) { result.push(separatorGetter(0, contentSize)); } contents.forEach((content, contentIndex) => { if (!elementType || elementType === 'border' || elementType === 'row') { result.push(content); } if (elementType === 'cell' && rowIndex === undefined) { result.push(content); } if (elementType === 'cell' && rowIndex !== undefined) { /* istanbul ignore next */ const containingRange = spanningCellManager?.getContainingRange({col: contentIndex, row: rowIndex}); // when drawing content row, just add a cell when it is a normal cell // or belongs to first column of spanning cell if (!containingRange || contentIndex === containingRange.topLeft.col) { result.push(content); } } // Only append the middle separator if the content is not the last if (contentIndex + 1 < contentSize && drawSeparator(contentIndex + 1, contentSize)) { const separator = separatorGetter(contentIndex + 1, contentSize); if (elementType === 'cell' && rowIndex !== undefined) { const currentCell: CellCoordinates = {col: contentIndex + 1, row: rowIndex}; /* istanbul ignore next */ const containingRange = spanningCellManager?.getContainingRange(currentCell); if (!containingRange || containingRange.topLeft.col === currentCell.col) { result.push(separator); } } else { result.push(separator); } } }); if (drawSeparator(contentSize, contentSize)) { result.push(separatorGetter(contentSize, contentSize)); } return result.join(''); }
type DrawContentParameters = { contents: string[], drawSeparator: (index: number, size: number) => boolean, separatorGetter: (index: number, size: number) => string, spanningCellManager?: SpanningCellManager, rowIndex?: number, elementType?: 'border' | 'cell' | 'row', };
2,073
(rangeConfig: RangeConfig, dependencies: SpanningCellParameters): number => { const {columnsConfig, drawVerticalLine} = dependencies; const {topLeft, bottomRight} = rangeConfig; const totalWidth = sumArray( columnsConfig.slice(topLeft.col, bottomRight.col + 1).map(({width}) => { return width; }), ); const totalPadding = topLeft.col === bottomRight.col ? columnsConfig[topLeft.col].paddingRight + columnsConfig[bottomRight.col].paddingLeft : sumArray( columnsConfig .slice(topLeft.col, bottomRight.col + 1) .map(({paddingLeft, paddingRight}) => { return paddingLeft + paddingRight; }), ); const totalBorderWidths = bottomRight.col - topLeft.col; const totalHiddenVerticalBorders = sequence(topLeft.col + 1, bottomRight.col).filter((verticalBorderIndex) => { return !drawVerticalLine(verticalBorderIndex, columnsConfig.length); }).length; return totalWidth + totalPadding + totalBorderWidths - totalHiddenVerticalBorders; }
type SpanningCellParameters = { spanningCellConfigs: SpanningCellConfig[], rows: Row[], columnsConfig: ColumnConfig[], drawVerticalLine: DrawVerticalLine, drawHorizontalLine: DrawHorizontalLine, };
2,074
(rangeConfig: RangeConfig, dependencies: SpanningCellParameters): number => { const {columnsConfig, drawVerticalLine} = dependencies; const {topLeft, bottomRight} = rangeConfig; const totalWidth = sumArray( columnsConfig.slice(topLeft.col, bottomRight.col + 1).map(({width}) => { return width; }), ); const totalPadding = topLeft.col === bottomRight.col ? columnsConfig[topLeft.col].paddingRight + columnsConfig[bottomRight.col].paddingLeft : sumArray( columnsConfig .slice(topLeft.col, bottomRight.col + 1) .map(({paddingLeft, paddingRight}) => { return paddingLeft + paddingRight; }), ); const totalBorderWidths = bottomRight.col - topLeft.col; const totalHiddenVerticalBorders = sequence(topLeft.col + 1, bottomRight.col).filter((verticalBorderIndex) => { return !drawVerticalLine(verticalBorderIndex, columnsConfig.length); }).length; return totalWidth + totalPadding + totalBorderWidths - totalHiddenVerticalBorders; }
type RangeConfig = RangeCoordinate & Required<CellUserConfig>;
2,075
(cell: CellCoordinates, options?: {mapped: true, }) => ResolvedRangeConfig | undefined
type CellCoordinates = { row: number, col: number, };
2,076
(cell1: CellCoordinates, cell2: CellCoordinates) => boolean
type CellCoordinates = { row: number, col: number, };
2,077
(cell: CellCoordinates, rangeConfigs: RangeConfig[]): RangeConfig | undefined => { return rangeConfigs.find((rangeCoordinate) => { return isCellInRange(cell, rangeCoordinate); }); }
type CellCoordinates = { row: number, col: number, };
2,078
(rangeConfig: RangeConfig, context: SpanningCellContext): ResolvedRangeConfig | undefined => { const width = calculateSpanningCellWidth(rangeConfig, context); const wrappedContent = wrapRangeContent(rangeConfig, width, context); const alignedContent = alignVerticalRangeContent(rangeConfig, wrappedContent, context); const getCellContent = (rowIndex: number) => { const {topLeft} = rangeConfig; const {drawHorizontalLine, rowHeights} = context; const totalWithinHorizontalBorderHeight = rowIndex - topLeft.row; const totalHiddenHorizontalBorderHeight = sequence(topLeft.row + 1, rowIndex).filter((index) => { /* istanbul ignore next */ return !drawHorizontalLine?.(index, rowHeights.length); }).length; const offset = sumArray(rowHeights.slice(topLeft.row, rowIndex)) + totalWithinHorizontalBorderHeight - totalHiddenHorizontalBorderHeight; return alignedContent.slice(offset, offset + rowHeights[rowIndex]); }; const getBorderContent = (borderIndex: number) => { const {topLeft} = rangeConfig; const offset = sumArray(context.rowHeights.slice(topLeft.row, borderIndex)) + (borderIndex - topLeft.row - 1); return alignedContent[offset]; }; return { ...rangeConfig, extractBorderContent: getBorderContent, extractCellContent: getCellContent, height: wrappedContent.length, width, }; }
type SpanningCellContext = SpanningCellParameters & { rowHeights: number[], };
2,079
(rangeConfig: RangeConfig, context: SpanningCellContext): ResolvedRangeConfig | undefined => { const width = calculateSpanningCellWidth(rangeConfig, context); const wrappedContent = wrapRangeContent(rangeConfig, width, context); const alignedContent = alignVerticalRangeContent(rangeConfig, wrappedContent, context); const getCellContent = (rowIndex: number) => { const {topLeft} = rangeConfig; const {drawHorizontalLine, rowHeights} = context; const totalWithinHorizontalBorderHeight = rowIndex - topLeft.row; const totalHiddenHorizontalBorderHeight = sequence(topLeft.row + 1, rowIndex).filter((index) => { /* istanbul ignore next */ return !drawHorizontalLine?.(index, rowHeights.length); }).length; const offset = sumArray(rowHeights.slice(topLeft.row, rowIndex)) + totalWithinHorizontalBorderHeight - totalHiddenHorizontalBorderHeight; return alignedContent.slice(offset, offset + rowHeights[rowIndex]); }; const getBorderContent = (borderIndex: number) => { const {topLeft} = rangeConfig; const offset = sumArray(context.rowHeights.slice(topLeft.row, borderIndex)) + (borderIndex - topLeft.row - 1); return alignedContent[offset]; }; return { ...rangeConfig, extractBorderContent: getBorderContent, extractCellContent: getCellContent, height: wrappedContent.length, width, }; }
type RangeConfig = RangeCoordinate & Required<CellUserConfig>;
2,080
(cell1: CellCoordinates, cell2: CellCoordinates, ranges: RangeConfig[]): boolean => { const range1 = findRangeConfig(cell1, ranges); const range2 = findRangeConfig(cell2, ranges); if (range1 && range2) { return areCellEqual(range1.topLeft, range2.topLeft); } return false; }
type CellCoordinates = { row: number, col: number, };
2,081
(range: RangeConfig): string => { const {row, col} = range.topLeft; return `${row}/${col}`; }
type RangeConfig = RangeCoordinate & Required<CellUserConfig>;
2,082
(parameters: SpanningCellParameters): SpanningCellManager => { const {spanningCellConfigs, columnsConfig} = parameters; const ranges = spanningCellConfigs.map((config) => { return makeRangeConfig(config, columnsConfig); }); const rangeCache: Record<string, ResolvedRangeConfig | undefined> = {}; let rowHeights: number[] = []; return {getContainingRange: (cell, options) => { const originalRow = options?.mapped ? findOriginalRowIndex(rowHeights, cell.row) : cell.row; const range = findRangeConfig({...cell, row: originalRow}, ranges); if (!range) { return undefined; } if (rowHeights.length === 0) { return getContainingRange(range, {...parameters, rowHeights}); } const hash = hashRange(range); rangeCache[hash] ??= getContainingRange(range, {...parameters, rowHeights}); return rangeCache[hash]; }, inSameRange: (cell1, cell2) => { return inSameRange(cell1, cell2, ranges); }, rowHeights, setRowHeights: (_rowHeights: number[]) => { rowHeights = _rowHeights; }}; }
type SpanningCellParameters = { spanningCellConfigs: SpanningCellConfig[], rows: Row[], columnsConfig: ColumnConfig[], drawVerticalLine: DrawVerticalLine, drawHorizontalLine: DrawHorizontalLine, };
2,083
(spanningCellConfig: SpanningCellConfig, columnsConfig: ColumnConfig[]): RangeConfig => { const {topLeft, bottomRight} = calculateRangeCoordinate(spanningCellConfig); const cellConfig: Required<CellUserConfig> = { ...columnsConfig[topLeft.col], ...spanningCellConfig, paddingRight: spanningCellConfig.paddingRight ?? columnsConfig[bottomRight.col].paddingRight, }; return {...cellConfig, bottomRight, topLeft}; }
type SpanningCellConfig = CellUserConfig & { readonly row: number, readonly col: number, readonly rowSpan?: number, readonly colSpan?: number, };
2,084
constructor(options?: PromptOptions)
type PromptOptions = | BasePromptOptions | ArrayPromptOptions | BooleanPromptOptions | StringPromptOptions | NumberPromptOptions | SnippetPromptOptions | SortPromptOptions
2,085
(this: Enquirer) => PromptOptions
class Enquirer<T = object> extends EventEmitter { constructor(options?: object, answers?: T); /** * Register a custom prompt type. * * @param type * @param fn `Prompt` class, or a function that returns a `Prompt` class. */ register(type: string, fn: typeof BasePrompt | (() => typeof BasePrompt)): this; /** * Register a custom prompt type. */ register(type: { [key: string]: typeof BasePrompt | (() => typeof BasePrompt) }): this; /** * Prompt function that takes a "question" object or array of question objects, * and returns an object with responses from the user. * * @param questions Options objects for one or more prompts to run. */ prompt( questions: | PromptOptions | ((this: Enquirer) => PromptOptions) | (PromptOptions | ((this: Enquirer) => PromptOptions))[] ): Promise<T>; /** * Use an enquirer plugin. * * @param plugin Plugin function that takes an instance of Enquirer. */ use(plugin: (this: this, enquirer: this) => void): this; }
2,086
constructor(opts: TracerOptions = {}) { super(); if (typeof opts !== "object") { throw new Error("Invalid options passed (must be an object)"); } if (opts.parent != null && typeof opts.parent !== "object") { throw new Error("Invalid option (parent) passed (must be an object)"); } if (opts.fields != null && typeof opts.fields !== "object") { throw new Error("Invalid option (fields) passed (must be an object)"); } if ( opts.objectMode != null && (opts.objectMode !== true && opts.objectMode !== false) ) { throw new Error( "Invalid option (objectsMode) passed (must be a boolean)" ); } this.noStream = opts.noStream || false; this.parent = opts.parent; if (this.parent) { this.fields = Object.assign({}, opts.parent && opts.parent.fields); } else { this.fields = {}; } if (opts.fields) { Object.assign(this.fields, opts.fields); } if (!this.fields.cat) { // trace-viewer *requires* `cat`, so let's have a fallback. this.fields.cat = "default"; } else if (Array.isArray(this.fields.cat)) { this.fields.cat = this.fields.cat.join(","); } if (!this.fields.args) { // trace-viewer *requires* `args`, so let's have a fallback. this.fields.args = {}; } if (this.parent) { // TODO: Not calling Readable ctor here. Does that cause probs? // Probably if trying to pipe from the child. // Might want a serpate TracerChild class for these guys. this._push = this.parent._push.bind(this.parent); } else { this._objectMode = Boolean(opts.objectMode); var streamOpts: ReadableOptions = { objectMode: this._objectMode }; if (this._objectMode) { this._push = this.push; } else { this._push = this._pushString; streamOpts.encoding = "utf8"; } ReadableStream.call(this, streamOpts); } }
interface TracerOptions { parent?: Tracer | null; fields?: Fields | null; objectMode?: boolean | null; noStream?: boolean; }
2,087
private _pushString(ev: Event) { var separator = ""; if (!this.firstPush) { this.push("["); this.firstPush = true; } else { separator = ",\n"; } this.push(separator + JSON.stringify(ev), "utf8"); }
interface Event { ts: number; pid: number; tid: number; /** event phase */ ph?: string; [otherData: string]: any; }
2,088
public child(fields: Fields) { return new Tracer({ parent: this, fields: fields }); }
interface Fields { cat?: any; args?: any; [filedName: string]: any; }
2,089
public begin(fields: Fields) { return this.mkEventFunc("b")(fields); }
interface Fields { cat?: any; args?: any; [filedName: string]: any; }
2,090
public end(fields: Fields) { return this.mkEventFunc("e")(fields); }
interface Fields { cat?: any; args?: any; [filedName: string]: any; }
2,091
public completeEvent(fields: Fields) { return this.mkEventFunc("X")(fields); }
interface Fields { cat?: any; args?: any; [filedName: string]: any; }
2,092
public instantEvent(fields: Fields) { return this.mkEventFunc("I")(fields); }
interface Fields { cat?: any; args?: any; [filedName: string]: any; }
2,093
(fields: Fields) => { var ev = evCommon(); // Assign the event phase. ev.ph = ph; if (fields) { if (typeof fields === "string") { ev.name = fields; } else { for (const k of Object.keys(fields)) { if (k === "cat") { ev.cat = fields.cat.join(","); } else { ev[k] = fields[k]; } } } } if (!this.noStream) { this._push(ev); } else { this.events.push(ev); } }
interface Fields { cat?: any; args?: any; [filedName: string]: any; }
2,094
function match<P extends object = object>( str: Path, options?: ParseOptions & TokensToRegexpOptions & RegexpToFunctionOptions ) { const keys: Key[] = []; const re = pathToRegexp(str, keys, options); return regexpToFunction<P>(re, keys, options); }
type Path = string | RegExp | Array<string | RegExp>;
2,095
function regexpToFunction<P extends object = object>( re: RegExp, keys: Key[], options: RegexpToFunctionOptions = {} ): MatchFunction<P> { const { decode = (x: string) => x } = options; return function (pathname: string) { const m = re.exec(pathname); if (!m) return false; const { 0: path, index } = m; const params = Object.create(null); for (let i = 1; i < m.length; i++) { if (m[i] === undefined) continue; const key = keys[i - 1]; if (key.modifier === "*" || key.modifier === "+") { params[key.name] = m[i].split(key.prefix + key.suffix).map((value) => { return decode(value, key); }); } else { params[key.name] = decode(m[i], key); } } return { path, index, params }; }; }
interface RegexpToFunctionOptions { /** * Function for decoding strings for params. */ decode?: (value: string, token: Key) => string; }
2,096
function pathToRegexp( path: Path, keys?: Key[], options?: TokensToRegexpOptions & ParseOptions ) { if (path instanceof RegExp) return regexpToRegexp(path, keys); if (Array.isArray(path)) return arrayToRegexp(path, keys, options); return stringToRegexp(path, keys, options); }
type Path = string | RegExp | Array<string | RegExp>;
2,097
function getAjvSyncInstances(extraOpts?: Options): AjvCore[] { return getAjvInstances( _Ajv, { strict: false, allErrors: true, code: {lines: true, optimize: false}, }, extraOpts ) }
type Options = CurrentOptions & DeprecatedOptions
2,098
function testTree(treeSchema: SchemaObject, strictTreeSchema: SchemaObject): void { const validTree = { data: 1, children: [ { data: 2, children: [{data: 3}], }, ], } const invalidTree = { data: 1, children: [ { data: 2, children: {}, }, ], } const treeWithExtra = { data: 1, children: [{data: 2, extra: 2}], } const treeWithDeepExtra = { data: 1, children: [ { data: 2, children: [{data: 3, extra: 3}], }, ], } ajvs.forEach((ajv) => { const validate = ajv.compile(treeSchema) assert.strictEqual(validate(validTree), true) assert.strictEqual(validate(invalidTree), false) assert.strictEqual(validate(treeWithExtra), true) // because unevaluated props allowed assert.strictEqual(validate(treeWithDeepExtra), true) // because unevaluated props allowed const validateStrict = ajv.compile(strictTreeSchema) assert.strictEqual(validateStrict(validTree), true) assert.strictEqual(validateStrict(invalidTree), false) assert.strictEqual(validateStrict(treeWithExtra), false) // because "extra" is "unevaluated" assert.strictEqual(validateStrict(treeWithDeepExtra), false) // because "extra" is "unevaluated" }) }
interface SchemaObject extends _SchemaObject { id?: string $id?: string $schema?: string $async?: false [x: string]: any // TODO }
2,099
function testInlined(validate: AnyValidateFunction, expectedInlined) { const inlined: any = !validate.source?.scopeValues.validate inlined.should.equal(expectedInlined) }
type AnyValidateFunction<T = any> = ValidateFunction<T> | AsyncValidateFunction<T>