Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: removing unused dependencies #1

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open

Conversation

trumant
Copy link
Owner

@trumant trumant commented Mar 30, 2024

No description provided.

@trumant trumant force-pushed the remove-unused-deps branch 2 times, most recently from 5bde719 to f3945dc Compare March 30, 2024 20:58
Copy link

github-actions bot commented Mar 30, 2024

New dependencies

@actions/core

DescriptionActions core lib
LicenseMIT
Created on2019-08-07T17:33:14.256Z
Last modified2023-09-11T15:12:48.398Z
Snyk Advisor Score
README.md# `@actions/core`

Core functions for setting results, logging, registering secrets and exporting variables across actions

Usage

Import the package

// javascript
const core = require('@actions/core');

// typescript
import * as core from '@actions/core';

Inputs/Outputs

Action inputs can be read with getInput which returns a string or getBooleanInput which parses a boolean based on the yaml 1.2 specification. If required set to be false, the input should have a default value in action.yml.

Outputs can be set with setOutput which makes them available to be mapped into inputs of other actions to ensure they are decoupled.

const myInput = core.getInput('inputName', { required: true });
const myBooleanInput = core.getBooleanInput('booleanInputName', { required: true });
const myMultilineInput = core.getMultilineInput('multilineInputName', { required: true });
core.setOutput('outputKey', 'outputVal');

Exporting variables

Since each step runs in a separate process, you can use exportVariable to add it to this step and future steps environment blocks.

core.exportVariable('envVar', 'Val');

Setting a secret

Setting a secret registers the secret with the runner to ensure it is masked in logs.

core.setSecret('myPassword');

PATH Manipulation

To make a tool's path available in the path for the remainder of the job (without altering the machine or containers state), use addPath. The runner will prepend the path given to the jobs PATH.

core.addPath('/path/to/mytool');

Exit codes

You should use this library to set the failing exit code for your action. If status is not set and the script runs to completion, that will lead to a success.

const core = require('@actions/core');

try {
  // Do stuff
}
catch (err) {
  // setFailed logs the message and sets a failing exit code
  core.setFailed(`Action failed with error ${err}`);
}

Note that setNeutral is not yet implemented in actions V2 but equivalent functionality is being planned.

Logging

Finally, this library provides some utilities for logging. Note that debug logging is hidden from the logs by default. This behavior can be toggled by enabling the Step Debug Logs.

const core = require('@actions/core');

const myInput = core.getInput('input');
try {
  core.debug('Inside try block');
  
  if (!myInput) {
    core.warning('myInput was not set');
  }
  
  if (core.isDebug()) {
    // curl -v https://github.com
  } else {
    // curl https://github.com
  }

  // Do stuff
  core.info('Output to the actions build log')

  core.notice('This is a message that will also emit an annotation')
}
catch (err) {
  core.error(`Error ${err}, action may still succeed though`);
}

This library can also wrap chunks of output in foldable groups.

const core = require('@actions/core')

// Manually wrap output
core.startGroup('Do some function')
doSomeFunction()
core.endGroup()

// Wrap an asynchronous function call
const result = await core.group('Do something async', async () => {
  const response = await doSomeHTTPRequest()
  return response
})

Annotations

This library has 3 methods that will produce annotations.

core.error('This is a bad error, action may still succeed though.')

core.warning('Something went wrong, but it\'s not bad enough to fail the build.')

core.notice('Something happened that you might want to know about.')

These will surface to the UI in the Actions page and on Pull Requests. They look something like this:

Annotations Image

These annotations can also be attached to particular lines and columns of your source files to show exactly where a problem is occuring.

These options are:

export interface AnnotationProperties {
  /**
   * A title for the annotation.
   */
  title?: string

  /**
   * The name of the file for which the annotation should be created.
   */
  file?: string

  /**
   * The start line for the annotation.
   */
  startLine?: number

  /**
   * The end line for the annotation. Defaults to `startLine` when `startLine` is provided.
   */
  endLine?: number

  /**
   * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
   */
  startColumn?: number

  /**
   * The end column for the annotation. Cannot be sent when `startLine` and `endLine` are different values.
   * Defaults to `startColumn` when `startColumn` is provided.
   */
  endColumn?: number
}

Styling output

Colored output is supported in the Action logs via standard ANSI escape codes. 3/4 bit, 8 bit and 24 bit colors are all supported.

Foreground colors:

// 3/4 bit
core.info('\u001b[35mThis foreground will be magenta')

// 8 bit
core.info('\u001b[38;5;6mThis foreground will be cyan')

// 24 bit
core.info('\u001b[38;2;255;0;0mThis foreground will be bright red')

Background colors:

// 3/4 bit
core.info('\u001b[43mThis background will be yellow');

// 8 bit
core.info('\u001b[48;5;6mThis background will be cyan')

// 24 bit
core.info('\u001b[48;2;255;0;0mThis background will be bright red')

Special styles:

core.info('\u001b[1mBold text')
core.info('\u001b[3mItalic text')
core.info('\u001b[4mUnderlined text')

ANSI escape codes can be combined with one another:

core.info('\u001b[31;46mRed foreground with a cyan background and \u001b[1mbold text at the end');

Note: Escape codes reset at the start of each line

core.info('\u001b[35mThis foreground will be magenta')
core.info('This foreground will reset to the default')

Manually typing escape codes can be a little difficult, but you can use third party modules such as ansi-styles.

const style = require('ansi-styles');
core.info(style.color.ansi16m.hex('#abcdef') + 'Hello world!')

Action state

You can use this library to save state and get state for sharing information between a given wrapper action:

action.yml:

name: 'Wrapper action sample'
inputs:
  name:
    default: 'GitHub'
runs:
  using: 'node12'
  main: 'main.js'
  post: 'cleanup.js'

In action's main.js:

const core = require('@actions/core');

core.saveState("pidToKill", 12345);

In action's cleanup.js:

const core = require('@actions/core');

var pid = core.getState("pidToKill");

process.kill(pid);

OIDC Token

You can use these methods to interact with the GitHub OIDC provider and get a JWT ID token which would help to get access token from third party cloud providers.

Method Name: getIDToken()

Inputs

audience : optional

Outputs

A JWT ID Token

In action's main.ts:

const core = require('@actions/core');
async function getIDTokenAction(): Promise<void> {
  
   const audience = core.getInput('audience', {required: false})
   
   const id_token1 = await core.getIDToken()            // ID Token with default audience
   const id_token2 = await core.getIDToken(audience)    // ID token with custom audience
   
   // this id_token can be used to get access token from third party cloud providers
}
getIDTokenAction()

In action's actions.yml:

name: 'GetIDToken'
description: 'Get ID token from Github OIDC provider'
inputs:
  audience:  
    description: 'Audience for which the ID token is intended for'
    required: false
outputs:
  id_token1: 
    description: 'ID token obtained from OIDC provider'
  id_token2: 
    description: 'ID token obtained from OIDC provider'
runs:
  using: 'node12'
  main: 'dist/index.js'

Filesystem path helpers

You can use these methods to manipulate file paths across operating systems.

The toPosixPath function converts input paths to Posix-style (Linux) paths.
The toWin32Path function converts input paths to Windows-style paths. These
functions work independently of the underlying runner operating system.

toPosixPath('\\foo\\bar') // => /foo/bar
toWin32Path('/foo/bar') // => \foo\bar

The toPlatformPath function converts input paths to the expected value on the runner's operating system.

// On a Windows runner.
toPlatformPath('/foo/bar') // => \foo\bar

// On a Linux runner.
toPlatformPath('\\foo\\bar') // => /foo/bar

@actions/github

DescriptionActions github lib
LicenseMIT
Created on2019-08-07T17:33:14.370Z
Last modified2023-10-10T14:50:27.273Z
Snyk Advisor Score
README.md# `@actions/github`

A hydrated Octokit client.

Usage

Returns an authenticated Octokit client that follows the machine proxy settings and correctly sets GHES base urls. See https://octokit.github.io/rest.js for the API.

const github = require('@actions/github');
const core = require('@actions/core');

async function run() {
    // This should be a token with access to your repository scoped in as a secret.
    // The YML workflow will need to set myToken with the GitHub Secret Token
    // myToken: ${{ secrets.GITHUB_TOKEN }}
    // https://help.github.com/en/actions/automating-your-workflow-with-github-actions/authenticating-with-the-github_token#about-the-github_token-secret
    const myToken = core.getInput('myToken');

    const octokit = github.getOctokit(myToken)

    // You can also pass in additional options as a second parameter to getOctokit
    // const octokit = github.getOctokit(myToken, {userAgent: "MyActionVersion1"});

    const { data: pullRequest } = await octokit.rest.pulls.get({
        owner: 'octokit',
        repo: 'rest.js',
        pull_number: 123,
        mediaType: {
          format: 'diff'
        }
    });

    console.log(pullRequest);
}

run();

You can also make GraphQL requests. See https://github.com/octokit/graphql.js for the API.

const result = await octokit.graphql(query, variables);

Finally, you can get the context of the current action:

const github = require('@actions/github');

const context = github.context;

const newIssue = await octokit.rest.issues.create({
  ...context.repo,
  title: 'New issue!',
  body: 'Hello Universe!'
});

Webhook payload typescript definitions

The npm module @octokit/webhooks-definitions provides type definitions for the response payloads. You can cast the payload to these types for better type information.

First, install the npm module npm install @octokit/webhooks-definitions

Then, assert the type based on the eventName

import * as core from '@actions/core'
import * as github from '@actions/github'
import {PushEvent} from '@octokit/webhooks-definitions/schema'

if (github.context.eventName === 'push') {
  const pushPayload = github.context.payload as PushEvent
  core.info(`The head commit is: ${pushPayload.head_commit}`)
}

Extending the Octokit instance

@octokit/core now supports the plugin architecture. You can extend the GitHub instance using plugins.

For example, using the @octokit/plugin-enterprise-server you can now access enterprise admin apis on GHES instances.

import { GitHub, getOctokitOptions } from '@actions/github/lib/utils'
import { enterpriseServer220Admin } from '@octokit/plugin-enterprise-server'

const octokit = GitHub.plugin(enterpriseServer220Admin)
// or override some of the default values as well 
// const octokit = GitHub.plugin(enterpriseServer220Admin).defaults({userAgent: "MyNewUserAgent"})

const myToken = core.getInput('myToken');
const myOctokit = new octokit(getOctokitOptions(token))
// Create a new user
myOctokit.rest.enterpriseAdmin.createUser({
  login: "testuser",
  email: "testuser@test.com",
});

jsdom

DescriptionA JavaScript implementation of many web standards
LicenseMIT
Created on2011-11-21T03:09:04.421Z
Last modified2024-01-21T13:06:09.586Z
Snyk Advisor Score
README.md


jsdom

jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG DOM and HTML Standards, for use with Node.js. In general, the goal of the project is to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications.

The latest versions of jsdom require Node.js v18 or newer. (Versions of jsdom below v23 still work with previous Node.js versions, but are unsupported.)

Basic usage

const jsdom = require("jsdom");
const { JSDOM } = jsdom;

To use jsdom, you will primarily use the JSDOM constructor, which is a named export of the jsdom main module. Pass the constructor a string. You will get back a JSDOM object, which has a number of useful properties, notably window:

const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"

(Note that jsdom will parse the HTML you pass it just like a browser does, including implied <html>, <head>, and <body> tags.)

The resulting object is an instance of the JSDOM class, which contains a number of useful properties and methods besides window. In general, it can be used to act on the jsdom from the "outside," doing things that are not possible with the normal DOM APIs. For simple cases, where you don't need any of this functionality, we recommend a coding pattern like

const { window } = new JSDOM(`...`);
// or even
const { document } = (new JSDOM(`...`)).window;

Full documentation on everything you can do with the JSDOM class is below, in the section "JSDOM Object API".

Customizing jsdom

The JSDOM constructor accepts a second parameter which can be used to customize your jsdom in the following ways.

Simple options

const dom = new JSDOM(``, {
  url: "https://example.org/",
  referrer: "https://example.com/",
  contentType: "text/html",
  includeNodeLocations: true,
  storageQuota: 10000000
});
  • url sets the value returned by window.location, document.URL, and document.documentURI, and affects things like resolution of relative URLs within the document and the same-origin restrictions and referrer used while fetching subresources. It defaults to "about:blank".
  • referrer just affects the value read from document.referrer. It defaults to no referrer (which reflects as the empty string).
  • contentType affects the value read from document.contentType, as well as how the document is parsed: as HTML or as XML. Values that are not a HTML MIME type or an XML MIME type will throw. It defaults to "text/html". If a charset parameter is present, it can affect binary data processing.
  • includeNodeLocations preserves the location info produced by the HTML parser, allowing you to retrieve it with the nodeLocation() method (described below). It also ensures that line numbers reported in exception stack traces for code running inside <script> elements are correct. It defaults to false to give the best performance, and cannot be used with an XML content type since our XML parser does not support location info.
  • storageQuota is the maximum size in code units for the separate storage areas used by localStorage and sessionStorage. Attempts to store data larger than this limit will cause a DOMException to be thrown. By default, it is set to 5,000,000 code units per origin, as inspired by the HTML specification.

Note that both url and referrer are canonicalized before they're used, so e.g. if you pass in "https:example.com", jsdom will interpret that as if you had given "https://example.com/". If you pass an unparseable URL, the call will throw. (URLs are parsed and serialized according to the URL Standard.)

Executing scripts

jsdom's most powerful ability is that it can execute scripts inside the jsdom. These scripts can modify the content of the page and access all the web platform APIs jsdom implements.

However, this is also highly dangerous when dealing with untrusted content. The jsdom sandbox is not foolproof, and code running inside the DOM's <script>s can, if it tries hard enough, get access to the Node.js environment, and thus to your machine. As such, the ability to execute scripts embedded in the HTML is disabled by default:

const dom = new JSDOM(`<body>
  <div id="content"></div>
  <script>document.getElementById("content").append(document.createElement("hr"));</script>
</body>`);

// The script will not be executed, by default:
console.log(dom.window.document.getElementById("content").children.length); // 0

To enable executing scripts inside the page, you can use the runScripts: "dangerously" option:

const dom = new JSDOM(`<body>
  <div id="content"></div>
  <script>document.getElementById("content").append(document.createElement("hr"));</script>
</body>`, { runScripts: "dangerously" });

// The script will be executed and modify the DOM:
console.log(dom.window.document.getElementById("content").children.length); // 1

Again we emphasize to only use this when feeding jsdom code you know is safe. If you use it on arbitrary user-supplied code, or code from the Internet, you are effectively running untrusted Node.js code, and your machine could be compromised.

If you want to execute external scripts, included via <script src="">, you'll also need to ensure that they load them. To do this, add the option resources: "usable" as described below. (You'll likely also want to set the url option, for the reasons discussed there.)

Event handler attributes, like <div onclick="">, are also governed by this setting; they will not function unless runScripts is set to "dangerously". (However, event handler properties, like div.onclick = ..., will function regardless of runScripts.)

If you are simply trying to execute script "from the outside", instead of letting <script> elements and event handlers attributes run "from the inside", you can use the runScripts: "outside-only" option, which enables fresh copies of all the JavaScript spec-provided globals to be installed on window. This includes things like window.Array, window.Promise, etc. It also, notably, includes window.eval, which allows running scripts, but with the jsdom window as the global:

const dom = new JSDOM(`<body>
  <div id="content"></div>
  <script>document.getElementById("content").append(document.createElement("hr"));</script>
</body>`, { runScripts: "outside-only" });

// run a script outside of JSDOM:
dom.window.eval('document.getElementById("content").append(document.createElement("p"));');

console.log(dom.window.document.getElementById("content").children.length); // 1
console.log(dom.window.document.getElementsByTagName("hr").length); // 0
console.log(dom.window.document.getElementsByTagName("p").length); // 1

This is turned off by default for performance reasons, but is safe to enable.

Note that in the default configuration, without setting runScripts, the values of window.Array, window.eval, etc. will be the same as those provided by the outer Node.js environment. That is, window.eval === eval will hold, so window.eval will not run scripts in a useful way.

We strongly advise against trying to "execute scripts" by mashing together the jsdom and Node global environments (e.g. by doing global.window = dom.window), and then executing scripts or test code inside the Node global environment. Instead, you should treat jsdom like you would a browser, and run all scripts and tests that need access to a DOM inside the jsdom environment, using window.eval or runScripts: "dangerously". This might require, for example, creating a browserify bundle to execute as a <script> element—just like you would in a browser.

Finally, for advanced use cases you can use the dom.getInternalVMContext() method, documented below.

Pretending to be a visual browser

jsdom does not have the capability to render visual content, and will act like a headless browser by default. It provides hints to web pages through APIs such as document.hidden that their content is not visible.

When the pretendToBeVisual option is set to true, jsdom will pretend that it is rendering and displaying content. It does this by:

  • Changing document.hidden to return false instead of true
  • Changing document.visibilityState to return "visible" instead of "prerender"
  • Enabling window.requestAnimationFrame() and window.cancelAnimationFrame() methods, which otherwise do not exist
const window = (new JSDOM(``, { pretendToBeVisual: true })).window;

window.requestAnimationFrame(timestamp => {
  console.log(timestamp > 0);
});

Note that jsdom still does not do any layout or rendering, so this is really just about pretending to be visual, not about implementing the parts of the platform a real, visual web browser would implement.

Loading subresources

Basic options

By default, jsdom will not load any subresources such as scripts, stylesheets, images, or iframes. If you'd like jsdom to load such resources, you can pass the resources: "usable" option, which will load all usable resources. Those are:

  • Frames and iframes, via <frame> and <iframe>
  • Stylesheets, via <link rel="stylesheet">
  • Scripts, via <script>, but only if runScripts: "dangerously" is also set
  • Images, via <img>, but only if the canvas npm package is also installed (see "Canvas Support" below)

When attempting to load resources, recall that the default value for the url option is "about:blank", which means that any resources included via relative URLs will fail to load. (The result of trying to parse the URL /something against the URL about:blank is an error.) So, you'll likely want to set a non-default value for the url option in those cases, or use one of the convenience APIs that do so automatically.

Advanced configuration

To more fully customize jsdom's resource-loading behavior, you can pass an instance of the ResourceLoader class as the resources option value:

const resourceLoader = new jsdom.ResourceLoader({
  proxy: "http://127.0.0.1:9001",
  strictSSL: false,
  userAgent: "Mellblomenator/9000",
});
const dom = new JSDOM(``, { resources: resourceLoader });

The three options to the ResourceLoader constructor are:

  • proxy is the address of an HTTP proxy to be used.
  • strictSSL can be set to false to disable the requirement that SSL certificates be valid.
  • userAgent affects the User-Agent header sent, and thus the resulting value for navigator.userAgent. It defaults to `Mozilla/5.0 (${process.platform || "unknown OS"}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`.

You can further customize resource fetching by subclassing ResourceLoader and overriding the fetch() method. For example, here is a version that overrides the response provided for a specific URL:

class CustomResourceLoader extends jsdom.ResourceLoader {
  fetch(url, options) {
    // Override the contents of this script to do something unusual.
    if (url === "https://example.com/some-specific-script.js") {
      return Promise.resolve(Buffer.from("window.someGlobal = 5;"));
    }

    return super.fetch(url, options);
  }
}

jsdom will call your custom resource loader's fetch() method whenever it encounters a "usable" resource, per the above section. The method takes a URL string, as well as a few options which you should pass through unmodified if calling super.fetch(). It must return a promise for a Node.js Buffer object, or return null if the resource is intentionally not to be loaded. In general, most cases will want to delegate to super.fetch(), as shown.

One of the options you will receive in fetch() will be the element (if applicable) that is fetching a resource.

class CustomResourceLoader extends jsdom.ResourceLoader {
  fetch(url, options) {
    if (options.element) {
      console.log(`Element ${options.element.localName} is requesting the url ${url}`);
    }

    return super.fetch(url, options);
  }
}

Virtual consoles

Like web browsers, jsdom has the concept of a "console". This records both information directly sent from the page, via scripts executing inside the document, as well as information from the jsdom implementation itself. We call the user-controllable console a "virtual console", to distinguish it from the Node.js console API and from the inside-the-page window.console API.

By default, the JSDOM constructor will return an instance with a virtual console that forwards all its output to the Node.js console. To create your own virtual console and pass it to jsdom, you can override this default by doing

const virtualConsole = new jsdom.VirtualConsole();
const dom = new JSDOM(``, { virtualConsole });

Code like this will create a virtual console with no behavior. You can give it behavior by adding event listeners for all the possible console methods:

virtualConsole.on("error", () => { ... });
virtualConsole.on("warn", () => { ... });
virtualConsole.on("info", () => { ... });
virtualConsole.on("dir", () => { ... });
// ... etc. See https://console.spec.whatwg.org/#logging

(Note that it is probably best to set up these event listeners before calling new JSDOM(), since errors or console-invoking script might occur during parsing.)

If you simply want to redirect the virtual console output to another console, like the default Node.js one, you can do

virtualConsole.sendTo(console);

There is also a special event, "jsdomError", which will fire with error objects to report errors from jsdom itself. This is similar to how error messages often show up in web browser consoles, even if they are not initiated by console.error. So far, the following errors are output this way:

  • Errors loading or parsing subresources (scripts, stylesheets, frames, and iframes)
  • Script execution errors that are not handled by a window onerror event handler that returns true or calls event.preventDefault()
  • Not-implemented errors resulting from calls to methods, like window.alert, which jsdom does not implement, but installs anyway for web compatibility

If you're using sendTo(c) to send errors to c, by default it will call c.error(errorStack[, errorDetail]) with information from "jsdomError" events. If you'd prefer to maintain a strict one-to-one mapping of events to method calls, and perhaps handle "jsdomError"s yourself, then you can do

virtualConsole.sendTo(c, { omitJSDOMErrors: true });

Cookie jars

Like web browsers, jsdom has the concept of a cookie jar, storing HTTP cookies. Cookies that have a URL on the same domain as the document, and are not marked HTTP-only, are accessible via the document.cookie API. Additionally, all cookies in the cookie jar will impact the fetching of subresources.

By default, the JSDOM constructor will return an instance with an empty cookie jar. To create your own cookie jar and pass it to jsdom, you can override this default by doing

const cookieJar = new jsdom.CookieJar(store, options);
const dom = new JSDOM(``, { cookieJar });

This is mostly useful if you want to share the same cookie jar among multiple jsdoms, or prime the cookie jar with certain values ahead of time.

Cookie jars are provided by the tough-cookie package. The jsdom.CookieJar constructor is a subclass of the tough-cookie cookie jar which by default sets the looseMode: true option, since that matches better how browsers behave. If you want to use tough-cookie's utilities and classes yourself, you can use the jsdom.toughCookie module export to get access to the tough-cookie module instance packaged with jsdom.

Intervening before parsing

jsdom allows you to intervene in the creation of a jsdom very early: after the Window and Document objects are created, but before any HTML is parsed to populate the document with nodes:

const dom = new JSDOM(`<p>Hello</p>`, {
  beforeParse(window) {
    window.document.childNodes.length === 0;
    window.someCoolAPI = () => { /* ... */ };
  }
});

This is especially useful if you are wanting to modify the environment in some way, for example adding shims for web platform APIs jsdom does not support.

JSDOM object API

Once you have constructed a JSDOM object, it will have the following useful capabilities:

Properties

The property window retrieves the Window object that was created for you.

The properties virtualConsole and cookieJar reflect the options you pass in, or the defaults created for you if nothing was passed in for those options.

Serializing the document with serialize()

The serialize() method will return the HTML serialization of the document, including the doctype:

const dom = new JSDOM(`<!DOCTYPE html>hello`);

dom.serialize() === "<!DOCTYPE html><html><head></head><body>hello</body></html>";

// Contrast with:
dom.window.document.documentElement.outerHTML === "<html><head></head><body>hello</body></html>";

Getting the source location of a node with nodeLocation(node)

The nodeLocation() method will find where a DOM node is within the source document, returning the parse5 location info for the node:

const dom = new JSDOM(
  `<p>Hello
    <img src="foo.jpg">
  </p>`,
  { includeNodeLocations: true }
);

const document = dom.window.document;
const bodyEl = document.body; // implicitly created
const pEl = document.querySelector("p");
const textNode = pEl.firstChild;
const imgEl = document.querySelector("img");

console.log(dom.nodeLocation(bodyEl));   // null; it's not in the source
console.log(dom.nodeLocation(pEl));      // { startOffset: 0, endOffset: 39, startTag: ..., endTag: ... }
console.log(dom.nodeLocation(textNode)); // { startOffset: 3, endOffset: 13 }
console.log(dom.nodeLocation(imgEl));    // { startOffset: 13, endOffset: 32 }

Note that this feature only works if you have set the includeNodeLocations option; node locations are off by default for performance reasons.

Interfacing with the Node.js vm module using getInternalVMContext()

The built-in vm module of Node.js is what underpins jsdom's script-running magic. Some advanced use cases, like pre-compiling a script and then running it multiple times, benefit from using the vm module directly with a jsdom-created Window.

To get access to the contextified global object, suitable for use with the vm APIs, you can use the getInternalVMContext() method:

const { Script } = require("vm");

const dom = new JSDOM(``, { runScripts: "outside-only" });
const script = new Script(`
  if (!this.ran) {
    this.ran = 0;
  }

  ++this.ran;
`);

const vmContext = dom.getInternalVMContext();

script.runInContext(vmContext);
script.runInContext(vmContext);
script.runInContext(vmContext);

console.assert(dom.window.ran === 3);

This is somewhat-advanced functionality, and we advise sticking to normal DOM APIs (such as window.eval() or document.createElement("script")) unless you have very specific needs.

Note that this method will throw an exception if the JSDOM instance was created without runScripts set, or if you are using jsdom in a web browser.

Reconfiguring the jsdom with reconfigure(settings)

The top property on window is marked [Unforgeable] in the spec, meaning it is a non-configurable own property and thus cannot be overridden or shadowed by normal code running inside the jsdom, even using Object.defineProperty.

Similarly, at present jsdom does not handle navigation (such as setting window.location.href = "https://example.com/"); doing so will cause the virtual console to emit a "jsdomError" explaining that this feature is not implemented, and nothing will change: there will be no new Window or Document object, and the existing window's location object will still have all the same property values.

However, if you're acting from outside the window, e.g. in some test framework that creates jsdoms, you can override one or both of these using the special reconfigure() method:

const dom = new JSDOM();

dom.window.top === dom.window;
dom.window.location.href === "about:blank";

dom.reconfigure({ windowTop: myFakeTopForTesting, url: "https://example.com/" });

dom.window.top === myFakeTopForTesting;
dom.window.location.href === "https://example.com/";

Note that changing the jsdom's URL will impact all APIs that return the current document URL, such as window.location, document.URL, and document.documentURI, as well as the resolution of relative URLs within the document, and the same-origin checks and referrer used while fetching subresources. It will not, however, perform navigation to the contents of that URL; the contents of the DOM will remain unchanged, and no new instances of Window, Document, etc. will be created.

Convenience APIs

fromURL()

In addition to the JSDOM constructor itself, jsdom provides a promise-returning factory method for constructing a jsdom from a URL:

JSDOM.fromURL("https://example.com/", options).then(dom => {
  console.log(dom.serialize());
});

The returned promise will fulfill with a JSDOM instance if the URL is valid and the request is successful. Any redirects will be followed to their ultimate destination.

The options provided to fromURL() are similar to those provided to the JSDOM constructor, with the following additional restrictions and consequences:

  • The url and contentType options cannot be provided.
  • The referrer option is used as the HTTP Referer request header of the initial request.
  • The resources option also affects the initial request; this is useful if you want to, for example, configure a proxy (see above).
  • The resulting jsdom's URL, content type, and referrer are determined from the response.
  • Any cookies set via HTTP Set-Cookie response headers are stored in the jsdom's cookie jar. Similarly, any cookies already in a supplied cookie jar are sent as HTTP Cookie request headers.

fromFile()

Similar to fromURL(), jsdom also provides a fromFile() factory method for constructing a jsdom from a filename:

JSDOM.fromFile("stuff.html", options).then(dom => {
  console.log(dom.serialize());
});

The returned promise will fulfill with a JSDOM instance if the given file can be opened. As usual in Node.js APIs, the filename is given relative to the current working directory.

The options provided to fromFile() are similar to those provided to the JSDOM constructor, with the following additional defaults:

  • The url option will default to a file URL corresponding to the given filename, instead of to "about:blank".
  • The contentType option will default to "application/xhtml+xml" if the given filename ends in .xht, .xhtml, or .xml; otherwise it will continue to default to "text/html".

fragment()

For the very simplest of cases, you might not need a whole JSDOM instance with all its associated power. You might not even need a Window or Document! Instead, you just need to parse some HTML, and get a DOM object you can manipulate. For that, we have fragment(), which creates a DocumentFragment from a given string:

const frag = JSDOM.fragment(`<p>Hello</p><p><strong>Hi!</strong>`);

frag.childNodes.length === 2;
frag.querySelector("strong").textContent === "Hi!";
// etc.

Here frag is a DocumentFragment instance, whose contents are created by parsing the provided string. The parsing is done using a <template> element, so you can include any element there (including ones with weird parsing rules like <td>). It's also important to note that the resulting DocumentFragment will not have an associated browsing context: that is, elements' ownerDocument will have a null defaultView property, resources will not load, etc.

All invocations of the fragment() factory result in DocumentFragments that share the same template owner Document. This allows many calls to fragment() with no extra overhead. But it also means that calls to fragment() cannot be customized with any options.

Note that serialization is not as easy with DocumentFragments as it is with full JSDOM objects. If you need to serialize your DOM, you should probably use the JSDOM constructor more directly. But for the special case of a fragment containing a single element, it's pretty easy to do through normal means:

const frag = JSDOM.fragment(`<p>Hello</p>`);
console.log(frag.firstChild.outerHTML); // logs "<p>Hello</p>"

Other noteworthy features

Canvas support

jsdom includes support for using the canvas package to extend any <canvas> elements with the canvas API. To make this work, you need to include canvas as a dependency in your project, as a peer of jsdom. If jsdom can find the canvas package, it will use it, but if it's not present, then <canvas> elements will behave like <div>s. Since jsdom v13, version 2.x of canvas is required; version 1.x is no longer supported.

Encoding sniffing

In addition to supplying a string, the JSDOM constructor can also be supplied binary data, in the form of a Node.js Buffer or a standard JavaScript binary data type like ArrayBuffer, Uint8Array, DataView, etc. When this is done, jsdom will sniff the encoding from the supplied bytes, scanning for <meta charset> tags just like a browser does.

If the supplied contentType option contains a charset parameter, that encoding will override the sniffed encoding—unless a UTF-8 or UTF-16 BOM is present, in which case those take precedence. (Again, this is just like a browser.)

This encoding sniffing also applies to JSDOM.fromFile() and JSDOM.fromURL(). In the latter case, any Content-Type headers sent with the response will take priority, in the same fashion as the constructor's contentType option.

Note that in many cases supplying bytes in this fashion can be better than supplying a string. For example, if you attempt to use Node.js's buffer.toString("utf-8") API, Node.js will not strip any leading BOMs. If you then give this string to jsdom, it will interpret it verbatim, leaving the BOM intact. But jsdom's binary data decoding code will strip leading BOMs, just like a browser; in such cases, supplying buffer directly will give the desired result.

Closing down a jsdom

Timers in the jsdom (set by window.setTimeout() or window.setInterval()) will, by definition, execute code in the future in the context of the window. Since there is no way to execute code in the future without keeping the process alive, outstanding jsdom timers will keep your Node.js process alive. Similarly, since there is no way to execute code in the context of an object without keeping that object alive, outstanding jsdom timers will prevent garbage collection of the window on which they are scheduled.

If you want to be sure to shut down a jsdom window, use window.close(), which will terminate all running timers (and also remove any event listeners on the window and document).

Debugging the DOM using Chrome DevTools

In Node.js you can debug programs using Chrome DevTools. See the official documentation for how to get started.

By default jsdom elements are formatted as plain old JS objects in the console. To make it easier to debug, you can use jsdom-devtools-formatter, which lets you inspect them like real DOM elements.

Caveats

Asynchronous script loading

People often have trouble with asynchronous script loading when using jsdom. Many pages load scripts asynchronously, but there is no way to tell when they're done doing so, and thus when it's a good time to run your code and inspect the resulting DOM structure. This is a fundamental limitation; we cannot predict what scripts on the web page will do, and so cannot tell you when they are done loading more scripts.

This can be worked around in a few ways. The best way, if you control the page in question, is to use whatever mechanisms are given by the script loader to detect when loading is done. For example, if you're using a module loader like RequireJS, the code could look like:

// On the Node.js side:
const window = (new JSDOM(...)).window;
window.onModulesLoaded = () => {
  console.log("ready to roll!");
};
<!-- Inside the HTML you supply to jsdom -->
<script>
requirejs(["entry-module"], () => {
  window.onModulesLoaded();
});
</script>

If you do not control the page, you could try workarounds such as polling for the presence of a specific element.

For more details, see the discussion in #640, especially @matthewkastor's insightful comment.

Unimplemented parts of the web platform

Although we enjoy adding new features to jsdom and keeping it up to date with the latest web specs, it has many missing APIs. Please feel free to file an issue for anything missing, but we're a small and busy team, so a pull request might work even better.

Some features of jsdom are provided by our dependencies. Notable documentation in that regard includes the list of supported CSS selectors for our CSS selector engine, nwsapi.

Beyond just features that we haven't gotten to yet, there are two major features that are currently outside the scope of jsdom. These are:

  • Navigation: the ability to change the global object, and all other objects, when clicking a link or assigning location.href or similar.
  • Layout: the ability to calculate where elements will be visually laid out as a result of CSS, which impacts methods like getBoundingClientRects() or properties like offsetTop.

Currently jsdom has dummy behaviors for some aspects of these features, such as sending a "not implemented" "jsdomError" to the virtual console for navigation, or returning zeros for many layout-related properties. Often you can work around these limitations in your code, e.g. by creating new JSDOM instances for each page you "navigate" to during a crawl, or using Object.defineProperty() to change what various layout-related getters and methods return.

Note that other tools in the same space, such as PhantomJS, do support these features. On the wiki, we have a more complete writeup about jsdom vs. PhantomJS.

Supporting jsdom

jsdom is a community-driven project maintained by a team of volunteers. You could support jsdom by:

Getting help

If you need help with jsdom, please feel free to use any of the following venues:

lodash

DescriptionLodash modular utilities.
LicenseMIT
Created on2012-04-23T16:37:11.912Z
Last modified2024-03-08T02:42:02.938Z
Snyk Advisor Score
README.md# lodash v4.17.21

The Lodash library exported as Node.js modules.

Installation

Using npm:

$ npm i -g npm
$ npm i --save lodash

In Node.js:

// Load the full build.
var _ = require('lodash');
// Load the core build.
var _ = require('lodash/core');
// Load the FP build for immutable auto-curried iteratee-first data-last methods.
var fp = require('lodash/fp');

// Load method categories.
var array = require('lodash/array');
var object = require('lodash/fp/object');

// Cherry-pick methods for smaller browserify/rollup/webpack bundles.
var at = require('lodash/at');
var curryN = require('lodash/fp/curryN');

See the package source for more details.

Note:

Install n_ for Lodash use in the Node.js < 6 REPL.

Support

Tested in Chrome 74-75, Firefox 66-67, IE 11, Edge 18, Safari 11-12, & Node.js 8-12.

Automated browser & CI test runs are available.

package-json

DescriptionGet metadata of a package from the npm registry
LicenseMIT
Created on2014-06-15T17:37:21.782Z
Last modified2024-02-25T03:16:59.744Z
Snyk Advisor Score
README.md# package-json

Get metadata of a package from the npm registry

Install

npm install package-json

Usage

import packageJson from 'package-json';

console.log(await packageJson('ava'));
//=> {name: 'ava', …}

// Also works with scoped packages
console.log(await packageJson('@sindresorhus/df'));

API

packageJson(packageName, options?)

packageName

Type: string

Name of the package.

options

Type: object

version

Type: string
Default: latest

Package version such as 1.0.0 or a dist tag such as latest.

The version can also be in any format supported by the semver module. For example:

  • 1 - Get the latest 1.x.x
  • 1.2 - Get the latest 1.2.x
  • ^1.2.3 - Get the latest 1.x.x but at least 1.2.3
  • ~1.2.3 - Get the latest 1.2.x but at least 1.2.3
fullMetadata

Type: boolean
Default: false

By default, only an abbreviated metadata object is returned for performance reasons. Read more, or see the type definitions.

allVersions

Type: boolean
Default: false

Return the main entry containing all versions.

registryUrl

Type: string
Default: Auto-detected

The registry URL is by default inferred from the npm defaults and .npmrc. This is beneficial as package-json and any project using it will work just like npm. This option is only intended for internal tools. You should not use this option in reusable packages. Prefer just using .npmrc whenever possible.

omitDeprecated

Type: boolean
Default: true

Whether or not to omit deprecated versions of a package.

If set, versions marked as deprecated on the registry are omitted from results. Providing a dist tag or a specific version will still return that version, even if it's deprecated. If no version can be found once deprecated versions are omitted, a VersionNotFoundError is thrown.

PackageNotFoundError

The error thrown when the given package name cannot be found.

VersionNotFoundError

The error thrown when the given package version cannot be found.

Authentication

Both public and private registries are supported, for both scoped and unscoped packages, as long as the registry uses either bearer tokens or basic authentication.

Proxies

Proxy support is not implemented in this package. If necessary, use a global agent that modifies fetch, which this package uses internally.

Support for this may come to Node.js in the future.

Related

underscore

DescriptionJavaScript's functional programming helper library.
LicenseMIT
Created on2011-01-09T19:04:10.529Z
Last modified2023-11-07T05:00:52.243Z
Snyk Advisor Score
README.md __ /\ \ __ __ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ /\_\ ____ /\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ \/\ \ /',__\ \ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ __ \ \ \/\__, `\ \ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\/\_\ _\ \ \/\____/ \/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/\/_//\ \_\ \/___/ \ \____/ \/___/

Underscore.js is a utility-belt library for JavaScript that provides
support for the usual functional suspects (each, map, reduce, filter...)
without extending any core JavaScript objects.

For Docs, License, Tests, and pre-packed downloads, see:
https://underscorejs.org

For support and questions, please consult
our security policy,
the gitter channel
or stackoverflow

Underscore is an open-sourced component of DocumentCloud:
https://github.com/documentcloud

Many thanks to our contributors:
https://github.com/jashkenas/underscore/contributors

You can support the project by donating on
Patreon.
Enterprise coverage is available as part of the
Tidelift Subscription.

This project adheres to a code of conduct. By participating, you are expected to uphold this code.

New devDevelopment

@types/jest

DescriptionTypeScript definitions for jest
LicenseMIT
Created on2016-05-17T05:15:55.334Z
Last modified2024-03-11T10:27:13.863Z
Snyk Advisor Score
README.md[object Object]

@types/jsdom

DescriptionTypeScript definitions for jsdom
LicenseMIT
Created on2016-05-17T05:24:36.982Z
Last modified2024-03-11T09:10:03.448Z
Snyk Advisor Score
README.md[object Object]

@types/lodash

DescriptionTypeScript definitions for lodash
LicenseMIT
Created on2016-05-17T05:32:21.382Z
Last modified2024-03-12T10:07:16.335Z
Snyk Advisor Score
README.md[object Object]

@types/node

DescriptionTypeScript definitions for node
LicenseMIT
Created on2016-05-17T18:26:38.670Z
Last modified2024-03-30T05:36:13.754Z
Snyk Advisor Score
README.md[object Object]

@types/underscore

DescriptionTypeScript definitions for underscore
LicenseMIT
Created on2016-05-17T19:09:14.994Z
Last modified2024-03-11T10:17:17.947Z
Snyk Advisor Score
README.md[object Object]

@typescript-eslint/eslint-plugin

DescriptionTypeScript plugin for ESLint
LicenseMIT
Created on2019-01-19T17:13:21.414Z
Last modified2024-03-28T09:56:21.574Z
Snyk Advisor Score

@typescript-eslint/parser

DescriptionAn ESLint custom parser which leverages TypeScript ESTree
LicenseBSD-2-Clause
Created on2019-01-19T17:13:21.526Z
Last modified2024-03-28T09:55:39.087Z
Snyk Advisor Score

@vercel/ncc

DescriptionSimple CLI for compiling a Node.js module into a single file, together with all its dependencies, gcc-style.
LicenseMIT
Created on2020-08-12T19:37:29.704Z
Last modified2023-10-18T21:17:06.853Z
Snyk Advisor Score
README.md# ncc

CI Status

Simple CLI for compiling a Node.js module into a single file,
together with all its dependencies, gcc-style.

Motivation

  • Publish minimal packages to npm
  • Only ship relevant app code to serverless environments
  • Don't waste time configuring bundlers
  • Generally faster bootup time and less I/O overhead
  • Compiled language-like experience (e.g.: go)

Design goals

  • Zero configuration
  • TypeScript built-in
  • Only supports Node.js programs as input / output
  • Support all Node.js patterns and npm modules

Usage

Installation

npm i -g @vercel/ncc

Usage

$ ncc <cmd> <opts>

Eg:

$ ncc build input.js -o dist

If building an .mjs or .js module inside a "type": "module" package boundary, an ES module output will be created automatically.

Outputs the Node.js compact build of input.js into dist/index.js.

Note: If the input file is using a .cjs extension, then so will the corresponding output file.
This is useful for packages that want to use .js files as modules in native Node.js using
a "type": "module" in the package.json file.

Commands:

  build <input-file> [opts]
  run <input-file> [opts]
  cache clean|dir|size
  help
  version

Options:

  -o, --out [dir]          Output directory for build (defaults to dist)
  -m, --minify             Minify output
  -C, --no-cache           Skip build cache population
  -s, --source-map         Generate source map
  -a, --asset-builds       Build nested JS assets recursively, useful for
                           when code is loaded as an asset eg for workers.
  --no-source-map-register Skip source-map-register source map support
  -e, --external [mod]     Skip bundling 'mod'. Can be used many times
  -q, --quiet              Disable build summaries / non-error outputs
  -w, --watch              Start a watched build
  -t, --transpile-only     Use transpileOnly option with the ts-loader
  --v8-cache               Emit a build using the v8 compile cache
  --license [file]         Adds a file containing licensing information to the output
  --stats-out [file]       Emit webpack stats as json to the specified output file
  --target [es]            ECMAScript target to use for output (default: es2015)
                           Learn more: https://webpack.js.org/configuration/target
  -d, --debug              Show debug logs

Execution Testing

For testing and debugging, a file can be built into a temporary directory and executed with full source maps support with the command:

$ ncc run input.js

With TypeScript

The only requirement is to point ncc to .ts or .tsx files. A tsconfig.json
file is necessary. Most likely you want to indicate es2015 support:

{
  "compilerOptions": {
    "target": "es2015",
    "moduleResolution": "node"
  }
}

If typescript is found in devDependencies, that version will be used.

Package Support

Some packages may need some extra options for ncc support in order to better work with the static analysis.

See package-support.md for some common packages and their usage with ncc.

Programmatically From Node.js

require('@vercel/ncc')('/path/to/input', {
  // provide a custom cache path or disable caching
  cache: "./custom/cache/path" | false,
  // externals to leave as requires of the build
  externals: ["externalpackage"],
  // directory outside of which never to emit assets
  filterAssetBase: process.cwd(), // default
  minify: false, // default
  sourceMap: false, // default
  assetBuilds: false, // default
  sourceMapBasePrefix: '../', // default treats sources as output-relative
  // when outputting a sourcemap, automatically include
  // source-map-support in the output file (increases output by 32kB).
  sourceMapRegister: true, // default
  watch: false, // default
  license: '', // default does not generate a license file
  target: 'es2015', // default
  v8cache: false, // default
  quiet: false, // default
  debugLog: false // default
}).then(({ code, map, assets }) => {
  console.log(code);
  // Assets is an object of asset file names to { source, permissions, symlinks }
  // expected relative to the output code (if any)
})

When watch: true is set, the build object is not a promise, but has the following signature:

{
  // handler re-run on each build completion
  // watch errors are reported on "err"
  handler (({ err, code, map, assets }) => { ... })
  // handler re-run on each rebuild start
  rebuild (() => {})
  // close the watcher
  void close ();
}

Caveats

  • Files / assets are relocated based on a static evaluator. Dynamic non-statically analyzable asset loads may not work out correctly

commitlint

DescriptionLint your commit messages
LicenseMIT
Created on2017-10-14T09:41:14.660Z
Last modified2024-03-19T02:24:03.966Z
Snyk Advisor Score
README.md# commitlint

Alias of @commitlint/cli

eslint

DescriptionAn AST-based pattern checker for JavaScript.
LicenseMIT
Created on2013-07-04T17:01:29.347Z
Last modified2024-03-29T20:45:00.948Z
Snyk Advisor Score

eslint-plugin-jest

DescriptionESLint rules for Jest
LicenseMIT
Created on2016-11-06T18:19:40.199Z
Last modified2024-03-29T22:22:37.659Z
Snyk Advisor Score

eslint-plugin-prettier

DescriptionRuns prettier as an eslint rule
LicenseMIT
Created on2017-01-26T04:15:55.798Z
Last modified2024-01-10T03:34:34.618Z
Snyk Advisor Score
README.md# eslint-plugin-prettier [![Build Status](https://github.com/prettier/eslint-plugin-prettier/workflows/CI/badge.svg?branch=master)](https://github.com/prettier/eslint-plugin-prettier/actions?query=workflow%3ACI+branch%3Amaster)

Runs Prettier as an ESLint rule and reports differences as individual ESLint issues.

If your desired formatting does not match Prettier’s output, you should use a different tool such as prettier-eslint instead.

Please read Integrating with linters before installing.

TOC

Sample

error: Insert `,` (prettier/prettier) at pkg/commons-atom/ActiveEditorRegistry.js:22:25:
  20 | import {
  21 |   observeActiveEditorsDebounced,
> 22 |   editorChangesDebounced
     |                         ^
  23 | } from './debounced';;
  24 |
  25 | import {observableFromSubscribeFunction} from '../commons-node/event';


error: Delete `;` (prettier/prettier) at pkg/commons-atom/ActiveEditorRegistry.js:23:21:
  21 |   observeActiveEditorsDebounced,
  22 |   editorChangesDebounced
> 23 | } from './debounced';;
     |                     ^
  24 |
  25 | import {observableFromSubscribeFunction} from '../commons-node/event';
  26 | import {cacheWhileSubscribed} from '../commons-node/observable';


2 errors found.

./node_modules/.bin/eslint --format codeframe pkg/commons-atom/ActiveEditorRegistry.js (code from nuclide).

Installation

npm install --save-dev eslint-plugin-prettier eslint-config-prettier
npm install --save-dev --save-exact prettier

eslint-plugin-prettier does not install Prettier or ESLint for you. You must install these yourself.

This plugin works best if you disable all other ESLint rules relating to code formatting, and only enable rules that detect potential bugs. If another active ESLint rule disagrees with prettier about how code should be formatted, it will be impossible to avoid lint errors. Our recommended configuration automatically enables eslint-config-prettier to disable all formatting-related ESLint rules.

Configuration (legacy: .eslintrc*)

For legacy configuration, this plugin ships with a plugin:prettier/recommended config that sets up both eslint-plugin-prettier and eslint-config-prettier in one go.

Add plugin:prettier/recommended as the last item in the extends array in your .eslintrc* config file, so that eslint-config-prettier has the opportunity to override other configs:

{
  "extends": ["plugin:prettier/recommended"]
}

This will:

  • Enable the prettier/prettier rule.
  • Disable the arrow-body-style and prefer-arrow-callback rules which are problematic with this plugin - see the below for why.
  • Enable the eslint-config-prettier config which will turn off ESLint rules that conflict with Prettier.

Configuration (new: eslint.config.js)

For flat configuration, this plugin ships with an eslint-plugin-prettier/recommended config that sets up both eslint-plugin-prettier and eslint-config-prettier in one go.

Import eslint-plugin-prettier/recommended and add it as the last item in the configuration array in your eslint.config.js file so that eslint-config-prettier has the opportunity to override other configs:

const eslintPluginPrettierRecommended = require('eslint-plugin-prettier/recommended');

module.exports = [
  // Any other config imports go at the top
  eslintPluginPrettierRecommended,
];

This will:

  • Enable the prettier/prettier rule.
  • Disable the arrow-body-style and prefer-arrow-callback rules which are problematic with this plugin - see the below for why.
  • Enable the eslint-config-prettier config which will turn off ESLint rules that conflict with Prettier.

Svelte support

We recommend to use eslint-plugin-svelte instead of eslint-plugin-svelte3 because eslint-plugin-svelte has a correct eslint-svelte-parser instead of hacking.

When use with eslint-plugin-svelte3, eslint-plugin-prettier will just ignore the text passed by eslint-plugin-svelte3, because the text has been modified.

If you still decide to use eslint-plugin-svelte3, you'll need to run prettier --write *.svelte manually.

arrow-body-style and prefer-arrow-callback issue

If you use arrow-body-style or prefer-arrow-callback together with the prettier/prettier rule from this plugin, you can in some cases end up with invalid code due to a bug in ESLint’s autofix – see issue #65.

For this reason, it’s recommended to turn off these rules. The plugin:prettier/recommended config does that for you.

You can still use these rules together with this plugin if you want, because the bug does not occur all the time. But if you do, you need to keep in mind that you might end up with invalid code, where you manually have to insert a missing closing parenthesis to get going again.

If you’re fixing large of amounts of previously unformatted code, consider temporarily disabling the prettier/prettier rule and running eslint --fix and prettier --write separately.

Options

Note: While it is possible to pass options to Prettier via your ESLint configuration file, it is not recommended because editor extensions such as prettier-atom and prettier-vscode will read .prettierrc, but won't read settings from ESLint, which can lead to an inconsistent experience.

  • The first option:

    • An object representing options that will be passed into prettier. Example:

      {
        "prettier/prettier": [
          "error",
          {
            "singleQuote": true,
            "parser": "flow"
          }
        ]
      }

      NB: This option will merge and override any config set with .prettierrc files

  • The second option:

    • An object with the following options

      • usePrettierrc: Enables loading of the Prettier configuration file, (default: true). May be useful if you are using multiple tools that conflict with each other, or do not wish to mix your ESLint settings with your Prettier configuration. And also, it is possible to run prettier without loading the prettierrc config file via the CLI's --no-config option or through the API by calling prettier.format() without passing through the options generated by calling resolveConfig.

        {
          "prettier/prettier": [
            "error",
            {},
            {
              "usePrettierrc": false
            }
          ]
        }
      • fileInfoOptions: Options that are passed to prettier.getFileInfo to decide whether a file needs to be formatted. Can be used for example to opt-out from ignoring files located in node_modules directories.

        {
          "prettier/prettier": [
            "error",
            {},
            {
              "fileInfoOptions": {
                "withNodeModules": true
              }
            }
          ]
        }
  • The rule is auto fixable -- if you run eslint with the --fix flag, your code will be formatted according to prettier style.


Sponsors

@prettier/plugin-eslint eslint-config-prettier eslint-plugin-prettier prettier-eslint prettier-eslint-cli
@prettier/plugin-eslint Open Collective sponsors eslint-config-prettier Open Collective backers eslint-plugin-prettier Open Collective backers prettier-eslint Open Collective sponsors prettier-eslint-cli Open Collective backers

Backers

@prettier/plugin-eslint eslint-config-prettier eslint-plugin-prettier prettier-eslint prettier-eslint-cli
@prettier/plugin-eslint Open Collective backers eslint-config-prettier Open Collective backers eslint-plugin-prettier Open Collective backers prettier-eslint Open Collective backers prettier-eslint-cli Open Collective backers

Contributing

See CONTRIBUTING.md

Changelog

Detailed changes for each release are documented in CHANGELOG.md.

License

MIT

jest

DescriptionDelightful JavaScript Testing.
LicenseMIT
Created on2012-02-22T15:25:44.365Z
Last modified2024-02-26T15:59:15.885Z
Snyk Advisor Score

jest-circus

Description[type-definitions]: https://github.com/jestjs/jest/blob/main/packages/jest-types/src/Circus.ts
LicenseMIT
Created on2017-06-02T14:31:17.306Z
Last modified2024-02-26T15:57:24.171Z
Snyk Advisor Score

js-yaml

DescriptionYAML 1.2 parser and serializer
LicenseMIT
Created on2011-11-02T01:56:02.870Z
Last modified2023-06-09T21:33:18.974Z
Snyk Advisor Score
README.mdJS-YAML - YAML 1.2 parser / writer for JavaScript =================================================

CI
NPM version

Online Demo

This is an implementation of YAML, a human-friendly data
serialization language. Started as PyYAML port, it was
completely rewritten from scratch. Now it's very fast, and supports 1.2 spec.

Installation

YAML module for node.js

npm install js-yaml

CLI executable

If you want to inspect your YAML files from CLI, install js-yaml globally:

npm install -g js-yaml

Usage

usage: js-yaml [-h] [-v] [-c] [-t] file

Positional arguments:
  file           File with YAML document(s)

Optional arguments:
  -h, --help     Show this help message and exit.
  -v, --version  Show program's version number and exit.
  -c, --compact  Display errors in compact mode
  -t, --trace    Show stack trace on error

API

Here we cover the most 'useful' methods. If you need advanced details (creating
your own tags), see examples
for more info.

const yaml = require('js-yaml');
const fs   = require('fs');

// Get document, or throw exception on error
try {
  const doc = yaml.load(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
  console.log(doc);
} catch (e) {
  console.log(e);
}

load (string [ , options ])

Parses string as single YAML document. Returns either a
plain object, a string, a number, null or undefined, or throws YAMLException on error. By default, does
not support regexps, functions and undefined.

options:

  • filename (default: null) - string to be used as a file path in
    error/warning messages.
  • onWarning (default: null) - function to call on warning messages.
    Loader will call this function with an instance of YAMLException for each warning.
  • schema (default: DEFAULT_SCHEMA) - specifies a schema to use.
  • json (default: false) - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error.

NOTE: This function does not understand multi-document sources, it throws
exception on those.

NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
So, the JSON schema is not as strictly defined in the YAML specification.
It allows numbers in any notation, use Null and NULL as null, etc.
The core schema also has no such restrictions. It allows binary notation for integers.

loadAll (string [, iterator] [, options ])

Same as load(), but understands multi-document sources. Applies
iterator to each document if specified, or returns array of documents.

const yaml = require('js-yaml');

yaml.loadAll(data, function (doc) {
  console.log(doc);
});

dump (object [ , options ])

Serializes object as a YAML document. Uses DEFAULT_SCHEMA, so it will
throw an exception if you try to dump regexps or functions. However, you can
disable exceptions by setting the skipInvalid option to true.

options:

  • indent (default: 2) - indentation width to use (in spaces).
  • noArrayIndent (default: false) - when true, will not add an indentation level to array elements
  • skipInvalid (default: false) - do not throw on invalid types (like function
    in the safe schema) and skip pairs and single values with such types.
  • flowLevel (default: -1) - specifies level of nesting, when to switch from
    block to flow style for collections. -1 means block style everwhere
  • styles - "tag" => "style" map. Each tag may have own set of styles.
  • schema (default: DEFAULT_SCHEMA) specifies a schema to use.
  • sortKeys (default: false) - if true, sort keys when dumping YAML. If a
    function, use the function to sort the keys.
  • lineWidth (default: 80) - set max line width. Set -1 for unlimited width.
  • noRefs (default: false) - if true, don't convert duplicate objects into references
  • noCompatMode (default: false) - if true don't try to be compatible with older
    yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1
  • condenseFlow (default: false) - if true flow sequences will be condensed, omitting the space between a, b. Eg. '[a,b]', and omitting the space between key: value and quoting the key. Eg. '{"a":b}' Can be useful when using yaml for pretty URL query params as spaces are %-encoded.
  • quotingType (' or ", default: ') - strings will be quoted using this quoting style. If you specify single quotes, double quotes will still be used for non-printable characters.
  • forceQuotes (default: false) - if true, all non-key strings will be quoted even if they normally don't need to.
  • replacer - callback function (key, value) called recursively on each key/value in source object (see replacer docs for JSON.stringify).

The following table show availlable styles (e.g. "canonical",
"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml
output is shown on the right side after => (default setting) or ->:

!!null
  "canonical"   -> "~"
  "lowercase"   => "null"
  "uppercase"   -> "NULL"
  "camelcase"   -> "Null"

!!int
  "binary"      -> "0b1", "0b101010", "0b1110001111010"
  "octal"       -> "0o1", "0o52", "0o16172"
  "decimal"     => "1", "42", "7290"
  "hexadecimal" -> "0x1", "0x2A", "0x1C7A"

!!bool
  "lowercase"   => "true", "false"
  "uppercase"   -> "TRUE", "FALSE"
  "camelcase"   -> "True", "False"

!!float
  "lowercase"   => ".nan", '.inf'
  "uppercase"   -> ".NAN", '.INF'
  "camelcase"   -> ".NaN", '.Inf'

Example:

dump(object, {
  'styles': {
    '!!null': 'canonical' // dump null as ~
  },
  'sortKeys': true        // sort object keys
});

Supported YAML types

The list of standard YAML tags and corresponding JavaScript types. See also
YAML tag discussion and
YAML types repository.

!!null ''                   # null
!!bool 'yes'                # bool
!!int '3...'                # number
!!float '3.14...'           # number
!!binary '...base64...'     # buffer
!!timestamp 'YYYY-...'      # date
!!omap [ ... ]              # array of key-value pairs
!!pairs [ ... ]             # array or array pairs
!!set { ... }               # array of objects with given keys and null values
!!str '...'                 # string
!!seq [ ... ]               # array
!!map { ... }               # object

JavaScript-specific tags

See js-yaml-js-types for
extra types.

Caveats

Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects
or arrays as keys, and stringifies (by calling toString() method) them at the
moment of adding them.

---
? [ foo, bar ]
: - baz
? { foo: bar }
: - baz
  - baz
{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] }

Also, reading of properties on implicit block mapping keys is not supported yet.
So, the following YAML document cannot be loaded.

&anchor foo:
  foo: bar
  *anchor: duplicate key
  baz: bat
  *anchor: duplicate key

js-yaml for enterprise

Available as part of the Tidelift Subscription

The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

prettier

DescriptionPrettier is an opinionated code formatter
LicenseMIT
Created on2017-01-10T03:45:38.963Z
Last modified2024-02-25T15:54:08.863Z
Snyk Advisor Score
README.md[![Prettier Banner](https://unpkg.com/prettier-logo@1.0.3/images/prettier-banner-light.svg)](https://prettier.io)

Opinionated Code Formatter

JavaScript · TypeScript · Flow · JSX · JSON
CSS · SCSS · Less
HTML · Vue · Angular
GraphQL · Markdown · YAML
Your favorite language?

Github Actions Build Status Github Actions Build Status Github Actions Build Status Codecov Coverage Status Blazing Fast
npm version weekly downloads from npm code style: prettier Follow Prettier on Twitter

Intro

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

Input

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());

Output

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis(),
  isThereSeriouslyAnotherOne(),
);

Prettier can be run in your editor on-save, in a pre-commit hook, or in CI environments to ensure your codebase has a consistent style without devs ever having to post a nit-picky comment on a code review ever again!


Documentation

Install ·
Options ·
CLI ·
API

Playground


Badge

Show the world you're using Prettiercode style: prettier

[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

Contributing

See CONTRIBUTING.md.

ts-jest

DescriptionA Jest transformer with source map support that lets you use Jest to test projects written in TypeScript
LicenseMIT
Created on2016-08-31T07:36:04.630Z
Last modified2024-01-22T10:40:13.705Z
Snyk Advisor Score
README.md

ts-jest

A Jest transformer with source map support that lets you use Jest to test projects written in TypeScript.

NPM version NPM downloads Known vulnerabilities Coverage status GitHub actions GitHub license

It supports all features of TypeScript including type-checking. Read more about Babel7 + preset-typescript vs TypeScript (and ts-jest).


We are not doing semantic versioning and 23.10 is a re-write, run npm i -D ts-jest@"<23.10.0" to go back to the previous version

View the online documentation (usage & technical)

Ask for some help in the Jest Discord community or ts-jest GitHub Discussion

Before reporting any issues, be sure to check the troubleshooting page

We're looking for collaborators! Want to help improve ts-jest?


Getting Started

These instructions will get you setup to use ts-jest in your project. For more detailed documentation, please check online documentation.

using npm using yarn
Prerequisites npm i -D jest typescript yarn add --dev jest typescript
Installing npm i -D ts-jest @types/jest yarn add --dev ts-jest @types/jest
Creating config npx ts-jest config:init yarn ts-jest config:init
Running tests npm test or npx jest yarn test or yarn jest

Built With

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

Versioning

We DO NOT use SemVer for versioning. Though you can think about SemVer when reading our version, except our major number follows the one of Jest. For the versions available, see the tags on this repository.

Authors/maintainers

See also the list of contributors who participated in this project.

Supporters

License

This project is licensed under the MIT License - see the LICENSE.md file for details

typescript

DescriptionTypeScript is a language for application scale JavaScript development
LicenseApache-2.0
Created on2012-10-01T15:35:39.553Z
Last modified2024-03-30T07:12:05.100Z
Snyk Advisor Score

@trumant trumant force-pushed the remove-unused-deps branch 2 times, most recently from b2c4dbe to 44b4ddb Compare March 30, 2024 21:25
@trumant trumant changed the base branch from upgrade-to-node-20 to main March 30, 2024 22:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant