Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
code-block-writer
Advanced tools
A simple code writer that assists with formatting and visualizing blocks of code.
The code-block-writer npm package is a utility for generating code with proper formatting, such as indentation and line breaks. It is particularly useful when writing code generators or transpilers that need to output human-readable code.
Writing code with automatic indentation and new lines
This feature allows you to write code blocks with automatic indentation management. The code sample demonstrates how to create a class with a constructor and a property.
const CodeBlockWriter = require('code-block-writer');
const writer = new CodeBlockWriter();
writer.writeLine('class MyClass {').indent(() => {
writer.writeLine('constructor() {').indent(() => {
writer.writeLine('this.myProperty = 1;');
}).writeLine('}');
}).writeLine('}');
console.log(writer.toString());
Conditional writing
This feature enables writing parts of the code conditionally. In the code sample, 'someCondition' is only written if the 'condition' is true.
const writer = new CodeBlockWriter();
const condition = true;
writer.write('if (').conditionalWrite(condition, 'someCondition').writeLine(') {').indent(() => {
writer.writeLine('doSomething();');
}).writeLine('}');
console.log(writer.toString());
Block indentation
This feature allows for easy indentation of entire blocks of code. The code sample shows how to write a function with multiple lines inside its body, all properly indented.
const writer = new CodeBlockWriter();
writer.writeLine('function myFunction() {').indentBlock(() => {
writer.writeLine('let x = 10;').writeLine('return x;');
}).writeLine('}');
console.log(writer.toString());
Prettier is an opinionated code formatter that supports many languages and integrates with most editors. Unlike code-block-writer, which is used for generating code, Prettier formats existing code according to its style rules.
js-beautify is a package that can format HTML, CSS, and JavaScript. It is similar to Prettier in that it formats existing code. It is not specifically designed for code generation like code-block-writer.
Recast is a JavaScript AST tool that allows you to parse your code, modify it, and then generate new code. It is more complex than code-block-writer as it deals with abstract syntax trees, but it can be used for similar code generation tasks.
Code writer for JavaScript and TypeScript code.
With Deno:
deno add jsr:@david/code-block-writer
Or with Node:
npm install --save code-block-writer
// import CodeBlockWriter from "code-block-writer"; // for npm
import CodeBlockWriter from "@david/code-block-writer";
const writer = new CodeBlockWriter({
// optional options
newLine: "\r\n", // default: "\n"
indentNumberOfSpaces: 2, // default: 4
useTabs: false, // default: false
useSingleQuote: true // default: false
});
writer.write("class MyClass extends OtherClass").block(() => {
writer.writeLine(`@MyDecorator(1, 2)`);
writer.write(`myMethod(myParam: any)`).block(() => {
writer.write("return this.post(").quote("myArgument").write(");");
});
});
console.log(writer.toString());
Outputs (using "\r\n" for newlines):
class MyClass extends OtherClass {
@MyDecorator(1, 2)
myMethod(myParam: any) {
return this.post('myArgument');
}
}
block(block?: () => void)
- Indents all the code written within and surrounds it in braces.inlineBlock(block?: () => void)
- Same as block, but doesn't add a space before the first brace and doesn't add a newline at the end.getLength()
- Get the current number of characters.writeLine(text: string)
- Writes some text and adds a newline.newLine()
- Writes a newline.newLineIfLastNot()
- Writes a newline if what was written last wasn't a newline.blankLine()
- Writes a blank line. Does not allow consecutive blank lines.blankLineIfLastNot()
- Writes a blank line if what was written last wasn't a blank line.quote()
- Writes a quote character.quote(text: string)
- Writes text surrounded in quotes.indent(times?: number)
- Indents the current line. Optionally indents multiple times when providing a number.indent(block?: () => void)
- Indents a block of code.space(times?: number)
- Writes a space. Optionally writes multiple spaces when providing a number.spaceIfLastNot()
- Writes a space if the last was not a space.tab(times?: number)
- Writes a tab. Optionally writes multiple tabs when providing a number.tabIfLastNot()
- Writes a tab if the last was not a tab.write(text: string)
- Writes some text.conditionalNewLine(condition: boolean)
- Writes a newline if the condition is matched.conditionalBlankLine(condition: boolean)
- Writes a blank line if the condition is matched.conditionalWrite(condition: boolean, text: string)
- Writes if the condition is matched.conditionalWrite(condition: boolean, textFunc: () => string)
- Writes if the condition is matched.conditionalWriteLine(condition: boolean, text: string)
- Writes some text and adds a newline if the condition is matched.conditionalWriteLine(condition: boolean, textFunc: () => string)
- Writes some text and adds a newline if the condition is matched.setIndentationLevel(indentationLevel: number)
- Sets the current indentation level.setIndentationLevel(whitespaceText: string)
- Sets the current indentation level based on the provided whitespace text.withIndentationLevel(indentationLevel: number, action: () => void)
- Sets the indentation level within the provided action.withIndentationLevel(whitespaceText: string, action: () => void)
- Sets the indentation level based on the provided whitespace text within the action.getIndentationLevel()
- Gets the current indentation level.queueIndentationLevel(indentationLevel: number)
- Queues an indentation level to be used once a new line is written.queueIndentationLevel(whitespaceText: string)
- Queues an indentation level to be used once a new line is written based on the provided whitespace text.hangingIndent(action: () => void)
- Writes the code within the action with hanging indentation.hangingIndentUnlessBlock(action: () => void)
- Writes the code within the action with hanging indentation unless a block is written going from the first line to the second.closeComment()
- Writes text to exit a comment if in a comment.unsafeInsert(pos: number, text: string)
- Inserts text into the writer. This will not update the writer's state. Read more in its jsdoc.isInComment()
- Gets if the writer is currently in a comment.isAtStartOfFirstLineOfBlock()
- Gets if the writer is currently at the start of the first line of the text, block, or indentation block.isOnFirstLineOfBlock()
- Gets if the writer is currently on the first line of the text, block, or indentation block.isInString()
- Gets if the writer is currently in a string.isLastNewLine()
- Gets if the writer last wrote a newline.isLastBlankLine()
- Gets if the writer last wrote a blank line.isLastSpace()
- Gets if the writer last wrote a space.isLastTab()
- Gets if the writer last wrote a tab.getLastChar()
- Gets the last character written.endsWith(text: string)
- Gets if the writer ends with the provided text.iterateLastChars<T>(action: (char: string, index: number) => T | undefined): T | undefined
- Iterates over the writer's characters in reverse order, stopping once a non-null or undefined value is returned and returns that value.iterateLastCharCodes<T>(action: (charCode: number, index: number) => T | undefined): T | undefined
- A slightly faster version of iterateLastChars
that doesn't allocate a string per character.getOptions()
- Gets the writer options.toString()
- Gets the string..quote(text)
.See CodeBlockWriterSharp.
FAQs
A simple code writer that assists with formatting and visualizing blocks of code.
The npm package code-block-writer receives a total of 2,169,476 weekly downloads. As such, code-block-writer popularity was classified as popular.
We found that code-block-writer demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.