diff --git a/node_modules/strip-comments/CHANGELOG.md b/node_modules/strip-comments/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..7d215655e3a08d52b6acd84959abbea92b1529a8 --- /dev/null +++ b/node_modules/strip-comments/CHANGELOG.md @@ -0,0 +1,136 @@ +# Release history + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +
+ Guiding Principles + +- Changelogs are for humans, not machines. +- There should be an entry for every single version. +- The same types of changes should be grouped. +- Versions and sections should be linkable. +- The latest version comes first. +- The release date of each versions is displayed. +- Mention whether you follow Semantic Versioning. + +
+ +
+ Types of changes + +Changelog entries are classified using the following labels _(from [keep-a-changelog](http://keepachangelog.com/)_): + +- `Added` for new features. +- `Changed` for changes in existing functionality. +- `Deprecated` for soon-to-be removed features. +- `Removed` for now removed features. +- `Fixed` for any bug fixes. +- `Security` in case of vulnerabilities. + +
+ + +## [2.0.0] - 2019-09-14 + +**Changed** + +- Refactored again to use a custom parser that is much faster and supports a number of different languages. + +## [1.0.2] - 2018-05-03 + +- refactored +- Remove default objectRestSpread plugin #40 allows for user configured plugins +- Merge pull request #42 from tallarium/remove-default-transform +- Merge remote-tracking branch 'origin/master' into refactor +- Merge remote-tracking branch 'origin/master' into refactor +- Merge pull request #44 from jonschlinkert/refactor + +## [1.0.1] - 2018-03-24 + +- feat: Allow users to specify their own babylon plugins +- Merge pull request #40 from briandipalma/patch-1 +- adds `allowReturnOutsideFunction` to defaults + +## [1.0.0] - 2018-03-24 + +- adds object-rest-spread plugin + +## [0.4.4] - 2016-02-14 + +- refactor to use babylon + +## [0.4.3] - 2015-12-25 + +- minor tweak + +## [0.4.2] - 2015-12-11 + +- bump extract-comments per issue https://github.com/jonschlinkert/strip-comments/issues/29 +- Merge branch 'master' of https://github.com/lebbe/strip-comments into lebbe-master +- Merge branch 'lebbe-master' + +## [0.4.0] - 2015-11-04 + +- adds more test cases +- closes https://github.com/jonschlinkert/strip-comments/issues/18 +- Handles comments that are substrings of a later comment +- Merge pull request #28 from epicoxymoron/bugfix/27-discard-is-too-greedy +- adds example +- adds json test + +## [0.3.4] - 2015-10-22 + +- refactored +- expose `first` method. code comments, minor formatting +- allow line/block to be specified as options +- Merge pull request #23 from jonschlinkert/dev +- fixes examples +- adds editorconfig + +## [0.3.0] - 2014-09-02 + +- merge fix from origin +- Merge pull request #13 from mk-pmb/tests_literals_nocomment +- Merge pull request #15 from mk-pmb/tests_literals_snake +- Merge pull request #22 from kgryte/patch-1 +- Merge pull request #9 from tunnckoCore/master +- Merge remote-tracking branch 'origin/line-comments' +- Merge remote-tracking branch 'origin/master' +- tests: not a comment: snake-y ASCII art +- tests: string and regexp literals +- adds tests for URLs +- fix globstars +- lint + +## [0.2.0] - 2014-08-10 + +- fixes `use strict` statement + +## [0.1.6] - 2014-02-13 + +- Merge branch 'master' of https://github.com/tunnckoCore/strip-comments into tunnckoCore-master +- Merge branch 'tunnckoCore-master' +- minor formatting + +## [0.1.0] - 2014-02-10 + +- first commit + +[1.0.2]: https://github.com/jonschlinkert/strip-comments/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/jonschlinkert/strip-comments/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/jonschlinkert/strip-comments/compare/0.4.4...1.0.0 +[0.4.4]: https://github.com/jonschlinkert/strip-comments/compare/0.4.3...0.4.4 +[0.4.3]: https://github.com/jonschlinkert/strip-comments/compare/0.4.2...0.4.3 +[0.4.2]: https://github.com/jonschlinkert/strip-comments/compare/0.4.0...0.4.2 +[0.4.0]: https://github.com/jonschlinkert/strip-comments/compare/0.3.4...0.4.0 +[0.3.4]: https://github.com/jonschlinkert/strip-comments/compare/0.3.0...0.3.4 +[0.3.0]: https://github.com/jonschlinkert/strip-comments/compare/0.2.0...0.3.0 +[0.2.0]: https://github.com/jonschlinkert/strip-comments/compare/0.1.6...0.2.0 +[0.1.6]: https://github.com/jonschlinkert/strip-comments/compare/0.1.0...0.1.6 + +[Unreleased]: https://github.com/jonschlinkert/strip-comments/compare/0.1.0...HEAD +[keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog + diff --git a/node_modules/strip-comments/LICENSE b/node_modules/strip-comments/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9af4a67d206f24ecdbb5fdff2839041ca0bbd346 --- /dev/null +++ b/node_modules/strip-comments/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/strip-comments/README.md b/node_modules/strip-comments/README.md new file mode 100644 index 0000000000000000000000000000000000000000..62ec4fece34a0c771f5015a781436349ad1e7f82 --- /dev/null +++ b/node_modules/strip-comments/README.md @@ -0,0 +1,237 @@ +# strip-comments [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/strip-comments.svg?style=flat)](https://www.npmjs.com/package/strip-comments) [![NPM monthly downloads](https://img.shields.io/npm/dm/strip-comments.svg?style=flat)](https://npmjs.org/package/strip-comments) [![NPM total downloads](https://img.shields.io/npm/dt/strip-comments.svg?style=flat)](https://npmjs.org/package/strip-comments) [![Build Status](https://travis-ci.org/jonschlinkert/strip-comments.svg?branch=master)](https://travis-ci.org/jonschlinkert/strip-comments) + +> Strip line and/or block comments from a string. Blazing fast, and works with JavaScript, Sass, CSS, Less.js, and a number of other languages. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +- [Install](#install) +- [What does this do?](#what-does-this-do) +- [Usage](#usage) +- [API](#api) +- [About](#about) + +_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ + +## Install + +Install with [npm](https://www.npmjs.com/) (requires [Node.js](https://nodejs.org/en/) >=10): + +```sh +$ npm install --save strip-comments +``` + +## What does this do? + +Takes a string and returns a new string with comments removed. Works with line comments and/or block comments. Optionally removes the first comment only or ignores protected comments. + +Works with: + +* ada +* apl +* applescript +* c +* csharp +* css +* hashbang +* haskell +* html +* java +* javascript +* less +* lua +* matlab +* ocaml +* pascal +* perl +* php +* python +* ruby +* sass +* shebang +* sql +* swift +* typscript +* xml + +## Usage + +By default all comments are stripped. + +```js +const strip = require('strip-comments'); +const str = strip('const foo = "bar";// this is a comment\n /* me too *\/'); +console.log(str); +// => 'const foo = "bar";\n' +``` + +For more use-cases see the [tests](./test/test.js) + +## API + +### [strip](index.js#L33) + +Strip all code comments from the given `input`, including protected comments that start with `!`, unless disabled by setting `options.keepProtected` to true. + +**Params** + +* `input` **{String}**: string from which to strip comments +* `options` **{Object}**: optional options, passed to [extract-comments](https://github.com/jonschlinkert/extract-comments) + +- `line` **{Boolean}**: if `false` strip only block comments, default `true` +- `block` **{Boolean}**: if `false` strip only line comments, default `true` +- `keepProtected` **{Boolean}**: Keep ignored comments (e.g. `/*!` and `//!`) +- `preserveNewlines` **{Boolean}**: Preserve newlines after comments are stripped +* `returns` **{String}**: modified input + +**Example** + +```js +const str = strip('const foo = "bar";// this is a comment\n /* me too */'); +console.log(str); +// => 'const foo = "bar";' +``` + +### [.block](index.js#L54) + +Strip only block comments. + +**Params** + +* `input` **{String}**: string from which to strip comments +* `options` **{Object}**: pass `opts.keepProtected: true` to keep ignored comments (e.g. `/*!`) +* `returns` **{String}**: modified string + +**Example** + +```js +const strip = require('..'); +const str = strip.block('const foo = "bar";// this is a comment\n /* me too */'); +console.log(str); +// => 'const foo = "bar";// this is a comment' +``` + +### [.line](index.js#L74) + +Strip only line comments. + +**Params** + +* `input` **{String}**: string from which to strip comments +* `options` **{Object}**: pass `opts.keepProtected: true` to keep ignored comments (e.g. `//!`) +* `returns` **{String}**: modified string + +**Example** + +```js +const str = strip.line('const foo = "bar";// this is a comment\n /* me too */'); +console.log(str); +// => 'const foo = "bar";\n/* me too */' +``` + +### [.first](index.js#L95) + +Strip the first comment from the given `input`. Or, if `opts.keepProtected` is true, the first non-protected comment will be stripped. + +**Params** + +* `input` **{String}** +* `options` **{Object}**: pass `opts.keepProtected: true` to keep comments with `!` +* `returns` **{String}** + +**Example** + +```js +const output = strip.first(input, { keepProtected: true }); +console.log(output); +// => '//! first comment\nfoo; ' +``` + +### [.block](index.js#L116) + +Parses a string and returns a basic CST (Concrete Syntax Tree). + +**Params** + +* `input` **{String}**: string from which to strip comments +* `options` **{Object}**: pass `opts.keepProtected: true` to keep ignored comments (e.g. `/*!`) +* `returns` **{String}**: modified string + +**Example** + +```js +const strip = require('..'); +const str = strip.block('const foo = "bar";// this is a comment\n /* me too */'); +console.log(str); +// => 'const foo = "bar";// this is a comment' +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [code-context](https://www.npmjs.com/package/code-context): Parse a string of javascript to determine the context for functions, variables and comments based… [more](https://github.com/jonschlinkert/code-context) | [homepage](https://github.com/jonschlinkert/code-context "Parse a string of javascript to determine the context for functions, variables and comments based on the code that follows.") +* [extract-comments](https://www.npmjs.com/package/extract-comments): Uses esprima to extract line and block comments from a string of JavaScript. Also optionally… [more](https://github.com/jonschlinkert/extract-comments) | [homepage](https://github.com/jonschlinkert/extract-comments "Uses esprima to extract line and block comments from a string of JavaScript. Also optionally parses code context (the next line of code after a comment).") +* [parse-code-context](https://www.npmjs.com/package/parse-code-context): Fast and simple way to parse code context for use with documentation from code comments… [more](https://github.com/jonschlinkert/parse-code-context) | [homepage](https://github.com/jonschlinkert/parse-code-context "Fast and simple way to parse code context for use with documentation from code comments. Parses context from a single line of JavaScript, for functions, variable declarations, methods, prototype properties, prototype methods etc.") +* [parse-comments](https://www.npmjs.com/package/parse-comments): Parse code comments from JavaScript or any language that uses the same format. | [homepage](https://github.com/jonschlinkert/parse-comments "Parse code comments from JavaScript or any language that uses the same format.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 82 | [jonschlinkert](https://github.com/jonschlinkert) | +| 4 | [tunnckoCore](https://github.com/tunnckoCore) | +| 2 | [mk-pmb](https://github.com/mk-pmb) | +| 1 | [kgryte](https://github.com/kgryte) | +| 1 | [briandipalma](https://github.com/briandipalma) | +| 1 | [epicoxymoron](https://github.com/epicoxymoron) | +| 1 | [XuluWarrior](https://github.com/XuluWarrior) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on November 13, 2019._ \ No newline at end of file diff --git a/node_modules/strip-comments/index.js b/node_modules/strip-comments/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7dcedb30c2ef03879e7bb93b921261a0eb38041f --- /dev/null +++ b/node_modules/strip-comments/index.js @@ -0,0 +1,116 @@ +/*! + * strip-comments + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +const compile = require('./lib/compile'); +const parse = require('./lib/parse'); + +/** + * Strip all code comments from the given `input`, including protected + * comments that start with `!`, unless disabled by setting `options.keepProtected` + * to true. + * + * ```js + * const str = strip('const foo = "bar";// this is a comment\n /* me too *\/'); + * console.log(str); + * // => 'const foo = "bar";' + * ``` + * @name strip + * @param {String} `input` string from which to strip comments + * @param {Object} `options` optional options, passed to [extract-comments][extract-comments] + * @option {Boolean} [options] `line` if `false` strip only block comments, default `true` + * @option {Boolean} [options] `block` if `false` strip only line comments, default `true` + * @option {Boolean} [options] `keepProtected` Keep ignored comments (e.g. `/*!` and `//!`) + * @option {Boolean} [options] `preserveNewlines` Preserve newlines after comments are stripped + * @return {String} modified input + * @api public + */ + +const strip = module.exports = (input, options) => { + const opts = { ...options, block: true, line: true }; + return compile(parse(input, opts), opts); +}; + +/** + * Strip only block comments. + * + * ```js + * const strip = require('..'); + * const str = strip.block('const foo = "bar";// this is a comment\n /* me too *\/'); + * console.log(str); + * // => 'const foo = "bar";// this is a comment' + * ``` + * @name .block + * @param {String} `input` string from which to strip comments + * @param {Object} `options` pass `opts.keepProtected: true` to keep ignored comments (e.g. `/*!`) + * @return {String} modified string + * @api public + */ + +strip.block = (input, options) => { + const opts = { ...options, block: true }; + return compile(parse(input, opts), opts); +}; + +/** + * Strip only line comments. + * + * ```js + * const str = strip.line('const foo = "bar";// this is a comment\n /* me too *\/'); + * console.log(str); + * // => 'const foo = "bar";\n/* me too *\/' + * ``` + * @name .line + * @param {String} `input` string from which to strip comments + * @param {Object} `options` pass `opts.keepProtected: true` to keep ignored comments (e.g. `//!`) + * @return {String} modified string + * @api public + */ + +strip.line = (input, options) => { + const opts = { ...options, line: true }; + return compile(parse(input, opts), opts); +}; + +/** + * Strip the first comment from the given `input`. Or, if `opts.keepProtected` is true, + * the first non-protected comment will be stripped. + * + * ```js + * const output = strip.first(input, { keepProtected: true }); + * console.log(output); + * // => '//! first comment\nfoo; ' + * ``` + * @name .first + * @param {String} `input` + * @param {Object} `options` pass `opts.keepProtected: true` to keep comments with `!` + * @return {String} + * @api public + */ + +strip.first = (input, options) => { + const opts = { ...options, block: true, line: true, first: true }; + return compile(parse(input, opts), opts); +}; + +/** + * Parses a string and returns a basic CST (Concrete Syntax Tree). + * + * ```js + * const strip = require('..'); + * const str = strip.block('const foo = "bar";// this is a comment\n /* me too *\/'); + * console.log(str); + * // => 'const foo = "bar";// this is a comment' + * ``` + * @name .block + * @param {String} `input` string from which to strip comments + * @param {Object} `options` pass `opts.keepProtected: true` to keep ignored comments (e.g. `/*!`) + * @return {String} modified string + * @api public + */ + +strip.parse = parse; diff --git a/node_modules/strip-comments/lib/Node.js b/node_modules/strip-comments/lib/Node.js new file mode 100644 index 0000000000000000000000000000000000000000..c0c81f71454aba15d6273118579fe6d77da22aeb --- /dev/null +++ b/node_modules/strip-comments/lib/Node.js @@ -0,0 +1,28 @@ +'use strict'; + +class Node { + constructor(node) { + this.type = node.type; + if (node.value) this.value = node.value; + if (node.match) this.match = node.match; + this.newline = node.newline || ''; + } + get protected() { + return Boolean(this.match) && this.match[1] === '!'; + } +} + +class Block extends Node { + constructor(node) { + super(node); + this.nodes = node.nodes || []; + } + push(node) { + this.nodes.push(node); + } + get protected() { + return this.nodes.length > 0 && this.nodes[0].protected === true; + } +} + +module.exports = { Node, Block }; diff --git a/node_modules/strip-comments/lib/compile.js b/node_modules/strip-comments/lib/compile.js new file mode 100644 index 0000000000000000000000000000000000000000..951ff3ed8307d353204bdb100212c7b8cf5c5ef0 --- /dev/null +++ b/node_modules/strip-comments/lib/compile.js @@ -0,0 +1,63 @@ +'use strict'; + +const compile = (cst, options = {}) => { + const keepProtected = options.safe === true || options.keepProtected === true; + let firstSeen = false; + + const walk = (node, parent) => { + let output = ''; + let inner; + let lines; + + for (const child of node.nodes) { + switch (child.type) { + case 'block': + if (options.first && firstSeen === true) { + output += walk(child, node); + break; + } + + if (options.preserveNewlines === true) { + inner = walk(child, node); + lines = inner.split('\n'); + output += '\n'.repeat(lines.length - 1); + break; + } + + if (keepProtected === true && child.protected === true) { + output += walk(child, node); + break; + } + + firstSeen = true; + break; + case 'line': + if (options.first && firstSeen === true) { + output += child.value; + break; + } + + if (keepProtected === true && child.protected === true) { + output += child.value; + } + + firstSeen = true; + break; + case 'open': + case 'close': + case 'text': + case 'newline': + default: { + output += child.value || ''; + break; + } + } + } + + return output; + }; + + return walk(cst); +}; + +module.exports = compile; diff --git a/node_modules/strip-comments/lib/languages.js b/node_modules/strip-comments/lib/languages.js new file mode 100644 index 0000000000000000000000000000000000000000..362776daa593ccaf17415202636bf94e2a2c680d --- /dev/null +++ b/node_modules/strip-comments/lib/languages.js @@ -0,0 +1,85 @@ +'use strict'; + +exports.ada = { LINE_REGEX: /^--.*/ }; +exports.apl = { LINE_REGEX: /^⍝.*/ }; + +exports.applescript = { + BLOCK_OPEN_REGEX: /^\(\*/, + BLOCK_CLOSE_REGEX: /^\*\)/ +}; + +exports.csharp = { + LINE_REGEX: /^\/\/.*/ +}; + +exports.haskell = { + BLOCK_OPEN_REGEX: /^\{-/, + BLOCK_CLOSE_REGEX: /^-\}/, + LINE_REGEX: /^--.*/ +}; + +exports.html = { + BLOCK_OPEN_REGEX: /^\n*/, + BLOCK_CLOSE_LOOSE_REGEX: /^(?/, + BLOCK_CLOSE_STRICT_NEWLINE_REGEX: /^(?(\s*\n+|\n*)/, + BLOCK_CLOSE_STRICT_LOOSE_REGEX: /^(?(\s*\n+|\n*)/ +}; + +exports.javascript = { + BLOCK_OPEN_REGEX: /^\/\*\*?(!?)/, + BLOCK_CLOSE_REGEX: /^\*\/(\n?)/, + LINE_REGEX: /^\/\/(!?).*/ +}; + +exports.lua = { + BLOCK_OPEN_REGEX: /^--\[\[/, + BLOCK_CLOSE_REGEX: /^\]\]/, + LINE_REGEX: /^--.*/ +}; + +exports.matlab = { + BLOCK_OPEN_REGEX: /^%{/, + BLOCK_CLOSE_REGEX: /^%}/, + LINE_REGEX: /^%.*/ +}; + +exports.perl = { + LINE_REGEX: /^#.*/ +}; + +exports.php = { + ...exports.javascript, + LINE_REGEX: /^(#|\/\/).*?(?=\?>|\n)/ +}; + +exports.python = { + BLOCK_OPEN_REGEX: /^"""/, + BLOCK_CLOSE_REGEX: /^"""/, + LINE_REGEX: /^#.*/ +}; + +exports.ruby = { + BLOCK_OPEN_REGEX: /^=begin/, + BLOCK_CLOSE_REGEX: /^=end/, + LINE_REGEX: /^#.*/ +}; + +exports.shebang = exports.hashbang = { + LINE_REGEX: /^#!.*/ +}; + +exports.c = exports.javascript; +exports.csharp = exports.javascript; +exports.css = exports.javascript; +exports.java = exports.javascript; +exports.js = exports.javascript; +exports.less = exports.javascript; +exports.pascal = exports.applescript; +exports.ocaml = exports.applescript; +exports.sass = exports.javascript; +exports.sql = exports.ada; +exports.swift = exports.javascript; +exports.ts = exports.javascript; +exports.typscript = exports.javascript; +exports.xml = exports.html; diff --git a/node_modules/strip-comments/lib/parse.js b/node_modules/strip-comments/lib/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..1097ba375e04bb4b7fa8919c50a2cb9e2fc77769 --- /dev/null +++ b/node_modules/strip-comments/lib/parse.js @@ -0,0 +1,141 @@ +'use strict'; + +const { Node, Block } = require('./Node'); +const languages = require('./languages'); + +const constants = { + ESCAPED_CHAR_REGEX: /^\\./, + QUOTED_STRING_REGEX: /^(['"`])((?:\\.|[^\1])+?)(\1)/, + NEWLINE_REGEX: /^\r*\n/ +}; + +const parse = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + const cst = new Block({ type: 'root', nodes: [] }); + const stack = [cst]; + const name = (options.language || 'javascript').toLowerCase(); + const lang = languages[name]; + + if (typeof lang === 'undefined') { + throw new Error(`Language "${name}" is not supported by strip-comments`); + } + + const { LINE_REGEX, BLOCK_OPEN_REGEX, BLOCK_CLOSE_REGEX } = lang; + let block = cst; + let remaining = input; + let token; + let prev; + + const source = [BLOCK_OPEN_REGEX, BLOCK_CLOSE_REGEX].filter(Boolean); + let tripleQuotes = false; + + if (source.every(regex => regex.source === '^"""')) { + tripleQuotes = true; + } + + /** + * Helpers + */ + + const consume = (value = remaining[0] || '') => { + remaining = remaining.slice(value.length); + return value; + }; + + const scan = (regex, type = 'text') => { + const match = regex.exec(remaining); + if (match) { + consume(match[0]); + return { type, value: match[0], match }; + } + }; + + const push = node => { + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + block.push(node); + if (node.nodes) { + stack.push(node); + block = node; + } + prev = node; + }; + + const pop = () => { + if (block.type === 'root') { + throw new SyntaxError('Unclosed block comment'); + } + stack.pop(); + block = stack[stack.length - 1]; + }; + + /** + * Parse input string + */ + + while (remaining !== '') { + // escaped characters + if ((token = scan(constants.ESCAPED_CHAR_REGEX, 'text'))) { + push(new Node(token)); + continue; + } + + // quoted strings + if (block.type !== 'block' && (!prev || !/\w$/.test(prev.value)) && !(tripleQuotes && remaining.startsWith('"""'))) { + if ((token = scan(constants.QUOTED_STRING_REGEX, 'text'))) { + push(new Node(token)); + continue; + } + } + + // newlines + if ((token = scan(constants.NEWLINE_REGEX, 'newline'))) { + push(new Node(token)); + continue; + } + + // block comment open + if (BLOCK_OPEN_REGEX && options.block && !(tripleQuotes && block.type === 'block')) { + if ((token = scan(BLOCK_OPEN_REGEX, 'open'))) { + push(new Block({ type: 'block' })); + push(new Node(token)); + continue; + } + } + + // block comment close + if (BLOCK_CLOSE_REGEX && block.type === 'block' && options.block) { + if ((token = scan(BLOCK_CLOSE_REGEX, 'close'))) { + token.newline = token.match[1] || ''; + push(new Node(token)); + pop(); + continue; + } + } + + // line comment + if (LINE_REGEX && block.type !== 'block' && options.line) { + if ((token = scan(LINE_REGEX, 'line'))) { + push(new Node(token)); + continue; + } + } + + // Plain text (skip "C" since some languages use "C" to start comments) + if ((token = scan(/^[a-zABD-Z0-9\t ]+/, 'text'))) { + push(new Node(token)); + continue; + } + + push(new Node({ type: 'text', value: consume(remaining[0]) })); + } + + return cst; +}; + +module.exports = parse; diff --git a/node_modules/strip-comments/package.json b/node_modules/strip-comments/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7926efe3bc88d5b2872edca6bc3393ccd7f313c4 --- /dev/null +++ b/node_modules/strip-comments/package.json @@ -0,0 +1,102 @@ +{ + "name": "strip-comments", + "description": "Strip line and/or block comments from a string. Blazing fast, and works with JavaScript, Sass, CSS, Less.js, and a number of other languages.", + "version": "2.0.1", + "homepage": "https://github.com/jonschlinkert/strip-comments", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "repository": "jonschlinkert/strip-comments", + "bugs": { + "url": "https://github.com/jonschlinkert/strip-comments/issues" + }, + "license": "MIT", + "files": [ + "index.js", + "lib" + ], + "main": "index.js", + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "mocha", + "cover": "nyc --reporter=text --reporter=html mocha" + }, + "devDependencies": { + "gulp-format-md": "^2.0.0", + "mocha": "^6.2.2", + "nyc": "^14.1.1" + }, + "keywords": [ + "ada comments", + "apl comments", + "applescript comments", + "block comment", + "block", + "block-comment", + "c comments", + "code comment", + "comment", + "comments", + "csharp comments", + "css comments", + "css", + "hashbang comments", + "haskell comments", + "html comments", + "java comments", + "javascript comments", + "javascript", + "js", + "less comments", + "less css", + "less", + "less.js", + "lessjs", + "line comment", + "line comments", + "line", + "line-comment", + "line-comments", + "lua comments", + "matlab comments", + "ocaml comments", + "pascal comments", + "perl comments", + "php comments", + "python comments", + "remove", + "ruby comments", + "sass comments", + "sass", + "shebang comments", + "sql comments", + "strip", + "swift comments", + "typscript comments", + "xml comments" + ], + "verb": { + "toc": true, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "helpers": [ + "./examples/support/helpers.js" + ], + "related": { + "list": [ + "code-context", + "extract-comments", + "parse-code-context", + "parse-comments" + ] + }, + "lint": { + "reflinks": true + } + } +} \ No newline at end of file diff --git a/node_modules/strip-indent/index.d.ts b/node_modules/strip-indent/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..44f2304b9d4817c4592b23110348d35d1881816a --- /dev/null +++ b/node_modules/strip-indent/index.d.ts @@ -0,0 +1,21 @@ +/** +Strip leading whitespace from each line in a string. + +The line with the least number of leading whitespace, ignoring empty lines, determines the number to remove. + +@example +``` +import stripIndent = require('strip-indent'); + +const string = '\tunicorn\n\t\tcake'; +// unicorn +// cake + +stripIndent(string); +//unicorn +// cake +``` +*/ +declare function stripIndent(string: string): string; + +export = stripIndent; diff --git a/node_modules/strip-indent/index.js b/node_modules/strip-indent/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7ba3b15b3e60f64a739d049a05fdd1a7df0546d5 --- /dev/null +++ b/node_modules/strip-indent/index.js @@ -0,0 +1,14 @@ +'use strict'; +const minIndent = require('min-indent'); + +module.exports = string => { + const indent = minIndent(string); + + if (indent === 0) { + return string; + } + + const regex = new RegExp(`^[ \\t]{${indent}}`, 'gm'); + + return string.replace(regex, ''); +}; diff --git a/node_modules/strip-indent/license b/node_modules/strip-indent/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/node_modules/strip-indent/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/strip-indent/package.json b/node_modules/strip-indent/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d66a003b8ba555cb3316ee8c95f9f24b8c384cb6 --- /dev/null +++ b/node_modules/strip-indent/package.json @@ -0,0 +1,42 @@ +{ + "name": "strip-indent", + "version": "3.0.0", + "description": "Strip leading whitespace from each line in a string", + "license": "MIT", + "repository": "sindresorhus/strip-indent", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "indent", + "indentation", + "normalize", + "remove", + "delete", + "whitespace", + "space", + "tab", + "string" + ], + "dependencies": { + "min-indent": "^1.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/strip-indent/readme.md b/node_modules/strip-indent/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..f14f6ba78912c8d2dfa8df678a6e03075c51a58c --- /dev/null +++ b/node_modules/strip-indent/readme.md @@ -0,0 +1,44 @@ +# strip-indent [![Build Status](https://travis-ci.org/sindresorhus/strip-indent.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-indent) + +> Strip leading whitespace from each line in a string + +The line with the least number of leading whitespace, ignoring empty lines, determines the number to remove. + +Useful for removing redundant indentation. + + +## Install + +``` +$ npm install strip-indent +``` + + +## Usage + +```js +const stripIndent = require('strip-indent'); + +const string = '\tunicorn\n\t\tcake'; +/* + unicorn + cake +*/ + +stripIndent(string); +/* +unicorn + cake +*/ +``` + + +## Related + +- [strip-indent-cli](https://github.com/sindresorhus/strip-indent-cli) - CLI for this module +- [indent-string](https://github.com/sindresorhus/indent-string) - Indent each line in a string + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/strip-json-comments/index.js b/node_modules/strip-json-comments/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4e6576e6d3c3883bdfaf1f67a05fd04a8d6927c5 --- /dev/null +++ b/node_modules/strip-json-comments/index.js @@ -0,0 +1,70 @@ +'use strict'; +var singleComment = 1; +var multiComment = 2; + +function stripWithoutWhitespace() { + return ''; +} + +function stripWithWhitespace(str, start, end) { + return str.slice(start, end).replace(/\S/g, ' '); +} + +module.exports = function (str, opts) { + opts = opts || {}; + + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var offset = 0; + var ret = ''; + var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && currentChar === '"') { + var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + ret += str.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { + i++; + insideComment = false; + ret += strip(str, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentChar === '\n') { + insideComment = false; + ret += strip(str, offset, i); + offset = i; + } else if (!insideComment && currentChar + nextChar === '/*') { + ret += str.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentChar + nextChar === '*/') { + i++; + insideComment = false; + ret += strip(str, offset, i + 1); + offset = i + 1; + continue; + } + } + + return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); +}; diff --git a/node_modules/strip-json-comments/license b/node_modules/strip-json-comments/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/node_modules/strip-json-comments/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/strip-json-comments/package.json b/node_modules/strip-json-comments/package.json new file mode 100644 index 0000000000000000000000000000000000000000..288ecc7745b0d181320327c71716d3d3a1e3669f --- /dev/null +++ b/node_modules/strip-json-comments/package.json @@ -0,0 +1,42 @@ +{ + "name": "strip-json-comments", + "version": "2.0.1", + "description": "Strip comments from JSON. Lets you use comments in your JSON files!", + "license": "MIT", + "repository": "sindresorhus/strip-json-comments", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "json", + "strip", + "remove", + "delete", + "trim", + "comments", + "multiline", + "parse", + "config", + "configuration", + "conf", + "settings", + "util", + "env", + "environment" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/strip-json-comments/readme.md b/node_modules/strip-json-comments/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..0ee58dfe3a2e9bd059402c6b89c1c145305cda47 --- /dev/null +++ b/node_modules/strip-json-comments/readme.md @@ -0,0 +1,64 @@ +# strip-json-comments [![Build Status](https://travis-ci.org/sindresorhus/strip-json-comments.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-json-comments) + +> Strip comments from JSON. Lets you use comments in your JSON files! + +This is now possible: + +```js +{ + // rainbows + "unicorn": /* ❤ */ "cake" +} +``` + +It will replace single-line comments `//` and multi-line comments `/**/` with whitespace. This allows JSON error positions to remain as close as possible to the original source. + +Also available as a [gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin. + + +## Install + +``` +$ npm install --save strip-json-comments +``` + + +## Usage + +```js +const json = '{/*rainbows*/"unicorn":"cake"}'; + +JSON.parse(stripJsonComments(json)); +//=> {unicorn: 'cake'} +``` + + +## API + +### stripJsonComments(input, [options]) + +#### input + +Type: `string` + +Accepts a string with JSON and returns a string without comments. + +#### options + +##### whitespace + +Type: `boolean` +Default: `true` + +Replace comments with whitespace instead of stripping them entirely. + + +## Related + +- [strip-json-comments-cli](https://github.com/sindresorhus/strip-json-comments-cli) - CLI for this module +- [strip-css-comments](https://github.com/sindresorhus/strip-css-comments) - Strip comments from CSS + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/strnum/CHANGELOG.md b/node_modules/strnum/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..15f39212b16e644cc895fbe86d60d10bb85982cb --- /dev/null +++ b/node_modules/strnum/CHANGELOG.md @@ -0,0 +1,51 @@ + +**2.4.0 / 2026-06-09** +- support unicode numerals using 'anynum' + +**2.3.0 / 2026-05-07** +- support octal and binary, test with @byspec/numbers +- test with @byspec/numbers + + +**2.2.3 / 2026-04-07** +- remove unnecessary files from npm package + +**2.2.2 / 2026-03-23** +- fix for space string + + +**2.2.1 / 2026-03-19** +- fix false positive for eNotation when no leading zeros + +**2.2.0 / 2026-02-28** +- support infinity + +**2.1.0 / 2025-05-01** +- fix e-notation + - to return string when invalid enotation is found. Eg `E24` + - to return valid number when only leading zero before e char is present + +**2.0.5 / 2025-02-27** +- changes done in 1.1.2 + +**1.1.2 / 2025-02-27** +- fix skiplike for 0 + +**1.1.1 / 2025-02-21** +- All recent fixes of version 2 + +**2.0.4 / 2025-02-20** +- remove console log + +**2.0.3 / 2025-02-20** +- fix for string which are falsly identified as e-notation + +**2.0.1 / 2025-02-20** +- fix: handle only zeros +- fix: return original string when NaN + +**2.0.0 / 2025-02-20** +- Migrating to ESM modules. No functional change + +**1.1.0 / 2025-02-20** +- fix (#9): support missing floating point and e notations \ No newline at end of file diff --git a/node_modules/strnum/LICENSE b/node_modules/strnum/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..64505544befa413eb28175a0db3532876a58412a --- /dev/null +++ b/node_modules/strnum/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Natural Intelligence + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/strnum/README.md b/node_modules/strnum/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d95da5ece7d660e4f2f834858c8ba52e0f4d4fa0 --- /dev/null +++ b/node_modules/strnum/README.md @@ -0,0 +1,113 @@ +# strnum +Parse string into Number based on configuration + +[![strnum downloads](https://img.shields.io/npm/dw/strnum.svg)](https://npm-compare.com/strnum) +[![strnum version](https://img.shields.io/npm/v/strnum.svg)](https://www.npmjs.com/package/strnum) +[![strnum license](https://img.shields.io/npm/l/strnum.svg)](https://github.com/NaturalIntelligence/strnum) + +## Users + + + + + +Many React Native projects and plugins + +## Usage + +```bash +npm install strnum +``` +```js +const toNumber = require("strnum"); + +toNumber(undefined) // undefined +toNumber(null)) //null +toNumber("")) // "" +toNumber("string"); //"string") +toNumber("12,12"); //"12,12") +toNumber("12 12"); //"12 12") +toNumber("12-12"); //"12-12") +toNumber("12.12.12"); //"12.12.12") +toNumber("0x2f"); //47) +toNumber("-0x2f"); //-47) +toNumber("0x2f", { hex : true}); //47) +toNumber("-0x2f", { hex : true}); //-47) +toNumber("0x2f", { hex : false}); //"0x2f") +toNumber("-0x2f", { hex : false}); //"-0x2f") +toNumber("06"); //6) +toNumber("06", { leadingZeros : true}); //6) +toNumber("06", { leadingZeros : false}); //"06") + +toNumber("006"); //6) +toNumber("006", { leadingZeros : true}); //6) +toNumber("006", { leadingZeros : false}); //"006") +toNumber("0.0"); //0) +toNumber("00.00"); //0) +toNumber("0.06"); //0.06) +toNumber("00.6"); //0.6) +toNumber(".006"); //0.006) +toNumber("6.0"); //6) +toNumber("06.0"); //6) + +toNumber("0.0", { leadingZeros : false}); //0) +toNumber("00.00", { leadingZeros : false}); //"00.00") +toNumber("0.06", { leadingZeros : false}); //0.06) +toNumber("00.6", { leadingZeros : false}); //"00.6") +toNumber(".006", { leadingZeros : false}); //0.006) +toNumber("6.0" , { leadingZeros : false}); //6) +toNumber("06.0" , { leadingZeros : false}); //"06.0") +toNumber("-06"); //-6) +toNumber("-06", { leadingZeros : true}); //-6) +toNumber("-06", { leadingZeros : false}); //"-06") + +toNumber("-0.0"); //-0) +toNumber("-00.00"); //-0) +toNumber("-0.06"); //-0.06) +toNumber("-00.6"); //-0.6) +toNumber("-.006"); //-0.006) +toNumber("-6.0"); //-6) +toNumber("-06.0"); //-6) + +toNumber("-0.0" , { leadingZeros : false}); //-0) +toNumber("-00.00", { leadingZeros : false}); //"-00.00") +toNumber("-0.06", { leadingZeros : false}); //-0.06) +toNumber("-00.6", { leadingZeros : false}); //"-00.6") +toNumber("-.006", {leadingZeros : false}); //-0.006) +toNumber("-6.0" , { leadingZeros : false}); //-6) +toNumber("-06.0" , { leadingZeros : false}); //"-06.0") +toNumber("420926189200190257681175017717") ; //4.209261892001902e+29) +toNumber("000000000000000000000000017717" , { leadingZeros : false}); //"000000000000000000000000017717") +toNumber("000000000000000000000000017717" , { leadingZeros : true}); //17717) +toNumber("01.0e2" , { leadingZeros : false}); //"01.0e2") +toNumber("-01.0e2" , { leadingZeros : false}); //"-01.0e2") +toNumber("01.0e2") ; //100) +toNumber("-01.0e2") ; //-100) +toNumber("1.0e2") ; //100) + +toNumber("-1.0e2") ; //-100) +toNumber("1.0e-2"); //0.01) + +toNumber("+1212121212"); // 1212121212 +toNumber("+1212121212", { skipLike: /\+[0-9]{10}/} )); //"+1212121212" + +toNumber("1e1000", { unicode: true, infinity: "original" }); //"1e1000" +toNumber("1000", { unicode: true }); //1000 +toNumber("1000", { unicode: false }); //"1000" +``` + +Supported Options +```js +hex: true, //when hexadecimal string should be parsed +leadingZeros: true, //when number with leading zeros like 08 should be parsed. 0.0 is not impacted +eNotation: true, //when number with eNotation or number parsed in eNotation should be considered +skipLike: /regex/ //when string should not be parsed when it matches the specified regular expression +infinity: "original", // "null", "infinity" (Infinity type), "string" ("Infinity" (the string literal)) +unicode: false, //when number with unicode numerals should be parsed +``` + + +# Try out our other work + +WishIn - You need it if negative thoughts take over all the time
+ diff --git a/node_modules/strnum/package.json b/node_modules/strnum/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9a0cf14be8af9b84c109f5d2ac2022329bd3f8a0 --- /dev/null +++ b/node_modules/strnum/package.json @@ -0,0 +1,35 @@ +{ + "name": "strnum", + "version": "2.4.0", + "description": "Parse String to Number based on configuration", + "type": "module", + "main": "strnum.js", + "scripts": { + "test": "jasmine tests/*_test.js" + }, + "keywords": [ + "string", + "number", + "parse", + "convert" + ], + "repository": { + "type": "git", + "url": "https://github.com/NaturalIntelligence/strnum" + }, + "author": "Amit Gupta (https://solothought.work/)", + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "devDependencies": { + "@byspec/numbers": "^0.1.1", + "jasmine": "^5.6.0" + }, + "dependencies": { + "anynum": "^1.0.0" + } +} \ No newline at end of file diff --git a/node_modules/strnum/strnum.js b/node_modules/strnum/strnum.js new file mode 100644 index 0000000000000000000000000000000000000000..402436fac9b797670818c244fd45251cb8f6d1b5 --- /dev/null +++ b/node_modules/strnum/strnum.js @@ -0,0 +1,171 @@ +const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; +const binRegex = /^0b[01]+$/; +const octRegex = /^0o[0-7]+$/; +const numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/; + +import anynum from "anynum"; + +const consider = { + hex: true, + binary: false, + octal: false, + leadingZeros: true, + decimalPoint: "\.", + eNotation: true, + //skipLike: /regex/, + infinity: "original", // "null", "infinity" (Infinity type), "string" ("Infinity" (the string literal)) + unicode: false, +}; + +export default function toNumber(str, options = {}) { + options = Object.assign({}, consider, options); + if (!str || typeof str !== "string") return str; + + let trimmedStr = str.trim(); + + if (trimmedStr.length === 0) return str; + else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str; + else if (trimmedStr === "0") return 0; + + if (options.unicode) { + trimmedStr = anynum(trimmedStr); + if (trimmedStr === "0") return 0; // re-check after normalization + } + if (options.hex && hexRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 16); + } else if (options.binary && binRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 2); + } else if (options.octal && octRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 8); + } else if (!isFinite(trimmedStr)) { //Infinity + return handleInfinity(str, Number(trimmedStr), options); + } else if (trimmedStr.includes('e') || trimmedStr.includes('E')) { //eNotation + return resolveEnotation(str, trimmedStr, options); + } else { + //separate negative sign, leading zeros, and rest number + const match = numRegex.exec(trimmedStr); + // +00.123 => [ , '+', '00', '.123', .. + if (match) { + const sign = match[1] || ""; + const leadingZeros = match[2]; + let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros + const decimalAdjacentToLeadingZeros = sign ? // 0., -00., 000. + str[leadingZeros.length + 1] === "." + : str[leadingZeros.length] === "."; + + //trim ending zeros for floating number + if (!options.leadingZeros //leading zeros are not allowed + && (leadingZeros.length > 1 + || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))) { + // 00, 00.3, +03.24, 03, 03.24 + return str; + } + else {//no leading zeros or leading zeros are allowed + const num = Number(trimmedStr); + const parsedStr = String(num); + + if (num === 0) return num; + if (parsedStr.search(/[eE]/) !== -1) { //given number is long and parsed to eNotation + if (options.eNotation) return num; + else return str; + } else if (trimmedStr.indexOf(".") !== -1) { //floating number + if (parsedStr === "0") return num; //0.0 + else if (parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000 + else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num; + else return str; + } + + let n = leadingZeros ? numTrimmedByZeros : trimmedStr; + if (leadingZeros) { + // -009 => -9 + return (n === parsedStr) || (sign + n === parsedStr) ? num : str + } else { + // +9 + return (n === parsedStr) || (n === sign + parsedStr) ? num : str + } + } + } else { //non-numeric string + return str; + } + } +} + +const eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/; +function resolveEnotation(str, trimmedStr, options) { + if (!options.eNotation) return str; + const notation = trimmedStr.match(eNotationRegx); + if (notation) { + let sign = notation[1] || ""; + const eChar = notation[3].indexOf("e") === -1 ? "E" : "e"; + const leadingZeros = notation[2]; + const eAdjacentToLeadingZeros = sign ? // 0E. + str[leadingZeros.length + 1] === eChar + : str[leadingZeros.length] === eChar; + + if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str; + else if (leadingZeros.length === 1 + && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) { + return Number(trimmedStr); + } else if (leadingZeros.length > 0) { + // Has leading zeros — only accept if leadingZeros option allows it + if (options.leadingZeros && !eAdjacentToLeadingZeros) { + trimmedStr = (notation[1] || "") + notation[3]; + return Number(trimmedStr); + } else return str; + } else { + // No leading zeros — always valid e-notation, parse it + return Number(trimmedStr); + } + } else { + return str; + } +} + +/** + * + * @param {string} numStr without leading zeros + * @returns + */ +function trimZeros(numStr) { + if (numStr && numStr.indexOf(".") !== -1) {//float + numStr = numStr.replace(/0+$/, ""); //remove ending zeros + if (numStr === ".") numStr = "0"; + else if (numStr[0] === ".") numStr = "0" + numStr; + else if (numStr[numStr.length - 1] === ".") numStr = numStr.substring(0, numStr.length - 1); + return numStr; + } + return numStr; +} + +function parse_int(numStr, base) { + const str = numStr.trim(); + if (base === 2 || base === 8) numStr = str.substring(2); + + if (parseInt) return parseInt(numStr, base); + else if (Number.parseInt) return Number.parseInt(numStr, base); + else if (window && window.parseInt) return window.parseInt(numStr, base); + else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported"); +} + +/** + * Handle infinite values based on user option + * @param {string} str - original input string + * @param {number} num - parsed number (Infinity or -Infinity) + * @param {object} options - user options + * @returns {string|number|null} based on infinity option + */ +function handleInfinity(str, num, options) { + const isPositive = num === Infinity; + + switch (options.infinity.toLowerCase()) { + case "null": + return null; + case "infinity": + return num; // Return Infinity or -Infinity + case "string": + return isPositive ? "Infinity" : "-Infinity"; + case "original": + default: + return str; // Return original string like "1e1000" + } +} \ No newline at end of file diff --git a/node_modules/strtok3/LICENSE.txt b/node_modules/strtok3/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e35e50810518d587fd5405c7821c766529d20e5 --- /dev/null +++ b/node_modules/strtok3/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright © 2026 Borewit + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/strtok3/README.md b/node_modules/strtok3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2772c264d33b70f251354b2b0eec7af4382a29a7 --- /dev/null +++ b/node_modules/strtok3/README.md @@ -0,0 +1,399 @@ +[![Node.js CI](https://github.com/Borewit/strtok3/actions/workflows/ci.yml/badge.svg)](https://github.com/Borewit/strtok3/actions/workflows/ci.yml) +[![CodeQL](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml/badge.svg?branch=master)](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml) +[![NPM version](https://badge.fury.io/js/strtok3.svg)](https://npmjs.org/package/strtok3) +[![npm downloads](http://img.shields.io/npm/dm/strtok3.svg)](https://npmcharts.com/compare/strtok3,token-types?start=1200&interval=30) +[![DeepScan grade](https://deepscan.io/api/teams/5165/projects/8526/branches/103329/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=8526&bid=103329) +[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/strtok3/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/strtok3?targetFile=package.json) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/59dd6795e61949fb97066ca52e6097ef)](https://www.codacy.com/app/Borewit/strtok3?utm_source=github.com&utm_medium=referral&utm_content=Borewit/strtok3&utm_campaign=Badge_Grade) +# strtok3 + +A promise based streaming [*tokenizer*](#tokenizer-object) for [Node.js](http://nodejs.org) and browsers. + +The `strtok3` module provides several methods for creating a [*tokenizer*](#tokenizer-object) from various input sources. +Designed for: +* Seamless support in streaming environments. +* Efficiently decode binary data, strings, and numbers. +* Reading [predefined](https://github.com/Borewit/token-types) or custom tokens. +* Offering [*tokenizers*](#tokenizer-object) for reading from [files](#method-strtok3fromfile), [streams](#fromstream-function) or [Uint8Arrays](#frombuffer-function). + +### Features +`strtok3` can read from: +* Files, using a file path as input. +* Node.js [streams](https://nodejs.org/api/stream.html). +* [Buffer](https://nodejs.org/api/buffer.html) or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array). +* HTTP chunked transfer provided by [@tokenizer/http](https://github.com/Borewit/tokenizer-http). +* [Amazon S3](https://aws.amazon.com/s3) chunks with [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3). + +## Installation + +```sh +npm install strtok3 +``` + +### Compatibility + +Starting with version 7, the module has migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). +The distributed JavaScript codebase is compliant with the [ECMAScript 2020 (11th Edition)](https://en.wikipedia.org/wiki/ECMAScript_version_history#11th_Edition_%E2%80%93_ECMAScript_2020) standard. + +Requires a modern browser, Node.js (V8) ≥ 18 engine or Bun (JavaScriptCore) ≥ 1.2. + +For TypeScript CommonJs backward compatibility, you can use [load-esm](https://github.com/Borewit/load-esm). + +> [!NOTE] +> This module requires a [Node.js ≥ 16](https://nodejs.org/en/about/previous-releases) engine. +> It can also be used in a browser environment when bundled with a module bundler. + +## Support the Project +If you find this project useful and would like to support its development, consider sponsoring or contributing: + +- [Become a sponsor to Borewit](https://github.com/sponsors/Borewit) + +- Buy me a coffee: + + Buy me A coffee + +## API Documentation + +### strtok3 methods + +Use one of the methods to instantiate an [*abstract tokenizer*](#tokenizer-object): +- [fromBlob](#fromblob-function) +- [fromBuffer](#frombuffer-function) +- [fromFile](#fromfile-function)* +- [fromStream](#fromstream-function)* +- [fromWebStream](#fromwebstream-function) + +> [!NOTE] +> `fromFile` and `fromStream` only available when importing this module with Node.js + +All methods return a [`Tokenizer`](#tokenizer-object), either directly or via a promise. + +#### `fromBlob()` function + +Create a tokenizer from a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + +```ts +function fromBlob(blob: Blob, options?: ITokenizerOptions): BlobTokenizer +``` + +| Parameter | Optional | Type | Description | +|-----------|-----------|---------------------------------------------------|----------------------------------------------------------------------------------------| +| blob | no | [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) | [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [File](https://developer.mozilla.org/en-US/docs/Web/API/File) to read from | +| options | yes | [ITokenizerOptions](#ITokenizerOptions) | Tokenizer options | + +Returns a [*tokenizer*](#tokenizer-object). + +```js +import { fromBlob } from 'strtok3'; +import { openAsBlob } from 'node:fs'; +import * as Token from 'token-types'; + +async function parse() { + const blob = await openAsBlob('somefile.bin'); + + const tokenizer = fromBlob(blob); + + const myUint8Number = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myUint8Number}`); +} + +parse(); + +``` + +#### `fromBuffer()` function + +Create a tokenizer from memory ([Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) or Node.js [Buffer](https://nodejs.org/api/buffer.html)). + +```ts +function fromBuffer(uint8Array: Uint8Array, options?: ITokenizerOptions): BufferTokenizer +``` + +| Parameter | Optional | Type | Description | +|------------|----------|--------------------------------------------------|-----------------------------------| +| uint8Array | no | [Uint8Array](https://nodejs.org/api/buffer.html) | Buffer or Uint8Array to read from | +| options | yes | [ITokenizerOptions](#ITokenizerOptions) | Tokenizer options | + +Returns a [*tokenizer*](#tokenizer-object). + +```js +import { fromBuffer } from 'strtok3'; +import * as Token from 'token-types'; + +const tokenizer = fromBuffer(buffer); + +async function parse() { + const myUint8Number = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myUint8Number}`); +} + +parse(); +``` + +#### `fromFile` function + +Creates a [*tokenizer*](#tokenizer-object) from a local file. + +```ts +function fromFile(sourceFilePath: string): Promise +``` + +| Parameter | Type | Description | +|----------------|----------|----------------------------| +| sourceFilePath | `string` | Path to file to read from | + +> [!NOTE] +> - Only available for Node.js engines +> - `fromFile` automatically embeds [file-information](#file-information) + +A Promise resolving to a [*tokenizer*](#tokenizer-object) which can be used to parse a file. + +```js +import { fromFile } from 'strtok3'; +import * as Token from 'token-types'; + +async function parse() { + const tokenizer = await fromFile('somefile.bin'); + try { + const myNumber = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myNumber}`); + } finally { + tokenizer.close(); // Close the file + } +} + +parse(); + + +``` + +#### `fromWebStream()` function + +Create a tokenizer from a [WHATWG ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream). + +```ts +function fromWebStream(webStream: AnyWebByteStream, options?: ITokenizerOptions): ReadStreamTokenizer +``` + +| Parameter | Optional | Type | Description | +|----------------|----------|--------------------------------------------------------------------------|------------------------------------| +| webStream | no | [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) | WHATWG ReadableStream to read from | +| options | yes | [ITokenizerOptions](#ITokenizerOptions) | Tokenizer options | + +Returns a [*tokenizer*](#tokenizer-object). + +```js +import { fromWebStream } from 'strtok3'; +import * as Token from 'token-types'; + +async function parse() { + const tokenizer = fromWebStream(readableStream); + try { + const myUint8Number = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myUint8Number}`); + } finally { + await tokenizer.close(); + } +} + +parse(); +``` + +### `Tokenizer` object +The *tokenizer* is an abstraction of a [stream](https://nodejs.org/api/stream.html), file or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), allowing _reading_ or _peeking_ from the stream. +It can also be translated in chunked reads, as done in [@tokenizer/http](https://github.com/Borewit/tokenizer-http); + +#### Key Features: + +- Supports seeking within the stream using `tokenizer.ignore()`. +- Offers `peek` methods to preview data without advancing the read pointer. +- Maintains the read position via tokenizer.position. + +#### Tokenizer functions + +_Read_ methods advance the stream pointer, while _peek_ methods do not. + +There are two kind of functions: +1. *read* methods: used to read a *token* of [Buffer](https://nodejs.org/api/buffer.html) from the [*tokenizer*](#tokenizer-object). The position of the *tokenizer-stream* will advance with the size of the token. +2. *peek* methods: same as the read, but it will *not* advance the pointer. It allows to read (peek) ahead. + +#### `readBuffer` function + +Read data from the _tokenizer_ into provided "buffer" (`Uint8Array`). +`readBuffer(buffer, options?)` + +```ts +readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; +``` + +| Parameter | Type | Description | +|------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| buffer | [Buffer](https://nodejs.org/api/buffer.html) | Uint8Array | Target buffer to write the data read to | +| options | [IReadChunkOptions](#ireadchunkoptions-interface) | An integer specifying the number of bytes to read | + +Return promise with number of bytes read. +The number of bytes read may be less than requested if the `mayBeLess` flag is set. + +#### `peekBuffer` function + +Peek (read ahead), from [*tokenizer*](#tokenizer-object), into the buffer without advancing the stream pointer. + +```ts +peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; +``` + +| Parameter | Type | Description | +|------------|-----------------------------------------|-----------------------------------------------------| +| buffer | Buffer | Uint8Array | Target buffer to write the data read (peeked) to. | +| options | [IReadChunkOptions](#ireadchunkoptions-interface) | An integer specifying the number of bytes to read. | | + +Return value `Promise` Promise with number of bytes read. The number of bytes read may be less if the `mayBeLess` flag was set. + +#### `readToken` function + +Read a *token* from the tokenizer-stream. + +```ts +readToken(token: IGetToken, position: number = this.position): Promise +``` + +| Parameter | Type | Description | +|------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- | +| token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. | +| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. | + +Return value `Promise`. Promise with number of bytes read. The number of bytes read maybe if less, `mayBeLess` flag was set. + +#### `peek` function + +Peek a *token* from the [*tokenizer*](#tokenizer-object). + +```ts +peekToken(token: IGetToken, position: number = this.position): Promise +``` + +| Parameter | Type | Description | +|------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------| +| token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. | +| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. | + +Return a promise with the token value peeked from the [*tokenizer*](#tokenizer-object). + +#### `readNumber` function + +Read a numeric [*token*](#token) from the [*tokenizer*](#tokenizer-object). + +```ts +readNumber(token: IToken): Promise +``` + +| Parameter | Type | Description | +|------------|---------------------------------|----------------------------------------------------| +| token | [IGetToken](#IGetToken) | Numeric token to read from the tokenizer-stream. | + +A promise resolving to a numeric value read and decoded from the *tokenizer-stream*. + +#### `ignore` function + +Advance the offset pointer with the token number of bytes provided. + +```ts +ignore(length: number): Promise +``` + +| Parameter | Type | Description | +|------------|--------|------------------------------------------------------------------| +| length | number | Number of bytes to ignore. Will advance the `tokenizer.position` | + +A promise resolving to the number of bytes ignored from the *tokenizer-stream*. + +#### `close` function +Clean up resources, such as closing a file pointer if applicable. + +#### `Tokenizer` attributes + +- `fileInfo` + + Optional attribute describing the file information, see [IFileInfo](#IFileInfo) + +- `position` + + Pointer to the current position in the [*tokenizer*](#tokenizer-object) stream. + If a *position* is provided to a _read_ or _peek_ method, is should be, at least, equal or greater than this value. + +### `IReadChunkOptions` interface + +Each attribute is optional: + +| Attribute | Type | Description | +|-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| length | number | Requested number of bytes to read. | +| position | number | Position where to peek from the file. If position is null, data will be read from the [current file position](#attribute-tokenizerposition). Position may not be less then [tokenizer.position](#attribute-tokenizerposition) | +| mayBeLess | boolean | If and only if set, will not throw an EOF error if less than the requested `mayBeLess` could be read. | + +Example usage: +```js + tokenizer.peekBuffer(buffer, {mayBeLess: true}); +``` + +### `IFileInfo` interface + +Provides optional metadata about the file being tokenized. + +| Attribute | Type | Description | +|-----------|---------|---------------------------------------------------------------------------------------------------| +| size | number | File size in bytes | +| mimeType | string | [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of file. | +| path | string | File path | +| url | string | File URL | + +### `Token` object + +The *token* is basically a description of what to read from the [*tokenizer-stream*](#tokenizer-object). +A basic set of *token types* can be found here: [*token-types*](https://github.com/Borewit/token-types). + +A token is something which implements the following interface: +```ts +export interface IGetToken { + + /** + * Length in bytes of encoded value + */ + len: number; + + /** + * Decode value from buffer at offset + * @param buf Buffer to read the decoded value from + * @param off Decode offset + */ + get(buf: Uint8Array, off: number): T; +} +``` +The *tokenizer* reads `token.len` bytes from the *tokenizer-stream* into a Buffer. +The `token.get` will be called with the Buffer. `token.get` is responsible for conversion from the buffer to the desired output type. + +### Working with Web-API readable stream +To convert a [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) into a [Node.js readable stream]((https://nodejs.org/api/stream.html#stream_readable_streams)), you can use [readable-web-to-node-stream](https://github.com/Borewit/readable-web-to-node-stream) to convert one in another. + +```js +import { fromWebStream } from 'strtok3'; +import { ReadableWebToNodeStream } from 'readable-web-to-node-stream'; + +(async () => { + + const response = await fetch(url); + const readableWebStream = response.body; // Web-API readable stream + const webStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream + + const tokenizer = fromWebStream(webStream); // And we now have tokenizer in a web environment +})(); +``` + +## Dependencies + +Dependencies: +- [@tokenizer/token](https://github.com/Borewit/tokenizer-token): Provides token definitions and utilities used by `strtok3` for interpreting binary data. + +## Licence + +This project is licensed under the [MIT License](LICENSE.txt). Feel free to use, modify, and distribute as needed. diff --git a/node_modules/strtok3/lib/AbstractTokenizer.d.ts b/node_modules/strtok3/lib/AbstractTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01b540eb84e7dca12b2c630484812e71c38e44ac --- /dev/null +++ b/node_modules/strtok3/lib/AbstractTokenizer.d.ts @@ -0,0 +1,76 @@ +import type { ITokenizer, IFileInfo, IReadChunkOptions, ITokenizerOptions } from './types.js'; +import type { IGetToken, IToken } from '@tokenizer/token'; +interface INormalizedReadChunkOptions extends IReadChunkOptions { + length: number; + position: number; + mayBeLess?: boolean; +} +/** + * Core tokenizer + */ +export declare abstract class AbstractTokenizer implements ITokenizer { + private onClose?; + private numBuffer; + abstract fileInfo: IFileInfo; + /** + * Tokenizer-stream position + */ + position: number; + /** + * Constructor + * @param options Tokenizer options + * @protected + */ + protected constructor(options?: ITokenizerOptions); + abstract supportsRandomAccess(): boolean; + /** + * Read buffer from tokenizer + * @param buffer - Target buffer to fill with data read from the tokenizer-stream + * @param options - Additional read options + * @returns Promise with number of bytes read + */ + abstract readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Target buffer to fill with data peeked from the tokenizer-stream + * @param options - Peek behaviour options + * @returns Promise with number of bytes read + */ + abstract peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Read a token from the tokenizer-stream + * @param token - The token to read + * @param position - If provided, the desired position in the tokenizer-stream + * @returns Promise with token data + */ + readToken(token: IGetToken, position?: number): Promise; + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @returns Promise with token data + */ + peekToken(token: IGetToken, position?: number): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + readNumber(token: IToken): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + peekNumber(token: IToken): Promise; + /** + * Ignore number of bytes, advances the pointer in under tokenizer-stream. + * @param length - Number of bytes to ignore. Must be ≥ 0. + * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available + */ + ignore(length: number): Promise; + close(): Promise; + protected normalizeOptions(uint8Array: Uint8Array, options?: IReadChunkOptions): INormalizedReadChunkOptions; + abort(): Promise; +} +export {}; diff --git a/node_modules/strtok3/lib/AbstractTokenizer.js b/node_modules/strtok3/lib/AbstractTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..eaa8a01c036c2c2fb81897c242ecc1bcbedbea75 --- /dev/null +++ b/node_modules/strtok3/lib/AbstractTokenizer.js @@ -0,0 +1,111 @@ +import { EndOfStreamError } from './stream/index.js'; +/** + * Core tokenizer + */ +export class AbstractTokenizer { + /** + * Constructor + * @param options Tokenizer options + * @protected + */ + constructor(options) { + this.numBuffer = new Uint8Array(8); + /** + * Tokenizer-stream position + */ + this.position = 0; + this.onClose = options?.onClose; + if (options?.abortSignal) { + options.abortSignal.addEventListener('abort', () => { + this.abort(); + }); + } + } + /** + * Read a token from the tokenizer-stream + * @param token - The token to read + * @param position - If provided, the desired position in the tokenizer-stream + * @returns Promise with token data + */ + async readToken(token, position = this.position) { + const uint8Array = new Uint8Array(token.len); + const len = await this.readBuffer(uint8Array, { position }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @returns Promise with token data + */ + async peekToken(token, position = this.position) { + const uint8Array = new Uint8Array(token.len); + const len = await this.peekBuffer(uint8Array, { position }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async readNumber(token) { + const len = await this.readBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async peekNumber(token) { + const len = await this.peekBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Ignore number of bytes, advances the pointer in under tokenizer-stream. + * @param length - Number of bytes to ignore. Must be ≥ 0. + * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available + */ + async ignore(length) { + if (length < 0) { + throw new RangeError('ignore length must be ≥ 0 bytes'); + } + if (this.fileInfo.size !== undefined) { + const bytesLeft = this.fileInfo.size - this.position; + if (length > bytesLeft) { + this.position += bytesLeft; + return bytesLeft; + } + } + this.position += length; + return length; + } + async close() { + await this.abort(); + await this.onClose?.(); + } + normalizeOptions(uint8Array, options) { + if (!this.supportsRandomAccess() && options && options.position !== undefined && options.position < this.position) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + return { + ...{ + mayBeLess: false, + offset: 0, + length: uint8Array.length, + position: this.position + }, ...options + }; + } + abort() { + return Promise.resolve(); // Ignore abort signal + } +} diff --git a/node_modules/strtok3/lib/BlobTokenizer.d.ts b/node_modules/strtok3/lib/BlobTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e0bc9852fb6027a32f13ae942bf98113c5a0037 --- /dev/null +++ b/node_modules/strtok3/lib/BlobTokenizer.d.ts @@ -0,0 +1,29 @@ +import type { ITokenizerOptions, IReadChunkOptions, IRandomAccessFileInfo, IRandomAccessTokenizer } from './types.js'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export declare class BlobTokenizer extends AbstractTokenizer implements IRandomAccessTokenizer { + private blob; + fileInfo: IRandomAccessFileInfo; + /** + * Construct BufferTokenizer + * @param blob - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(blob: Blob, options?: ITokenizerOptions); + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer + * @param options - Read behaviour options + * @returns {Promise} + */ + peekBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; + supportsRandomAccess(): boolean; + setPosition(position: number): void; +} diff --git a/node_modules/strtok3/lib/BlobTokenizer.js b/node_modules/strtok3/lib/BlobTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..f68dfa243f1b30a77a84cabef4255bf0f3a559fe --- /dev/null +++ b/node_modules/strtok3/lib/BlobTokenizer.js @@ -0,0 +1,53 @@ +import { EndOfStreamError } from './stream/index.js'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export class BlobTokenizer extends AbstractTokenizer { + /** + * Construct BufferTokenizer + * @param blob - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(blob, options) { + super(options); + this.blob = blob; + this.fileInfo = { ...options?.fileInfo ?? {}, ...{ size: blob.size, mimeType: blob.type } }; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + async readBuffer(uint8Array, options) { + if (options?.position) { + this.position = options.position; + } + const bytesRead = await this.peekBuffer(uint8Array, options); + this.position += bytesRead; + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer + * @param options - Read behaviour options + * @returns {Promise} + */ + async peekBuffer(buffer, options) { + const normOptions = this.normalizeOptions(buffer, options); + const bytes2read = Math.min(this.blob.size - normOptions.position, normOptions.length); + if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) { + throw new EndOfStreamError(); + } + const arrayBuffer = await this.blob.slice(normOptions.position, normOptions.position + bytes2read).arrayBuffer(); + buffer.set(new Uint8Array(arrayBuffer)); + return bytes2read; + } + close() { + return super.close(); + } + supportsRandomAccess() { + return true; + } + setPosition(position) { + this.position = position; + } +} diff --git a/node_modules/strtok3/lib/BufferTokenizer.d.ts b/node_modules/strtok3/lib/BufferTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e5c4071e3f5806a470232d9d1dcd0848f81e8ba --- /dev/null +++ b/node_modules/strtok3/lib/BufferTokenizer.d.ts @@ -0,0 +1,29 @@ +import type { ITokenizerOptions, IReadChunkOptions, IRandomAccessFileInfo, IRandomAccessTokenizer } from './types.js'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export declare class BufferTokenizer extends AbstractTokenizer implements IRandomAccessTokenizer { + private uint8Array; + fileInfo: IRandomAccessFileInfo; + /** + * Construct BufferTokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(uint8Array: Uint8Array, options?: ITokenizerOptions); + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array + * @param options - Read behaviour options + * @returns {Promise} + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; + supportsRandomAccess(): boolean; + setPosition(position: number): void; +} diff --git a/node_modules/strtok3/lib/BufferTokenizer.js b/node_modules/strtok3/lib/BufferTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..eec03746e02fd7af5e1ba7789be59dda25f46e68 --- /dev/null +++ b/node_modules/strtok3/lib/BufferTokenizer.js @@ -0,0 +1,52 @@ +import { EndOfStreamError } from './stream/index.js'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export class BufferTokenizer extends AbstractTokenizer { + /** + * Construct BufferTokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(uint8Array, options) { + super(options); + this.uint8Array = uint8Array; + this.fileInfo = { ...options?.fileInfo ?? {}, ...{ size: uint8Array.length } }; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + async readBuffer(uint8Array, options) { + if (options?.position) { + this.position = options.position; + } + const bytesRead = await this.peekBuffer(uint8Array, options); + this.position += bytesRead; + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array + * @param options - Read behaviour options + * @returns {Promise} + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length); + if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) { + throw new EndOfStreamError(); + } + uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read)); + return bytes2read; + } + close() { + return super.close(); + } + supportsRandomAccess() { + return true; + } + setPosition(position) { + this.position = position; + } +} diff --git a/node_modules/strtok3/lib/FileTokenizer.d.ts b/node_modules/strtok3/lib/FileTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98229ffd5674d0eb23ec3082879d357dbfaf0c7d --- /dev/null +++ b/node_modules/strtok3/lib/FileTokenizer.d.ts @@ -0,0 +1,37 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import type { IRandomAccessTokenizer, IRandomAccessFileInfo, IReadChunkOptions, ITokenizerOptions } from './types.js'; +import { type FileHandle } from 'node:fs/promises'; +interface IFileTokenizerOptions extends ITokenizerOptions { + /** + * Pass additional file information to the tokenizer + */ + fileInfo: IRandomAccessFileInfo; +} +export declare class FileTokenizer extends AbstractTokenizer implements IRandomAccessTokenizer { + private fileHandle; + fileInfo: IRandomAccessFileInfo; + /** + * Create tokenizer from provided file path + * @param sourceFilePath File path + */ + static fromFile(sourceFilePath: string): Promise; + protected constructor(fileHandle: FileHandle, options: IFileTokenizerOptions); + /** + * Read buffer from file + * @param uint8Array - Uint8Array to write result to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek buffer from file + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; + setPosition(position: number): void; + supportsRandomAccess(): boolean; +} +export {}; diff --git a/node_modules/strtok3/lib/FileTokenizer.js b/node_modules/strtok3/lib/FileTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..1d5e7655da541ec0662665f926b2c737dfdbb4fa --- /dev/null +++ b/node_modules/strtok3/lib/FileTokenizer.js @@ -0,0 +1,61 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { EndOfStreamError } from './stream/index.js'; +import { open as fsOpen } from 'node:fs/promises'; +export class FileTokenizer extends AbstractTokenizer { + /** + * Create tokenizer from provided file path + * @param sourceFilePath File path + */ + static async fromFile(sourceFilePath) { + const fileHandle = await fsOpen(sourceFilePath, 'r'); + const stat = await fileHandle.stat(); + return new FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat.size } }); + } + constructor(fileHandle, options) { + super(options); + this.fileHandle = fileHandle; + this.fileInfo = options.fileInfo; + } + /** + * Read buffer from file + * @param uint8Array - Uint8Array to write result to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + this.position = normOptions.position; + if (normOptions.length === 0) + return 0; + const res = await this.fileHandle.read(uint8Array, 0, normOptions.length, normOptions.position); + this.position += res.bytesRead; + if (res.bytesRead < normOptions.length && (!options || !options.mayBeLess)) { + throw new EndOfStreamError(); + } + return res.bytesRead; + } + /** + * Peek buffer from file + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const res = await this.fileHandle.read(uint8Array, 0, normOptions.length, normOptions.position); + if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + return res.bytesRead; + } + async close() { + await this.fileHandle.close(); + return super.close(); + } + setPosition(position) { + this.position = position; + } + supportsRandomAccess() { + return true; + } +} diff --git a/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts b/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e78a83e1fe361b3a7864e007416a61ef35dc51fd --- /dev/null +++ b/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts @@ -0,0 +1,34 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { type IStreamReader } from './stream/index.js'; +import type { IFileInfo, IReadChunkOptions, ITokenizerOptions } from './types.js'; +export declare class ReadStreamTokenizer extends AbstractTokenizer { + private streamReader; + fileInfo: IFileInfo; + /** + * Constructor + * @param streamReader stream-reader to read from + * @param options Tokenizer options + */ + constructor(streamReader: IStreamReader, options?: ITokenizerOptions); + /** + * Read buffer from tokenizer + * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise with number of bytes peeked + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * @param length Number of bytes to ignore. Must be ≥ 0. + */ + ignore(length: number): Promise; + abort(): Promise; + close(): Promise; + supportsRandomAccess(): boolean; +} diff --git a/node_modules/strtok3/lib/ReadStreamTokenizer.js b/node_modules/strtok3/lib/ReadStreamTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..7b0cf4a929136fc80fe0d8900086333859ce73ae --- /dev/null +++ b/node_modules/strtok3/lib/ReadStreamTokenizer.js @@ -0,0 +1,107 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { EndOfStreamError } from './stream/index.js'; +const maxBufferSize = 256000; +export class ReadStreamTokenizer extends AbstractTokenizer { + /** + * Constructor + * @param streamReader stream-reader to read from + * @param options Tokenizer options + */ + constructor(streamReader, options) { + super(options); + this.streamReader = streamReader; + this.fileInfo = options?.fileInfo ?? {}; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + await this.ignore(skipBytes); + return this.readBuffer(uint8Array, options); + } + if (skipBytes < 0) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + if (normOptions.length === 0) { + return 0; + } + const bytesRead = await this.streamReader.read(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess); + this.position += bytesRead; + if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise with number of bytes peeked + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + let bytesRead = 0; + if (normOptions.position) { + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + const skipBuffer = new Uint8Array(normOptions.length + skipBytes); + bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess }); + uint8Array.set(skipBuffer.subarray(skipBytes)); + return bytesRead - skipBytes; + } + if (skipBytes < 0) { + throw new Error('Cannot peek from a negative offset in a stream'); + } + } + if (normOptions.length > 0) { + try { + bytesRead = await this.streamReader.peek(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess); + } + catch (err) { + if (options?.mayBeLess && err instanceof EndOfStreamError) { + return 0; + } + throw err; + } + if ((!normOptions.mayBeLess) && bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + } + return bytesRead; + } + /** + * @param length Number of bytes to ignore. Must be ≥ 0. + */ + async ignore(length) { + if (length < 0) { + throw new RangeError('ignore length must be ≥ 0 bytes'); + } + const bufSize = Math.min(maxBufferSize, length); + const buf = new Uint8Array(bufSize); + let totBytesRead = 0; + while (totBytesRead < length) { + const remaining = length - totBytesRead; + const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) }); + if (bytesRead < 0) { + return bytesRead; + } + totBytesRead += bytesRead; + } + return totBytesRead; + } + abort() { + return this.streamReader.abort(); + } + async close() { + return this.streamReader.close(); + } + supportsRandomAccess() { + return false; + } +} diff --git a/node_modules/strtok3/lib/core.d.ts b/node_modules/strtok3/lib/core.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fb2f7d5f88302bedff48584c15e390cbeaa2b5f --- /dev/null +++ b/node_modules/strtok3/lib/core.d.ts @@ -0,0 +1,40 @@ +import type { Readable } from 'node:stream'; +import { type AnyWebByteStream } from './stream/index.js'; +import { ReadStreamTokenizer } from './ReadStreamTokenizer.js'; +import { BufferTokenizer } from './BufferTokenizer.js'; +import type { ITokenizerOptions } from './types.js'; +import { BlobTokenizer } from './BlobTokenizer.js'; +export { EndOfStreamError, AbortError, type AnyWebByteStream } from './stream/index.js'; +export type { ITokenizer, IRandomAccessTokenizer, IFileInfo, IRandomAccessFileInfo, ITokenizerOptions, IReadChunkOptions, OnClose } from './types.js'; +export type { IToken, IGetToken } from '@tokenizer/token'; +export { AbstractTokenizer } from './AbstractTokenizer.js'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property/ + * @param stream - Read from Node.js Stream.Readable + * @param options - Tokenizer options + * @returns ReadStreamTokenizer + */ +export declare function fromStream(stream: Readable, options?: ITokenizerOptions): ReadStreamTokenizer; +/** + * Construct ReadStreamTokenizer from given ReadableStream (WebStream API). + * Will set fileSize, if provided given Stream has set the .path property/ + * @param webStream - Read from Node.js Stream.Readable (must be a byte stream) + * @param options - Tokenizer options + * @returns ReadStreamTokenizer + */ +export declare function fromWebStream(webStream: AnyWebByteStream, options?: ITokenizerOptions): ReadStreamTokenizer; +/** + * Construct ReadStreamTokenizer from given Buffer. + * @param uint8Array - Uint8Array to tokenize + * @param options - Tokenizer options + * @returns BufferTokenizer + */ +export declare function fromBuffer(uint8Array: Uint8Array, options?: ITokenizerOptions): BufferTokenizer; +/** + * Construct ReadStreamTokenizer from given Blob. + * @param blob - Uint8Array to tokenize + * @param options - Tokenizer options + * @returns BufferTokenizer + */ +export declare function fromBlob(blob: Blob, options?: ITokenizerOptions): BlobTokenizer; diff --git a/node_modules/strtok3/lib/core.js b/node_modules/strtok3/lib/core.js new file mode 100644 index 0000000000000000000000000000000000000000..22f41cf82ecfd45d5b438203ef8797e82c88306c --- /dev/null +++ b/node_modules/strtok3/lib/core.js @@ -0,0 +1,62 @@ +import { StreamReader, makeWebStreamReader } from './stream/index.js'; +import { ReadStreamTokenizer } from './ReadStreamTokenizer.js'; +import { BufferTokenizer } from './BufferTokenizer.js'; +import { BlobTokenizer } from './BlobTokenizer.js'; +export { EndOfStreamError, AbortError } from './stream/index.js'; +export { AbstractTokenizer } from './AbstractTokenizer.js'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property/ + * @param stream - Read from Node.js Stream.Readable + * @param options - Tokenizer options + * @returns ReadStreamTokenizer + */ +export function fromStream(stream, options) { + const streamReader = new StreamReader(stream); + const _options = options ?? {}; + const chainedClose = _options.onClose; + _options.onClose = async () => { + await streamReader.close(); + if (chainedClose) { + return chainedClose(); + } + }; + return new ReadStreamTokenizer(streamReader, _options); +} +/** + * Construct ReadStreamTokenizer from given ReadableStream (WebStream API). + * Will set fileSize, if provided given Stream has set the .path property/ + * @param webStream - Read from Node.js Stream.Readable (must be a byte stream) + * @param options - Tokenizer options + * @returns ReadStreamTokenizer + */ +export function fromWebStream(webStream, options) { + const webStreamReader = makeWebStreamReader(webStream); + const _options = options ?? {}; + const chainedClose = _options.onClose; + _options.onClose = async () => { + await webStreamReader.close(); + if (chainedClose) { + return chainedClose(); + } + }; + return new ReadStreamTokenizer(webStreamReader, _options); +} +/** + * Construct ReadStreamTokenizer from given Buffer. + * @param uint8Array - Uint8Array to tokenize + * @param options - Tokenizer options + * @returns BufferTokenizer + */ +export function fromBuffer(uint8Array, options) { + return new BufferTokenizer(uint8Array, options); +} +/** + * Construct ReadStreamTokenizer from given Blob. + * @param blob - Uint8Array to tokenize + * @param options - Tokenizer options + * @returns BufferTokenizer + */ +export function fromBlob(blob, options) { + return new BlobTokenizer(blob, options); +} diff --git a/node_modules/strtok3/lib/index.d.ts b/node_modules/strtok3/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6b34d82f906d5470041715619857d520da3d109 --- /dev/null +++ b/node_modules/strtok3/lib/index.d.ts @@ -0,0 +1,16 @@ +import type { Readable } from 'node:stream'; +import type { ReadStreamTokenizer } from './ReadStreamTokenizer.js'; +import { type ITokenizerOptions } from './core.js'; +import { FileTokenizer } from "./FileTokenizer.js"; +export { FileTokenizer } from './FileTokenizer.js'; +export * from './core.js'; +export type { IToken, IGetToken } from '@tokenizer/token'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property. + * @param stream - Node.js Stream.Readable + * @param options - Pass additional file information to the tokenizer + * @returns Tokenizer + */ +export declare function fromStream(stream: Readable, options?: ITokenizerOptions): Promise; +export declare const fromFile: typeof FileTokenizer.fromFile; diff --git a/node_modules/strtok3/lib/index.js b/node_modules/strtok3/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..aef7d6d538ee99456de2cccab9834d4b2b74834a --- /dev/null +++ b/node_modules/strtok3/lib/index.js @@ -0,0 +1,22 @@ +import { stat as fsStat } from 'node:fs/promises'; +import { fromStream as coreFromStream } from './core.js'; +import { FileTokenizer } from "./FileTokenizer.js"; +export { FileTokenizer } from './FileTokenizer.js'; +export * from './core.js'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property. + * @param stream - Node.js Stream.Readable + * @param options - Pass additional file information to the tokenizer + * @returns Tokenizer + */ +export async function fromStream(stream, options) { + const rst = coreFromStream(stream, options); + if (stream.path) { + const stat = await fsStat(stream.path); + rst.fileInfo.path = stream.path; + rst.fileInfo.size = stat.size; + } + return rst; +} +export const fromFile = FileTokenizer.fromFile; diff --git a/node_modules/strtok3/lib/stream/AbstractStreamReader.d.ts b/node_modules/strtok3/lib/stream/AbstractStreamReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..55f69a2e7b90c6561b6a22932bf038d8a979d3fd --- /dev/null +++ b/node_modules/strtok3/lib/stream/AbstractStreamReader.d.ts @@ -0,0 +1,54 @@ +export interface IStreamReader { + /** + * Peak ahead (peek) from stream. Subsequent read or peeks will return the same data. + * @param uint8Array - Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - Allow the read to complete, without the buffer being fully filled (length may be smaller) + * @returns Number of bytes peeked. If `maybeLess` is set, this shall be the `uint8Array.length`. + */ + peek(uint8Array: Uint8Array, mayBeLess?: boolean): Promise; + /** + * Read from stream the stream. + * @param uint8Array - Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - Allow the read to complete, without the buffer being fully filled (length may be smaller) + * @returns Number of actually bytes read. If `maybeLess` is set, this shall be the `uint8Array.length`. + */ + read(uint8Array: Uint8Array, mayBeLess?: boolean): Promise; + close(): Promise; + /** + * Abort any active asynchronous operation are active, abort those before they may have completed. + */ + abort(): Promise; +} +export declare abstract class AbstractStreamReader implements IStreamReader { + protected endOfStream: boolean; + protected interrupted: boolean; + /** + * Store peeked data + * @type {Array} + */ + protected peekQueue: Uint8Array[]; + peek(uint8Array: Uint8Array, mayBeLess?: boolean): Promise; + read(buffer: Uint8Array, mayBeLess?: boolean): Promise; + /** + * Read chunk from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @returns Number of bytes read + */ + protected readFromPeekBuffer(buffer: Uint8Array): number; + readRemainderFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + protected abstract readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + /** + * abort synchronous operations + */ + abstract close(): Promise; + /** + * Abort any active asynchronous operation are active, abort those before they may have completed. + */ + abstract abort(): Promise; +} diff --git a/node_modules/strtok3/lib/stream/AbstractStreamReader.js b/node_modules/strtok3/lib/stream/AbstractStreamReader.js new file mode 100644 index 0000000000000000000000000000000000000000..dd77385fdabda16f7686357f26cb33ca4f9c2194 --- /dev/null +++ b/node_modules/strtok3/lib/stream/AbstractStreamReader.js @@ -0,0 +1,71 @@ +import { EndOfStreamError, AbortError } from "./Errors.js"; +export class AbstractStreamReader { + constructor() { + this.endOfStream = false; + this.interrupted = false; + /** + * Store peeked data + * @type {Array} + */ + this.peekQueue = []; + } + async peek(uint8Array, mayBeLess = false) { + const bytesRead = await this.read(uint8Array, mayBeLess); + this.peekQueue.push(uint8Array.subarray(0, bytesRead)); // Put read data back to peek buffer + return bytesRead; + } + async read(buffer, mayBeLess = false) { + if (buffer.length === 0) { + return 0; + } + let bytesRead = this.readFromPeekBuffer(buffer); + if (!this.endOfStream) { + bytesRead += await this.readRemainderFromStream(buffer.subarray(bytesRead), mayBeLess); + } + if (bytesRead === 0 && !mayBeLess) { + throw new EndOfStreamError(); + } + return bytesRead; + } + /** + * Read chunk from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @returns Number of bytes read + */ + readFromPeekBuffer(buffer) { + let remaining = buffer.length; + let bytesRead = 0; + // consume peeked data first + while (this.peekQueue.length > 0 && remaining > 0) { + const peekData = this.peekQueue.pop(); // Front of queue + if (!peekData) + throw new Error('peekData should be defined'); + const lenCopy = Math.min(peekData.length, remaining); + buffer.set(peekData.subarray(0, lenCopy), bytesRead); + bytesRead += lenCopy; + remaining -= lenCopy; + if (lenCopy < peekData.length) { + // remainder back to queue + this.peekQueue.push(peekData.subarray(lenCopy)); + } + } + return bytesRead; + } + async readRemainderFromStream(buffer, mayBeLess) { + let bytesRead = 0; + // Continue reading from stream if required + while (bytesRead < buffer.length && !this.endOfStream) { + if (this.interrupted) { + throw new AbortError(); + } + const chunkLen = await this.readFromStream(buffer.subarray(bytesRead), mayBeLess); + if (chunkLen === 0) + break; + bytesRead += chunkLen; + } + if (!mayBeLess && bytesRead < buffer.length) { + throw new EndOfStreamError(); + } + return bytesRead; + } +} diff --git a/node_modules/strtok3/lib/stream/Deferred.d.ts b/node_modules/strtok3/lib/stream/Deferred.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..03d2dbbb68d7ff117c5626dbfb40946f71882351 --- /dev/null +++ b/node_modules/strtok3/lib/stream/Deferred.d.ts @@ -0,0 +1,6 @@ +export declare class Deferred { + promise: Promise; + resolve: (value: T) => void; + reject: (reason: Error) => void; + constructor(); +} diff --git a/node_modules/strtok3/lib/stream/Deferred.js b/node_modules/strtok3/lib/stream/Deferred.js new file mode 100644 index 0000000000000000000000000000000000000000..c7e42a62ad978a173bcc6df7501a00ef7dfa5160 --- /dev/null +++ b/node_modules/strtok3/lib/stream/Deferred.js @@ -0,0 +1,10 @@ +export class Deferred { + constructor() { + this.resolve = () => null; + this.reject = () => null; + this.promise = new Promise((resolve, reject) => { + this.reject = reject; + this.resolve = resolve; + }); + } +} diff --git a/node_modules/strtok3/lib/stream/Errors.d.ts b/node_modules/strtok3/lib/stream/Errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0d2a8d78209dbd2e85918ecbc51be16c7f36e3e --- /dev/null +++ b/node_modules/strtok3/lib/stream/Errors.d.ts @@ -0,0 +1,10 @@ +export declare const defaultMessages = "End-Of-Stream"; +/** + * Thrown on read operation of the end of file or stream has been reached + */ +export declare class EndOfStreamError extends Error { + constructor(); +} +export declare class AbortError extends Error { + constructor(message?: string); +} diff --git a/node_modules/strtok3/lib/stream/Errors.js b/node_modules/strtok3/lib/stream/Errors.js new file mode 100644 index 0000000000000000000000000000000000000000..7fa17793c79f706b1423beef74ab13cab1735ede --- /dev/null +++ b/node_modules/strtok3/lib/stream/Errors.js @@ -0,0 +1,16 @@ +export const defaultMessages = 'End-Of-Stream'; +/** + * Thrown on read operation of the end of file or stream has been reached + */ +export class EndOfStreamError extends Error { + constructor() { + super(defaultMessages); + this.name = "EndOfStreamError"; + } +} +export class AbortError extends Error { + constructor(message = "The operation was aborted") { + super(message); + this.name = "AbortError"; + } +} diff --git a/node_modules/strtok3/lib/stream/StreamReader.d.ts b/node_modules/strtok3/lib/stream/StreamReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd163f90cfb7770d8c16ce06092a0c5687dcbd02 --- /dev/null +++ b/node_modules/strtok3/lib/stream/StreamReader.d.ts @@ -0,0 +1,29 @@ +import type { Readable } from 'node:stream'; +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +/** + * Node.js Readable Stream Reader + * Ref: https://nodejs.org/api/stream.html#readable-streams + */ +export declare class StreamReader extends AbstractStreamReader { + private s; + /** + * Deferred used for postponed read request (as not data is yet available to read) + */ + private deferred; + constructor(s: Readable); + /** + * Read chunk from stream + * @param buffer Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @returns Number of bytes read + */ + protected readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + /** + * Process deferred read request + * @param request Deferred read request + */ + private readDeferred; + private reject; + abort(): Promise; + close(): Promise; +} diff --git a/node_modules/strtok3/lib/stream/StreamReader.js b/node_modules/strtok3/lib/stream/StreamReader.js new file mode 100644 index 0000000000000000000000000000000000000000..44c161656e4055c3e67c1883d5b3faa1b0a2e1af --- /dev/null +++ b/node_modules/strtok3/lib/stream/StreamReader.js @@ -0,0 +1,83 @@ +import { AbortError, } from './Errors.js'; +import { Deferred } from './Deferred.js'; +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +/** + * Node.js Readable Stream Reader + * Ref: https://nodejs.org/api/stream.html#readable-streams + */ +export class StreamReader extends AbstractStreamReader { + constructor(s) { + super(); + this.s = s; + /** + * Deferred used for postponed read request (as not data is yet available to read) + */ + this.deferred = null; + if (!s.read || !s.once) { + throw new Error('Expected an instance of stream.Readable'); + } + this.s.once('end', () => { + this.endOfStream = true; + if (this.deferred) { + this.deferred.resolve(0); + } + }); + this.s.once('error', err => this.reject(err)); + this.s.once('close', () => this.abort()); + } + /** + * Read chunk from stream + * @param buffer Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @returns Number of bytes read + */ + async readFromStream(buffer, mayBeLess) { + if (buffer.length === 0) + return 0; + const readBuffer = this.s.read(buffer.length); + if (readBuffer) { + buffer.set(readBuffer); + return readBuffer.length; + } + const request = { + buffer, + mayBeLess, + deferred: new Deferred() + }; + this.deferred = request.deferred; + this.s.once('readable', () => { + this.readDeferred(request); + }); + return request.deferred.promise; + } + /** + * Process deferred read request + * @param request Deferred read request + */ + readDeferred(request) { + const readBuffer = this.s.read(request.buffer.length); + if (readBuffer) { + request.buffer.set(readBuffer); + request.deferred.resolve(readBuffer.length); + this.deferred = null; + } + else { + this.s.once('readable', () => { + this.readDeferred(request); + }); + } + } + reject(err) { + this.interrupted = true; + if (this.deferred) { + this.deferred.reject(err); + this.deferred = null; + } + } + async abort() { + this.reject(new AbortError()); + } + async close() { + return this.abort(); + } +} diff --git a/node_modules/strtok3/lib/stream/WebStreamByobReader.d.ts b/node_modules/strtok3/lib/stream/WebStreamByobReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..71bec4f3516b5358f58981fbe441bad823101dcf --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamByobReader.d.ts @@ -0,0 +1,14 @@ +import { WebStreamReader } from './WebStreamReader.js'; +/** + * Read from a WebStream using a BYOB reader + * Reference: https://nodejs.org/api/webstreams.html#class-readablestreambyobreader + */ +export declare class WebStreamByobReader extends WebStreamReader { + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + protected readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; +} diff --git a/node_modules/strtok3/lib/stream/WebStreamByobReader.js b/node_modules/strtok3/lib/stream/WebStreamByobReader.js new file mode 100644 index 0000000000000000000000000000000000000000..6c8d253fcd103deafcfb1df6b81d84daeb085f41 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamByobReader.js @@ -0,0 +1,27 @@ +import { WebStreamReader } from './WebStreamReader.js'; +/** + * Read from a WebStream using a BYOB reader + * Reference: https://nodejs.org/api/webstreams.html#class-readablestreambyobreader + */ +export class WebStreamByobReader extends WebStreamReader { + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + async readFromStream(buffer, mayBeLess) { + if (buffer.length === 0) + return 0; + // @ts-expect-error + const result = await this.reader.read(new Uint8Array(buffer.length), { min: mayBeLess ? undefined : buffer.length }); + if (result.done) { + this.endOfStream = result.done; + } + if (result.value) { + buffer.set(result.value); + return result.value.length; + } + return 0; + } +} diff --git a/node_modules/strtok3/lib/stream/WebStreamDefaultReader.d.ts b/node_modules/strtok3/lib/stream/WebStreamDefaultReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9c469f15d07fcf1850bd406717964d444fb67d1 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamDefaultReader.d.ts @@ -0,0 +1,19 @@ +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +export declare class WebStreamDefaultReader extends AbstractStreamReader { + private reader; + private buffer; + constructor(reader: ReadableStreamDefaultReader); + /** + * Copy chunk to target, and store the remainder in this.buffer + */ + private writeChunk; + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + protected readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + abort(): Promise; + close(): Promise; +} diff --git a/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js b/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js new file mode 100644 index 0000000000000000000000000000000000000000..76fe36822079fadd69d73646c1868b1001fdd385 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js @@ -0,0 +1,62 @@ +import { EndOfStreamError } from './Errors.js'; +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +export class WebStreamDefaultReader extends AbstractStreamReader { + constructor(reader) { + super(); + this.reader = reader; + this.buffer = null; // Internal buffer to store excess data + } + /** + * Copy chunk to target, and store the remainder in this.buffer + */ + writeChunk(target, chunk) { + const written = Math.min(chunk.length, target.length); + target.set(chunk.subarray(0, written)); + // Adjust the remainder of the buffer + if (written < chunk.length) { + this.buffer = chunk.subarray(written); + } + else { + this.buffer = null; + } + return written; + } + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + async readFromStream(buffer, mayBeLess) { + if (buffer.length === 0) + return 0; + let totalBytesRead = 0; + // Serve from the internal buffer first + if (this.buffer) { + totalBytesRead += this.writeChunk(buffer, this.buffer); + } + // Continue reading from the stream if more data is needed + while (totalBytesRead < buffer.length && !this.endOfStream) { + const result = await this.reader.read(); + if (result.done) { + this.endOfStream = true; + break; + } + if (result.value) { + totalBytesRead += this.writeChunk(buffer.subarray(totalBytesRead), result.value); + } + } + if (!mayBeLess && totalBytesRead === 0 && this.endOfStream) { + throw new EndOfStreamError(); + } + return totalBytesRead; + } + abort() { + this.interrupted = true; + return this.reader.cancel(); + } + async close() { + await this.abort(); + this.reader.releaseLock(); + } +} diff --git a/node_modules/strtok3/lib/stream/WebStreamReader.d.ts b/node_modules/strtok3/lib/stream/WebStreamReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc46e3d34b4254079f79ef35ec0df2920ce813e4 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamReader.d.ts @@ -0,0 +1,14 @@ +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +export declare abstract class WebStreamReader extends AbstractStreamReader { + protected reader: ReadableStreamDefaultReader | ReadableStreamBYOBReader; + constructor(reader: ReadableStreamDefaultReader | ReadableStreamBYOBReader); + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + protected abstract readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + abort(): Promise; + close(): Promise; +} diff --git a/node_modules/strtok3/lib/stream/WebStreamReader.js b/node_modules/strtok3/lib/stream/WebStreamReader.js new file mode 100644 index 0000000000000000000000000000000000000000..048074e684d0c9c19c710356fab81b0b2808106e --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamReader.js @@ -0,0 +1,13 @@ +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +export class WebStreamReader extends AbstractStreamReader { + constructor(reader) { + super(); + this.reader = reader; + } + async abort() { + return this.close(); + } + async close() { + this.reader.releaseLock(); + } +} diff --git a/node_modules/strtok3/lib/stream/WebStreamReaderFactory.d.ts b/node_modules/strtok3/lib/stream/WebStreamReaderFactory.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..565563d7cf4d5bcb944d34cc6b2f8b5a913e261b --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamReaderFactory.d.ts @@ -0,0 +1,5 @@ +import type { ReadableStream as NodeReadableStream } from 'node:stream/web'; +import { WebStreamByobReader } from './WebStreamByobReader.js'; +import { WebStreamDefaultReader } from './WebStreamDefaultReader.js'; +export type AnyWebByteStream = NodeReadableStream | ReadableStream; +export declare function makeWebStreamReader(stream: AnyWebByteStream): WebStreamByobReader | WebStreamDefaultReader; diff --git a/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js b/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..e6767840317369a9cfbe2b3280df56d936f81480 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js @@ -0,0 +1,19 @@ +import { WebStreamByobReader } from './WebStreamByobReader.js'; +import { WebStreamDefaultReader } from './WebStreamDefaultReader.js'; +export function makeWebStreamReader(stream) { + try { + const reader = stream.getReader({ mode: "byob" }); + if (reader instanceof ReadableStreamDefaultReader) { + // Fallback to default reader in case `mode: byob` is ignored + return new WebStreamDefaultReader(reader); + } + return new WebStreamByobReader(reader); + } + catch (error) { + if (error instanceof TypeError) { + // Fallback to default reader in case `mode: byob` rejected by a `TypeError` + return new WebStreamDefaultReader(stream.getReader()); + } + throw error; + } +} diff --git a/node_modules/strtok3/lib/stream/index.d.ts b/node_modules/strtok3/lib/stream/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b973ea79dd23ff6ae84581ddf0f64ad2d83ec69 --- /dev/null +++ b/node_modules/strtok3/lib/stream/index.d.ts @@ -0,0 +1,6 @@ +export { AbortError, EndOfStreamError } from './Errors.js'; +export { StreamReader } from './StreamReader.js'; +export { WebStreamByobReader } from './WebStreamByobReader.js'; +export { WebStreamDefaultReader } from './WebStreamDefaultReader.js'; +export type { IStreamReader } from './AbstractStreamReader.js'; +export { type AnyWebByteStream, makeWebStreamReader } from './WebStreamReaderFactory.js'; diff --git a/node_modules/strtok3/lib/stream/index.js b/node_modules/strtok3/lib/stream/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6df5a2ce9a67342d6788df2c79590fd690091dbf --- /dev/null +++ b/node_modules/strtok3/lib/stream/index.js @@ -0,0 +1,5 @@ +export { AbortError, EndOfStreamError } from './Errors.js'; +export { StreamReader } from './StreamReader.js'; +export { WebStreamByobReader } from './WebStreamByobReader.js'; +export { WebStreamDefaultReader } from './WebStreamDefaultReader.js'; +export { makeWebStreamReader } from './WebStreamReaderFactory.js'; diff --git a/node_modules/strtok3/lib/types.d.ts b/node_modules/strtok3/lib/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..295608e5977046b650e395ce18c9f445b587efeb --- /dev/null +++ b/node_modules/strtok3/lib/types.d.ts @@ -0,0 +1,139 @@ +import type { IGetToken } from '@tokenizer/token'; +export interface IFileInfo { + /** + * File size in bytes + */ + size?: number; + /** + * MIME-type of file + */ + mimeType?: string; + /** + * File path + */ + path?: string; + /** + * File URL + */ + url?: string; +} +export interface IRandomAccessFileInfo extends IFileInfo { + /** + * File size in bytes + */ + size: number; +} +export interface IReadChunkOptions { + /** + * Number of bytes to read. + */ + length?: number; + /** + * Position where to begin reading from the file. + * Default it is `tokenizer.position`. + * Position may not be less than `tokenizer.position`, unless `supportsRandomAccess()` returns `true`. + */ + position?: number; + /** + * If set, will not throw an EOF error if not all off the requested data could be read + */ + mayBeLess?: boolean; +} +export interface IRandomAccessTokenizer extends ITokenizer { + /** + * Provide access to information of the underlying information stream or file. + */ + fileInfo: IRandomAccessFileInfo; + /** + * Change the position (offset) of the tokenizer + * @param position New position + */ + setPosition(position: number): void; +} +/** + * The tokenizer allows us to read or peek from the tokenizer-stream. + * The tokenizer-stream is an abstraction of a stream, file or Buffer. + */ +export interface ITokenizer { + /** + * Provide access to information of the underlying information stream or file. + */ + readonly fileInfo: IFileInfo; + /** + * Offset in bytes (= number of bytes read) since beginning of file or stream + */ + readonly position: number; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer - Target buffer to fill with data peek from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + peekBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer - Target buffer to fill with data peeked from the tokenizer-stream + * @param options - Additional read options + * @returns Promise with number of bytes read + */ + readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @param maybeless - If set, will not throw an EOF error if the less then the requested length could be read. + */ + peekToken(token: IGetToken, position?: number | null, maybeless?: boolean): Promise; + /** + * Read a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + */ + readToken(token: IGetToken, position?: number): Promise; + /** + * Peek a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + peekNumber(token: IGetToken): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + readNumber(token: IGetToken): Promise; + /** + * Ignore given number of bytes + * @param length - Number of bytes ignored + */ + ignore(length: number): Promise; + /** + * Clean up resources. + * It does not close the stream for StreamReader, but is does close the file-descriptor. + */ + close(): Promise; + /** + * Abort pending asynchronous operations + */ + abort(): Promise; + /** + * Returns true when the underlying file supports random access + */ + supportsRandomAccess(): boolean; +} +export type OnClose = () => Promise; +export interface ITokenizerOptions { + /** + * Pass additional file information to the tokenizer + */ + fileInfo?: IFileInfo; + /** + * On tokenizer close handler + */ + onClose?: OnClose; + /** + * Pass `AbortSignal` which can stop active async operations + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal + */ + abortSignal?: AbortSignal; +} diff --git a/node_modules/strtok3/lib/types.js b/node_modules/strtok3/lib/types.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/strtok3/lib/types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/strtok3/package.json b/node_modules/strtok3/package.json new file mode 100644 index 0000000000000000000000000000000000000000..42b2265c47f2db503dd0f2b06a6748bf090033f4 --- /dev/null +++ b/node_modules/strtok3/package.json @@ -0,0 +1,94 @@ +{ + "name": "strtok3", + "version": "10.3.5", + "description": "A promise based streaming tokenizer", + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + "scripts": { + "clean": "del-cli 'lib/**/*.js' 'lib/**/*.js.map' 'lib/**/*.d.ts' 'test/**/*.js' 'test/**/*.js.map'", + "compile-src": "tsc -p lib --sourceMap false", + "compile-test": "tsc -p test", + "compile": "yarn run compile-src && yarn run compile-test", + "build": "yarn run clean && yarn run compile", + "prepublishOnly": "yarn run build", + "eslint": "eslint lib test", + "lint:md": "remark -u preset-lint-recommended .", + "lint:ts": "biome check", + "lint": "yarn run lint:md && yarn run lint:ts", + "fix": "yarn run biome lint --write", + "test": "mocha", + "bun:test": "bun run --bun test", + "test-coverage": "c8 yarn run test", + "send-codacy": "c8 report --reporter=text-lcov | codacy-coverage", + "start": "yarn run compile && yarn run lint && yarn run cover-test", + "update-biome": "yarn add -D --exact @biomejs/biome && npx @biomejs/biome migrate --write" + }, + "engines": { + "node": ">=18" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Borewit/strtok3.git" + }, + "license": "MIT", + "type": "module", + "exports": { + ".": { + "node": "./lib/index.js", + "default": "./lib/core.js" + }, + "./core": "./lib/core.js" + }, + "types": "lib/index.d.ts", + "files": [ + "lib/**/*.js", + "lib/**/*.d.ts" + ], + "bugs": { + "url": "https://github.com/Borewit/strtok3/issues" + }, + "dependencies": { + "@tokenizer/token": "^0.3.0" + }, + "devDependencies": { + "@biomejs/biome": "2.4.8", + "@types/chai": "^5.2.2", + "@types/chai-as-promised": "^8.0.2", + "@types/debug": "^4.1.12", + "@types/mocha": "^10.0.10", + "@types/node": "^24.1.0", + "c8": "^11.0.0", + "chai": "^5.2.1", + "chai-as-promised": "^8.0.2", + "del-cli": "^7.0.0", + "mocha": "^11.7.5", + "node-readable-to-web-readable-stream": "^0.4.2", + "remark-cli": "^12.0.1", + "remark-preset-lint-recommended": "^7.0.1", + "token-types": "^6.1.2", + "ts-node": "^10.9.2", + "typescript": "^5.8.3", + "uint8array-extras": "^1.4.0" + }, + "keywords": [ + "tokenizer", + "reader", + "token", + "async", + "promise", + "parser", + "decoder", + "binary", + "endian", + "uint", + "stream", + "streaming" + ], + "packageManager": "yarn@4.9.2" +} diff --git a/node_modules/style-to-js/LICENSE b/node_modules/style-to-js/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..09562a52bb9c841f6b523a4e09bff16008b71f8c --- /dev/null +++ b/node_modules/style-to-js/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2020 Menglin "Mark" Xu + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/style-to-js/README.md b/node_modules/style-to-js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..210ce8a6c8004a9b23be163c1ca149ba4a0cb75a --- /dev/null +++ b/node_modules/style-to-js/README.md @@ -0,0 +1,271 @@ +# style-to-js + +[![NPM](https://nodei.co/npm/style-to-js.png)](https://nodei.co/npm/style-to-js/) + +[![NPM version](https://img.shields.io/npm/v/style-to-js)](https://www.npmjs.com/package/style-to-js) +[![BNPM bundle size](https://img.shields.io/bundlephobia/minzip/style-to-js)](https://bundlephobia.com/package/style-to-js) +[![build](https://github.com/remarkablemark/style-to-js/actions/workflows/build.yml/badge.svg)](https://github.com/remarkablemark/style-to-js/actions/workflows/build.yml) +[![codecov](https://codecov.io/gh/remarkablemark/style-to-js/branch/master/graph/badge.svg?token=JWKUKTFT3E)](https://codecov.io/gh/remarkablemark/style-to-js) +[![NPM downloads](https://img.shields.io/npm/dm/style-to-js)](https://www.npmjs.com/package/style-to-js) + +Parses CSS inline style to JavaScript object (camelCased): + +``` +StyleToJS(string) +``` + +## Example + +```js +import parse from 'style-to-js'; + +parse('background-color: #BADA55;'); +``` + +Output: + +```json +{ "backgroundColor": "#BADA55" } +``` + +[JSFiddle](https://jsfiddle.net/remarkablemark/04nob1y7/) | [Examples](https://github.com/remarkablemark/style-to-js/tree/master/examples) + +## Install + +[NPM](https://www.npmjs.com/package/style-to-js): + +```sh +npm install style-to-js --save +``` + +[Yarn](https://yarnpkg.com/package/style-to-js): + +```sh +yarn add style-to-js +``` + +[CDN](https://unpkg.com/style-to-js/): + +```html + + +``` + +## Usage + +### Import + +Import with ES Modules: + +```js +import parse from 'style-to-js'; +``` + +Require with CommonJS: + +```js +const parse = require('style-to-js'); +``` + +### Parse style + +Parse single declaration: + +```js +parse('line-height: 42'); +``` + +Output: + +```json +{ "lineHeight": "42" } +``` + +> [!NOTE] +> Notice that the CSS property is camelCased. + +Parse multiple declarations: + +```js +parse(` + border-color: #ACE; + z-index: 1337; +`); +``` + +Output: + +```json +{ + "borderColor": "#ACE", + "zIndex": "1337" +} +``` + +### Vendor prefix + +Parse [vendor prefix](https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix): + +```js +parse(` + -webkit-transition: all 4s ease; + -moz-transition: all 4s ease; + -ms-transition: all 4s ease; + -o-transition: all 4s ease; + -khtml-transition: all 4s ease; +`); +``` + +Output: + +```json +{ + "webkitTransition": "all 4s ease", + "mozTransition": "all 4s ease", + "msTransition": "all 4s ease", + "oTransition": "all 4s ease", + "khtmlTransition": "all 4s ease" +} +``` + +### Custom property + +Parse [custom property](https://developer.mozilla.org/en-US/docs/Web/CSS/--*): + +```js +parse('--custom-property: #f00'); +``` + +Output: + +```json +{ "--custom-property": "#f00" } +``` + +### Unknown declaration + +This library does not validate declarations, so unknown declarations can be parsed: + +```js +parse('the-answer: 42;'); +``` + +Output: + +```json +{ "theAnswer": "42" } +``` + +### Invalid declaration + +Declarations with missing value are removed: + +```js +parse(` + margin-top: ; + margin-right: 1em; +`); +``` + +Output: + +```json +{ "marginRight": "1em" } +``` + +Other invalid declarations or arguments: + +```js +parse(); // {} +parse(null); // {} +parse(1); // {} +parse(true); // {} +parse('top:'); // {} +parse(':12px'); // {} +parse(':'); // {} +parse(';'); // {} +``` + +The following values will throw an error: + +```js +parse('top'); // Uncaught Error: property missing ':' +parse('/*'); // Uncaught Error: End of comment missing +``` + +### Options + +#### reactCompat + +When option `reactCompat` is true, the [vendor prefix](https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix) will be capitalized: + +```js +parse( + ` + -webkit-transition: all 4s ease; + -moz-transition: all 4s ease; + -ms-transition: all 4s ease; + -o-transition: all 4s ease; + -khtml-transition: all 4s ease; + `, + { reactCompat: true }, +); +``` + +Output: + +```json +{ + "WebkitTransition": "all 4s ease", + "MozTransition": "all 4s ease", + "msTransition": "all 4s ease", + "OTransition": "all 4s ease", + "KhtmlTransition": "all 4s ease" +} +``` + +This removes the React warning: + +``` +Warning: Unsupported vendor-prefixed style property %s. Did you mean %s?%s", "oTransition", "OTransition" +``` + +## Testing + +Run tests with coverage: + +```sh +npm test +``` + +Run tests in watch mode: + +```sh +npm run test:watch +``` + +Lint files: + +```sh +npm run lint +``` + +Fix lint errors: + +```sh +npm run lint:fix +``` + +## Release + +Release and publish are automated by [Release Please](https://github.com/googleapis/release-please). + +## Special Thanks + +- [style-to-object](https://github.com/remarkablemark/style-to-object) + +## License + +[MIT](https://github.com/remarkablemark/style-to-js/blob/master/LICENSE) diff --git a/node_modules/style-to-js/cjs/index.d.ts b/node_modules/style-to-js/cjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc864a60a1779fa47b79407fb3b0266bc48ee588 --- /dev/null +++ b/node_modules/style-to-js/cjs/index.d.ts @@ -0,0 +1,14 @@ +import { CamelCaseOptions } from './utilities'; +type StyleObject = Record; +interface StyleToJSOptions extends CamelCaseOptions { +} +/** + * Parses CSS inline style to JavaScript object (camelCased). + */ +declare function StyleToJS(style: string, options?: StyleToJSOptions): StyleObject; +declare namespace StyleToJS { + var _a: typeof StyleToJS; + export { _a as default }; +} +export = StyleToJS; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/style-to-js/cjs/index.d.ts.map b/node_modules/style-to-js/cjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..fd882d6001ee2666df37c97e21655444bbe4bd8c --- /dev/null +++ b/node_modules/style-to-js/cjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAa,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE1D,KAAK,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAE1C,UAAU,gBAAiB,SAAQ,gBAAgB;CAAG;AAEtD;;GAEG;AACH,iBAAS,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,WAAW,CAezE;kBAfQ,SAAS;;;;AAmBlB,SAAS,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/style-to-js/cjs/index.js b/node_modules/style-to-js/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..557407e5d33032040d79e6dbab23a96679b2348f --- /dev/null +++ b/node_modules/style-to-js/cjs/index.js @@ -0,0 +1,25 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var style_to_object_1 = __importDefault(require("style-to-object")); +var utilities_1 = require("./utilities"); +/** + * Parses CSS inline style to JavaScript object (camelCased). + */ +function StyleToJS(style, options) { + var output = {}; + if (!style || typeof style !== 'string') { + return output; + } + (0, style_to_object_1.default)(style, function (property, value) { + // skip CSS comment + if (property && value) { + output[(0, utilities_1.camelCase)(property, options)] = value; + } + }); + return output; +} +StyleToJS.default = StyleToJS; +module.exports = StyleToJS; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/style-to-js/cjs/index.js.map b/node_modules/style-to-js/cjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1a9b2992f63f50820e9d3bd4dbacb83da586c2c4 --- /dev/null +++ b/node_modules/style-to-js/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAAA,oEAA4C;AAE5C,yCAA0D;AAM1D;;GAEG;AACH,SAAS,SAAS,CAAC,KAAa,EAAE,OAA0B;IAC1D,IAAM,MAAM,GAAgB,EAAE,CAAC;IAE/B,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,IAAA,yBAAa,EAAC,KAAK,EAAE,UAAC,QAAQ,EAAE,KAAK;QACnC,mBAAmB;QACnB,IAAI,QAAQ,IAAI,KAAK,EAAE,CAAC;YACtB,MAAM,CAAC,IAAA,qBAAS,EAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,GAAG,KAAK,CAAC;QAC/C,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,CAAC,OAAO,GAAG,SAAS,CAAC;AAE9B,iBAAS,SAAS,CAAC"} \ No newline at end of file diff --git a/node_modules/style-to-js/cjs/utilities.d.ts b/node_modules/style-to-js/cjs/utilities.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6743592d2d6dfe6f213280572eb181847fca3cef --- /dev/null +++ b/node_modules/style-to-js/cjs/utilities.d.ts @@ -0,0 +1,11 @@ +/** + * CamelCase options. + */ +export interface CamelCaseOptions { + reactCompat?: boolean; +} +/** + * CamelCases a CSS property. + */ +export declare const camelCase: (property: string, options?: CamelCaseOptions) => string; +//# sourceMappingURL=utilities.d.ts.map \ No newline at end of file diff --git a/node_modules/style-to-js/cjs/utilities.d.ts.map b/node_modules/style-to-js/cjs/utilities.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..783a74c493880a422c0f0a49de1bdc290e531a53 --- /dev/null +++ b/node_modules/style-to-js/cjs/utilities.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../src/utilities.ts"],"names":[],"mappings":"AAyBA;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED;;GAEG;AACH,eAAO,MAAM,SAAS,GAAI,UAAU,MAAM,EAAE,UAAS,gBAAqB,WAgBzE,CAAC"} \ No newline at end of file diff --git a/node_modules/style-to-js/cjs/utilities.js b/node_modules/style-to-js/cjs/utilities.js new file mode 100644 index 0000000000000000000000000000000000000000..10ad55ad8a0eb1657063d2e810372ce4729ee1ac --- /dev/null +++ b/node_modules/style-to-js/cjs/utilities.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.camelCase = void 0; +var CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9_-]+$/; +var HYPHEN_REGEX = /-([a-z])/g; +var NO_HYPHEN_REGEX = /^[^-]+$/; +var VENDOR_PREFIX_REGEX = /^-(webkit|moz|ms|o|khtml)-/; +var MS_VENDOR_PREFIX_REGEX = /^-(ms)-/; +/** + * Checks whether to skip camelCase. + */ +var skipCamelCase = function (property) { + return !property || + NO_HYPHEN_REGEX.test(property) || + CUSTOM_PROPERTY_REGEX.test(property); +}; +/** + * Replacer that capitalizes first character. + */ +var capitalize = function (match, character) { + return character.toUpperCase(); +}; +/** + * Replacer that removes beginning hyphen of vendor prefix property. + */ +var trimHyphen = function (match, prefix) { return "".concat(prefix, "-"); }; +/** + * CamelCases a CSS property. + */ +var camelCase = function (property, options) { + if (options === void 0) { options = {}; } + if (skipCamelCase(property)) { + return property; + } + property = property.toLowerCase(); + if (options.reactCompat) { + // `-ms` vendor prefix should not be capitalized + property = property.replace(MS_VENDOR_PREFIX_REGEX, trimHyphen); + } + else { + // for non-React, remove first hyphen so vendor prefix is not capitalized + property = property.replace(VENDOR_PREFIX_REGEX, trimHyphen); + } + return property.replace(HYPHEN_REGEX, capitalize); +}; +exports.camelCase = camelCase; +//# sourceMappingURL=utilities.js.map \ No newline at end of file diff --git a/node_modules/style-to-js/cjs/utilities.js.map b/node_modules/style-to-js/cjs/utilities.js.map new file mode 100644 index 0000000000000000000000000000000000000000..111ab54b9f5118fa74b146b89f6d5eef12ef6ce9 --- /dev/null +++ b/node_modules/style-to-js/cjs/utilities.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utilities.js","sourceRoot":"","sources":["../src/utilities.ts"],"names":[],"mappings":";;;AAAA,IAAM,qBAAqB,GAAG,oBAAoB,CAAC;AACnD,IAAM,YAAY,GAAG,WAAW,CAAC;AACjC,IAAM,eAAe,GAAG,SAAS,CAAC;AAClC,IAAM,mBAAmB,GAAG,4BAA4B,CAAC;AACzD,IAAM,sBAAsB,GAAG,SAAS,CAAC;AAEzC;;GAEG;AACH,IAAM,aAAa,GAAG,UAAC,QAAgB;IACrC,OAAA,CAAC,QAAQ;QACT,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC;QAC9B,qBAAqB,CAAC,IAAI,CAAC,QAAQ,CAAC;AAFpC,CAEoC,CAAC;AAEvC;;GAEG;AACH,IAAM,UAAU,GAAG,UAAC,KAAa,EAAE,SAAiB;IAClD,OAAA,SAAS,CAAC,WAAW,EAAE;AAAvB,CAAuB,CAAC;AAE1B;;GAEG;AACH,IAAM,UAAU,GAAG,UAAC,KAAa,EAAE,MAAc,IAAK,OAAA,UAAG,MAAM,MAAG,EAAZ,CAAY,CAAC;AASnE;;GAEG;AACI,IAAM,SAAS,GAAG,UAAC,QAAgB,EAAE,OAA8B;IAA9B,wBAAA,EAAA,YAA8B;IACxE,IAAI,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5B,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;IAElC,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;QACxB,gDAAgD;QAChD,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,sBAAsB,EAAE,UAAU,CAAC,CAAC;IAClE,CAAC;SAAM,CAAC;QACN,yEAAyE;QACzE,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC;IAC/D,CAAC;IAED,OAAO,QAAQ,CAAC,OAAO,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;AACpD,CAAC,CAAC;AAhBW,QAAA,SAAS,aAgBpB"} \ No newline at end of file diff --git a/node_modules/style-to-js/package.json b/node_modules/style-to-js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..896f04d563494bb309a1814e73d14eb2bcd81bf3 --- /dev/null +++ b/node_modules/style-to-js/package.json @@ -0,0 +1,70 @@ +{ + "name": "style-to-js", + "version": "1.1.21", + "description": "Parses CSS inline style to JavaScript object (camelCased).", + "author": "Mark ", + "main": "cjs/index.js", + "scripts": { + "build": "npm run build:cjs && npm run build:umd", + "build:cjs": "tsc --declaration --outDir cjs", + "build:umd": "rollup --config --failAfterWarnings", + "clean": "rm -rf cjs umd", + "lint": "eslint .", + "lint:tsc": "tsc --noEmit", + "lint:fix": "npm run lint -- --fix", + "prepare": "husky", + "prepublishOnly": "npm run lint && npm run lint:tsc && npm run test:ci && npm run clean && npm run build", + "test": "jest", + "test:ci": "CI=true jest --ci --colors --coverage", + "test:watch": "jest --watch" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/remarkablemark/style-to-js.git" + }, + "bugs": { + "url": "https://github.com/remarkablemark/style-to-js/issues" + }, + "keywords": [ + "style-to-js", + "css", + "style", + "javascript", + "object", + "pojo" + ], + "dependencies": { + "style-to-object": "1.0.14" + }, + "devDependencies": { + "@commitlint/cli": "20.1.0", + "@commitlint/config-conventional": "20.0.0", + "@eslint/compat": "2.0.0", + "@eslint/eslintrc": "3.3.1", + "@eslint/js": "9.39.1", + "@rollup/plugin-commonjs": "29.0.0", + "@rollup/plugin-node-resolve": "16.0.3", + "@rollup/plugin-terser": "0.4.4", + "@types/jest": "30.0.0", + "@typescript-eslint/eslint-plugin": "8.46.4", + "@typescript-eslint/parser": "8.46.4", + "eslint": "9.39.1", + "eslint-plugin-prettier": "5.5.4", + "eslint-plugin-simple-import-sort": "12.1.1", + "globals": "16.5.0", + "husky": "9.1.7", + "jest": "30.2.0", + "lint-staged": "16.2.6", + "prettier": "3.6.2", + "rollup": "4.53.2", + "ts-jest": "29.4.5", + "ts-node": "10.9.2", + "typescript": "5.9.3" + }, + "files": [ + "cjs/", + "src/", + "umd/" + ], + "license": "MIT" +} diff --git a/node_modules/style-to-js/src/index.test.ts b/node_modules/style-to-js/src/index.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..169eba36527be5d4893687ccbcc015ea5ccdaa8f --- /dev/null +++ b/node_modules/style-to-js/src/index.test.ts @@ -0,0 +1,129 @@ +import styleToJS = require('.'); + +it('exposes itself as default', () => { + expect(styleToJS).toBe(styleToJS.default); +}); + +it('parses empty style to object', () => { + expect(styleToJS('')).toEqual({}); +}); + +it('does not parse CSS comment', () => { + expect(styleToJS('/* comment */')).toEqual({}); +}); + +// invalid argument +it.each([undefined, null, 0, 1, true, false, {}, [], () => {}, new Date()])( + 'parses "%s" to empty object', + (text) => { + expect(styleToJS(text as string)).toEqual({}); + }, +); + +it.each(['top:', ':12px', ':', ';'])('parses "%s" to empty object', (text) => { + expect(styleToJS(text)).toEqual({}); +}); + +it('parses common styles to object', () => { + const style = ` + color: #f00; + font-size: 42px; + z-index: -1; + `; + expect(styleToJS(style)).toMatchInlineSnapshot(` + { + "color": "#f00", + "fontSize": "42px", + "zIndex": "-1", + } + `); +}); + +it('parses style with vendor prefix to object', () => { + const style = ` + display: -ms-grid; + display: grid; + -webkit-transition: all .5s; + -o-transition: all .5s; + transition: all .5s; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + background: -webkit-gradient(linear, left top, left bottom, from(white), to(black)); + background: -o-linear-gradient(top, white, black); + background: linear-gradient(to bottom, white, black); + `; + expect(styleToJS(style)).toMatchInlineSnapshot(` + { + "background": "linear-gradient(to bottom, white, black)", + "display": "grid", + "mozUserSelect": "none", + "msUserSelect": "none", + "oTransition": "all .5s", + "transition": "all .5s", + "userSelect": "none", + "webkitTransition": "all .5s", + "webkitUserSelect": "none", + } + `); +}); + +it('parses background style to object', () => { + const style = + 'background: url(data:image/png; base64,ivborw0kggoaaaansaaaabgdbtueaalgpc/xhbqaaaafzmuexurczmzpf399fx1+bm5mzy9avzxbesmgces5/p8/t9furvcrmu73jwlzosgsiizurcjo/ad+eqjjb4hv8bft+idpqocx1wjosbfhh2xssxeiyn3uli/6mnree07uiwjev8u8czwyuqdlkpg1bkb4nnm+veanfhqn1k4+gpt6ugqcvu2h2ovuif)'; + expect(styleToJS(style)).toMatchInlineSnapshot(` + { + "background": "url(data:image/png; base64,ivborw0kggoaaaansaaaabgdbtueaalgpc/xhbqaaaafzmuexurczmzpf399fx1+bm5mzy9avzxbesmgces5/p8/t9furvcrmu73jwlzosgsiizurcjo/ad+eqjjb4hv8bft+idpqocx1wjosbfhh2xssxeiyn3uli/6mnree07uiwjev8u8czwyuqdlkpg1bkb4nnm+veanfhqn1k4+gpt6ugqcvu2h2ovuif)", + } + `); +}); + +it('parses style with no spaces to object', () => { + const style = + 'border-bottom-left-radius:1em;border-right-style:solid;Z-Index:-1;-moz-border-radius-bottomleft:20px'; + expect(styleToJS(style)).toMatchInlineSnapshot(` + { + "borderBottomLeftRadius": "1em", + "borderRightStyle": "solid", + "mozBorderRadiusBottomleft": "20px", + "zIndex": "-1", + } + `); +}); + +describe('when option reactCompat is true', () => { + const options = { reactCompat: true }; + + it('capitalizes vendor prefixes', () => { + const style = ` + -khtml-user-select: none; + -moz-user-select: -moz-none; + -o-user-select: none; + -webkit-user-select: none; + user-select: none; + `; + expect(styleToJS(style, options)).toMatchInlineSnapshot(` + { + "KhtmlUserSelect": "none", + "MozUserSelect": "-moz-none", + "OUserSelect": "none", + "WebkitUserSelect": "none", + "userSelect": "none", + } + `); + }); + + it('does not capitalize ms prefixes', () => { + const style = ` + -ms-transform: none; + -ms-user-select: none; + `; + expect(styleToJS(style, options)).toMatchInlineSnapshot(` + { + "msTransform": "none", + "msUserSelect": "none", + } + `); + }); +}); diff --git a/node_modules/style-to-js/src/index.ts b/node_modules/style-to-js/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e53ded3d43bee2ec336491066792a346e35dd3f --- /dev/null +++ b/node_modules/style-to-js/src/index.ts @@ -0,0 +1,31 @@ +import StyleToObject from 'style-to-object'; + +import { camelCase, CamelCaseOptions } from './utilities'; + +type StyleObject = Record; + +interface StyleToJSOptions extends CamelCaseOptions {} + +/** + * Parses CSS inline style to JavaScript object (camelCased). + */ +function StyleToJS(style: string, options?: StyleToJSOptions): StyleObject { + const output: StyleObject = {}; + + if (!style || typeof style !== 'string') { + return output; + } + + StyleToObject(style, (property, value) => { + // skip CSS comment + if (property && value) { + output[camelCase(property, options)] = value; + } + }); + + return output; +} + +StyleToJS.default = StyleToJS; + +export = StyleToJS; diff --git a/node_modules/style-to-js/src/utilities.test.ts b/node_modules/style-to-js/src/utilities.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..adbcdc9bdb85ae37603a4624bd0757096b9f3751 --- /dev/null +++ b/node_modules/style-to-js/src/utilities.test.ts @@ -0,0 +1,62 @@ +import { camelCase } from './utilities'; + +describe('camelCase', () => { + it('returns "" for empty string', () => { + expect(camelCase('')).toBe(''); + }); + + // no hyphen + it.each([ + ['foo', 'foo'], + ['fooBar', 'fooBar'], + ])('does not transform "%s"', (property, expected) => { + expect(camelCase(property)).toBe(expected); + }); + + // custom property + it.each([ + ['--fooBar', '--fooBar'], + ['--foo-bar', '--foo-bar'], + ['--foo-100', '--foo-100'], + ['--test_ing', '--test_ing'], + ])('does not transform custom property "%s"', (property, expected) => { + expect(camelCase(property)).toBe(expected); + }); + + // vendor prefix + it.each([ + ['-khtml-transition', 'khtmlTransition'], + ['-moz-user-select', 'mozUserSelect'], + ['-ms-transform', 'msTransform'], + ['-ms-user-select', 'msUserSelect'], + ['-o-transition', 'oTransition'], + ['-webkit-transition', 'webkitTransition'], + ['-webkit-user-select', 'webkitUserSelect'], + ])('transforms vendor prefix "%s" to "%s"', (property, expected) => { + expect(camelCase(property)).toBe(expected); + }); + + it.each([ + ['foo-bar', 'fooBar'], + ['foo-bar-baz', 'fooBarBaz'], + ['CAMEL-CASE', 'camelCase'], + ])('transforms "%s" to "%s"', (property, expected) => { + expect(camelCase(property)).toBe(expected); + }); + + describe('option reactCompat is true', () => { + const options = { reactCompat: true }; + + it.each([ + ['-khtml-transition', 'KhtmlTransition'], + ['-o-transition', 'OTransition'], + ['-moz-user-select', 'MozUserSelect'], + ['-ms-transform', 'msTransform'], + ['-ms-user-select', 'msUserSelect'], + ['-webkit-transition', 'WebkitTransition'], + ['-webkit-user-select', 'WebkitUserSelect'], + ])('capitalizes vendor prefix "%s" to "%s"', (property, expected) => { + expect(camelCase(property, options)).toBe(expected); + }); + }); +}); diff --git a/node_modules/style-to-js/src/utilities.ts b/node_modules/style-to-js/src/utilities.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5bd6027ea28bf7ee74b59c7157938cc1ac18bd1 --- /dev/null +++ b/node_modules/style-to-js/src/utilities.ts @@ -0,0 +1,52 @@ +const CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9_-]+$/; +const HYPHEN_REGEX = /-([a-z])/g; +const NO_HYPHEN_REGEX = /^[^-]+$/; +const VENDOR_PREFIX_REGEX = /^-(webkit|moz|ms|o|khtml)-/; +const MS_VENDOR_PREFIX_REGEX = /^-(ms)-/; + +/** + * Checks whether to skip camelCase. + */ +const skipCamelCase = (property: string) => + !property || + NO_HYPHEN_REGEX.test(property) || + CUSTOM_PROPERTY_REGEX.test(property); + +/** + * Replacer that capitalizes first character. + */ +const capitalize = (match: string, character: string) => + character.toUpperCase(); + +/** + * Replacer that removes beginning hyphen of vendor prefix property. + */ +const trimHyphen = (match: string, prefix: string) => `${prefix}-`; + +/** + * CamelCase options. + */ +export interface CamelCaseOptions { + reactCompat?: boolean; +} + +/** + * CamelCases a CSS property. + */ +export const camelCase = (property: string, options: CamelCaseOptions = {}) => { + if (skipCamelCase(property)) { + return property; + } + + property = property.toLowerCase(); + + if (options.reactCompat) { + // `-ms` vendor prefix should not be capitalized + property = property.replace(MS_VENDOR_PREFIX_REGEX, trimHyphen); + } else { + // for non-React, remove first hyphen so vendor prefix is not capitalized + property = property.replace(VENDOR_PREFIX_REGEX, trimHyphen); + } + + return property.replace(HYPHEN_REGEX, capitalize); +}; diff --git a/node_modules/style-to-js/umd/style-to-js.js b/node_modules/style-to-js/umd/style-to-js.js new file mode 100644 index 0000000000000000000000000000000000000000..e2d7fd5ee62a0a66bc9a546d1bb42759ed16c751 --- /dev/null +++ b/node_modules/style-to-js/umd/style-to-js.js @@ -0,0 +1,429 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.StyleToJS = factory()); +})(this, (function () { 'use strict'; + + function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + var cjs$2 = {}; + + var cjs$1; + var hasRequiredCjs$2; + + function requireCjs$2 () { + if (hasRequiredCjs$2) return cjs$1; + hasRequiredCjs$2 = 1; + + // http://www.w3.org/TR/CSS21/grammar.html + // https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027 + var COMMENT_REGEX = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g; + + var NEWLINE_REGEX = /\n/g; + var WHITESPACE_REGEX = /^\s*/; + + // declaration + var PROPERTY_REGEX = /^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/; + var COLON_REGEX = /^:\s*/; + var VALUE_REGEX = /^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/; + var SEMICOLON_REGEX = /^[;\s]*/; + + // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill + var TRIM_REGEX = /^\s+|\s+$/g; + + // strings + var NEWLINE = '\n'; + var FORWARD_SLASH = '/'; + var ASTERISK = '*'; + var EMPTY_STRING = ''; + + // types + var TYPE_COMMENT = 'comment'; + var TYPE_DECLARATION = 'declaration'; + + /** + * @param {String} style + * @param {Object} [options] + * @return {Object[]} + * @throws {TypeError} + * @throws {Error} + */ + function index (style, options) { + if (typeof style !== 'string') { + throw new TypeError('First argument must be a string'); + } + + if (!style) return []; + + options = options || {}; + + /** + * Positional. + */ + var lineno = 1; + var column = 1; + + /** + * Update lineno and column based on `str`. + * + * @param {String} str + */ + function updatePosition(str) { + var lines = str.match(NEWLINE_REGEX); + if (lines) lineno += lines.length; + var i = str.lastIndexOf(NEWLINE); + column = ~i ? str.length - i : column + str.length; + } + + /** + * Mark position and patch `node.position`. + * + * @return {Function} + */ + function position() { + var start = { line: lineno, column: column }; + return function (node) { + node.position = new Position(start); + whitespace(); + return node; + }; + } + + /** + * Store position information for a node. + * + * @constructor + * @property {Object} start + * @property {Object} end + * @property {undefined|String} source + */ + function Position(start) { + this.start = start; + this.end = { line: lineno, column: column }; + this.source = options.source; + } + + /** + * Non-enumerable source string. + */ + Position.prototype.content = style; + + /** + * Error `msg`. + * + * @param {String} msg + * @throws {Error} + */ + function error(msg) { + var err = new Error( + options.source + ':' + lineno + ':' + column + ': ' + msg + ); + err.reason = msg; + err.filename = options.source; + err.line = lineno; + err.column = column; + err.source = style; + + if (options.silent) ; else { + throw err; + } + } + + /** + * Match `re` and return captures. + * + * @param {RegExp} re + * @return {undefined|Array} + */ + function match(re) { + var m = re.exec(style); + if (!m) return; + var str = m[0]; + updatePosition(str); + style = style.slice(str.length); + return m; + } + + /** + * Parse whitespace. + */ + function whitespace() { + match(WHITESPACE_REGEX); + } + + /** + * Parse comments. + * + * @param {Object[]} [rules] + * @return {Object[]} + */ + function comments(rules) { + var c; + rules = rules || []; + while ((c = comment())) { + if (c !== false) { + rules.push(c); + } + } + return rules; + } + + /** + * Parse comment. + * + * @return {Object} + * @throws {Error} + */ + function comment() { + var pos = position(); + if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return; + + var i = 2; + while ( + EMPTY_STRING != style.charAt(i) && + (ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1)) + ) { + ++i; + } + i += 2; + + if (EMPTY_STRING === style.charAt(i - 1)) { + return error('End of comment missing'); + } + + var str = style.slice(2, i - 2); + column += 2; + updatePosition(str); + style = style.slice(i); + column += 2; + + return pos({ + type: TYPE_COMMENT, + comment: str + }); + } + + /** + * Parse declaration. + * + * @return {Object} + * @throws {Error} + */ + function declaration() { + var pos = position(); + + // prop + var prop = match(PROPERTY_REGEX); + if (!prop) return; + comment(); + + // : + if (!match(COLON_REGEX)) return error("property missing ':'"); + + // val + var val = match(VALUE_REGEX); + + var ret = pos({ + type: TYPE_DECLARATION, + property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)), + value: val + ? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING)) + : EMPTY_STRING + }); + + // ; + match(SEMICOLON_REGEX); + + return ret; + } + + /** + * Parse declarations. + * + * @return {Object[]} + */ + function declarations() { + var decls = []; + + comments(decls); + + // declarations + var decl; + while ((decl = declaration())) { + if (decl !== false) { + decls.push(decl); + comments(decls); + } + } + + return decls; + } + + whitespace(); + return declarations(); + } + + /** + * Trim `str`. + * + * @param {String} str + * @return {String} + */ + function trim(str) { + return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING; + } + + cjs$1 = index; + + return cjs$1; + } + + var hasRequiredCjs$1; + + function requireCjs$1 () { + if (hasRequiredCjs$1) return cjs$2; + hasRequiredCjs$1 = 1; + var __importDefault = (cjs$2 && cjs$2.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(cjs$2, "__esModule", { value: true }); + cjs$2.default = StyleToObject; + const inline_style_parser_1 = __importDefault(requireCjs$2()); + /** + * Parses inline style to object. + * + * @param style - Inline style. + * @param iterator - Iterator. + * @returns - Style object or null. + * + * @example Parsing inline style to object: + * + * ```js + * import parse from 'style-to-object'; + * parse('line-height: 42;'); // { 'line-height': '42' } + * ``` + */ + function StyleToObject(style, iterator) { + let styleObject = null; + if (!style || typeof style !== 'string') { + return styleObject; + } + const declarations = (0, inline_style_parser_1.default)(style); + const hasIterator = typeof iterator === 'function'; + declarations.forEach((declaration) => { + if (declaration.type !== 'declaration') { + return; + } + const { property, value } = declaration; + if (hasIterator) { + iterator(property, value, declaration); + } + else if (value) { + styleObject = styleObject || {}; + styleObject[property] = value; + } + }); + return styleObject; + } + + return cjs$2; + } + + var utilities = {}; + + var hasRequiredUtilities; + + function requireUtilities () { + if (hasRequiredUtilities) return utilities; + hasRequiredUtilities = 1; + Object.defineProperty(utilities, "__esModule", { value: true }); + utilities.camelCase = void 0; + var CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9_-]+$/; + var HYPHEN_REGEX = /-([a-z])/g; + var NO_HYPHEN_REGEX = /^[^-]+$/; + var VENDOR_PREFIX_REGEX = /^-(webkit|moz|ms|o|khtml)-/; + var MS_VENDOR_PREFIX_REGEX = /^-(ms)-/; + /** + * Checks whether to skip camelCase. + */ + var skipCamelCase = function (property) { + return !property || + NO_HYPHEN_REGEX.test(property) || + CUSTOM_PROPERTY_REGEX.test(property); + }; + /** + * Replacer that capitalizes first character. + */ + var capitalize = function (match, character) { + return character.toUpperCase(); + }; + /** + * Replacer that removes beginning hyphen of vendor prefix property. + */ + var trimHyphen = function (match, prefix) { return "".concat(prefix, "-"); }; + /** + * CamelCases a CSS property. + */ + var camelCase = function (property, options) { + if (options === void 0) { options = {}; } + if (skipCamelCase(property)) { + return property; + } + property = property.toLowerCase(); + if (options.reactCompat) { + // `-ms` vendor prefix should not be capitalized + property = property.replace(MS_VENDOR_PREFIX_REGEX, trimHyphen); + } + else { + // for non-React, remove first hyphen so vendor prefix is not capitalized + property = property.replace(VENDOR_PREFIX_REGEX, trimHyphen); + } + return property.replace(HYPHEN_REGEX, capitalize); + }; + utilities.camelCase = camelCase; + + return utilities; + } + + var cjs; + var hasRequiredCjs; + + function requireCjs () { + if (hasRequiredCjs) return cjs; + hasRequiredCjs = 1; + var __importDefault = (cjs && cjs.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + var style_to_object_1 = __importDefault(requireCjs$1()); + var utilities_1 = requireUtilities(); + /** + * Parses CSS inline style to JavaScript object (camelCased). + */ + function StyleToJS(style, options) { + var output = {}; + if (!style || typeof style !== 'string') { + return output; + } + (0, style_to_object_1.default)(style, function (property, value) { + // skip CSS comment + if (property && value) { + output[(0, utilities_1.camelCase)(property, options)] = value; + } + }); + return output; + } + StyleToJS.default = StyleToJS; + cjs = StyleToJS; + + return cjs; + } + + var cjsExports = requireCjs(); + var index = /*@__PURE__*/getDefaultExportFromCjs(cjsExports); + + return index; + +})); +//# sourceMappingURL=style-to-js.js.map diff --git a/node_modules/style-to-js/umd/style-to-js.js.map b/node_modules/style-to-js/umd/style-to-js.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8e7de56dad6fc58b22d52320c46ca8deb7d4f8cd --- /dev/null +++ b/node_modules/style-to-js/umd/style-to-js.js.map @@ -0,0 +1 @@ +{"version":3,"file":"style-to-js.js","sources":["../node_modules/inline-style-parser/cjs/index.js","../node_modules/style-to-object/cjs/index.js","../cjs/utilities.js","../cjs/index.js","../cjs/index.js?commonjs-entry"],"sourcesContent":["'use strict';\n\n// http://www.w3.org/TR/CSS21/grammar.html\n// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027\nvar COMMENT_REGEX = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\n\nvar NEWLINE_REGEX = /\\n/g;\nvar WHITESPACE_REGEX = /^\\s*/;\n\n// declaration\nvar PROPERTY_REGEX = /^(\\*?[-#/*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/;\nvar COLON_REGEX = /^:\\s*/;\nvar VALUE_REGEX = /^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^)]*?\\)|[^};])+)/;\nvar SEMICOLON_REGEX = /^[;\\s]*/;\n\n// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill\nvar TRIM_REGEX = /^\\s+|\\s+$/g;\n\n// strings\nvar NEWLINE = '\\n';\nvar FORWARD_SLASH = '/';\nvar ASTERISK = '*';\nvar EMPTY_STRING = '';\n\n// types\nvar TYPE_COMMENT = 'comment';\nvar TYPE_DECLARATION = 'declaration';\n\n/**\n * @param {String} style\n * @param {Object} [options]\n * @return {Object[]}\n * @throws {TypeError}\n * @throws {Error}\n */\nfunction index (style, options) {\n if (typeof style !== 'string') {\n throw new TypeError('First argument must be a string');\n }\n\n if (!style) return [];\n\n options = options || {};\n\n /**\n * Positional.\n */\n var lineno = 1;\n var column = 1;\n\n /**\n * Update lineno and column based on `str`.\n *\n * @param {String} str\n */\n function updatePosition(str) {\n var lines = str.match(NEWLINE_REGEX);\n if (lines) lineno += lines.length;\n var i = str.lastIndexOf(NEWLINE);\n column = ~i ? str.length - i : column + str.length;\n }\n\n /**\n * Mark position and patch `node.position`.\n *\n * @return {Function}\n */\n function position() {\n var start = { line: lineno, column: column };\n return function (node) {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n\n /**\n * Store position information for a node.\n *\n * @constructor\n * @property {Object} start\n * @property {Object} end\n * @property {undefined|String} source\n */\n function Position(start) {\n this.start = start;\n this.end = { line: lineno, column: column };\n this.source = options.source;\n }\n\n /**\n * Non-enumerable source string.\n */\n Position.prototype.content = style;\n\n /**\n * Error `msg`.\n *\n * @param {String} msg\n * @throws {Error}\n */\n function error(msg) {\n var err = new Error(\n options.source + ':' + lineno + ':' + column + ': ' + msg\n );\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = style;\n\n if (options.silent) ; else {\n throw err;\n }\n }\n\n /**\n * Match `re` and return captures.\n *\n * @param {RegExp} re\n * @return {undefined|Array}\n */\n function match(re) {\n var m = re.exec(style);\n if (!m) return;\n var str = m[0];\n updatePosition(str);\n style = style.slice(str.length);\n return m;\n }\n\n /**\n * Parse whitespace.\n */\n function whitespace() {\n match(WHITESPACE_REGEX);\n }\n\n /**\n * Parse comments.\n *\n * @param {Object[]} [rules]\n * @return {Object[]}\n */\n function comments(rules) {\n var c;\n rules = rules || [];\n while ((c = comment())) {\n if (c !== false) {\n rules.push(c);\n }\n }\n return rules;\n }\n\n /**\n * Parse comment.\n *\n * @return {Object}\n * @throws {Error}\n */\n function comment() {\n var pos = position();\n if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;\n\n var i = 2;\n while (\n EMPTY_STRING != style.charAt(i) &&\n (ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))\n ) {\n ++i;\n }\n i += 2;\n\n if (EMPTY_STRING === style.charAt(i - 1)) {\n return error('End of comment missing');\n }\n\n var str = style.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n style = style.slice(i);\n column += 2;\n\n return pos({\n type: TYPE_COMMENT,\n comment: str\n });\n }\n\n /**\n * Parse declaration.\n *\n * @return {Object}\n * @throws {Error}\n */\n function declaration() {\n var pos = position();\n\n // prop\n var prop = match(PROPERTY_REGEX);\n if (!prop) return;\n comment();\n\n // :\n if (!match(COLON_REGEX)) return error(\"property missing ':'\");\n\n // val\n var val = match(VALUE_REGEX);\n\n var ret = pos({\n type: TYPE_DECLARATION,\n property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),\n value: val\n ? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING))\n : EMPTY_STRING\n });\n\n // ;\n match(SEMICOLON_REGEX);\n\n return ret;\n }\n\n /**\n * Parse declarations.\n *\n * @return {Object[]}\n */\n function declarations() {\n var decls = [];\n\n comments(decls);\n\n // declarations\n var decl;\n while ((decl = declaration())) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n }\n\n return decls;\n }\n\n whitespace();\n return declarations();\n}\n\n/**\n * Trim `str`.\n *\n * @param {String} str\n * @return {String}\n */\nfunction trim(str) {\n return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING;\n}\n\nmodule.exports = index;\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = StyleToObject;\nconst inline_style_parser_1 = __importDefault(require(\"inline-style-parser\"));\n/**\n * Parses inline style to object.\n *\n * @param style - Inline style.\n * @param iterator - Iterator.\n * @returns - Style object or null.\n *\n * @example Parsing inline style to object:\n *\n * ```js\n * import parse from 'style-to-object';\n * parse('line-height: 42;'); // { 'line-height': '42' }\n * ```\n */\nfunction StyleToObject(style, iterator) {\n let styleObject = null;\n if (!style || typeof style !== 'string') {\n return styleObject;\n }\n const declarations = (0, inline_style_parser_1.default)(style);\n const hasIterator = typeof iterator === 'function';\n declarations.forEach((declaration) => {\n if (declaration.type !== 'declaration') {\n return;\n }\n const { property, value } = declaration;\n if (hasIterator) {\n iterator(property, value, declaration);\n }\n else if (value) {\n styleObject = styleObject || {};\n styleObject[property] = value;\n }\n });\n return styleObject;\n}\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.camelCase = void 0;\nvar CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9_-]+$/;\nvar HYPHEN_REGEX = /-([a-z])/g;\nvar NO_HYPHEN_REGEX = /^[^-]+$/;\nvar VENDOR_PREFIX_REGEX = /^-(webkit|moz|ms|o|khtml)-/;\nvar MS_VENDOR_PREFIX_REGEX = /^-(ms)-/;\n/**\n * Checks whether to skip camelCase.\n */\nvar skipCamelCase = function (property) {\n return !property ||\n NO_HYPHEN_REGEX.test(property) ||\n CUSTOM_PROPERTY_REGEX.test(property);\n};\n/**\n * Replacer that capitalizes first character.\n */\nvar capitalize = function (match, character) {\n return character.toUpperCase();\n};\n/**\n * Replacer that removes beginning hyphen of vendor prefix property.\n */\nvar trimHyphen = function (match, prefix) { return \"\".concat(prefix, \"-\"); };\n/**\n * CamelCases a CSS property.\n */\nvar camelCase = function (property, options) {\n if (options === void 0) { options = {}; }\n if (skipCamelCase(property)) {\n return property;\n }\n property = property.toLowerCase();\n if (options.reactCompat) {\n // `-ms` vendor prefix should not be capitalized\n property = property.replace(MS_VENDOR_PREFIX_REGEX, trimHyphen);\n }\n else {\n // for non-React, remove first hyphen so vendor prefix is not capitalized\n property = property.replace(VENDOR_PREFIX_REGEX, trimHyphen);\n }\n return property.replace(HYPHEN_REGEX, capitalize);\n};\nexports.camelCase = camelCase;\n//# sourceMappingURL=utilities.js.map","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar style_to_object_1 = __importDefault(require(\"style-to-object\"));\nvar utilities_1 = require(\"./utilities\");\n/**\n * Parses CSS inline style to JavaScript object (camelCased).\n */\nfunction StyleToJS(style, options) {\n var output = {};\n if (!style || typeof style !== 'string') {\n return output;\n }\n (0, style_to_object_1.default)(style, function (property, value) {\n // skip CSS comment\n if (property && value) {\n output[(0, utilities_1.camelCase)(property, options)] = value;\n }\n });\n return output;\n}\nStyleToJS.default = StyleToJS;\nmodule.exports = StyleToJS;\n//# sourceMappingURL=index.js.map","import { getDefaultExportFromCjs } from \"\u0000commonjsHelpers.js\";\nimport { __require as requireCjs } from \"/home/runner/work/style-to-js/style-to-js/cjs/index.js\";\nvar cjsExports = requireCjs();\nexport { cjsExports as __moduleExports };\nexport default /*@__PURE__*/getDefaultExportFromCjs(cjsExports);"],"names":["cjs","this","require$$0","require$$1"],"mappings":";;;;;;;;;;;;;;;;;;;CAEA;CACA;EACA,IAAI,aAAa,GAAG,iCAAiC;;EAErD,IAAI,aAAa,GAAG,KAAK;EACzB,IAAI,gBAAgB,GAAG,MAAM;;CAE7B;EACA,IAAI,cAAc,GAAG,wCAAwC;EAC7D,IAAI,WAAW,GAAG,OAAO;EACzB,IAAI,WAAW,GAAG,sDAAsD;EACxE,IAAI,eAAe,GAAG,SAAS;;CAE/B;EACA,IAAI,UAAU,GAAG,YAAY;;CAE7B;EACA,IAAI,OAAO,GAAG,IAAI;EAClB,IAAI,aAAa,GAAG,GAAG;EACvB,IAAI,QAAQ,GAAG,GAAG;EAClB,IAAI,YAAY,GAAG,EAAE;;CAErB;EACA,IAAI,YAAY,GAAG,SAAS;EAC5B,IAAI,gBAAgB,GAAG,aAAa;;CAEpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA,CAAA,SAAS,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE;CAChC,GAAE,IAAI,OAAO,KAAK,KAA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,UAAU,CAAC;;;;;;;;","x_google_ignoreList":[0,1]} \ No newline at end of file diff --git a/node_modules/style-to-js/umd/style-to-js.min.js b/node_modules/style-to-js/umd/style-to-js.min.js new file mode 100644 index 0000000000000000000000000000000000000000..e5f0d6adda43f73e4432375207c69a5990b4f5b5 --- /dev/null +++ b/node_modules/style-to-js/umd/style-to-js.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).StyleToJS=t()}(this,(function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t,r,n,o={};function u(){if(n)return o;n=1;var e=o&&o.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(o,"__esModule",{value:!0}),o.default=function(e,t){let r=null;if(!e||"string"!=typeof e)return r;const n=(0,u.default)(e),o="function"==typeof t;return n.forEach((e=>{if("declaration"!==e.type)return;const{property:n,value:u}=e;o?t(n,u,e):u&&(r=r||{},r[n]=u)})),r};const u=e(function(){if(r)return t;r=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,o=/^\s*/,u=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,a=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,f=/^\s+|\s+$/g,l="";function s(e){return e?e.replace(f,l):l}return t=function(t,r){if("string"!=typeof t)throw new TypeError("First argument must be a string");if(!t)return[];r=r||{};var f=1,p=1;function d(e){var t=e.match(n);t&&(f+=t.length);var r=e.lastIndexOf("\n");p=~r?e.length-r:p+e.length}function m(){var e={line:f,column:p};return function(t){return t.position=new v(e),g(),t}}function v(e){this.start=e,this.end={line:f,column:p},this.source=r.source}function h(e){var n=new Error(r.source+":"+f+":"+p+": "+e);if(n.reason=e,n.filename=r.source,n.line=f,n.column=p,n.source=t,!r.silent)throw n}function y(e){var r=e.exec(t);if(r){var n=r[0];return d(n),t=t.slice(n.length),r}}function g(){y(o)}function _(e){var t;for(e=e||[];t=w();)!1!==t&&e.push(t);return e}function w(){var e=m();if("/"==t.charAt(0)&&"*"==t.charAt(1)){for(var r=2;l!=t.charAt(r)&&("*"!=t.charAt(r)||"/"!=t.charAt(r+1));)++r;if(r+=2,l===t.charAt(r-1))return h("End of comment missing");var n=t.slice(2,r-2);return p+=2,d(n),t=t.slice(r),p+=2,e({type:"comment",comment:n})}}function b(){var t=m(),r=y(u);if(r){if(w(),!y(i))return h("property missing ':'");var n=y(a),o=t({type:"declaration",property:s(r[0].replace(e,l)),value:n?s(n[0].replace(e,l)):l});return y(c),o}}return v.prototype.content=t,g(),function(){var e,t=[];for(_(t);e=b();)!1!==e&&(t.push(e),_(t));return t}()}}());return o}var i,a,c,f={};function l(){if(i)return f;i=1,Object.defineProperty(f,"__esModule",{value:!0}),f.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,o=/^-(ms)-/,u=function(e,t){return t.toUpperCase()},a=function(e,t){return"".concat(t,"-")};return f.camelCase=function(i,c){return void 0===c&&(c={}),function(t){return!t||r.test(t)||e.test(t)}(i)?i:(i=i.toLowerCase(),(i=c.reactCompat?i.replace(o,a):i.replace(n,a)).replace(t,u))},f}return e(function(){if(c)return a;c=1;var e=(a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(u()),t=l();function r(r,n){var o={};return r&&"string"==typeof r?((0,e.default)(r,(function(e,r){e&&r&&(o[(0,t.camelCase)(e,n)]=r)})),o):o}return r.default=r,a=r}())})); +//# sourceMappingURL=style-to-js.min.js.map diff --git a/node_modules/style-to-js/umd/style-to-js.min.js.map b/node_modules/style-to-js/umd/style-to-js.min.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5b5ca23df8cdf31bf1bf5235516a4c444359ce6a --- /dev/null +++ b/node_modules/style-to-js/umd/style-to-js.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"style-to-js.min.js","sources":["../node_modules/style-to-object/cjs/index.js","../node_modules/inline-style-parser/cjs/index.js","../cjs/utilities.js","../cjs/index.js?commonjs-entry","../cjs/index.js"],"sourcesContent":["\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = StyleToObject;\nconst inline_style_parser_1 = __importDefault(require(\"inline-style-parser\"));\n/**\n * Parses inline style to object.\n *\n * @param style - Inline style.\n * @param iterator - Iterator.\n * @returns - Style object or null.\n *\n * @example Parsing inline style to object:\n *\n * ```js\n * import parse from 'style-to-object';\n * parse('line-height: 42;'); // { 'line-height': '42' }\n * ```\n */\nfunction StyleToObject(style, iterator) {\n let styleObject = null;\n if (!style || typeof style !== 'string') {\n return styleObject;\n }\n const declarations = (0, inline_style_parser_1.default)(style);\n const hasIterator = typeof iterator === 'function';\n declarations.forEach((declaration) => {\n if (declaration.type !== 'declaration') {\n return;\n }\n const { property, value } = declaration;\n if (hasIterator) {\n iterator(property, value, declaration);\n }\n else if (value) {\n styleObject = styleObject || {};\n styleObject[property] = value;\n }\n });\n return styleObject;\n}\n//# sourceMappingURL=index.js.map","'use strict';\n\n// http://www.w3.org/TR/CSS21/grammar.html\n// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027\nvar COMMENT_REGEX = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\n\nvar NEWLINE_REGEX = /\\n/g;\nvar WHITESPACE_REGEX = /^\\s*/;\n\n// declaration\nvar PROPERTY_REGEX = /^(\\*?[-#/*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/;\nvar COLON_REGEX = /^:\\s*/;\nvar VALUE_REGEX = /^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^)]*?\\)|[^};])+)/;\nvar SEMICOLON_REGEX = /^[;\\s]*/;\n\n// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill\nvar TRIM_REGEX = /^\\s+|\\s+$/g;\n\n// strings\nvar NEWLINE = '\\n';\nvar FORWARD_SLASH = '/';\nvar ASTERISK = '*';\nvar EMPTY_STRING = '';\n\n// types\nvar TYPE_COMMENT = 'comment';\nvar TYPE_DECLARATION = 'declaration';\n\n/**\n * @param {String} style\n * @param {Object} [options]\n * @return {Object[]}\n * @throws {TypeError}\n * @throws {Error}\n */\nfunction index (style, options) {\n if (typeof style !== 'string') {\n throw new TypeError('First argument must be a string');\n }\n\n if (!style) return [];\n\n options = options || {};\n\n /**\n * Positional.\n */\n var lineno = 1;\n var column = 1;\n\n /**\n * Update lineno and column based on `str`.\n *\n * @param {String} str\n */\n function updatePosition(str) {\n var lines = str.match(NEWLINE_REGEX);\n if (lines) lineno += lines.length;\n var i = str.lastIndexOf(NEWLINE);\n column = ~i ? str.length - i : column + str.length;\n }\n\n /**\n * Mark position and patch `node.position`.\n *\n * @return {Function}\n */\n function position() {\n var start = { line: lineno, column: column };\n return function (node) {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n\n /**\n * Store position information for a node.\n *\n * @constructor\n * @property {Object} start\n * @property {Object} end\n * @property {undefined|String} source\n */\n function Position(start) {\n this.start = start;\n this.end = { line: lineno, column: column };\n this.source = options.source;\n }\n\n /**\n * Non-enumerable source string.\n */\n Position.prototype.content = style;\n\n /**\n * Error `msg`.\n *\n * @param {String} msg\n * @throws {Error}\n */\n function error(msg) {\n var err = new Error(\n options.source + ':' + lineno + ':' + column + ': ' + msg\n );\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = style;\n\n if (options.silent) ; else {\n throw err;\n }\n }\n\n /**\n * Match `re` and return captures.\n *\n * @param {RegExp} re\n * @return {undefined|Array}\n */\n function match(re) {\n var m = re.exec(style);\n if (!m) return;\n var str = m[0];\n updatePosition(str);\n style = style.slice(str.length);\n return m;\n }\n\n /**\n * Parse whitespace.\n */\n function whitespace() {\n match(WHITESPACE_REGEX);\n }\n\n /**\n * Parse comments.\n *\n * @param {Object[]} [rules]\n * @return {Object[]}\n */\n function comments(rules) {\n var c;\n rules = rules || [];\n while ((c = comment())) {\n if (c !== false) {\n rules.push(c);\n }\n }\n return rules;\n }\n\n /**\n * Parse comment.\n *\n * @return {Object}\n * @throws {Error}\n */\n function comment() {\n var pos = position();\n if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;\n\n var i = 2;\n while (\n EMPTY_STRING != style.charAt(i) &&\n (ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))\n ) {\n ++i;\n }\n i += 2;\n\n if (EMPTY_STRING === style.charAt(i - 1)) {\n return error('End of comment missing');\n }\n\n var str = style.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n style = style.slice(i);\n column += 2;\n\n return pos({\n type: TYPE_COMMENT,\n comment: str\n });\n }\n\n /**\n * Parse declaration.\n *\n * @return {Object}\n * @throws {Error}\n */\n function declaration() {\n var pos = position();\n\n // prop\n var prop = match(PROPERTY_REGEX);\n if (!prop) return;\n comment();\n\n // :\n if (!match(COLON_REGEX)) return error(\"property missing ':'\");\n\n // val\n var val = match(VALUE_REGEX);\n\n var ret = pos({\n type: TYPE_DECLARATION,\n property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),\n value: val\n ? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING))\n : EMPTY_STRING\n });\n\n // ;\n match(SEMICOLON_REGEX);\n\n return ret;\n }\n\n /**\n * Parse declarations.\n *\n * @return {Object[]}\n */\n function declarations() {\n var decls = [];\n\n comments(decls);\n\n // declarations\n var decl;\n while ((decl = declaration())) {\n if (decl !== false) {\n decls.push(decl);\n comments(decls);\n }\n }\n\n return decls;\n }\n\n whitespace();\n return declarations();\n}\n\n/**\n * Trim `str`.\n *\n * @param {String} str\n * @return {String}\n */\nfunction trim(str) {\n return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING;\n}\n\nmodule.exports = index;\n//# sourceMappingURL=index.js.map\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.camelCase = void 0;\nvar CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9_-]+$/;\nvar HYPHEN_REGEX = /-([a-z])/g;\nvar NO_HYPHEN_REGEX = /^[^-]+$/;\nvar VENDOR_PREFIX_REGEX = /^-(webkit|moz|ms|o|khtml)-/;\nvar MS_VENDOR_PREFIX_REGEX = /^-(ms)-/;\n/**\n * Checks whether to skip camelCase.\n */\nvar skipCamelCase = function (property) {\n return !property ||\n NO_HYPHEN_REGEX.test(property) ||\n CUSTOM_PROPERTY_REGEX.test(property);\n};\n/**\n * Replacer that capitalizes first character.\n */\nvar capitalize = function (match, character) {\n return character.toUpperCase();\n};\n/**\n * Replacer that removes beginning hyphen of vendor prefix property.\n */\nvar trimHyphen = function (match, prefix) { return \"\".concat(prefix, \"-\"); };\n/**\n * CamelCases a CSS property.\n */\nvar camelCase = function (property, options) {\n if (options === void 0) { options = {}; }\n if (skipCamelCase(property)) {\n return property;\n }\n property = property.toLowerCase();\n if (options.reactCompat) {\n // `-ms` vendor prefix should not be capitalized\n property = property.replace(MS_VENDOR_PREFIX_REGEX, trimHyphen);\n }\n else {\n // for non-React, remove first hyphen so vendor prefix is not capitalized\n property = property.replace(VENDOR_PREFIX_REGEX, trimHyphen);\n }\n return property.replace(HYPHEN_REGEX, capitalize);\n};\nexports.camelCase = camelCase;\n//# sourceMappingURL=utilities.js.map","import { getDefaultExportFromCjs } from \"\u0000commonjsHelpers.js\";\nimport { __require as requireCjs } from \"/home/runner/work/style-to-js/style-to-js/cjs/index.js\";\nvar cjsExports = requireCjs();\nexport { cjsExports as __moduleExports };\nexport default /*@__PURE__*/getDefaultExportFromCjs(cjsExports);","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar style_to_object_1 = __importDefault(require(\"style-to-object\"));\nvar utilities_1 = require(\"./utilities\");\n/**\n * Parses CSS inline style to JavaScript object (camelCased).\n */\nfunction StyleToJS(style, options) {\n var output = {};\n if (!style || typeof style !== 'string') {\n return output;\n }\n (0, style_to_object_1.default)(style, function (property, value) {\n // skip CSS comment\n if (property && value) {\n output[(0, utilities_1.camelCase)(property, options)] = value;\n }\n });\n return output;\n}\nStyleToJS.default = StyleToJS;\nmodule.exports = StyleToJS;\n//# sourceMappingURL=index.js.map"],"names":["__importDefault","this","mod","__esModule","default","Object","defineProperty","cjs","value","style","iterator","styleObject","declarations","inline_style_parser_1","hasIterator","forEach","declaration","type","property","COMMENT_REGEX","NEWLINE_REGEX","WHITESPACE_REGEX","PROPERTY_REGEX","COLON_REGEX","VALUE_REGEX","SEMICOLON_REGEX","TRIM_REGEX","EMPTY_STRING","trim","str","replace","options","TypeError","lineno","column","updatePosition","lines","match","length","i","lastIndexOf","position","start","line","node","Position","whitespace","end","source","error","msg","err","Error","reason","filename","silent","re","m","exec","slice","comments","rules","c","comment","push","pos","charAt","prop","val","ret","prototype","content","decl","decls","require$$0","utilities","camelCase","CUSTOM_PROPERTY_REGEX","HYPHEN_REGEX","NO_HYPHEN_REGEX","VENDOR_PREFIX_REGEX","MS_VENDOR_PREFIX_REGEX","capitalize","character","toUpperCase","trimHyphen","prefix","concat","test","skipCamelCase","toLowerCase","reactCompat","getDefaultExportFromCjs","style_to_object_1","utilities_1","require$$1","StyleToJS","output","requireCjs"],"mappings":"4XACA,IAAIA,EAAmBC,GAAQA,EAAKD,iBAAoB,SAAUE,GAC9D,OAAQA,GAAOA,EAAIC,WAAcD,EAAM,CAAEE,QAAWF,EACxD,EACAG,OAAOC,eAAeC,EAAS,aAAc,CAAEC,OAAO,IACtDD,EAAAH,QAgBA,SAAuBK,EAAOC,GAC1B,IAAIC,EAAc,KAClB,IAAK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E,EAAS,CAAA,EACb,OAAKxF,GAA0B,iBAAVA,IAGrB,EAAIoF,EAAkBzF,SAASK,GAAO,SAAUS,EAAUV,GAElDU,GAAYV,IACZyF,GAAO,EAAIH,EAAYlB,WAAW1D,EAAUa,IAAYvB,EAEpE,IACWyF,GARIA,CASf,QACAD,EAAU5F,QAAU4F,EACpBzF,EAAiByF,EDrBAE","x_google_ignoreList":[0,1]} \ No newline at end of file diff --git a/node_modules/style-to-object/LICENSE b/node_modules/style-to-object/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e1090121f38db6c3da72dd438d025bed062de5d1 --- /dev/null +++ b/node_modules/style-to-object/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2017 Menglin "Mark" Xu + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/style-to-object/README.md b/node_modules/style-to-object/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9172d1f1d89e7f37850e068d197434272c354f9a --- /dev/null +++ b/node_modules/style-to-object/README.md @@ -0,0 +1,188 @@ +# style-to-object + +[![NPM](https://nodei.co/npm/style-to-object.png)](https://nodei.co/npm/style-to-object/) + +[![NPM version](https://img.shields.io/npm/v/style-to-object)](https://www.npmjs.com/package/style-to-object) +[![NPM bundle size](https://img.shields.io/bundlephobia/minzip/style-to-object)](https://bundlephobia.com/package/style-to-object) +[![build](https://github.com/remarkablemark/style-to-object/actions/workflows/build.yml/badge.svg)](https://github.com/remarkablemark/style-to-object/actions/workflows/build.yml) +[![codecov](https://codecov.io/gh/remarkablemark/style-to-object/branch/master/graph/badge.svg?token=XWxph9dpa4)](https://codecov.io/gh/remarkablemark/style-to-object) +[![NPM downloads](https://img.shields.io/npm/dm/style-to-object)](https://www.npmjs.com/package/style-to-object) + +Parse CSS inline style to JavaScript object: + +```js +import parse from 'style-to-object'; + +parse('color: #C0FFEE; background: #BADA55;'); +``` + +Output: + +```js +{ color: '#C0FFEE', background: '#BADA55' } +``` + +[JSFiddle](https://jsfiddle.net/remarkablemark/ykz2meot/) | [Examples](https://github.com/remarkablemark/style-to-object/tree/master/examples) + +## Installation + +[NPM](https://www.npmjs.com/package/style-to-object): + +```sh +npm install style-to-object --save +``` + +[Yarn](https://yarn.fyi/style-to-object): + +```sh +yarn add style-to-object +``` + +[CDN](https://unpkg.com/style-to-object/): + +```html + + +``` + +## Usage + +Import with ES Modules: + +```js +import parse from 'style-to-object'; +``` + +Require with CommonJS: + +```js +const parse = require('style-to-object').default; +``` + +Parse single declaration: + +```js +parse('line-height: 42'); +``` + +Output: + +```js +{ 'line-height': '42' } +``` + +Parse multiple declarations: + +```js +parse(` + border-color: #ACE; + z-index: 1337; +`); +``` + +Output: + +```js +{ 'border-color': '#ACE', 'z-index': '1337' } +``` + +Parse unknown declarations: + +```js +parse('answer: 42;'); +``` + +Output: + +```js +{ 'answer': '42' } +``` + +Invalid declarations/arguments: + + + +```js +parse(` + top: ; + right: 1em; +`); // { right: '1em' } + +parse(); // null +parse(null); // null +parse(1); // null +parse(true); // null +parse('top:'); // null +parse(':12px'); // null +parse(':'); // null +parse(';'); // null + +parse('top'); // throws Error +parse('/*'); // throws Error +``` + + + +### Iterator + +If the 2nd argument is a function, then the parser will return `null`: + +```js +parse('color: #f00', () => {}); // null +``` + +But the function will iterate through each declaration: + + + +```js +parse('color: #f00', (name, value, declaration) => { + console.log(name); // 'color' + console.log(value); // '#f00' + console.log(declaration); // { type: 'declaration', property: 'color', value: '#f00' } +}); +``` + + + +This makes it easy to customize the output: + +```js +const style = ` + color: red; + background: blue; +`; +const output = []; + +function iterator(name, value) { + output.push([name, value]); +} + +parse(style, iterator); +console.log(output); // [['color', 'red'], ['background', 'blue']] +``` + +## Migration + +### v1 + +Migrated to TypeScript. Iterator excludes `Comment`. CommonJS requires the `.default` key: + +```js +const parse = require('style-to-object').default; +``` + +## Release + +Release and publish are automated by [Release Please](https://github.com/googleapis/release-please). + +## Special Thanks + +- [inline-style-parser](https://github.com/remarkablemark/inline-style-parser) +- [Contributors](https://github.com/remarkablemark/style-to-object/graphs/contributors) + +## License + +[MIT](https://github.com/remarkablemark/style-to-object/blob/master/LICENSE) diff --git a/node_modules/style-to-object/cjs/index.d.ts b/node_modules/style-to-object/cjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8804e046fda128e3de6ab5b6efbe29c99ab910cb --- /dev/null +++ b/node_modules/style-to-object/cjs/index.d.ts @@ -0,0 +1,22 @@ +import type { Declaration } from 'inline-style-parser'; +export { Declaration }; +export interface StyleObject { + [name: string]: string; +} +type Iterator = (property: string, value: string, declaration: Declaration) => void; +/** + * Parses inline style to object. + * + * @param style - Inline style. + * @param iterator - Iterator. + * @returns - Style object or null. + * + * @example Parsing inline style to object: + * + * ```js + * import parse from 'style-to-object'; + * parse('line-height: 42;'); // { 'line-height': '42' } + * ``` + */ +export default function StyleToObject(style: string, iterator?: Iterator): StyleObject | null; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/style-to-object/cjs/index.d.ts.map b/node_modules/style-to-object/cjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..10f038cc2e94b414b386e0279d99983c7df4883a --- /dev/null +++ b/node_modules/style-to-object/cjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAGvD,OAAO,EAAE,WAAW,EAAE,CAAC;AAEvB,MAAM,WAAW,WAAW;IAC1B,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;CACxB;AAED,KAAK,QAAQ,GAAG,CACd,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,WAAW,KACrB,IAAI,CAAC;AAEV;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CACnC,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,QAAQ,GAClB,WAAW,GAAG,IAAI,CA0BpB"} \ No newline at end of file diff --git a/node_modules/style-to-object/cjs/index.js b/node_modules/style-to-object/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ddc74fc8106f16da53f65cbb2d3e5124c7ffd1e1 --- /dev/null +++ b/node_modules/style-to-object/cjs/index.js @@ -0,0 +1,44 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = StyleToObject; +const inline_style_parser_1 = __importDefault(require("inline-style-parser")); +/** + * Parses inline style to object. + * + * @param style - Inline style. + * @param iterator - Iterator. + * @returns - Style object or null. + * + * @example Parsing inline style to object: + * + * ```js + * import parse from 'style-to-object'; + * parse('line-height: 42;'); // { 'line-height': '42' } + * ``` + */ +function StyleToObject(style, iterator) { + let styleObject = null; + if (!style || typeof style !== 'string') { + return styleObject; + } + const declarations = (0, inline_style_parser_1.default)(style); + const hasIterator = typeof iterator === 'function'; + declarations.forEach((declaration) => { + if (declaration.type !== 'declaration') { + return; + } + const { property, value } = declaration; + if (hasIterator) { + iterator(property, value, declaration); + } + else if (value) { + styleObject = styleObject || {}; + styleObject[property] = value; + } + }); + return styleObject; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/style-to-object/cjs/index.js.map b/node_modules/style-to-object/cjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..55f505e00cce412e39744aac5f31780db66dacf8 --- /dev/null +++ b/node_modules/style-to-object/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AA6BA,gCA6BC;AAzDD,8EAAwC;AAcxC;;;;;;;;;;;;;GAaG;AACH,SAAwB,aAAa,CACnC,KAAa,EACb,QAAmB;IAEnB,IAAI,WAAW,GAAuB,IAAI,CAAC;IAE3C,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,MAAM,YAAY,GAAG,IAAA,6BAAK,EAAC,KAAK,CAAC,CAAC;IAClC,MAAM,WAAW,GAAG,OAAO,QAAQ,KAAK,UAAU,CAAC;IAEnD,YAAY,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,EAAE;QACnC,IAAI,WAAW,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;YACvC,OAAO;QACT,CAAC;QAED,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,WAAW,CAAC;QAExC,IAAI,WAAW,EAAE,CAAC;YAChB,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;QACzC,CAAC;aAAM,IAAI,KAAK,EAAE,CAAC;YACjB,WAAW,GAAG,WAAW,IAAI,EAAE,CAAC;YAChC,WAAW,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;QAChC,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/node_modules/style-to-object/esm/index.d.ts b/node_modules/style-to-object/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8804e046fda128e3de6ab5b6efbe29c99ab910cb --- /dev/null +++ b/node_modules/style-to-object/esm/index.d.ts @@ -0,0 +1,22 @@ +import type { Declaration } from 'inline-style-parser'; +export { Declaration }; +export interface StyleObject { + [name: string]: string; +} +type Iterator = (property: string, value: string, declaration: Declaration) => void; +/** + * Parses inline style to object. + * + * @param style - Inline style. + * @param iterator - Iterator. + * @returns - Style object or null. + * + * @example Parsing inline style to object: + * + * ```js + * import parse from 'style-to-object'; + * parse('line-height: 42;'); // { 'line-height': '42' } + * ``` + */ +export default function StyleToObject(style: string, iterator?: Iterator): StyleObject | null; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/style-to-object/esm/index.d.ts.map b/node_modules/style-to-object/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..10f038cc2e94b414b386e0279d99983c7df4883a --- /dev/null +++ b/node_modules/style-to-object/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAGvD,OAAO,EAAE,WAAW,EAAE,CAAC;AAEvB,MAAM,WAAW,WAAW;IAC1B,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;CACxB;AAED,KAAK,QAAQ,GAAG,CACd,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,WAAW,KACrB,IAAI,CAAC;AAEV;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CACnC,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,QAAQ,GAClB,WAAW,GAAG,IAAI,CA0BpB"} \ No newline at end of file diff --git a/node_modules/style-to-object/esm/index.js b/node_modules/style-to-object/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e774a1842d6059a1333be083217e37bfa282856f --- /dev/null +++ b/node_modules/style-to-object/esm/index.js @@ -0,0 +1,38 @@ +import parse from 'inline-style-parser'; +/** + * Parses inline style to object. + * + * @param style - Inline style. + * @param iterator - Iterator. + * @returns - Style object or null. + * + * @example Parsing inline style to object: + * + * ```js + * import parse from 'style-to-object'; + * parse('line-height: 42;'); // { 'line-height': '42' } + * ``` + */ +export default function StyleToObject(style, iterator) { + let styleObject = null; + if (!style || typeof style !== 'string') { + return styleObject; + } + const declarations = parse(style); + const hasIterator = typeof iterator === 'function'; + declarations.forEach((declaration) => { + if (declaration.type !== 'declaration') { + return; + } + const { property, value } = declaration; + if (hasIterator) { + iterator(property, value, declaration); + } + else if (value) { + styleObject = styleObject || {}; + styleObject[property] = value; + } + }); + return styleObject; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/style-to-object/esm/index.js.map b/node_modules/style-to-object/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..5f7670bc1b2562d036e4b3967341ee4e11326312 --- /dev/null +++ b/node_modules/style-to-object/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,qBAAqB,CAAC;AAcxC;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CACnC,KAAa,EACb,QAAmB;IAEnB,IAAI,WAAW,GAAuB,IAAI,CAAC;IAE3C,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;IAClC,MAAM,WAAW,GAAG,OAAO,QAAQ,KAAK,UAAU,CAAC;IAEnD,YAAY,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,EAAE;QACnC,IAAI,WAAW,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;YACvC,OAAO;QACT,CAAC;QAED,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,WAAW,CAAC;QAExC,IAAI,WAAW,EAAE,CAAC;YAChB,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;QACzC,CAAC;aAAM,IAAI,KAAK,EAAE,CAAC;YACjB,WAAW,GAAG,WAAW,IAAI,EAAE,CAAC;YAChC,WAAW,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;QAChC,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/node_modules/style-to-object/esm/index.mjs b/node_modules/style-to-object/esm/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9db01cbbca8696327467f62b429f6763edc6e9e4 --- /dev/null +++ b/node_modules/style-to-object/esm/index.mjs @@ -0,0 +1,41 @@ +import parse from 'inline-style-parser'; + +/** + * Parses inline style to object. + * + * @param style - Inline style. + * @param iterator - Iterator. + * @returns - Style object or null. + * + * @example Parsing inline style to object: + * + * ```js + * import parse from 'style-to-object'; + * parse('line-height: 42;'); // { 'line-height': '42' } + * ``` + */ +function StyleToObject(style, iterator) { + let styleObject = null; + if (!style || typeof style !== 'string') { + return styleObject; + } + const declarations = parse(style); + const hasIterator = typeof iterator === 'function'; + declarations.forEach((declaration) => { + if (declaration.type !== 'declaration') { + return; + } + const { property, value } = declaration; + if (hasIterator) { + iterator(property, value, declaration); + } + else if (value) { + styleObject = styleObject || {}; + styleObject[property] = value; + } + }); + return styleObject; +} + +export { StyleToObject as default }; +//# sourceMappingURL=index.mjs.map diff --git a/node_modules/style-to-object/esm/index.mjs.map b/node_modules/style-to-object/esm/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..4004121a0e9bff2307cd050e7af2940894742097 --- /dev/null +++ b/node_modules/style-to-object/esm/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":[null],"names":[],"mappings":";;AAeA;;;;;;;;;;;;;AAaG;AACW,SAAU,aAAa,CACnC,KAAa,EACb,QAAmB,EAAA;IAEnB,IAAI,WAAW,GAAuB,IAAI;IAE1C,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AACvC,QAAA,OAAO,WAAW;IACpB;AAEA,IAAA,MAAM,YAAY,GAAG,KAAK,CAAC,KAAK,CAAC;AACjC,IAAA,MAAM,WAAW,GAAG,OAAO,QAAQ,KAAK,UAAU;AAElD,IAAA,YAAY,CAAC,OAAO,CAAC,CAAC,WAAW,KAAI;AACnC,QAAA,IAAI,WAAW,CAAC,IAAI,KAAK,aAAa,EAAE;YACtC;QACF;AAEA,QAAA,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,WAAW;QAEvC,IAAI,WAAW,EAAE;AACf,YAAA,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,WAAW,CAAC;QACxC;aAAO,IAAI,KAAK,EAAE;AAChB,YAAA,WAAW,GAAG,WAAW,IAAI,EAAE;AAC/B,YAAA,WAAW,CAAC,QAAQ,CAAC,GAAG,KAAK;QAC/B;AACF,IAAA,CAAC,CAAC;AAEF,IAAA,OAAO,WAAW;AACpB;;;;"} \ No newline at end of file diff --git a/node_modules/style-to-object/package.json b/node_modules/style-to-object/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ea5da98402134e8d31a59017b8d7617878673f08 --- /dev/null +++ b/node_modules/style-to-object/package.json @@ -0,0 +1,92 @@ +{ + "name": "style-to-object", + "version": "1.0.14", + "description": "Parse CSS inline style to JavaScript object.", + "author": "Mark ", + "main": "./cjs/index.js", + "module": "./esm/index.mjs", + "types": "./esm/index.d.ts", + "exports": { + "import": { + "types": "./esm/index.d.ts", + "default": "./esm/index.mjs" + }, + "require": { + "types": "./cjs/index.d.ts", + "default": "./cjs/index.js" + } + }, + "scripts": { + "build": "run-s build:*", + "build:cjs": "tsc --project tsconfig.cjs.json", + "build:esm": "tsc --project tsconfig.json", + "build:umd": "rollup --config --failAfterWarnings", + "clean": "rm -rf cjs coverage dist esm", + "lint": "eslint .", + "lint:fix": "npm run lint -- --fix", + "lint:package": "publint", + "lint:tsc": "tsc --noEmit", + "prepare": "husky", + "prepublishOnly": "run-s lint lint:tsc test clean build", + "test": "jest", + "test:ci": "CI=true jest --ci --colors --coverage", + "test:esm": "npm run build && node --test **/*.test.mjs", + "test:watch": "npm run test -- --watch" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/remarkablemark/style-to-object.git" + }, + "bugs": { + "url": "https://github.com/remarkablemark/style-to-object/issues" + }, + "keywords": [ + "style-to-object", + "inline", + "style", + "parser", + "css", + "object", + "pojo" + ], + "dependencies": { + "inline-style-parser": "0.2.7" + }, + "devDependencies": { + "@commitlint/cli": "20.1.0", + "@commitlint/config-conventional": "20.0.0", + "@eslint/compat": "2.0.0", + "@eslint/eslintrc": "3.3.1", + "@eslint/js": "9.39.1", + "@rollup/plugin-commonjs": "29.0.0", + "@rollup/plugin-node-resolve": "16.0.3", + "@rollup/plugin-terser": "0.4.4", + "@rollup/plugin-typescript": "12.3.0", + "@types/jest": "30.0.0", + "@types/node": "24.10.1", + "@typescript-eslint/eslint-plugin": "8.46.4", + "@typescript-eslint/parser": "8.46.4", + "eslint": "9.39.1", + "eslint-plugin-prettier": "5.5.4", + "eslint-plugin-simple-import-sort": "12.1.1", + "globals": "16.5.0", + "husky": "9.1.7", + "jest": "30.2.0", + "lint-staged": "16.2.6", + "npm-run-all": "4.1.5", + "prettier": "3.6.2", + "publint": "0.3.15", + "rollup": "4.53.2", + "ts-jest": "29.4.5", + "ts-node": "10.9.2", + "tslib": "2.8.1", + "typescript": "5.9.3" + }, + "files": [ + "/cjs", + "/dist", + "/esm", + "/src" + ], + "license": "MIT" +} diff --git a/node_modules/style-to-object/src/index.ts b/node_modules/style-to-object/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..98b95a61bacb59f88a33679505b24816bcd665b5 --- /dev/null +++ b/node_modules/style-to-object/src/index.ts @@ -0,0 +1,59 @@ +import type { Declaration } from 'inline-style-parser'; +import parse from 'inline-style-parser'; + +export { Declaration }; + +export interface StyleObject { + [name: string]: string; +} + +type Iterator = ( + property: string, + value: string, + declaration: Declaration, +) => void; + +/** + * Parses inline style to object. + * + * @param style - Inline style. + * @param iterator - Iterator. + * @returns - Style object or null. + * + * @example Parsing inline style to object: + * + * ```js + * import parse from 'style-to-object'; + * parse('line-height: 42;'); // { 'line-height': '42' } + * ``` + */ +export default function StyleToObject( + style: string, + iterator?: Iterator, +): StyleObject | null { + let styleObject: StyleObject | null = null; + + if (!style || typeof style !== 'string') { + return styleObject; + } + + const declarations = parse(style); + const hasIterator = typeof iterator === 'function'; + + declarations.forEach((declaration) => { + if (declaration.type !== 'declaration') { + return; + } + + const { property, value } = declaration; + + if (hasIterator) { + iterator(property, value, declaration); + } else if (value) { + styleObject = styleObject || {}; + styleObject[property] = value; + } + }); + + return styleObject; +} diff --git a/node_modules/sucrase/LICENSE b/node_modules/sucrase/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..06d77d6ad38ff147f6da4057ce1ad6955b9cd15e --- /dev/null +++ b/node_modules/sucrase/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012-2018 various contributors (see AUTHORS) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/sucrase/README.md b/node_modules/sucrase/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c45138a3f729bd17aece0a7d3ad6c36c36f5282f --- /dev/null +++ b/node_modules/sucrase/README.md @@ -0,0 +1,295 @@ +# Sucrase + +[![Build Status](https://github.com/alangpierce/sucrase/workflows/All%20tests/badge.svg)](https://github.com/alangpierce/sucrase/actions) +[![npm version](https://img.shields.io/npm/v/sucrase.svg)](https://www.npmjs.com/package/sucrase) +[![Install Size](https://packagephobia.now.sh/badge?p=sucrase)](https://packagephobia.now.sh/result?p=sucrase) +[![MIT License](https://img.shields.io/npm/l/express.svg?maxAge=2592000)](LICENSE) +[![Join the chat at https://gitter.im/sucrasejs](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sucrasejs/Lobby) + +## [Try it out](https://sucrase.io) + +## Quick usage + +```bash +yarn add --dev sucrase # Or npm install --save-dev sucrase +node -r sucrase/register main.ts +``` + +Using the [ts-node](https://github.com/TypeStrong/ts-node) integration: + +```bash +yarn add --dev sucrase ts-node typescript +./node_modules/.bin/ts-node --transpiler sucrase/ts-node-plugin main.ts +``` + +## Project overview + +Sucrase is an alternative to Babel that allows super-fast development builds. +Instead of compiling a large range of JS features to be able to work in Internet +Explorer, Sucrase assumes that you're developing with a recent browser or recent +Node.js version, so it focuses on compiling non-standard language extensions: +JSX, TypeScript, and Flow. Because of this smaller scope, Sucrase can get away +with an architecture that is much more performant but less extensible and +maintainable. Sucrase's parser is forked from Babel's parser (so Sucrase is +indebted to Babel and wouldn't be possible without it) and trims it down to a +focused subset of what Babel solves. If it fits your use case, hopefully Sucrase +can speed up your development experience! + +**Sucrase has been extensively tested.** It can successfully build +the [Benchling](https://benchling.com/) frontend code, +[Babel](https://github.com/babel/babel), +[React](https://github.com/facebook/react), +[TSLint](https://github.com/palantir/tslint), +[Apollo client](https://github.com/apollographql/apollo-client), and +[decaffeinate](https://github.com/decaffeinate/decaffeinate) +with all tests passing, about 1 million lines of code total. + +**Sucrase is about 20x faster than Babel.** Here's one measurement of how +Sucrase compares with other tools when compiling the Jest codebase 3 times, +about 360k lines of code total: + +```text + Time Speed +Sucrase 0.57 seconds 636975 lines per second +swc 1.19 seconds 304526 lines per second +esbuild 1.45 seconds 248692 lines per second +TypeScript 8.98 seconds 40240 lines per second +Babel 9.18 seconds 39366 lines per second +``` + +Details: Measured on July 2022. Tools run in single-threaded mode without warm-up. See the +[benchmark code](https://github.com/alangpierce/sucrase/blob/main/benchmark/benchmark.ts) +for methodology and caveats. + +## Transforms + +The main configuration option in Sucrase is an array of transform names. These +transforms are available: + +* **jsx**: Enables JSX syntax. By default, JSX is transformed to `React.createClass`, + but may be preserved or transformed to `_jsx()` by setting the `jsxRuntime` option. + Also adds `createReactClass` display names and JSX context information. +* **typescript**: Compiles TypeScript code to JavaScript, removing type + annotations and handling features like enums. Does not check types. Sucrase + transforms each file independently, so you should enable the `isolatedModules` + TypeScript flag so that the typechecker will disallow the few features like + `const enum`s that need cross-file compilation. The Sucrase option `keepUnusedImports` + can be used to disable all automatic removal of imports and exports, analogous to TS + `verbatimModuleSyntax`. +* **flow**: Removes Flow type annotations. Does not check types. +* **imports**: Transforms ES Modules (`import`/`export`) to CommonJS + (`require`/`module.exports`) using the same approach as Babel and TypeScript + with `--esModuleInterop`. If `preserveDynamicImport` is specified in the Sucrase + options, then dynamic `import` expressions are left alone, which is particularly + useful in Node to load ESM-only libraries. If `preserveDynamicImport` is not + specified, `import` expressions are transformed into a promise-wrapped call to + `require`. +* **react-hot-loader**: Performs the equivalent of the `react-hot-loader/babel` + transform in the [react-hot-loader](https://github.com/gaearon/react-hot-loader) + project. This enables advanced hot reloading use cases such as editing of + bound methods. +* **jest**: Hoist desired [jest](https://jestjs.io/) method calls above imports in + the same way as [babel-plugin-jest-hoist](https://github.com/facebook/jest/tree/master/packages/babel-plugin-jest-hoist). + Does not validate the arguments passed to `jest.mock`, but the same rules still apply. + +When the `imports` transform is *not* specified (i.e. when targeting ESM), the +`injectCreateRequireForImportRequire` option can be specified to transform TS +`import foo = require("foo");` in a way that matches the +[TypeScript 4.7 behavior](https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#commonjs-interoperability) +with `module: nodenext`. + +These newer JS features are transformed by default: + +* [Optional chaining](https://github.com/tc39/proposal-optional-chaining): `a?.b` +* [Nullish coalescing](https://github.com/tc39/proposal-nullish-coalescing): `a ?? b` +* [Class fields](https://github.com/tc39/proposal-class-fields): `class C { x = 1; }`. + This includes static fields but not the `#x` private field syntax. +* [Numeric separators](https://github.com/tc39/proposal-numeric-separator): + `const n = 1_234;` +* [Optional catch binding](https://github.com/tc39/proposal-optional-catch-binding): + `try { doThing(); } catch { }`. + +If your target runtime supports these features, you can specify +`disableESTransforms: true` so that Sucrase preserves the syntax rather than +trying to transform it. Note that transpiled and standard class fields behave +slightly differently; see the +[TypeScript 3.7 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier) +for details. If you use TypeScript, you can enable the TypeScript option +`useDefineForClassFields` to enable error checking related to these differences. + +### Unsupported syntax + +All JS syntax not mentioned above will "pass through" and needs to be supported +by your JS runtime. For example: + +* Decorators, private fields, `throw` expressions, generator arrow functions, + and `do` expressions are all unsupported in browsers and Node (as of this + writing), and Sucrase doesn't make an attempt to transpile them. +* Object rest/spread, async functions, and async iterators are all recent + features that should work fine, but might cause issues if you use older + versions of tools like webpack. BigInt and newer regex features may or may not + work, based on your tooling. + +### JSX Options + +By default, JSX is compiled to React functions in development mode. This can be +configured with a few options: + +* **jsxRuntime**: A string specifying the transform mode, which can be one of three values: + * `"classic"` (default): The original JSX transform that calls `React.createElement` by default. + To configure for non-React use cases, specify: + * **jsxPragma**: Element creation function, defaults to `React.createElement`. + * **jsxFragmentPragma**: Fragment component, defaults to `React.Fragment`. + * `"automatic"`: The [new JSX transform](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) + introduced with React 17, which calls `jsx` functions and auto-adds import statements. + To configure for non-React use cases, specify: + * **jsxImportSource**: Package name for auto-generated import statements, defaults to `react`. + * `"preserve"`: Don't transform JSX, and instead emit it as-is in the output code. +* **production**: If `true`, use production version of functions and don't include debugging + information. When using React in production mode with the automatic transform, this *must* be + set to true to avoid an error about `jsxDEV` being missing. + +### Legacy CommonJS interop + +Two legacy modes can be used with the `imports` transform: + +* **enableLegacyTypeScriptModuleInterop**: Use the default TypeScript approach + to CommonJS interop instead of assuming that TypeScript's `--esModuleInterop` + flag is enabled. For example, if a CJS module exports a function, legacy + TypeScript interop requires you to write `import * as add from './add';`, + while Babel, Webpack, Node.js, and TypeScript with `--esModuleInterop` require + you to write `import add from './add';`. As mentioned in the + [docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop), + the TypeScript team recommends you always use `--esModuleInterop`. +* **enableLegacyBabel5ModuleInterop**: Use the Babel 5 approach to CommonJS + interop, so that you can run `require('./MyModule')` instead of + `require('./MyModule').default`. Analogous to + [babel-plugin-add-module-exports](https://github.com/59naga/babel-plugin-add-module-exports). + +## Usage + +### Tool integrations + +* [Webpack](https://github.com/alangpierce/sucrase/tree/main/integrations/webpack-loader) +* [Gulp](https://github.com/alangpierce/sucrase/tree/main/integrations/gulp-plugin) +* [Jest](https://github.com/alangpierce/sucrase/tree/main/integrations/jest-plugin) +* [Rollup](https://github.com/rollup/plugins/tree/master/packages/sucrase) +* [Broccoli](https://github.com/stefanpenner/broccoli-sucrase) + +### Usage in Node + +The most robust way is to use the Sucrase plugin for [ts-node](https://github.com/TypeStrong/ts-node), +which has various Node integrations and configures Sucrase via `tsconfig.json`: +```bash +ts-node --transpiler sucrase/ts-node-plugin +``` + +For projects that don't target ESM, Sucrase also has a require hook with some +reasonable defaults that can be accessed in a few ways: + +* From code: `require("sucrase/register");` +* When invoking Node: `node -r sucrase/register main.ts` +* As a separate binary: `sucrase-node main.ts` + +Options can be passed to the require hook via a `SUCRASE_OPTIONS` environment +variable holding a JSON string of options. + +### Compiling a project to JS + +For simple use cases, Sucrase comes with a `sucrase` CLI that mirrors your +directory structure to an output directory: +```bash +sucrase ./srcDir -d ./outDir --transforms typescript,imports +``` + +### Usage from code + +For any advanced use cases, Sucrase can be called from JS directly: + +```js +import {transform} from "sucrase"; +const compiledCode = transform(code, {transforms: ["typescript", "imports"]}).code; +``` + +## What Sucrase is not + +Sucrase is intended to be useful for the most common cases, but it does not aim +to have nearly the scope and versatility of Babel. Some specific examples: + +* Sucrase does not check your code for errors. Sucrase's contract is that if you + give it valid code, it will produce valid JS code. If you give it invalid + code, it might produce invalid code, it might produce valid code, or it might + give an error. Always use Sucrase with a linter or typechecker, which is more + suited for error-checking. +* Sucrase is not pluginizable. With the current architecture, transforms need to + be explicitly written to cooperate with each other, so each additional + transform takes significant extra work. +* Sucrase is not good for prototyping language extensions and upcoming language + features. Its faster architecture makes new transforms more difficult to write + and more fragile. +* Sucrase will never produce code for old browsers like IE. Compiling code down + to ES5 is much more complicated than any transformation that Sucrase needs to + do. +* Sucrase is hesitant to implement upcoming JS features, although some of them + make sense to implement for pragmatic reasons. Its main focus is on language + extensions (JSX, TypeScript, Flow) that will never be supported by JS + runtimes. +* Like Babel, Sucrase is not a typechecker, and must process each file in + isolation. For example, TypeScript `const enum`s are treated as regular + `enum`s rather than inlining across files. +* You should think carefully before using Sucrase in production. Sucrase is + mostly beneficial in development, and in many cases, Babel or tsc will be more + suitable for production builds. + +See the [Project Vision](./docs/PROJECT_VISION.md) document for more details on +the philosophy behind Sucrase. + +## Motivation + +As JavaScript implementations mature, it becomes more and more reasonable to +disable Babel transforms, especially in development when you know that you're +targeting a modern runtime. You might hope that you could simplify and speed up +the build step by eventually disabling Babel entirely, but this isn't possible +if you're using a non-standard language extension like JSX, TypeScript, or Flow. +Unfortunately, disabling most transforms in Babel doesn't speed it up as much as +you might expect. To understand, let's take a look at how Babel works: + +1. Tokenize the input source code into a token stream. +2. Parse the token stream into an AST. +3. Walk the AST to compute the scope information for each variable. +4. Apply all transform plugins in a single traversal, resulting in a new AST. +5. Print the resulting AST. + +Only step 4 gets faster when disabling plugins, so there's always a fixed cost +to running Babel regardless of how many transforms are enabled. + +Sucrase bypasses most of these steps, and works like this: + +1. Tokenize the input source code into a token stream using a trimmed-down fork + of the Babel parser. This fork does not produce a full AST, but still + produces meaningful token metadata specifically designed for the later + transforms. +2. Scan through the tokens, computing preliminary information like all + imported/exported names. +3. Run the transform by doing a pass through the tokens and performing a number + of careful find-and-replace operations, like replacing `", + "license": "MIT", + "main": "dist/index.js", + "module": "dist/esm/index.js", + "types": "dist/types/index.d.ts", + "bin": { + "sucrase": "./bin/sucrase", + "sucrase-node": "./bin/sucrase-node" + }, + "scripts": { + "build": "sucrase-node script/build.ts", + "fast-build": "sucrase-node script/build.ts --fast", + "clean": "rm -rf ./build ./dist ./dist-self-build ./dist-types ./example-runner/example-repos ./spec-compliance-tests/test262/test262-checkout ./spec-compliance-tests/babel-tests/babel-tests-checkout", + "generate": "sucrase-node generator/generate.ts", + "benchmark": "cd benchmark && yarn && sucrase-node ./benchmark.ts", + "benchmark-compare": "sucrase-node ./benchmark/compare-performance.ts", + "microbenchmark": "sucrase-node benchmark/microbenchmark.ts", + "lint": "sucrase-node script/lint.ts", + "lint-fix": "sucrase-node script/lint.ts --fix", + "profile": "node --inspect-brk ./node_modules/.bin/sucrase-node ./benchmark/profile", + "profile-project": "node --inspect-brk ./node_modules/.bin/sucrase-node ./benchmark/benchmark-project.ts --profile", + "prepublishOnly": "yarn clean && yarn build", + "release": "sucrase-node script/release.ts", + "run-examples": "sucrase-node example-runner/example-runner.ts", + "test": "yarn lint && yarn test-only", + "test-only": "mocha './test/**/*.ts'", + "integration-test": "cd integration-test && yarn && yarn link @sucrase/jest-plugin && mocha --timeout 10000 ./integration-tests.ts", + "test262": "sucrase-node spec-compliance-tests/test262/run-test262.ts", + "check-babel-tests": "sucrase-node spec-compliance-tests/babel-tests/check-babel-tests.ts", + "test-with-coverage": "nyc mocha './test/**/*.ts'", + "report-coverage": "nyc report --reporter=text-lcov > coverage.lcov && codecov" + }, + "repository": { + "type": "git", + "url": "https://github.com/alangpierce/sucrase.git" + }, + "keywords": [ + "babel", + "jsx", + "typescript", + "flow" + ], + "bugs": { + "url": "https://github.com/alangpierce/sucrase/issues" + }, + "devDependencies": { + "@babel/core": "^7.22.5", + "@jridgewell/trace-mapping": "^0.3.18", + "@types/mocha": "^9.1.1", + "@types/mz": "^2.7.4", + "@types/node": "^20.3.2", + "@typescript-eslint/eslint-plugin": "^5.60.1", + "@typescript-eslint/parser": "^5.60.1", + "chalk": "^4", + "codecov": "^3.8.3", + "eslint": "^8.43.0", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-config-prettier": "^8.8.0", + "eslint-plugin-import": "~2.26", + "eslint-plugin-prettier": "^4.2.1", + "mocha": "^10.2.0", + "nyc": "^15.1.0", + "prettier": "^2.8.8", + "sucrase": "^3.35.0", + "test262-harness": "^10.0.0", + "ts-interface-builder": "^0.3.3", + "typescript": "~5.0" + }, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "resolutions": { + "**/eshost/socket.io": "4.7.0" + } +} diff --git a/node_modules/sucrase/register/index.js b/node_modules/sucrase/register/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f6eb814b5b6c63bca669b3461b7e05ec9210ef2b --- /dev/null +++ b/node_modules/sucrase/register/index.js @@ -0,0 +1 @@ +require("../dist/register").registerAll(); diff --git a/node_modules/sucrase/register/js.js b/node_modules/sucrase/register/js.js new file mode 100644 index 0000000000000000000000000000000000000000..48918960943c1aff94309098640832dc7b3d6043 --- /dev/null +++ b/node_modules/sucrase/register/js.js @@ -0,0 +1 @@ +require("../dist/register").registerJS(); diff --git a/node_modules/sucrase/register/jsx.js b/node_modules/sucrase/register/jsx.js new file mode 100644 index 0000000000000000000000000000000000000000..4bd476ea3611d4331b65fdccdcb9c25d05668d2e --- /dev/null +++ b/node_modules/sucrase/register/jsx.js @@ -0,0 +1 @@ +require("../dist/register").registerJSX(); diff --git a/node_modules/sucrase/register/ts-legacy-module-interop.js b/node_modules/sucrase/register/ts-legacy-module-interop.js new file mode 100644 index 0000000000000000000000000000000000000000..1ec5a6d78249e8bc3eb3222c9420dc165a27ef7c --- /dev/null +++ b/node_modules/sucrase/register/ts-legacy-module-interop.js @@ -0,0 +1 @@ +require("../dist/register").registerTSLegacyModuleInterop(); diff --git a/node_modules/sucrase/register/ts.js b/node_modules/sucrase/register/ts.js new file mode 100644 index 0000000000000000000000000000000000000000..23b8c8852ff3e9979a03a9dc53ed2e484c889608 --- /dev/null +++ b/node_modules/sucrase/register/ts.js @@ -0,0 +1 @@ +require("../dist/register").registerTS(); diff --git a/node_modules/sucrase/register/tsx-legacy-module-interop.js b/node_modules/sucrase/register/tsx-legacy-module-interop.js new file mode 100644 index 0000000000000000000000000000000000000000..a883680d07026308b50b170477ff91776d43b5ac --- /dev/null +++ b/node_modules/sucrase/register/tsx-legacy-module-interop.js @@ -0,0 +1 @@ +require("../dist/register").registerTSXLegacyModuleInterop(); diff --git a/node_modules/sucrase/register/tsx.js b/node_modules/sucrase/register/tsx.js new file mode 100644 index 0000000000000000000000000000000000000000..deb8b34ef8ec019cda99bd80eecaa7b886f70ff0 --- /dev/null +++ b/node_modules/sucrase/register/tsx.js @@ -0,0 +1 @@ +require("../dist/register").registerTSX(); diff --git a/node_modules/sucrase/ts-node-plugin/index.js b/node_modules/sucrase/ts-node-plugin/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b523fb36b47f15d8b959b254890ad8ac984acdc3 --- /dev/null +++ b/node_modules/sucrase/ts-node-plugin/index.js @@ -0,0 +1,83 @@ +const {transform} = require("../dist"); + +// Enum constants taken from the TypeScript codebase. +const ModuleKindCommonJS = 1; + +const JsxEmitReactJSX = 4; +const JsxEmitReactJSXDev = 5; + +/** + * ts-node transpiler plugin + * + * This plugin hooks into ts-node so that Sucrase can handle all TS-to-JS + * conversion while ts-node handles the ESM loader, require hook, REPL + * integration, etc. ts-node automatically discovers the relevant tsconfig file, + * so the main logic in this integration is translating tsconfig options to the + * corresponding Sucrase options. + * + * Any tsconfig options relevant to Sucrase are translated, but some config + * options outside the scope of Sucrase are ignored. For example, we assume the + * isolatedModules option, and we ignore target because Sucrase doesn't provide + * JS syntax downleveling (at least not in a way that is useful for Node). + * + * One notable caveat is that importsNotUsedAsValues and preserveValueImports + * are ignored right now, since they are deprecated and don't have exact Sucrase + * equivalents. To preserve imports and exports, use verbatimModuleSyntax. + */ +function create(createOptions) { + const {nodeModuleEmitKind} = createOptions; + const { + module, + jsx, + jsxFactory, + jsxFragmentFactory, + jsxImportSource, + esModuleInterop, + verbatimModuleSyntax, + } = createOptions.service.config.options; + + return { + transpile(input, transpileOptions) { + const {fileName} = transpileOptions; + const transforms = []; + // Detect JS rather than TS so we bias toward including the typescript + // transform, since almost always it doesn't hurt to include. + const isJS = + fileName.endsWith(".js") || + fileName.endsWith(".jsx") || + fileName.endsWith(".mjs") || + fileName.endsWith(".cjs"); + if (!isJS) { + transforms.push("typescript"); + } + if (module === ModuleKindCommonJS || nodeModuleEmitKind === "nodecjs") { + transforms.push("imports"); + } + if (fileName.endsWith(".tsx") || fileName.endsWith(".jsx")) { + transforms.push("jsx"); + } + + const {code, sourceMap} = transform(input, { + transforms, + disableESTransforms: true, + jsxRuntime: jsx === JsxEmitReactJSX || jsx === JsxEmitReactJSXDev ? "automatic" : "classic", + production: jsx === JsxEmitReactJSX, + jsxImportSource, + jsxPragma: jsxFactory, + jsxFragmentPragma: jsxFragmentFactory, + keepUnusedImports: verbatimModuleSyntax, + preserveDynamicImport: nodeModuleEmitKind === "nodecjs", + injectCreateRequireForImportRequire: nodeModuleEmitKind === "nodeesm", + enableLegacyTypeScriptModuleInterop: !esModuleInterop, + sourceMapOptions: {compiledFilename: fileName}, + filePath: fileName, + }); + return { + outputText: code, + sourceMapText: JSON.stringify(sourceMap), + }; + }, + }; +} + +exports.create = create; diff --git a/node_modules/superagent/LICENSE b/node_modules/superagent/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1b188ba5d80295b22b4c607ecfc27abc3afceb4b --- /dev/null +++ b/node_modules/superagent/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/superagent/README.md b/node_modules/superagent/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4ce4234d223922085247b7ff6ca6eb979c7b8f3b --- /dev/null +++ b/node_modules/superagent/README.md @@ -0,0 +1,273 @@ +# superagent + +[![build status](https://github.com/forwardemail/superagent/actions/workflows/ci.yml/badge.svg)](https://github.com/forwardemail/superagent/actions/workflows/ci.yml) +[![code coverage](https://img.shields.io/codecov/c/github/ladjs/superagent.svg)](https://codecov.io/gh/ladjs/superagent) +[![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) +[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) +[![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org) +[![license](https://img.shields.io/github/license/ladjs/superagent.svg)](LICENSE) + +> Small progressive client-side HTTP request library, and Node.js module with the same API, supporting many high-level HTTP client features. Maintained for [Forward Email](https://github.com/forwardemail) and [Lad](https://github.com/ladjs). + + +## Table of Contents + +* [Install](#install) +* [Usage](#usage) + * [Node](#node) + * [Browser](#browser) +* [Supported Platforms](#supported-platforms) + * [Required Browser Features](#required-browser-features) +* [Plugins](#plugins) +* [Upgrading from previous versions](#upgrading-from-previous-versions) +* [Contributors](#contributors) +* [License](#license) + + +## Install + +[npm][]: + +```sh +npm install superagent +``` + +[yarn][]: + +```sh +yarn add superagent +``` + + +## Usage + +### Node + +```js +const superagent = require('superagent'); + +// callback +superagent + .post('/api/pet') + .send({ name: 'Manny', species: 'cat' }) // sends a JSON post body + .set('X-API-Key', 'foobar') + .set('accept', 'json') + .end((err, res) => { + // Calling the end function will send the request + }); + +// promise with then/catch +superagent.post('/api/pet').then(console.log).catch(console.error); + +// promise with async/await +(async () => { + try { + const res = await superagent.post('/api/pet'); + console.log(res); + } catch (err) { + console.error(err); + } +})(); +``` + +### Browser + +**The browser-ready, minified version of `superagent` is only 50 KB (minified and gzipped).** + +Browser-ready versions of this module are available via [jsdelivr][], [unpkg][], and also in the `node_modules/superagent/dist` folder in downloads of the `superagent` package. + +> Note that we also provide unminified versions with `.js` instead of `.min.js` file extensions. + +#### VanillaJS + +This is the solution for you if you're just using ` + + + + +``` + +#### Bundler + +If you are using [browserify][], [webpack][], [rollup][], or another bundler, then you can follow the same usage as [Node](#node) above. + + +## Supported Platforms + +* Node: v14.18.0+ +* Browsers (see [.browserslistrc](.browserslistrc)): + + ```sh + npx browserslist + ``` + + ```sh + and_chr 102 + and_ff 101 + and_qq 10.4 + and_uc 12.12 + android 101 + chrome 103 + chrome 102 + chrome 101 + chrome 100 + edge 103 + edge 102 + edge 101 + firefox 101 + firefox 100 + firefox 91 + ios_saf 15.5 + ios_saf 15.4 + ios_saf 15.2-15.3 + ios_saf 15.0-15.1 + ios_saf 14.5-14.8 + ios_saf 14.0-14.4 + ios_saf 12.2-12.5 + kaios 2.5 + op_mini all + op_mob 64 + opera 86 + opera 85 + safari 15.5 + safari 15.4 + samsung 17.0 + samsung 16.0 + ``` + +### Required Browser Features + +We recommend using (specifically with the bundle mentioned in [VanillaJS](#vanillajs) above): + +```html + +``` + +* WeakRef is not supported in Opera 85, iOS Safari 12.2-12.5 +* BigInt is not supported in iOS Safari 12.2-12.5 + + +## Plugins + +SuperAgent is easily extended via plugins. + +```js +const nocache = require('superagent-no-cache'); +const superagent = require('superagent'); +const prefix = require('superagent-prefix')('/static'); + +superagent + .get('/some-url') + .query({ action: 'edit', city: 'London' }) // query string + .use(prefix) // Prefixes *only* this request + .use(nocache) // Prevents caching of *only* this request + .end((err, res) => { + // Do something + }); +``` + +Existing plugins: + +* [superagent-no-cache](https://github.com/johntron/superagent-no-cache) - prevents caching by including Cache-Control header +* [superagent-prefix](https://github.com/johntron/superagent-prefix) - prefixes absolute URLs (useful in test environment) +* [superagent-suffix](https://github.com/timneutkens1/superagent-suffix) - suffix URLs with a given path +* [superagent-mock](https://github.com/M6Web/superagent-mock) - simulate HTTP calls by returning data fixtures based on the requested URL +* [superagent-mocker](https://github.com/shuvalov-anton/superagent-mocker) — simulate REST API +* [superagent-cache](https://github.com/jpodwys/superagent-cache) - A global SuperAgent patch with built-in, flexible caching +* [superagent-cache-plugin](https://github.com/jpodwys/superagent-cache-plugin) - A SuperAgent plugin with built-in, flexible caching +* [superagent-jsonapify](https://github.com/alex94puchades/superagent-jsonapify) - A lightweight [json-api](http://jsonapi.org/format/) client addon for superagent +* [superagent-serializer](https://github.com/zzarcon/superagent-serializer) - Converts server payload into different cases +* [superagent-httpbackend](https://www.npmjs.com/package/superagent-httpbackend) - stub out requests using AngularJS' $httpBackend syntax +* [superagent-throttle](https://github.com/leviwheatcroft/superagent-throttle) - queues and intelligently throttles requests +* [superagent-charset](https://github.com/magicdawn/superagent-charset) - add charset support for node's SuperAgent +* [superagent-verbose-errors](https://github.com/jcoreio/superagent-verbose-errors) - include response body in error messages for failed requests +* [superagent-declare](https://github.com/damoclark/superagent-declare) - A simple [declarative](https://en.wikipedia.org/wiki/Declarative_programming) API for SuperAgent +* [superagent-node-http-timings](https://github.com/webuniverseio/superagent-node-http-timings) - measure http timings in node.js +* [superagent-cheerio](https://github.com/mmmmmrob/superagent-cheerio) - add [cheerio](https://www.npmjs.com/package/cheerio) to your response content automatically. Adds `res.$` for HTML and XML response bodies. +* [@certible/superagent-aws-sign](https://github.com/certible/superagent-aws-sign) - Sign AWS endpoint requests, it uses the aws4 to authenticate the SuperAgent requests + +Please prefix your plugin with `superagent-*` so that it can easily be found by others. + +For SuperAgent extensions such as couchdb and oauth visit the [wiki](https://github.com/ladjs/superagent/wiki). + + +## Upgrading from previous versions + +Please see [GitHub releases page](https://github.com/ladjs/superagent/releases) for the current changelog. + +Our breaking changes are mostly in rarely used functionality and from stricter error handling. + +* [6.0 to 6.1](https://github.com/ladjs/superagent/releases/tag/v6.1.0) + * Browser behaviour changed to match Node when serializing `application/x-www-form-urlencoded`, using `arrayFormat: 'indices'` semantics of `qs` library. (See: ) +* [5.x to 6.x](https://github.com/ladjs/superagent/releases/tag/v6.0.0): + * Retry behavior is still opt-in, however we now have a more fine-grained list of status codes and error codes that we retry against (see updated docs) + * A specific issue with Content-Type matching not being case-insensitive is fixed + * Set is now required for IE 9, see [Required Browser Features](#required-browser-features) for more insight +* [4.x to 5.x](https://github.com/ladjs/superagent/releases/tag/v5.0.0): + * We've implemented the build setup of [Lass](https://lass.js.org) to simplify our stack and linting + * Unminified browserified build size has been reduced from 48KB to 20KB (via `tinyify` and the latest version of Babel using `@babel/preset-env` and `.browserslistrc`) + * Linting support has been added using `caniuse-lite` and `eslint-plugin-compat` + * We can now target what versions of Node we wish to support more easily using `.babelrc` +* [3.x to 4.x](https://github.com/ladjs/superagent/releases/tag/v4.0.0-alpha.1): + * Ensure you're running Node 6 or later. We've dropped support for Node 4. + * We've started using ES6 and for compatibility with Internet Explorer you may need to use Babel. + * We suggest migrating from `.end()` callbacks to `.then()` or `await`. +* [2.x to 3.x](https://github.com/ladjs/superagent/releases/tag/v3.0.0): + * Ensure you're running Node 4 or later. We've dropped support for Node 0.x. + * Test code that calls `.send()` multiple times. Invalid calls to `.send()` will now throw instead of sending garbage. +* [1.x to 2.x](https://github.com/ladjs/superagent/releases/tag/v2.0.0): + * If you use `.parse()` in the *browser* version, rename it to `.serialize()`. + * If you rely on `undefined` in query-string values being sent literally as the text "undefined", switch to checking for missing value instead. `?key=undefined` is now `?key` (without a value). + * If you use `.then()` in Internet Explorer, ensure that you have a polyfill that adds a global `Promise` object. +* 0.x to 1.x: + * Instead of 1-argument callback `.end(function(res){})` use `.then(res => {})`. + + +## Contributors + +| Name | +| ------------------- | +| **Kornel Lesiński** | +| **Peter Lyons** | +| **Hunter Loftis** | +| **Nick Baugh** | + + +## License + +[MIT](LICENSE) © TJ Holowaychuk + + +## + +[npm]: https://www.npmjs.com/ + +[yarn]: https://yarnpkg.com/ + +[jsdelivr]: https://www.jsdelivr.com/ + +[unpkg]: https://unpkg.com/ + +[browserify]: https://github.com/browserify/browserify + +[webpack]: https://github.com/webpack/webpack + +[rollup]: https://github.com/rollup/rollup diff --git a/node_modules/superagent/lib/agent-base.js b/node_modules/superagent/lib/agent-base.js new file mode 100644 index 0000000000000000000000000000000000000000..b1a5e44efcbc6e884c399d31af511b5455a4ace7 --- /dev/null +++ b/node_modules/superagent/lib/agent-base.js @@ -0,0 +1,25 @@ +"use strict"; + +const defaults = ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts']; +class Agent { + constructor() { + this._defaults = []; + } + _setDefaults(request) { + for (const def of this._defaults) { + request[def.fn](...def.args); + } + } +} +for (const fn of defaults) { + // Default setting for all requests from this agent + Agent.prototype[fn] = function (...args) { + this._defaults.push({ + fn, + args + }); + return this; + }; +} +module.exports = Agent; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJkZWZhdWx0cyIsIkFnZW50IiwiY29uc3RydWN0b3IiLCJfZGVmYXVsdHMiLCJfc2V0RGVmYXVsdHMiLCJyZXF1ZXN0IiwiZGVmIiwiZm4iLCJhcmdzIiwicHJvdG90eXBlIiwicHVzaCIsIm1vZHVsZSIsImV4cG9ydHMiXSwic291cmNlcyI6WyIuLi9zcmMvYWdlbnQtYmFzZS5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJjb25zdCBkZWZhdWx0cyA9IFtcbiAgJ3VzZScsXG4gICdvbicsXG4gICdvbmNlJyxcbiAgJ3NldCcsXG4gICdxdWVyeScsXG4gICd0eXBlJyxcbiAgJ2FjY2VwdCcsXG4gICdhdXRoJyxcbiAgJ3dpdGhDcmVkZW50aWFscycsXG4gICdzb3J0UXVlcnknLFxuICAncmV0cnknLFxuICAnb2snLFxuICAncmVkaXJlY3RzJyxcbiAgJ3RpbWVvdXQnLFxuICAnYnVmZmVyJyxcbiAgJ3NlcmlhbGl6ZScsXG4gICdwYXJzZScsXG4gICdjYScsXG4gICdrZXknLFxuICAncGZ4JyxcbiAgJ2NlcnQnLFxuIC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RUFDLFlBQVlBLENBQUVDLE9BQU8sRUFBRTtJQUNyQixLQUFLLE1BQU1DLEdBQUcsSUFBSSxJQUFJLENBQUNILFNBQVMsRUFBRTtNQUNoQ0UsT0FBTyxDQUFDQyxHQUFHLENBQUNDLEVBQUUsQ0FBQyxDQUFDLEdBQUdELEdBQUcsQ0FBQ0UsSUFBSSxDQUFDO0lBQzlCO0VBQ0Y7QUFDRjtBQUVBLEtBQUssTUFBTUQsRUFBRSxJQUFJUCxRQUFRLEVBQUU7RUFDekI7RUFDQUMsS0FBSyxDQUFDUSxTQUFTLENBQUNGLEVBQUUsQ0FBQyxHQUFHLFVBQVUsR0FBR0MsSUFBSSxFQUFFO0lBQ3ZDLElBQUksQ0FBQ0wsU0FBUyxDQUFDTyxJQUFJLENBQUM7TUFBRUgsRUFBRTtNQUFFQztJQUFLLENBQUMsQ0FBQztJQUNqQyxPQUFPLElBQUk7RUFDYixDQUFDO0FBQ0g7QUFHQUcsTUFBTSxDQUFDQyxPQUFPLEdBQUdYLEtBQUsiLCJpZ25vcmVMaXN0IjpbXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/client.js b/node_modules/superagent/lib/client.js new file mode 100644 index 0000000000000000000000000000000000000000..aafb5eb10a92d5e27ad69a7e6cda40361b0338c1 --- /dev/null +++ b/node_modules/superagent/lib/client.js @@ -0,0 +1,957 @@ +"use strict"; + +/** + * Root reference for iframes. + */ + +let root; +if (typeof window !== 'undefined') { + // Browser window + root = window; +} else if (typeof self === 'undefined') { + // Other environments + console.warn('Using browser-only version of superagent in non-browser environment'); + root = void 0; +} else { + // Web Worker + root = self; +} +const Emitter = require('component-emitter'); +const safeStringify = require('fast-safe-stringify'); +const qs = require('qs'); +const RequestBase = require('./request-base'); +const { + isObject, + mixin, + hasOwn +} = require('./utils'); +const ResponseBase = require('./response-base'); +const Agent = require('./agent-base'); + +/** + * Noop. + */ + +function noop() {} + +/** + * Expose `request`. + */ + +module.exports = function (method, url) { + // callback + if (typeof url === 'function') { + return new exports.Request('GET', method).end(url); + } + + // url first + if (arguments.length === 1) { + return new exports.Request('GET', method); + } + return new exports.Request(method, url); +}; +exports = module.exports; +const request = exports; +exports.Request = Request; + +/** + * Determine XHR. + */ + +request.getXHR = () => { + if (root.XMLHttpRequest) { + return new root.XMLHttpRequest(); + } + throw new Error('Browser-only version of superagent could not find XHR'); +}; + +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + +const trim = ''.trim ? s => s.trim() : s => s.replace(/(^\s*|\s*$)/g, ''); + +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(object) { + if (!isObject(object)) return object; + const pairs = []; + for (const key in object) { + if (hasOwn(object, key)) pushEncodedKeyValuePair(pairs, key, object[key]); + } + return pairs.join('&'); +} + +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + +function pushEncodedKeyValuePair(pairs, key, value) { + if (value === undefined) return; + if (value === null) { + pairs.push(encodeURI(key)); + return; + } + if (Array.isArray(value)) { + for (const v of value) { + pushEncodedKeyValuePair(pairs, key, v); + } + } else if (isObject(value)) { + for (const subkey in value) { + if (hasOwn(value, subkey)) pushEncodedKeyValuePair(pairs, `${key}[${subkey}]`, value[subkey]); + } + } else { + pairs.push(encodeURI(key) + '=' + encodeURIComponent(value)); + } +} + +/** + * Expose serialization method. + */ + +request.serializeObject = serialize; + +/** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(string_) { + const object = {}; + const pairs = string_.split('&'); + let pair; + let pos; + for (let i = 0, length_ = pairs.length; i < length_; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + if (pos === -1) { + object[decodeURIComponent(pair)] = ''; + } else { + object[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); + } + } + return object; +} + +/** + * Expose parser. + */ + +request.parseString = parseString; + +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'text/xml', + urlencoded: 'application/x-www-form-urlencoded', + form: 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + +request.serialize = { + 'application/x-www-form-urlencoded': obj => { + return qs.stringify(obj, { + indices: false, + strictNullHandling: true + }); + }, + 'application/json': safeStringify +}; + +/** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; + +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(string_) { + const lines = string_.split(/\r?\n/); + const fields = {}; + let index; + let line; + let field; + let value; + for (let i = 0, length_ = lines.length; i < length_; ++i) { + line = lines[i]; + index = line.indexOf(':'); + if (index === -1) { + // could be empty line, just skip it + continue; + } + field = line.slice(0, index).toLowerCase(); + value = trim(line.slice(index + 1)); + fields[field] = value; + } + return fields; +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + // should match /json or +json + // but not /json-seq + return /[/+]json($|[^-\w])/i.test(mime); +} + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + +function Response(request_) { + this.req = request_; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null; + this.statusText = this.req.xhr.statusText; + let { + status + } = this.xhr; + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; + } + this._setStatusProperties(status); + this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + this.header = this.headers; + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this._setHeaderProperties(this.header); + if (this.text === null && request_._responseType) { + this.body = this.xhr.response; + } else { + this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response); + } +} +mixin(Response.prototype, ResponseBase.prototype); + +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function (string_) { + let parse = request.parse[this.type]; + if (this.req._parser) { + return this.req._parser(this, string_); + } + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + return parse && string_ && (string_.length > 0 || string_ instanceof Object) ? parse(string_) : null; +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function () { + const { + req + } = this; + const { + method + } = req; + const { + url + } = req; + const message = `cannot ${method} ${url} (${this.status})`; + const error = new Error(message); + error.status = this.status; + error.method = method; + error.url = url; + return error; +}; + +/** + * Expose `Response`. + */ + +request.Response = Response; + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + const self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + this._header = {}; // coerces header names to lowercase + this.on('end', () => { + let error = null; + let res = null; + try { + res = new Response(self); + } catch (err) { + error = new Error('Parser is unable to parse the response'); + error.parse = true; + error.original = err; + // issue #675: return the raw response if the response parsing fails + if (self.xhr) { + // ie9 doesn't have 'response' property + error.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; + // issue #876: return the http status code if the response parsing fails + error.status = self.xhr.status ? self.xhr.status : null; + error.statusCode = error.status; // backwards-compat only + } else { + error.rawResponse = null; + error.status = null; + } + return self.callback(error); + } + self.emit('response', res); + let new_error; + try { + if (!self._isResponseOK(res)) { + new_error = new Error(res.statusText || res.text || 'Unsuccessful HTTP response'); + } + } catch (err) { + new_error = err; // ok() callback can throw + } + + // #1000 don't catch errors from the callback to avoid double calling it + if (new_error) { + new_error.original = error; + new_error.response = res; + new_error.status = new_error.status || res.status; + self.callback(new_error, res); + } else { + self.callback(null, res); + } + }); +} + +/** + * Mixin `Emitter` and `RequestBase`. + */ + +// eslint-disable-next-line new-cap +Emitter(Request.prototype); +mixin(Request.prototype, RequestBase.prototype); + +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function (type) { + this.set('Content-Type', request.types[type] || type); + return this; +}; + +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function (type) { + this.set('Accept', request.types[type] || type); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} [pass] optional in case of using 'bearer' as type + * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function (user, pass, options) { + if (arguments.length === 1) pass = ''; + if (typeof pass === 'object' && pass !== null) { + // pass is optional and can be replaced with options + options = pass; + pass = ''; + } + if (!options) { + options = { + type: typeof btoa === 'function' ? 'basic' : 'auto' + }; + } + const encoder = options.encoder ? options.encoder : string => { + if (typeof btoa === 'function') { + return btoa(string); + } + throw new Error('Cannot use basic auth, btoa is not a function'); + }; + return this._auth(user, pass, options, encoder); +}; + +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.query = function (value) { + if (typeof value !== 'string') value = serialize(value); + if (value) this._query.push(value); + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function (field, file, options) { + if (file) { + if (this._data) { + throw new Error("superagent can't mix .send() and .attach()"); + } + this._getFormData().append(field, file, options || file.name); + } + return this; +}; +Request.prototype._getFormData = function () { + if (!this._formData) { + this._formData = new root.FormData(); + } + return this._formData; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function (error, res) { + if (this._shouldRetry(error, res)) { + return this._retry(); + } + const fn = this._callback; + this.clearTimeout(); + if (error) { + if (this._maxRetries) error.retries = this._retries - 1; + this.emit('error', error); + } + fn(error, res); +}; + +/** + * Invoke callback with x-domain error. + * + * @api private + */ + +Request.prototype.crossDomainError = function () { + const error = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + error.crossDomain = true; + error.status = this.status; + error.method = this.method; + error.url = this.url; + this.callback(error); +}; + +// This only warns, because the request is still likely to work +Request.prototype.agent = function () { + console.warn('This is not supported in browser version of superagent'); + return this; +}; +Request.prototype.ca = Request.prototype.agent; +Request.prototype.buffer = Request.prototype.ca; + +// This throws, because it can't send/receive data as expected +Request.prototype.write = () => { + throw new Error('Streaming is not supported in browser version of superagent'); +}; +Request.prototype.pipe = Request.prototype.write; + +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj host object + * @return {Boolean} is a host object + * @api private + */ +Request.prototype._isHost = function (object) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return object && typeof object === 'object' && !Array.isArray(object) && Object.prototype.toString.call(object) !== '[object Object]'; +}; + +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype.end = function (fn) { + if (this._endCalled) { + console.warn('Warning: .end() was called twice. This is not supported in superagent'); + } + this._endCalled = true; + + // store callback + this._callback = fn || noop; + + // querystring + this._finalizeQueryString(); + this._end(); +}; +Request.prototype._setUploadTimeout = function () { + const self = this; + + // upload timeout it's wokrs only if deadline timeout is off + if (this._uploadTimeout && !this._uploadTimeoutTimer) { + this._uploadTimeoutTimer = setTimeout(() => { + self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT'); + }, this._uploadTimeout); + } +}; + +// eslint-disable-next-line complexity +Request.prototype._end = function () { + if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); + const self = this; + this.xhr = request.getXHR(); + const { + xhr + } = this; + let data = this._formData || this._data; + this._setTimeouts(); + + // state change + xhr.addEventListener('readystatechange', () => { + const { + readyState + } = xhr; + if (readyState >= 2 && self._responseTimeoutTimer) { + clearTimeout(self._responseTimeoutTimer); + } + if (readyState !== 4) { + return; + } + + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + let status; + try { + status = xhr.status; + } catch (err) { + status = 0; + } + if (!status) { + if (self.timedout || self._aborted) return; + return self.crossDomainError(); + } + self.emit('end'); + }); + + // progress + const handleProgress = (direction, e) => { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + if (e.percent === 100) { + clearTimeout(self._uploadTimeoutTimer); + } + } + e.direction = direction; + self.emit('progress', e); + }; + if (this.hasListeners('progress')) { + try { + xhr.addEventListener('progress', handleProgress.bind(null, 'download')); + if (xhr.upload) { + xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload')); + } + } catch (err) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + if (xhr.upload) { + this._setUploadTimeout(); + } + + // initiate request + try { + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + } catch (err) { + // see #1149 + return this.callback(err); + } + + // CORS + if (this._withCredentials) xhr.withCredentials = true; + + // body + if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) { + // serialize stuff + const contentType = this._header['content-type']; + let serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) { + serialize = request.serialize['application/json']; + } + if (serialize) data = serialize(data); + } + + // set header fields + for (const field in this.header) { + if (this.header[field] === null) continue; + if (hasOwn(this.header, field)) xhr.setRequestHeader(field, this.header[field]); + } + if (this._responseType) { + xhr.responseType = this._responseType; + } + + // send stuff + this.emit('request', this); + + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + xhr.send(typeof data === 'undefined' ? null : data); +}; + +// create a Proxy that can instantiate a new Agent without using `new` keyword +// (for backward compatibility and chaining) +const proxyAgent = new Proxy(Agent, { + apply(target, thisArg, argumentsList) { + return new target(...argumentsList); + } +}); +request.agent = proxyAgent; +for (const method of ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE']) { + Agent.prototype[method.toLowerCase()] = function (url, fn) { + const request_ = new request.Request(method, url); + this._setDefaults(request_); + if (fn) { + request_.end(fn); + } + return request_; + }; +} +Agent.prototype.del = Agent.prototype.delete; + +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = (url, data, fn) => { + const request_ = request('GET', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.query(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.head = (url, data, fn) => { + const request_ = request('HEAD', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.query(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.options = (url, data, fn) => { + const request_ = request('OPTIONS', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * DELETE `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +function del(url, data, fn) { + const request_ = request('DELETE', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +} +request.del = del; +request.delete = del; + +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = (url, data, fn) => { + const request_ = request('PATCH', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.post = (url, data, fn) => { + const request_ = request('POST', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.put = (url, data, fn) => { + const request_ = request('PUT', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJyb290Iiwid2luZG93Iiwic2VsZiIsImNvbnNvbGUiLCJ3YXJuIiwiRW1pdHRlciIsInJlcXVpcmUiLCJzYWZlU3RyaW5naWZ5IiwicXMiLCJSZXF1ZXN0QmFzZSIsImlzT2JqZWN0IiwibWl4aW4iLCJoYXNPd24iLCJSZXNwb25zZUJhc2UiLCJBZ2VudCIsIm5vb3AiLCJtb2R1bGUiLCJleHBvcnRzIiwibWV0aG9kIiwidXJsIiwiUmVxdWVzdCIsImVuZCIsImFyZ3VtZW50cyIsImxlbmd0aCIsInJlcXVlc3QiLCJnZXRYSFIiLCJYTUxIdHRwUmVxdWVzdCIsIkVycm9yIiwidHJpbSIsInMiLCJyZXBsYWNlIiwic2VyaWFsaXplIiwib2JqZWN0IiwicGFpcnMiLCJrZXkiLCJwdXNoRW5jb2RlZEtleVZhbHVlUGFpciIsImpvaW4iLCJ2YWx1ZSIsInVuZGVmaW5lZCIsInB1c2giLCJlbmNvZGVVUkkiLCJBcnJheSIsImlz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UUsQ0FBQztFQUN4QixPQUFPMUQsUUFBUTtBQUNqQixDQUFDOztBQUVEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQXhELE9BQU8sQ0FBQ2dMLEdBQUcsR0FBRyxDQUFDckwsR0FBRyxFQUFFZ0osSUFBSSxFQUFFekIsRUFBRSxLQUFLO0VBQy9CLE1BQU0xRCxRQUFRLEdBQUd4RCxPQUFPLENBQUMsS0FBSyxFQUFFTCxHQUFHLENBQUM7RUFDcEMsSUFBSSxPQUFPZ0osSUFBSSxLQUFLLFVBQVUsRUFBRTtJQUM5QnpCLEVBQUUsR0FBR3lCLElBQUk7SUFDVEEsSUFBSSxHQUFHLElBQUk7RUFDYjtFQUVBLElBQUlBLElBQUksRUFBRW5GLFFBQVEsQ0FBQzBHLElBQUksQ0FBQ3ZCLElBQUksQ0FBQztFQUM3QixJQUFJekIsRUFBRSxFQUFFMUQsUUFBUSxDQUFDM0QsR0FBRyxDQUFDcUgsRUFBRSxDQUFDO0VBQ3hCLE9BQU8xRCxRQUFRO0FBQ2pCLENBQUMiLCJpZ25vcmVMaXN0IjpbXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/node/agent.js b/node_modules/superagent/lib/node/agent.js new file mode 100644 index 0000000000000000000000000000000000000000..d03ccf883d2338da89d0532892a01f755d56233d --- /dev/null +++ b/node_modules/superagent/lib/node/agent.js @@ -0,0 +1,101 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const { + CookieJar +} = require('cookiejar'); +const { + CookieAccessInfo +} = require('cookiejar'); +const methods = require('methods'); +const request = require('../..'); +const AgentBase = require('../agent-base'); + +/** + * Initialize a new `Agent`. + * + * @api public + */ + +class Agent extends AgentBase { + constructor(options) { + super(); + this.jar = new CookieJar(); + if (options) { + if (options.ca) { + this.ca(options.ca); + } + if (options.key) { + this.key(options.key); + } + if (options.pfx) { + this.pfx(options.pfx); + } + if (options.cert) { + this.cert(options.cert); + } + if (options.rejectUnauthorized === false) { + this.disableTLSCerts(); + } + } + } + + /** + * Save the cookies in the given `res` to + * the agent's cookie jar for persistence. + * + * @param {Response} res + * @api private + */ + _saveCookies(res) { + const cookies = res.headers['set-cookie']; + if (cookies) { + var _res$request; + const url = new URL(((_res$request = res.request) === null || _res$request === void 0 ? void 0 : _res$request.url) || ''); + this.jar.setCookies(cookies, url.hostname, url.pathname); + } + } + + /** + * Attach cookies when available to the given `req`. + * + * @param {Request} req + * @api private + */ + _attachCookies(request_) { + const url = new URL(request_.url); + const access = new CookieAccessInfo(url.hostname, url.pathname, url.protocol === 'https:'); + const cookies = this.jar.getCookies(access).toValueString(); + request_.cookies = cookies; + } +} +for (const name of methods) { + const method = name.toUpperCase(); + if (method === "QUERY") continue; + Agent.prototype[name] = function (url, fn) { + const request_ = new request.Request(method, url); + request_.on('response', this._saveCookies.bind(this)); + request_.on('redirect', this._saveCookies.bind(this)); + request_.on('redirect', this._attachCookies.bind(this, request_)); + this._setDefaults(request_); + this._attachCookies(request_); + if (fn) { + request_.end(fn); + } + return request_; + }; +} +Agent.prototype.del = Agent.prototype.delete; + +// create a Proxy that can instantiate a new Agent without using `new` keyword +// (for backward compatibility and chaining) +const proxyAgent = new Proxy(Agent, { + apply(target, thisArg, argumentsList) { + return new target(...argumentsList); + } +}); +module.exports = proxyAgent; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDb29raWVKYXIiLCJyZXF1aXJlIiwiQ29va2llQWNjZXNzSW5mbyIsIm1ldGhvZHMiLCJyZXF1ZXN0IiwiQWdlbnRCYXNlIiwiQWdlbnQiLCJjb25zdHJ1Y3RvciIsIm9wdGlvbnMiLCJqYXIiLCJjYSIsImtleSIsInBmeCIsImNlcnQiLCJyZWplY3RVbmF1dGhvcml6ZWQiLCJkaXNhYmxlVExTQ2VydHMiLCJfc2F2ZUNvb2tpZXMiLCJyZXMiLCJjb29raWVzIiwiaGVhZGVycyIs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akRNLFFBQVEsQ0FBQ1csRUFBRSxDQUFDLFVBQVUsRUFBRSxJQUFJLENBQUN0QixZQUFZLENBQUN1QixJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7SUFDckRaLFFBQVEsQ0FBQ1csRUFBRSxDQUFDLFVBQVUsRUFBRSxJQUFJLENBQUN0QixZQUFZLENBQUN1QixJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7SUFDckRaLFFBQVEsQ0FBQ1csRUFBRSxDQUFDLFVBQVUsRUFBRSxJQUFJLENBQUNaLGNBQWMsQ0FBQ2EsSUFBSSxDQUFDLElBQUksRUFBRVosUUFBUSxDQUFDLENBQUM7SUFDakUsSUFBSSxDQUFDYSxZQUFZLENBQUNiLFFBQVEsQ0FBQztJQUMzQixJQUFJLENBQUNELGNBQWMsQ0FBQ0MsUUFBUSxDQUFDO0lBRTdCLElBQUlTLEVBQUUsRUFBRTtNQUNOVCxRQUFRLENBQUNjLEdBQUcsQ0FBQ0wsRUFBRSxDQUFDO0lBQ2xCO0lBRUEsT0FBT1QsUUFBUTtFQUNqQixDQUFDO0FBQ0g7QUFFQXJCLEtBQUssQ0FBQzZCLFNBQVMsQ0FBQ08sR0FBRyxHQUFHcEMsS0FBSyxDQUFDNkIsU0FBUyxDQUFDUSxNQUFNOztBQUU1QztBQUNBO0FBQ0EsTUFBTUMsVUFBVSxHQUFHLElBQUlDLEtBQUssQ0FBQ3ZDLEtBQUssRUFBRTtFQUNsQ3dDLEtBQUtBLENBQUVDLE1BQU0sRUFBRUMsT0FBTyxFQUFFQyxhQUFhLEVBQUU7SUFDckMsT0FBTyxJQUFJRixNQUFNLENBQUMsR0FBR0UsYUFBYSxDQUFDO0VBQ3JDO0FBQ0YsQ0FBQyxDQUFDO0FBRUZDLE1BQU0sQ0FBQ0MsT0FBTyxHQUFHUCxVQUFVIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/decompress.js b/node_modules/superagent/lib/node/decompress.js new file mode 100644 index 0000000000000000000000000000000000000000..befe06c48dee494d788403aef2ca05b459ba4155 --- /dev/null +++ b/node_modules/superagent/lib/node/decompress.js @@ -0,0 +1,20 @@ +"use strict"; + +const zlib = require('zlib'); +const utils = require('../utils'); +const { + isGzipOrDeflateEncoding, + isBrotliEncoding +} = utils; +exports.chooseDecompresser = res => { + let decompresser; + if (isGzipOrDeflateEncoding(res)) { + decompresser = zlib.createUnzip(); + } else if (isBrotliEncoding(res)) { + decompresser = zlib.createBrotliDecompress(); + } else { + throw new Error('unknown content-encoding'); + } + return decompresser; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ6bGliIiwicmVxdWlyZSIsInV0aWxzIiwiaXNHemlwT3JEZWZsYXRlRW5jb2RpbmciLCJpc0Jyb3RsaUVuY29kaW5nIiwiZXhwb3J0cyIsImNob29zZURlY29tcHJlc3NlciIsInJlcyIsImRlY29tcHJlc3NlciIsImNyZWF0ZVVuemlwIiwiY3JlYXRlQnJvdGxpRGVjb21wcmVzcyIsIkVycm9yIl0sInNvdXJjZXMiOlsiLi4vLi4vc3JjL25vZGUvZGVjb21wcmVzcy5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJjb25zdCB6bGliID0gcmVxdWlyZSgnemxpYicpO1xuY29uc3QgdXRpbHMgPSByZXF1aXJlKCcuLi91dGlscycpO1xuY29uc3QgeyBpc0d6aXBPckRlZmxhdGVFbmNvZGluZywgaXNCcm90bGlFbmNvZGluZyB9ID0gdXRpbHM7XG5cbmV4cG9ydHMuY2hvb3NlRGVjb21wcmVzc2VyID0gKHJlcykgPT4ge1xuICBsZXQgZGVjb21wcmVzc2VyO1xuICBpZiAoaXNHemlwT3JEZWZsYXRlRW5jb2RpbmcocmVzKSkge1xuICAgIGRlY29tcHJlc3NlciA9IHpsaWIuY3JlYXRlVW56aXAoKTtcbiAgfSBlbHNlIGlmIChpc0Jyb3RsaUVuY29kaW5nKHJlcykpIHtcbiAgICBkZWNvbXByZXNzZXIgPSB6bGliLmNyZWF0ZUJyb3RsaURlY29tcHJlc3MoKTtcbiAgfSBlbHNlIHtcbiAgICB0aHJvdyBuZXcgRXJyb3IoJ3Vua25vd24gY29udGVudC1lbmNvZGluZycpO1xuICB9XG4gIHJldHVybiBkZWNvbXByZXNzZXI7XG59XG4iXSwibWFwcGluZ3MiOiI7O0FBQUEsTUFBTUEsSUFBSSxHQUFHQyxPQUFPLENBQUMsTUFBTSxDQUFDO0FBQzVCLE1BQU1DLEtBQUssR0FBR0QsT0FBTyxDQUFDLFVBQVUsQ0FBQztBQUNqQyxNQUFNO0VBQUVFLHVCQUF1QjtFQUFFQztBQUFpQixDQUFDLEdBQUdGLEtBQUs7QUFFM0RHLE9BQU8sQ0FBQ0Msa0JBQWtCLEdBQUlDLEdBQUcsSUFBSztFQUNwQyxJQUFJQyxZQUFZO0VBQ2hCLElBQUlMLHVCQUF1QixDQUFDSSxHQUFHLENBQUMsRUFBRTtJQUNoQ0MsWUFBWSxHQUFHUixJQUFJLENBQUNTLFdBQVcsQ0FBQyxDQUFDO0VBQ25DLENBQUMsTUFBTSxJQUFJTCxnQkFBZ0IsQ0FBQ0csR0FBRyxDQUFDLEVBQUU7SUFDaENDLFlBQVksR0FBR1IsSUFBSSxDQUFDVSxzQkFBc0IsQ0FBQyxDQUFDO0VBQzlDLENBQUMsTUFBTTtJQUNMLE1BQU0sSUFBSUMsS0FBSyxDQUFDLDBCQUEwQixDQUFDO0VBQzdDO0VBQ0EsT0FBT0gsWUFBWTtBQUNyQixDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/http2wrapper.js b/node_modules/superagent/lib/node/http2wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..9ba0955b25ec7da2c6dbaef2db13373843f91153 --- /dev/null +++ b/node_modules/superagent/lib/node/http2wrapper.js @@ -0,0 +1,158 @@ +"use strict"; + +const http2 = require('http2'); +const Stream = require('stream'); +const net = require('net'); +const tls = require('tls'); +const { + HTTP2_HEADER_PATH, + HTTP2_HEADER_STATUS, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_HOST, + HTTP2_HEADER_SET_COOKIE, + NGHTTP2_CANCEL +} = http2.constants; +function setProtocol(protocol) { + return { + request(options) { + return new Request(protocol, options); + } + }; +} +function normalizeIpv6Host(host) { + return net.isIP(host) === 6 ? `[${host}]` : host; +} +class Request extends Stream { + constructor(protocol, options) { + super(); + const defaultPort = protocol === 'https:' ? 443 : 80; + const defaultHost = 'localhost'; + const port = options.port || defaultPort; + const host = options.host || defaultHost; + delete options.port; + delete options.host; + this.method = options.method; + this.path = options.path; + this.protocol = protocol; + this.host = host; + delete options.method; + delete options.path; + const sessionOptions = { + ...options + }; + if (options.socketPath) { + sessionOptions.socketPath = options.socketPath; + sessionOptions.createConnection = this.createUnixConnection.bind(this); + } + this._headers = {}; + const normalizedHost = normalizeIpv6Host(host); + const session = http2.connect(`${protocol}//${normalizedHost}:${port}`, sessionOptions); + this.setHeader('host', `${normalizedHost}:${port}`); + session.on('error', error => this.emit('error', error)); + this.session = session; + } + createUnixConnection(authority, options) { + switch (this.protocol) { + case 'http:': + return net.connect(options.socketPath); + case 'https:': + options.ALPNProtocols = ['h2']; + options.servername = this.host; + options.allowHalfOpen = true; + return tls.connect(options.socketPath, options); + default: + throw new Error('Unsupported protocol', this.protocol); + } + } + setNoDelay(bool) { + // We can not use setNoDelay with HTTP/2. + // Node 10 limits http2session.socket methods to ones safe to use with HTTP/2. + // See also https://nodejs.org/api/http2.html#http2_http2session_socket + } + getFrame() { + if (this.frame) { + return this.frame; + } + const method = { + [HTTP2_HEADER_PATH]: this.path, + [HTTP2_HEADER_METHOD]: this.method + }; + let headers = this.mapToHttp2Header(this._headers); + headers = Object.assign(headers, method); + const frame = this.session.request(headers); + frame.once('response', (headers, flags) => { + headers = this.mapToHttpHeader(headers); + frame.headers = headers; + frame.statusCode = headers[HTTP2_HEADER_STATUS]; + frame.status = frame.statusCode; + this.emit('response', frame); + }); + this._headerSent = true; + frame.once('drain', () => this.emit('drain')); + frame.on('error', error => this.emit('error', error)); + frame.on('close', () => this.session.close()); + this.frame = frame; + return frame; + } + mapToHttpHeader(headers) { + const keys = Object.keys(headers); + const http2Headers = {}; + for (let key of keys) { + let value = headers[key]; + key = key.toLowerCase(); + switch (key) { + case HTTP2_HEADER_SET_COOKIE: + value = Array.isArray(value) ? value : [value]; + break; + default: + break; + } + http2Headers[key] = value; + } + return http2Headers; + } + mapToHttp2Header(headers) { + const keys = Object.keys(headers); + const http2Headers = {}; + for (let key of keys) { + let value = headers[key]; + key = key.toLowerCase(); + switch (key) { + case HTTP2_HEADER_HOST: + key = HTTP2_HEADER_AUTHORITY; + value = /^http:\/\/|^https:\/\//.test(value) ? new URL(value).host : value; + break; + default: + break; + } + http2Headers[key] = value; + } + return http2Headers; + } + setHeader(name, value) { + this._headers[name.toLowerCase()] = value; + } + getHeader(name) { + return this._headers[name.toLowerCase()]; + } + write(data, encoding) { + const frame = this.getFrame(); + return frame.write(data, encoding); + } + pipe(stream, options) { + const frame = this.getFrame(); + return frame.pipe(stream, options); + } + end(data) { + const frame = this.getFrame(); + frame.end(data); + } + abort(data) { + const frame = this.getFrame(); + frame.close(NGHTTP2_CANCEL); + this.session.destroy(); + } +} +exports.setProtocol = setProtocol; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJodHRwMiIsInJlcXVpcmUiLCJTdHJlYW0iLCJuZXQiLCJ0bHMiLCJIVFRQMl9IRUFERVJfUEFUSCIsIkhUVFAyX0hFQURFUl9TVEFUVVMiLCJIVFRQMl9IRUFERVJfTUVUSE9EIiwiSFRUUDJfSEVBREVSX0FVVEhPUklUWSIsIkhUVFAyX0hFQURFUl9IT1NUIiwiSFRUUDJfSEVBREVSX1NFVF9DT09LSUUiLCJOR0hUVFAyX0NBTkNFTCIsImNvbnN0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xDQUFDRCxRQUFRLENBQUMsQ0FBQztJQUM3QkMsS0FBSyxDQUFDNEIsR0FBRyxDQUFDSixJQUFJLENBQUM7RUFDakI7RUFFQUssS0FBS0EsQ0FBQ0wsSUFBSSxFQUFFO0lBQ1YsTUFBTXhCLEtBQUssR0FBRyxJQUFJLENBQUNELFFBQVEsQ0FBQyxDQUFDO0lBQzdCQyxLQUFLLENBQUNXLEtBQUssQ0FBQ2hELGNBQWMsQ0FBQztJQUMzQixJQUFJLENBQUN1QixPQUFPLENBQUM0QyxPQUFPLENBQUMsQ0FBQztFQUN4QjtBQUNGO0FBRUFDLE9BQU8sQ0FBQ2xFLFdBQVcsR0FBR0EsV0FBVyIsImlnbm9yZUxpc3QiOltdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/node/index.js b/node_modules/superagent/lib/node/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f12ccfd387f7373bbbc8ebe487cdb1e8a73db42c --- /dev/null +++ b/node_modules/superagent/lib/node/index.js @@ -0,0 +1,1332 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const { + format +} = require('url'); +const Stream = require('stream'); +const https = require('https'); +const http = require('http'); +const fs = require('fs'); +const zlib = require('zlib'); +const util = require('util'); +const qs = require('qs'); +const mime = require('mime'); +let methods = require('methods'); +const FormData = require('form-data'); +const formidable = require('formidable'); +const debug = require('debug')('superagent'); +const CookieJar = require('cookiejar'); +const safeStringify = require('fast-safe-stringify'); +const utils = require('../utils'); +const RequestBase = require('../request-base'); +const http2 = require('./http2wrapper'); +const { + decompress +} = require('./unzip'); +const Response = require('./response'); +const { + mixin, + hasOwn, + isBrotliEncoding, + isGzipOrDeflateEncoding +} = utils; +const { + chooseDecompresser +} = require('./decompress'); +function request(method, url) { + // callback + if (typeof url === 'function') { + return new exports.Request('GET', method).end(url); + } + + // url first + if (arguments.length === 1) { + return new exports.Request('GET', method); + } + return new exports.Request(method, url); +} +module.exports = request; +exports = module.exports; + +/** + * Expose `Request`. + */ + +exports.Request = Request; + +/** + * Expose the agent function + */ + +exports.agent = require('./agent'); + +/** + * Noop. + */ + +function noop() {} + +/** + * Expose `Response`. + */ + +exports.Response = Response; + +/** + * Define "form" mime type. + */ + +mime.define({ + 'application/x-www-form-urlencoded': ['form', 'urlencoded', 'form-data'] +}, true); + +/** + * Protocol map. + */ + +exports.protocols = { + 'http:': http, + 'https:': https, + 'http2:': http2 +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + +exports.serialize = { + 'application/x-www-form-urlencoded': obj => { + return qs.stringify(obj, { + indices: false, + strictNullHandling: true + }); + }, + 'application/json': safeStringify +}; + +/** + * Default parsers. + * + * superagent.parse['application/xml'] = function(res, fn){ + * fn(null, res); + * }; + * + */ + +exports.parse = require('./parsers'); + +/** + * Default buffering map. Can be used to set certain + * response types to buffer/not buffer. + * + * superagent.buffer['application/xml'] = true; + */ +exports.buffer = {}; + +/** + * Initialize internal header tracking properties on a request instance. + * + * @param {Object} req the instance + * @api private + */ +function _initHeaders(request_) { + request_._header = { + // coerces header names to lowercase + }; + request_.header = { + // preserves header name case + }; +} + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String|Object} url + * @api public + */ + +function Request(method, url) { + Stream.call(this); + if (typeof url !== 'string') url = format(url); + this._enableHttp2 = Boolean(process.env.HTTP2_TEST); // internal only + this._agent = false; + this._formData = null; + this.method = method; + this.url = url; + _initHeaders(this); + this.writable = true; + this._redirects = 0; + this.redirects(method === 'HEAD' ? 0 : 5); + this.cookies = ''; + this.qs = {}; + this._query = []; + this.qsRaw = this._query; // Unused, for backwards compatibility only + this._redirectList = []; + this._streamRequest = false; + this._lookup = undefined; + this.once('end', this.clearTimeout.bind(this)); +} + +/** + * Inherit from `Stream` (which inherits from `EventEmitter`). + * Mixin `RequestBase`. + */ +util.inherits(Request, Stream); +mixin(Request.prototype, RequestBase.prototype); + +/** + * Enable or Disable http2. + * + * Enable http2. + * + * ``` js + * request.get('http://localhost/') + * .http2() + * .end(callback); + * + * request.get('http://localhost/') + * .http2(true) + * .end(callback); + * ``` + * + * Disable http2. + * + * ``` js + * request = request.http2(); + * request.get('http://localhost/') + * .http2(false) + * .end(callback); + * ``` + * + * @param {Boolean} enable + * @return {Request} for chaining + * @api public + */ + +Request.prototype.http2 = function (bool) { + if (exports.protocols['http2:'] === undefined) { + throw new Error('superagent: this version of Node.js does not support http2'); + } + this._enableHttp2 = bool === undefined ? true : bool; + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('http://localhost/upload') + * .attach('field', Buffer.from('Hello world'), 'hello.html') + * .end(callback); + * ``` + * + * A filename may also be used: + * + * ``` js + * request.post('http://localhost/upload') + * .attach('files', 'image.jpg') + * .end(callback); + * ``` + * + * @param {String} field + * @param {String|fs.ReadStream|Buffer} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function (field, file, options) { + if (file) { + if (this._data) { + throw new Error("superagent can't mix .send() and .attach()"); + } + let o = options || {}; + if (typeof options === 'string') { + o = { + filename: options + }; + } + if (typeof file === 'string') { + if (!o.filename) o.filename = file; + debug('creating `fs.ReadStream` instance for file: %s', file); + file = fs.createReadStream(file); + file.on('error', error => { + const formData = this._getFormData(); + formData.emit('error', error); + }); + } else if (!o.filename && file.path) { + o.filename = file.path; + } + this._getFormData().append(field, file, o); + } + return this; +}; +Request.prototype._getFormData = function () { + if (!this._formData) { + this._formData = new FormData(); + this._formData.on('error', error => { + debug('FormData error', error); + if (this.called) { + // The request has already finished and the callback was called. + // Silently ignore the error. + return; + } + this.callback(error); + this.abort(); + }); + } + return this._formData; +}; + +/** + * Gets/sets the `Agent` to use for this HTTP request. The default (if this + * function is not called) is to opt out of connection pooling (`agent: false`). + * + * @param {http.Agent} agent + * @return {http.Agent} + * @api public + */ + +Request.prototype.agent = function (agent) { + if (arguments.length === 0) return this._agent; + this._agent = agent; + return this; +}; + +/** + * Gets/sets the `lookup` function to use custom DNS resolver. + * + * @param {Function} lookup + * @return {Function} + * @api public + */ + +Request.prototype.lookup = function (lookup) { + if (arguments.length === 0) return this._lookup; + this._lookup = lookup; + return this; +}; + +/** + * Set _Content-Type_ response header passed through `mime.getType()`. + * + * Examples: + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('json') + * .send(jsonstring) + * .end(callback); + * + * request.post('/') + * .type('application/json') + * .send(jsonstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function (type) { + return this.set('Content-Type', type.includes('/') ? type : mime.getType(type)); +}; + +/** + * Set _Accept_ response header passed through `mime.getType()`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function (type) { + return this.set('Accept', type.includes('/') ? type : mime.getType(type)); +}; + +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.query = function (value) { + if (typeof value === 'string') { + this._query.push(value); + } else { + Object.assign(this.qs, value); + } + return this; +}; + +/** + * Write raw `data` / `encoding` to the socket. + * + * @param {Buffer|String} data + * @param {String} encoding + * @return {Boolean} + * @api public + */ + +Request.prototype.write = function (data, encoding) { + const request_ = this.request(); + if (!this._streamRequest) { + this._streamRequest = true; + } + return request_.write(data, encoding); +}; + +/** + * Pipe the request body to `stream`. + * + * @param {Stream} stream + * @param {Object} options + * @return {Stream} + * @api public + */ + +Request.prototype.pipe = function (stream, options) { + this.piped = true; // HACK... + this.buffer(false); + this.end(); + return this._pipeContinue(stream, options); +}; +Request.prototype._pipeContinue = function (stream, options) { + this.req.once('response', res => { + // redirect + if (isRedirect(res.statusCode) && this._redirects++ !== this._maxRedirects) { + return this._redirect(res) === this ? this._pipeContinue(stream, options) : undefined; + } + this.res = res; + this._emitResponse(); + if (this._aborted) return; + if (this._shouldDecompress(res)) { + let decompresser = chooseDecompresser(res); + decompresser.on('error', error => { + if (error && error.code === 'Z_BUF_ERROR') { + // unexpected end of file is ignored by browsers and curl + stream.emit('end'); + return; + } + stream.emit('error', error); + }); + res.pipe(decompresser).pipe(stream, options); + // don't emit 'end' until decompresser has completed writing all its data. + decompresser.once('end', () => this.emit('end')); + } else { + res.pipe(stream, options); + res.once('end', () => this.emit('end')); + } + }); + return stream; +}; + +/** + * Enable / disable buffering. + * + * @return {Boolean} [val] + * @return {Request} for chaining + * @api public + */ + +Request.prototype.buffer = function (value) { + this._buffer = value !== false; + return this; +}; + +/** + * Redirect to `url + * + * @param {IncomingMessage} res + * @return {Request} for chaining + * @api private + */ + +Request.prototype._redirect = function (res) { + let url = res.headers.location; + if (!url) { + return this.callback(new Error('No location header for redirect'), res); + } + debug('redirect %s -> %s', this.url, url); + + // location + url = new URL(url, this.url).href; + + // ensure the response is being consumed + // this is required for Node v0.10+ + res.resume(); + let headers = this.req.getHeaders ? this.req.getHeaders() : this.req._headers; + const changesOrigin = new URL(url).host !== new URL(this.url).host; + + // implementation of 302 following defacto standard + if (res.statusCode === 301 || res.statusCode === 302) { + // strip Content-* related fields + // in case of POST etc + headers = utils.cleanHeader(headers, changesOrigin); + + // force GET + this.method = this.method === 'HEAD' ? 'HEAD' : 'GET'; + + // clear data + this._data = null; + } + + // 303 is always GET + if (res.statusCode === 303) { + // strip Content-* related fields + // in case of POST etc + headers = utils.cleanHeader(headers, changesOrigin); + + // force method + this.method = 'GET'; + + // clear data + this._data = null; + } + + // 307 preserves method + // 308 preserves method + delete headers.host; + delete this.req; + delete this._formData; + + // remove all add header except User-Agent + _initHeaders(this); + + // redirect + this.res = res; + this._endCalled = false; + this.url = url; + this.qs = {}; + this._query.length = 0; + this.set(headers); + this._emitRedirect(); + this._redirectList.push(this.url); + this.end(this._callback); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * Examples: + * + * .auth('tobi', 'learnboost') + * .auth('tobi:learnboost') + * .auth('tobi') + * .auth(accessToken, { type: 'bearer' }) + * + * @param {String} user + * @param {String} [pass] + * @param {Object} [options] options with authorization type 'basic' or 'bearer' ('basic' is default) + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function (user, pass, options) { + if (arguments.length === 1) pass = ''; + if (typeof pass === 'object' && pass !== null) { + // pass is optional and can be replaced with options + options = pass; + pass = ''; + } + if (!options) { + options = { + type: 'basic' + }; + } + const encoder = string => Buffer.from(string).toString('base64'); + return this._auth(user, pass, options, encoder); +}; + +/** + * Set the certificate authority option for https request. + * + * @param {Buffer | Array} cert + * @return {Request} for chaining + * @api public + */ + +Request.prototype.ca = function (cert) { + this._ca = cert; + return this; +}; + +/** + * Set the client certificate key option for https request. + * + * @param {Buffer | String} cert + * @return {Request} for chaining + * @api public + */ + +Request.prototype.key = function (cert) { + this._key = cert; + return this; +}; + +/** + * Set the key, certificate, and CA certs of the client in PFX or PKCS12 format. + * + * @param {Buffer | String} cert + * @return {Request} for chaining + * @api public + */ + +Request.prototype.pfx = function (cert) { + if (typeof cert === 'object' && !Buffer.isBuffer(cert)) { + this._pfx = cert.pfx; + this._passphrase = cert.passphrase; + } else { + this._pfx = cert; + } + return this; +}; + +/** + * Set the client certificate option for https request. + * + * @param {Buffer | String} cert + * @return {Request} for chaining + * @api public + */ + +Request.prototype.cert = function (cert) { + this._cert = cert; + return this; +}; + +/** + * Do not reject expired or invalid TLS certs. + * sets `rejectUnauthorized=true`. Be warned that this allows MITM attacks. + * + * @return {Request} for chaining + * @api public + */ + +Request.prototype.disableTLSCerts = function () { + this._disableTLSCerts = true; + return this; +}; + +/** + * Return an http[s] request. + * + * @return {OutgoingMessage} + * @api private + */ + +// eslint-disable-next-line complexity +Request.prototype.request = function () { + if (this.req) return this.req; + const options = {}; + try { + const query = qs.stringify(this.qs, { + indices: false, + strictNullHandling: true + }); + if (query) { + this.qs = {}; + this._query.push(query); + } + this._finalizeQueryString(); + } catch (err) { + return this.emit('error', err); + } + let { + url: urlString + } = this; + const retries = this._retries; + + // default to http:// + if (urlString.indexOf('http') !== 0) urlString = `http://${urlString}`; + const url = new URL(urlString); + let { + protocol + } = url; + let path = `${url.pathname}${url.search}`; + + // support unix sockets + if (/^https?\+unix:/.test(protocol) === true) { + // get the protocol + protocol = `${protocol.split('+')[0]}:`; + + // get the socket path + options.socketPath = url.hostname.replace(/%2F/g, '/'); + url.host = ''; + url.hostname = ''; + } + + // Override IP address of a hostname + if (this._connectOverride) { + const { + hostname + } = url; + const match = hostname in this._connectOverride ? this._connectOverride[hostname] : this._connectOverride['*']; + if (match) { + // backup the real host + if (!this._header.host) { + this.set('host', url.host); + } + let newHost; + let newPort; + if (typeof match === 'object') { + newHost = match.host; + newPort = match.port; + } else { + newHost = match; + newPort = url.port; + } + + // wrap [ipv6] + url.host = /:/.test(newHost) ? `[${newHost}]` : newHost; + if (newPort) { + url.host += `:${newPort}`; + url.port = newPort; + } + url.hostname = newHost; + } + } + + // options + options.method = this.method; + options.port = url.port; + options.path = path; + options.host = utils.normalizeHostname(url.hostname); // ex: [::1] -> ::1 + options.ca = this._ca; + options.key = this._key; + options.pfx = this._pfx; + options.cert = this._cert; + options.passphrase = this._passphrase; + options.agent = this._agent; + options.lookup = this._lookup; + options.rejectUnauthorized = typeof this._disableTLSCerts === 'boolean' ? !this._disableTLSCerts : process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'; + + // Allows request.get('https://1.2.3.4/').set('Host', 'example.com') + if (this._header.host) { + options.servername = this._header.host.replace(/:\d+$/, ''); + } + if (this._trustLocalhost && /^(?:localhost|127\.0\.0\.\d+|(0*:)+:0*1)$/.test(url.hostname)) { + options.rejectUnauthorized = false; + } + + // initiate request + const module_ = this._enableHttp2 ? exports.protocols['http2:'].setProtocol(protocol) : exports.protocols[protocol]; + + // request + this.req = module_.request(options); + const { + req + } = this; + + // set tcp no delay + req.setNoDelay(true); + if (options.method !== 'HEAD') { + req.setHeader('Accept-Encoding', 'gzip, deflate'); + } + this.protocol = protocol; + this.host = url.host; + + // expose events + req.once('drain', () => { + this.emit('drain'); + }); + req.on('error', error => { + // flag abortion here for out timeouts + // because node will emit a faux-error "socket hang up" + // when request is aborted before a connection is made + if (this._aborted) return; + // if not the same, we are in the **old** (cancelled) request, + // so need to continue (same as for above) + if (this._retries !== retries) return; + // if we've received a response then we don't want to let + // an error in the request blow up the response + if (this.response) return; + this.callback(error); + }); + + // auth + if (url.username || url.password) { + this.auth(url.username, url.password); + } + if (this.username && this.password) { + this.auth(this.username, this.password); + } + for (const key in this.header) { + if (hasOwn(this.header, key)) req.setHeader(key, this.header[key]); + } + + // add cookies + if (this.cookies) { + if (hasOwn(this._header, 'cookie')) { + // merge + const temporaryJar = new CookieJar.CookieJar(); + temporaryJar.setCookies(this._header.cookie.split('; ')); + temporaryJar.setCookies(this.cookies.split('; ')); + req.setHeader('Cookie', temporaryJar.getCookies(CookieJar.CookieAccessInfo.All).toValueString()); + } else { + req.setHeader('Cookie', this.cookies); + } + } + return req; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function (error, res) { + if (this._shouldRetry(error, res)) { + return this._retry(); + } + + // Avoid the error which is emitted from 'socket hang up' to cause the fn undefined error on JS runtime. + const fn = this._callback || noop; + this.clearTimeout(); + if (this.called) return console.warn('superagent: double callback bug'); + this.called = true; + if (!error) { + try { + if (!this._isResponseOK(res)) { + let message = 'Unsuccessful HTTP response'; + if (res) { + message = http.STATUS_CODES[res.status] || message; + } + error = new Error(message); + error.status = res ? res.status : undefined; + } + } catch (err) { + error = err; + error.status = error.status || (res ? res.status : undefined); + } + } + + // It's important that the callback is called outside try/catch + // to avoid double callback + if (!error) { + return fn(null, res); + } + error.response = res; + if (this._maxRetries) error.retries = this._retries - 1; + + // only emit error event if there is a listener + // otherwise we assume the callback to `.end()` will get the error + if (error && this.listeners('error').length > 0) { + this.emit('error', error); + } + fn(error, res); +}; + +/** + * Check if `obj` is a host object, + * + * @param {Object} obj host object + * @return {Boolean} is a host object + * @api private + */ +Request.prototype._isHost = function (object) { + return Buffer.isBuffer(object) || object instanceof Stream || object instanceof FormData; +}; + +/** + * Initiate request, invoking callback `fn(err, res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype._emitResponse = function (body, files) { + const response = new Response(this); + this.response = response; + response.redirects = this._redirectList; + if (undefined !== body) { + response.body = body; + } + response.files = files; + if (this._endCalled) { + response.pipe = function () { + throw new Error("end() has already been called, so it's too late to start piping"); + }; + } + this.emit('response', response); + return response; +}; + +/** + * Emit `redirect` event, passing an instanceof `Response`. + * + * @api private + */ + +Request.prototype._emitRedirect = function () { + const response = new Response(this); + response.redirects = this._redirectList; + this.emit('redirect', response); +}; +Request.prototype.end = function (fn) { + this.request(); + debug('%s %s', this.method, this.url); + if (this._endCalled) { + throw new Error('.end() was called twice. This is not supported in superagent'); + } + this._endCalled = true; + + // store callback + this._callback = fn || noop; + this._end(); +}; +Request.prototype._end = function () { + if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); + let data = this._data; + const { + req + } = this; + const { + method + } = this; + this._setTimeouts(); + + // body + if (method !== 'HEAD' && !req._headerSent) { + // serialize stuff + if (typeof data !== 'string') { + let contentType = req.getHeader('Content-Type'); + // Parse out just the content type from the header (ignore the charset) + if (contentType) contentType = contentType.split(';')[0]; + let serialize = this._serializer || exports.serialize[contentType]; + if (!serialize && isJSON(contentType)) { + serialize = exports.serialize['application/json']; + } + if (serialize) data = serialize(data); + } + + // content-length + if (data && !req.getHeader('Content-Length')) { + req.setHeader('Content-Length', Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data)); + } + } + + // response + // eslint-disable-next-line complexity + req.once('response', res => { + debug('%s %s -> %s', this.method, this.url, res.statusCode); + if (this._responseTimeoutTimer) { + clearTimeout(this._responseTimeoutTimer); + } + if (this.piped) { + return; + } + const max = this._maxRedirects; + const mime = utils.type(res.headers['content-type'] || '') || 'text/plain'; + let type = mime.split('/')[0]; + if (type) type = type.toLowerCase().trim(); + const multipart = type === 'multipart'; + const redirect = isRedirect(res.statusCode); + const responseType = this._responseType; + this.res = res; + + // redirect + if (redirect && this._redirects++ !== max) { + return this._redirect(res); + } + if (this.method === 'HEAD') { + this.emit('end'); + this.callback(null, this._emitResponse()); + return; + } + + // zlib support + if (this._shouldDecompress(res)) { + decompress(req, res); + } + let buffer = this._buffer; + if (buffer === undefined && mime in exports.buffer) { + buffer = Boolean(exports.buffer[mime]); + } + let parser = this._parser; + if (undefined === buffer && parser) { + console.warn("A custom superagent parser has been set, but buffering strategy for the parser hasn't been configured. Call `req.buffer(true or false)` or set `superagent.buffer[mime] = true or false`"); + buffer = true; + } + if (!parser) { + if (responseType) { + parser = exports.parse.image; // It's actually a generic Buffer + buffer = true; + } else if (multipart) { + const form = formidable.formidable(); + parser = (res, callback) => { + // Create a PassThrough stream that acts as a proper HTTP request + const bridgeStream = new Stream.PassThrough(); + + // Add HTTP request properties from the current request context + bridgeStream.method = this.method || 'POST'; + bridgeStream.url = this.url || '/'; + bridgeStream.httpVersion = res.httpVersion || '1.1'; + bridgeStream.headers = res.headers || {}; + bridgeStream.socket = res.socket || { + readable: true + }; + + // Pipe the response data through the bridge stream + res.pipe(bridgeStream); + form.parse(bridgeStream, (err, fields, files) => { + if (err) return callback(err); + + // Formidable v3 always returns arrays, but SuperAgent expects single values + // Flatten single-item arrays to maintain backward compatibility + const flattenedFields = {}; + if (fields) { + for (const key in fields) { + const value = fields[key]; + flattenedFields[key] = Array.isArray(value) && value.length === 1 ? value[0] : value; + } + } + const flattenedFiles = {}; + if (files) { + for (const key in files) { + const value = files[key]; + flattenedFiles[key] = Array.isArray(value) && value.length === 1 ? value[0] : value; + } + } + + // Return flattened fields as the object parameter to match SuperAgent's expected format + callback(null, flattenedFields, flattenedFiles); + }); + }; + buffer = true; + } else if (isBinary(mime)) { + parser = exports.parse.image; + buffer = true; // For backwards-compatibility buffering default is ad-hoc MIME-dependent + } else if (exports.parse[mime]) { + parser = exports.parse[mime]; + } else if (type === 'text') { + parser = exports.parse.text; + buffer = buffer !== false; + // everyone wants their own white-labeled json + } else if (isJSON(mime)) { + parser = exports.parse['application/json']; + buffer = buffer !== false; + } else if (buffer) { + parser = exports.parse.text; + } else if (undefined === buffer) { + parser = exports.parse.image; // It's actually a generic Buffer + buffer = true; + } + } + + // by default only buffer text/*, json and messed up thing from hell + if (undefined === buffer && isText(mime) || isJSON(mime)) { + buffer = true; + } + this._resBuffered = buffer; + let parserHandlesEnd = false; + if (buffer) { + // Protectiona against zip bombs and other nuisance + let responseBytesLeft = this._maxResponseSize || 200000000; + res.on('data', buf => { + responseBytesLeft -= buf.byteLength || buf.length > 0 ? buf.length : 0; + if (responseBytesLeft < 0) { + // This will propagate through error event + const error = new Error('Maximum response size reached'); + error.code = 'ETOOLARGE'; + // Parsers aren't required to observe error event, + // so would incorrectly report success + parserHandlesEnd = false; + // Will not emit error event + res.destroy(error); + // so we do callback now + this.callback(error, null); + } + }); + } + if (parser) { + try { + // Unbuffered parsers are supposed to emit response early, + // which is weird BTW, because response.body won't be there. + parserHandlesEnd = buffer; + parser(res, (error, object, files) => { + if (this.timedout) { + // Timeout has already handled all callbacks + return; + } + + // Intentional (non-timeout) abort is supposed to preserve partial response, + // even if it doesn't parse. + if (error && !this._aborted) { + return this.callback(error); + } + if (parserHandlesEnd) { + this.emit('end'); + this.callback(null, this._emitResponse(object, files)); + } + }); + } catch (err) { + this.callback(err); + return; + } + } + this.res = res; + + // unbuffered + if (!buffer) { + debug('unbuffered %s %s', this.method, this.url); + this.callback(null, this._emitResponse()); + if (multipart) return; // allow multipart to handle end event + res.once('end', () => { + debug('end %s %s', this.method, this.url); + this.emit('end'); + }); + return; + } + + // terminating events + res.once('error', error => { + parserHandlesEnd = false; + this.callback(error, null); + }); + if (!parserHandlesEnd) res.once('end', () => { + debug('end %s %s', this.method, this.url); + // TODO: unless buffering emit earlier to stream + this.emit('end'); + this.callback(null, this._emitResponse()); + }); + }); + this.emit('request', this); + const getProgressMonitor = () => { + const lengthComputable = true; + const total = req.getHeader('Content-Length'); + let loaded = 0; + const progress = new Stream.Transform(); + progress._transform = (chunk, encoding, callback) => { + loaded += chunk.length; + this.emit('progress', { + direction: 'upload', + lengthComputable, + loaded, + total + }); + callback(null, chunk); + }; + return progress; + }; + const bufferToChunks = buffer => { + const chunkSize = 16 * 1024; // default highWaterMark value + const chunking = new Stream.Readable(); + const totalLength = buffer.length; + const remainder = totalLength % chunkSize; + const cutoff = totalLength - remainder; + for (let i = 0; i < cutoff; i += chunkSize) { + const chunk = buffer.slice(i, i + chunkSize); + chunking.push(chunk); + } + if (remainder > 0) { + const remainderBuffer = buffer.slice(-remainder); + chunking.push(remainderBuffer); + } + chunking.push(null); // no more data + + return chunking; + }; + + // if a FormData instance got created, then we send that as the request body + const formData = this._formData; + if (formData) { + // set headers + const headers = formData.getHeaders(); + for (const i in headers) { + if (hasOwn(headers, i)) { + debug('setting FormData header: "%s: %s"', i, headers[i]); + req.setHeader(i, headers[i]); + } + } + + // attempt to get "Content-Length" header + formData.getLength((error, length) => { + // TODO: Add chunked encoding when no length (if err) + if (error) debug('formData.getLength had error', error, length); + debug('got FormData Content-Length: %s', length); + if (typeof length === 'number') { + req.setHeader('Content-Length', length); + } + formData.pipe(getProgressMonitor()).pipe(req); + }); + } else if (Buffer.isBuffer(data)) { + bufferToChunks(data).pipe(getProgressMonitor()).pipe(req); + } else { + req.end(data); + } +}; + +// Check whether response has a non-0-sized gzip-encoded body +Request.prototype._shouldDecompress = res => { + return hasNonEmptyResponseContent(res) && (isGzipOrDeflateEncoding(res) || isBrotliEncoding(res)); +}; + +/** + * Overrides DNS for selected hostnames. Takes object mapping hostnames to IP addresses. + * + * When making a request to a URL with a hostname exactly matching a key in the object, + * use the given IP address to connect, instead of using DNS to resolve the hostname. + * + * A special host `*` matches every hostname (keep redirects in mind!) + * + * request.connect({ + * 'test.example.com': '127.0.0.1', + * 'ipv6.example.com': '::1', + * }) + */ +Request.prototype.connect = function (connectOverride) { + if (typeof connectOverride === 'string') { + this._connectOverride = { + '*': connectOverride + }; + } else if (typeof connectOverride === 'object') { + this._connectOverride = connectOverride; + } else { + this._connectOverride = undefined; + } + return this; +}; +Request.prototype.trustLocalhost = function (toggle) { + this._trustLocalhost = toggle === undefined ? true : toggle; + return this; +}; + +// generate HTTP verb methods +if (!methods.includes('del')) { + // create a copy so we don't cause conflicts with + // other packages using the methods package and + // npm 3.x + methods = [...methods]; + methods.push('del'); +} +for (let method of methods) { + const name = method; + method = method === 'del' ? 'delete' : method; + method = method.toUpperCase(); + request[name] = (url, data, fn) => { + const request_ = request(method, url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) { + if (method === 'GET' || method === 'HEAD') { + request_.query(data); + } else { + request_.send(data); + } + } + if (fn) request_.end(fn); + return request_; + }; +} + +/** + * Check if `mime` is text and should be buffered. + * + * @param {String} mime + * @return {Boolean} + * @api public + */ + +function isText(mime) { + const parts = mime.split('/'); + let type = parts[0]; + if (type) type = type.toLowerCase().trim(); + let subtype = parts[1]; + if (subtype) subtype = subtype.toLowerCase().trim(); + return type === 'text' || subtype === 'x-www-form-urlencoded'; +} + +// This is not a catchall, but a start. It might be useful +// in the long run to have file that includes all binary +// content types from https://www.iana.org/assignments/media-types/media-types.xhtml +function isBinary(mime) { + let [registry, name] = mime.split('/'); + if (registry) registry = registry.toLowerCase().trim(); + if (name) name = name.toLowerCase().trim(); + return ['audio', 'font', 'image', 'video'].includes(registry) || ['gz', 'gzip'].includes(name); +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + // should match /json or +json + // but not /json-seq + return /[/+]json($|[^-\w])/i.test(mime); +} + +/** + * Check if we should follow the redirect `code`. + * + * @param {Number} code + * @return {Boolean} + * @api private + */ + +function isRedirect(code) { + return [301, 302, 303, 305, 307, 308].includes(code); +} +function hasNonEmptyResponseContent(res) { + if (res.statusCode === 204 || res.statusCode === 304) { + // These aren't supposed to have any body + return false; + } + + // header content is a string, and distinction between 0 and no information is crucial + if (res.headers['content-length'] === '0') { + // We know that the body is empty (unfortunately, this check does not cover chunked encoding) + return false; + } + return true; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmb3JtYXQiLCJyZXF1aXJlIiwiU3RyZWFtIiwiaHR0cHMiLCJodHRwIiwiZnMiLCJ6bGliIiwidXRpbCIsInFzIiwibWltZSIsIm1ldGhvZHMiLCJGb3JtRGF0YSIsImZvcm1pZGFibGUiLCJkZWJ1ZyIsIkNvb2tpZUphciIsInNhZmVTdHJpbmdpZnkiLCJ1dGlscyIsIlJlcXVlc3RCYXNlIiwiaHR0cDIiLCJkZWNvbXByZXNzIiwiUmVzcG9uc2UiLCJtaXhpbiIsImhhc093biIsImlzQnJvdGxpRW5jb2RpbmciLCJpc0d6aXBPckRlZmxhdGVFbmNvZGluZyIsImNob29zZURlY29tcHJlc3NlciIsInJlcXVlc3QiLCJtZXRob2QiLCJ1cmwiLCJleHBvcnRzIiwiUmVxdWVzdCIsImVuZCIsImFyZ3VtZW50cyIsImxlbmd0aCIsIm1vZHVsZSIsImFnZW50Iiwibm9vcCIsImRlZmluZSIsInByb3RvY29scyIsInNlcmlhbGl6ZSIsIm9iaiIsInN0cmluZ2lmeSIsImluZGljZXMiLCJzdHJpY3ROdWxsSGFuZGxpbmciLCJwYXJzZSIsImJ1ZmZlciIsIl9pbml0SGVhZGVycyIsInJlcXVlc3RfIiwiX2hlYWRlciIsImhlYWRlciIsImNhbGwiLCJfZW5hYmxlSHR0cDIiLCJCb29sZWFuIiwicHJvY2VzcyIsImVudiIsIkhUVFAyX1RFU1QiLCJfYWdlbnQiLCJfZm9ybURhdG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NBQVMzRCxNQUFNQSxDQUFDaE4sSUFBSSxFQUFFO0VBQ3BCO0VBQ0E7RUFDQSxPQUFPLHFCQUFxQixDQUFDOEosSUFBSSxDQUFDOUosSUFBSSxDQUFDO0FBQ3pDOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBLFNBQVN3RyxVQUFVQSxDQUFDUSxJQUFJLEVBQUU7RUFDeEIsT0FBTyxDQUFDLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxFQUFFLEdBQUcsRUFBRSxHQUFHLEVBQUUsR0FBRyxDQUFDLENBQUN6QixRQUFRLENBQUN5QixJQUFJLENBQUM7QUFDdEQ7QUFFQSxTQUFTc0osMEJBQTBCQSxDQUFDL0osR0FBRyxFQUFFO0VBQ3ZDLElBQUlBLEdBQUcsQ0FBQ0UsVUFBVSxLQUFLLEdBQUcsSUFBSUYsR0FBRyxDQUFDRSxVQUFVLEtBQUssR0FBRyxFQUFFO0lBQ3BEO0lBQ0EsT0FBTyxLQUFLO0VBQ2Q7O0VBRUE7RUFDQSxJQUFJRixHQUFHLENBQUNXLE9BQU8sQ0FBQyxnQkFBZ0IsQ0FBQyxLQUFLLEdBQUcsRUFBRTtJQUN6QztJQUNBLE9BQU8sS0FBSztFQUNkO0VBRUEsT0FBTyxJQUFJO0FBQ2IiLCJpZ25vcmVMaXN0IjpbXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/image.js b/node_modules/superagent/lib/node/parsers/image.js new file mode 100644 index 0000000000000000000000000000000000000000..c77432de92f635f835fac3ade18c09e564bc1864 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/image.js @@ -0,0 +1,13 @@ +"use strict"; + +module.exports = (res, fn) => { + const data = []; // Binary data needs binary storage + + res.on('data', chunk => { + data.push(chunk); + }); + res.on('end', () => { + fn(null, Buffer.concat(data)); + }); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJkYXRhIiwib24iLCJjaHVuayIsInB1c2giLCJCdWZmZXIiLCJjb25jYXQiXSwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvbm9kZS9wYXJzZXJzL2ltYWdlLmpzIl0sInNvdXJjZXNDb250ZW50IjpbIm1vZHVsZS5leHBvcnRzID0gKHJlcywgZm4pID0+IHtcbiAgY29uc3QgZGF0YSA9IFtdOyAvLyBCaW5hcnkgZGF0YSBuZWVkcyBiaW5hcnkgc3RvcmFnZVxuXG4gIHJlcy5vbignZGF0YScsIChjaHVuaykgPT4ge1xuICAgIGRhdGEucHVzaChjaHVuayk7XG4gIH0pO1xuICByZXMub24oJ2VuZCcsICgpID0+IHtcbiAgICBmbihudWxsLCBCdWZmZXIuY29uY2F0KGRhdGEpKTtcbiAgfSk7XG59O1xuIl0sIm1hcHBpbmdzIjoiOztBQUFBQSxNQUFNLENBQUNDLE9BQU8sR0FBRyxDQUFDQyxHQUFHLEVBQUVDLEVBQUUsS0FBSztFQUM1QixNQUFNQyxJQUFJLEdBQUcsRUFBRSxDQUFDLENBQUM7O0VBRWpCRixHQUFHLENBQUNHLEVBQUUsQ0FBQyxNQUFNLEVBQUdDLEtBQUssSUFBSztJQUN4QkYsSUFBSSxDQUFDRyxJQUFJLENBQUNELEtBQUssQ0FBQztFQUNsQixDQUFDLENBQUM7RUFDRkosR0FBRyxDQUFDRyxFQUFFLENBQUMsS0FBSyxFQUFFLE1BQU07SUFDbEJGLEVBQUUsQ0FBQyxJQUFJLEVBQUVLLE1BQU0sQ0FBQ0MsTUFBTSxDQUFDTCxJQUFJLENBQUMsQ0FBQztFQUMvQixDQUFDLENBQUM7QUFDSixDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/index.js b/node_modules/superagent/lib/node/parsers/index.js new file mode 100644 index 0000000000000000000000000000000000000000..06052a5e0fc92be78c12f4fd4354a3eb1c64a710 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/index.js @@ -0,0 +1,11 @@ +"use strict"; + +exports['application/x-www-form-urlencoded'] = require('./urlencoded'); +exports['application/json'] = require('./json'); +exports.text = require('./text'); +exports['application/json-seq'] = exports.text; +const binary = require('./image'); +exports['application/octet-stream'] = binary; +exports['application/pdf'] = binary; +exports.image = binary; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJleHBvcnRzIiwicmVxdWlyZSIsInRleHQiLCJiaW5hcnkiLCJpbWFnZSJdLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9ub2RlL3BhcnNlcnMvaW5kZXguanMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0c1snYXBwbGljYXRpb24veC13d3ctZm9ybS11cmxlbmNvZGVkJ10gPSByZXF1aXJlKCcuL3VybGVuY29kZWQnKTtcbmV4cG9ydHNbJ2FwcGxpY2F0aW9uL2pzb24nXSA9IHJlcXVpcmUoJy4vanNvbicpO1xuZXhwb3J0cy50ZXh0ID0gcmVxdWlyZSgnLi90ZXh0Jyk7XG5cbmV4cG9ydHNbJ2FwcGxpY2F0aW9uL2pzb24tc2VxJ10gPSBleHBvcnRzLnRleHQ7XG5cbmNvbnN0IGJpbmFyeSA9IHJlcXVpcmUoJy4vaW1hZ2UnKTtcblxuZXhwb3J0c1snYXBwbGljYXRpb24vb2N0ZXQtc3RyZWFtJ10gPSBiaW5hcnk7XG5leHBvcnRzWydhcHBsaWNhdGlvbi9wZGYnXSA9IGJpbmFyeTtcbmV4cG9ydHMuaW1hZ2UgPSBiaW5hcnk7XG4iXSwibWFwcGluZ3MiOiI7O0FBQUFBLE9BQU8sQ0FBQyxtQ0FBbUMsQ0FBQyxHQUFHQyxPQUFPLENBQUMsY0FBYyxDQUFDO0FBQ3RFRCxPQUFPLENBQUMsa0JBQWtCLENBQUMsR0FBR0MsT0FBTyxDQUFDLFFBQVEsQ0FBQztBQUMvQ0QsT0FBTyxDQUFDRSxJQUFJLEdBQUdELE9BQU8sQ0FBQyxRQUFRLENBQUM7QUFFaENELE9BQU8sQ0FBQyxzQkFBc0IsQ0FBQyxHQUFHQSxPQUFPLENBQUNFLElBQUk7QUFFOUMsTUFBTUMsTUFBTSxHQUFHRixPQUFPLENBQUMsU0FBUyxDQUFDO0FBRWpDRCxPQUFPLENBQUMsMEJBQTBCLENBQUMsR0FBR0csTUFBTTtBQUM1Q0gsT0FBTyxDQUFDLGlCQUFpQixDQUFDLEdBQUdHLE1BQU07QUFDbkNILE9BQU8sQ0FBQ0ksS0FBSyxHQUFHRCxNQUFNIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/json.js b/node_modules/superagent/lib/node/parsers/json.js new file mode 100644 index 0000000000000000000000000000000000000000..bce03c99d9cdc30be60ed39a05fc0f4d75f1a182 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/json.js @@ -0,0 +1,25 @@ +"use strict"; + +module.exports = function (res, fn) { + res.text = ''; + res.setEncoding('utf8'); + res.on('data', chunk => { + res.text += chunk; + }); + res.on('end', () => { + let body; + let error; + try { + body = res.text && JSON.parse(res.text); + } catch (err) { + error = err; + // issue #675: return the raw response if the response parsing fails + error.rawResponse = res.text || null; + // issue #876: return the http status code if the response parsing fails + error.statusCode = res.statusCode; + } finally { + fn(error, body); + } + }); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJ0ZXh0Iiwic2V0RW5jb2RpbmciLCJvbiIsImNodW5rIiwiYm9keSIsImVycm9yIiwiSlNPTiIsInBhcnNlIiwiZXJyIiwicmF3UmVzcG9uc2UiLCJzdGF0dXNDb2RlIl0sInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL25vZGUvcGFyc2Vycy9qc29uLmpzIl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JQUFLO0lBQ3hCTCxHQUFHLENBQUNFLElBQUksSUFBSUcsS0FBSztFQUNuQixDQUFDLENBQUM7RUFDRkwsR0FBRyxDQUFDSSxFQUFFLENBQUMsS0FBSyxFQUFFLE1BQU07SUFDbEIsSUFBSUUsSUFBSTtJQUNSLElBQUlDLEtBQUs7SUFDVCxJQUFJO01BQ0ZELElBQUksR0FBR04sR0FBRyxDQUFDRSxJQUFJLElBQUlNLElBQUksQ0FBQ0MsS0FBSyxDQUFDVCxHQUFHLENBQUNFLElBQUksQ0FBQztJQUN6QyxDQUFDLENBQUMsT0FBT1EsR0FBRyxFQUFFO01BQ1pILEtBQUssR0FBR0csR0FBRztNQUNYO01BQ0FILEtBQUssQ0FBQ0ksV0FBVyxHQUFHWCxHQUFHLENBQUNFLElBQUksSUFBSSxJQUFJO01BQ3BDO01BQ0FLLEtBQUssQ0FBQ0ssVUFBVSxHQUFHWixHQUFHLENBQUNZLFVBQVU7SUFDbkMsQ0FBQyxTQUFTO01BQ1JYLEVBQUUsQ0FBQ00sS0FBSyxFQUFFRCxJQUFJLENBQUM7SUFDakI7RUFDRixDQUFDLENBQUM7QUFDSixDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/text.js b/node_modules/superagent/lib/node/parsers/text.js new file mode 100644 index 0000000000000000000000000000000000000000..2304042a77cedef4391c07b57e7f9d809af67429 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/text.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = (res, fn) => { + res.text = ''; + res.setEncoding('utf8'); + res.on('data', chunk => { + res.text += chunk; + }); + res.on('end', fn); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJ0ZXh0Iiwic2V0RW5jb2RpbmciLCJvbiIsImNodW5rIl0sInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL25vZGUvcGFyc2Vycy90ZXh0LmpzIl0sInNvdXJjZXNDb250ZW50IjpbIm1vZHVsZS5leHBvcnRzID0gKHJlcywgZm4pID0+IHtcbiAgcmVzLnRleHQgPSAnJztcbiAgcmVzLnNldEVuY29kaW5nKCd1dGY4Jyk7XG4gIHJlcy5vbignZGF0YScsIChjaHVuaykgPT4ge1xuICAgIHJlcy50ZXh0ICs9IGNodW5rO1xuICB9KTtcbiAgcmVzLm9uKCdlbmQnLCBmbik7XG59O1xuIl0sIm1hcHBpbmdzIjoiOztBQUFBQSxNQUFNLENBQUNDLE9BQU8sR0FBRyxDQUFDQyxHQUFHLEVBQUVDLEVBQUUsS0FBSztFQUM1QkQsR0FBRyxDQUFDRSxJQUFJLEdBQUcsRUFBRTtFQUNiRixHQUFHLENBQUNHLFdBQVcsQ0FBQyxNQUFNLENBQUM7RUFDdkJILEdBQUcsQ0FBQ0ksRUFBRSxDQUFDLE1BQU0sRUFBR0MsS0FBSyxJQUFLO0lBQ3hCTCxHQUFHLENBQUNFLElBQUksSUFBSUcsS0FBSztFQUNuQixDQUFDLENBQUM7RUFDRkwsR0FBRyxDQUFDSSxFQUFFLENBQUMsS0FBSyxFQUFFSCxFQUFFLENBQUM7QUFDbkIsQ0FBQyIsImlnbm9yZUxpc3QiOltdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/urlencoded.js b/node_modules/superagent/lib/node/parsers/urlencoded.js new file mode 100644 index 0000000000000000000000000000000000000000..ea58bfa5b8a1729f2ee9499a2da88cb60fd79605 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/urlencoded.js @@ -0,0 +1,22 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const qs = require('qs'); +module.exports = (res, fn) => { + res.text = ''; + res.setEncoding('ascii'); + res.on('data', chunk => { + res.text += chunk; + }); + res.on('end', () => { + try { + fn(null, qs.parse(res.text)); + } catch (err) { + fn(err); + } + }); +}; +//# sourceMappingURL=data:application/json;charset=utf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BSSxJQUFJRyxLQUFLO0VBQ25CLENBQUMsQ0FBQztFQUNGTCxHQUFHLENBQUNJLEVBQUUsQ0FBQyxLQUFLLEVBQUUsTUFBTTtJQUNsQixJQUFJO01BQ0ZILEVBQUUsQ0FBQyxJQUFJLEVBQUVMLEVBQUUsQ0FBQ1UsS0FBSyxDQUFDTixHQUFHLENBQUNFLElBQUksQ0FBQyxDQUFDO0lBQzlCLENBQUMsQ0FBQyxPQUFPSyxHQUFHLEVBQUU7TUFDWk4sRUFBRSxDQUFDTSxHQUFHLENBQUM7SUFDVDtFQUNGLENBQUMsQ0FBQztBQUNKLENBQUMiLCJpZ25vcmVMaXN0IjpbXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/node/response.js b/node_modules/superagent/lib/node/response.js new file mode 100644 index 0000000000000000000000000000000000000000..3514fc7d5c373cc0ed0b762d73ac166c782cc1c5 --- /dev/null +++ b/node_modules/superagent/lib/node/response.js @@ -0,0 +1,143 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const util = require('util'); +const Stream = require('stream'); +const ResponseBase = require('../response-base'); +const { + mixin +} = require('../utils'); + +/** + * Expose `Response`. + */ + +module.exports = Response; + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * @param {Request} req + * @param {Object} options + * @constructor + * @extends {Stream} + * @implements {ReadableStream} + * @api private + */ + +function Response(request) { + Stream.call(this); + this.res = request.res; + const { + res + } = this; + this.request = request; + this.req = request.req; + this.text = res.text; + this.files = res.files || {}; + this.buffered = request._resBuffered; + this.headers = res.headers; + this.header = this.headers; + this._setStatusProperties(res.statusCode); + this._setHeaderProperties(this.header); + this.setEncoding = res.setEncoding.bind(res); + res.on('data', this.emit.bind(this, 'data')); + res.on('end', this.emit.bind(this, 'end')); + res.on('close', this.emit.bind(this, 'close')); + res.on('error', this.emit.bind(this, 'error')); +} + +// Lazy access res.body. +// https://github.com/nodejs/node/pull/39520#issuecomment-889697136 +Object.defineProperty(Response.prototype, 'body', { + get() { + return this._body !== undefined ? this._body : this.res.body !== undefined ? this.res.body : {}; + }, + set(value) { + this._body = value; + } +}); + +/** + * Inherit from `Stream`. + */ + +util.inherits(Response, Stream); +mixin(Response.prototype, ResponseBase.prototype); + +/** + * Implements methods of a `ReadableStream` + */ + +Response.prototype.destroy = function (error) { + this.res.destroy(error); +}; + +/** + * Pause. + */ + +Response.prototype.pause = function () { + this.res.pause(); +}; + +/** + * Resume. + */ + +Response.prototype.resume = function () { + this.res.resume(); +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function () { + const { + req + } = this; + const { + method + } = req; + const { + path + } = req; + const message = `cannot ${method} ${path} (${this.status})`; + const error = new Error(message); + error.status = this.status; + error.text = this.text; + error.method = method; + error.path = path; + return error; +}; +Response.prototype.setStatusProperties = function (status) { + console.warn('In superagent 2.x setStatusProperties is a private method'); + return this._setStatusProperties(status); +}; + +/** + * To json. + * + * @return {Object} + * @api public + */ + +Response.prototype.toJSON = function () { + return { + req: this.request.toJSON(), + header: this.header, + status: this.status, + text: this.text + }; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ1dGlsIiwicmVxdWlyZSIsIlN0cmVhbSIsIlJlc3BvbnNlQmFzZSIsIm1peGluIiwibW9kdWxlIiwiZXhwb3J0cyIsIlJlc3BvbnNlIiwicmVxdWVzdCIsImNhbGwiLCJyZXMiLCJyZXEiLCJ0ZXh0IiwiZmlsZXMiLCJidWZmZXJlZCIsIl9yZXNCdWZmZXJlZCIsImhlYWRlcnMiLCJoZWFkZXIiLCJfc2V0U3RhdHVzUHJvcGVydGllcyIsInN0YXR1c0NvZGUiLCJfc2V0SGVhZGVyUHJvcGVydGllcyIsInNldEVuY29kaW5nIiwiYmluZCIsIm9uIiwiZW1pdCIsIk9iamVjdCIsImRlZmluZVByb3BlcnR5IiwicHJvdG90eXBlIiwiZ2V0IiwiX2JvZH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UFBSUMsSUFBSSxLQUFLLElBQUksQ0FBQ0UsTUFBTSxHQUFHO0VBQzNELE1BQU1QLEtBQUssR0FBRyxJQUFJUSxLQUFLLENBQUNGLE9BQU8sQ0FBQztFQUNoQ04sS0FBSyxDQUFDTyxNQUFNLEdBQUcsSUFBSSxDQUFDQSxNQUFNO0VBQzFCUCxLQUFLLENBQUN4QixJQUFJLEdBQUcsSUFBSSxDQUFDQSxJQUFJO0VBQ3RCd0IsS0FBSyxDQUFDSSxNQUFNLEdBQUdBLE1BQU07RUFDckJKLEtBQUssQ0FBQ0ssSUFBSSxHQUFHQSxJQUFJO0VBRWpCLE9BQU9MLEtBQUs7QUFDZCxDQUFDO0FBRUQ3QixRQUFRLENBQUNvQixTQUFTLENBQUNrQixtQkFBbUIsR0FBRyxVQUFVRixNQUFNLEVBQUU7RUFDekRHLE9BQU8sQ0FBQ0MsSUFBSSxDQUFDLDJEQUEyRCxDQUFDO0VBQ3pFLE9BQU8sSUFBSSxDQUFDN0Isb0JBQW9CLENBQUN5QixNQUFNLENBQUM7QUFDMUMsQ0FBQzs7QUFFRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUFwQyxRQUFRLENBQUNvQixTQUFTLENBQUNxQixNQUFNLEdBQUcsWUFBWTtFQUN0QyxPQUFPO0lBQ0xyQyxHQUFHLEVBQUUsSUFBSSxDQUFDSCxPQUFPLENBQUN3QyxNQUFNLENBQUMsQ0FBQztJQUMxQi9CLE1BQU0sRUFBRSxJQUFJLENBQUNBLE1BQU07SUFDbkIwQixNQUFNLEVBQUUsSUFBSSxDQUFDQSxNQUFNO0lBQ25CL0IsSUFBSSxFQUFFLElBQUksQ0FBQ0E7RUFDYixDQUFDO0FBQ0gsQ0FBQyIsImlnbm9yZUxpc3QiOltdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/node/unzip.js b/node_modules/superagent/lib/node/unzip.js new file mode 100644 index 0000000000000000000000000000000000000000..b473d16b3882ee22d809bc18e4008741024b5536 --- /dev/null +++ b/node_modules/superagent/lib/node/unzip.js @@ -0,0 +1,74 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const { + StringDecoder +} = require('string_decoder'); +const Stream = require('stream'); +const { + chooseDecompresser +} = require('./decompress'); + +/** + * Buffers response data events and re-emits when they're decompressed. + * + * @param {Request} req + * @param {Response} res + * @api private + */ + +exports.decompress = (request, res) => { + let decompresser = chooseDecompresser(res); + const stream = new Stream(); + let decoder; + + // make node responseOnEnd() happy + stream.req = request; + decompresser.on('error', error => { + if (error && error.code === 'Z_BUF_ERROR') { + // unexpected end of file is ignored by browsers and curl + stream.emit('end'); + return; + } + stream.emit('error', error); + }); + + // pipe to unzip + res.pipe(decompresser); + + // override `setEncoding` to capture encoding + res.setEncoding = type => { + decoder = new StringDecoder(type); + }; + + // decode upon decompressing with captured encoding + decompresser.on('data', buf => { + if (decoder) { + const string_ = decoder.write(buf); + if (string_.length > 0) stream.emit('data', string_); + } else { + stream.emit('data', buf); + } + }); + decompresser.on('end', () => { + stream.emit('end'); + }); + + // override `on` to capture data listeners + const _on = res.on; + res.on = function (type, fn) { + if (type === 'data' || type === 'end') { + stream.on(type, fn.bind(res)); + } else if (type === 'error') { + stream.on(type, fn.bind(res)); + _on.call(res, type, fn); + } else { + _on.call(res, type, fn); + } + return this; + }; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJTdHJpbmdEZWNvZGVyIiwicmVxdWlyZSIsIlN0cmVhbSIsImNob29zZURlY29tcHJlc3NlciIsImV4cG9ydHMiLCJkZWNvbXByZXNzIiwicmVxdWVzdCIsInJlcyIsImRlY29tcHJlc3NlciIsInN0cmVhbSIsImRlY29kZXIiLCJyZXEiLCJvbiIsImVycm9yIiwiY29kZSIsImVtaXQiLCJwaXBlIiwic2V0RW5jb2RpbmciLCJ0eXBlIiwiYnVmIiwic3RyaW5nXyIsIndyaXRlIiwibGVuZ3RoIiwiX29uIiwiZm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BQyxNQUFNLElBQUlXLElBQUksS0FBSyxPQUFPLEVBQUU7TUFDM0JULE1BQU0sQ0FBQ0csRUFBRSxDQUFDTSxJQUFJLEVBQUVNLEVBQUUsQ0FBQ0MsSUFBSSxDQUFDbEIsR0FBRyxDQUFDLENBQUM7TUFDN0JnQixHQUFHLENBQUNHLElBQUksQ0FBQ25CLEdBQUcsRUFBRVcsSUFBSSxFQUFFTSxFQUFFLENBQUM7SUFDekIsQ0FBQyxNQUFNO01BQ0xELEdBQUcsQ0FBQ0csSUFBSSxDQUFDbkIsR0FBRyxFQUFFVyxJQUFJLEVBQUVNLEVBQUUsQ0FBQztJQUN6QjtJQUVBLE9BQU8sSUFBSTtFQUNiLENBQUM7QUFDSCxDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/request-base.js b/node_modules/superagent/lib/request-base.js new file mode 100644 index 0000000000000000000000000000000000000000..19fbbd28c5c9a6aa6cd01186264fc5ba4deb3a42 --- /dev/null +++ b/node_modules/superagent/lib/request-base.js @@ -0,0 +1,720 @@ +"use strict"; + +/** + * Module of mixed-in functions shared between node and client code + */ +const { + isObject, + hasOwn +} = require('./utils'); + +/** + * Expose `RequestBase`. + */ + +module.exports = RequestBase; + +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase() {} + +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.clearTimeout = function () { + clearTimeout(this._timer); + clearTimeout(this._responseTimeoutTimer); + clearTimeout(this._uploadTimeoutTimer); + delete this._timer; + delete this._responseTimeoutTimer; + delete this._uploadTimeoutTimer; + return this; +}; + +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.parse = function (fn) { + this._parser = fn; + return this; +}; + +/** + * Set format of binary response body. + * In browser valid formats are 'blob' and 'arraybuffer', + * which return Blob and ArrayBuffer, respectively. + * + * In Node all values result in Buffer. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.responseType = function (value) { + this._responseType = value; + return this; +}; + +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.serialize = function (fn) { + this._serializer = fn; + return this; +}; + +/** + * Set timeouts. + * + * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. + * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. + * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off + * + * Value of 0 or false means no timeout. + * + * @param {Number|Object} ms or {response, deadline} + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.timeout = function (options) { + if (!options || typeof options !== 'object') { + this._timeout = options; + this._responseTimeout = 0; + this._uploadTimeout = 0; + return this; + } + for (const option in options) { + if (hasOwn(options, option)) { + switch (option) { + case 'deadline': + this._timeout = options.deadline; + break; + case 'response': + this._responseTimeout = options.response; + break; + case 'upload': + this._uploadTimeout = options.upload; + break; + default: + console.warn('Unknown timeout option', option); + } + } + } + return this; +}; + +/** + * Set number of retry attempts on error. + * + * Failed requests will be retried 'count' times if timeout or err.code >= 500. + * + * @param {Number} count + * @param {Function} [fn] + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.retry = function (count, fn) { + // Default to 1 if no count passed or true + if (arguments.length === 0 || count === true) count = 1; + if (count <= 0) count = 0; + this._maxRetries = count; + this._retries = 0; + this._retryCallback = fn; + return this; +}; + +// +// NOTE: we do not include ESOCKETTIMEDOUT because that is from `request` package +// +// +// NOTE: we do not include EADDRINFO because it was removed from libuv in 2014 +// +// +// +// +// TODO: expose these as configurable defaults +// +const ERROR_CODES = new Set(['ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN']); +const STATUS_CODES = new Set([408, 413, 429, 500, 502, 503, 504, 521, 522, 524]); + +// TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) +// const METHODS = new Set(['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE']); + +/** + * Determine if a request should be retried. + * (Inspired by https://github.com/sindresorhus/got#retry) + * + * @param {Error} err an error + * @param {Response} [res] response + * @returns {Boolean} if segment should be retried + */ +RequestBase.prototype._shouldRetry = function (error, res) { + if (!this._maxRetries || this._retries++ >= this._maxRetries) { + return false; + } + if (this._retryCallback) { + try { + const override = this._retryCallback(error, res); + if (override === true) return true; + if (override === false) return false; + // undefined falls back to defaults + } catch (err) { + console.error(err); + } + } + + // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) + /* + if ( + this.req && + this.req.method && + !METHODS.has(this.req.method.toUpperCase()) + ) + return false; + */ + if (res && res.status && STATUS_CODES.has(res.status)) return true; + if (error) { + if (error.code && ERROR_CODES.has(error.code)) return true; + // Superagent timeout + if (error.timeout && error.code === 'ECONNABORTED') return true; + if (error.crossDomain) return true; + } + return false; +}; + +/** + * Retry request + * + * @return {Request} for chaining + * @api private + */ + +RequestBase.prototype._retry = function () { + this.clearTimeout(); + + // node + if (this.req) { + this.req = null; + this.req = this.request(); + } + this._aborted = false; + this.timedout = false; + this.timedoutError = null; + return this._end(); +}; + +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} [reject] + * @return {Request} + */ + +RequestBase.prototype.then = function (resolve, reject) { + if (!this._fullfilledPromise) { + const self = this; + if (this._endCalled) { + console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises'); + } + this._fullfilledPromise = new Promise((resolve, reject) => { + self.on('abort', () => { + if (this._maxRetries && this._maxRetries > this._retries) { + return; + } + if (this.timedout && this.timedoutError) { + reject(this.timedoutError); + return; + } + const error = new Error('Aborted'); + error.code = 'ABORTED'; + error.status = this.status; + error.method = this.method; + error.url = this.url; + reject(error); + }); + self.end((error, res) => { + if (error) reject(error);else resolve(res); + }); + }); + } + return this._fullfilledPromise.then(resolve, reject); +}; +RequestBase.prototype.catch = function (callback) { + return this.then(undefined, callback); +}; + +/** + * Allow for extension + */ + +RequestBase.prototype.use = function (fn) { + fn(this); + return this; +}; +RequestBase.prototype.ok = function (callback) { + if (typeof callback !== 'function') throw new Error('Callback required'); + this._okCallback = callback; + return this; +}; +RequestBase.prototype._isResponseOK = function (res) { + if (!res) { + return false; + } + if (this._okCallback) { + return this._okCallback(res); + } + return res.status >= 200 && res.status < 300; +}; + +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + +RequestBase.prototype.get = function (field) { + return this._header[field.toLowerCase()]; +}; + +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + +RequestBase.prototype.getHeader = RequestBase.prototype.get; + +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.set = function (field, value) { + if (isObject(field)) { + for (const key in field) { + if (hasOwn(field, key)) this.set(key, field[key]); + } + return this; + } + this._header[field.toLowerCase()] = value; + this.header[field] = value; + return this; +}; + +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field field name + */ +RequestBase.prototype.unset = function (field) { + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; + +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name name of field + * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field + * @param {String} options extra options, e.g. 'blob' + * @return {Request} for chaining + * @api public + */ +RequestBase.prototype.field = function (name, value, options) { + // name should be either a string or an object. + if (name === null || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + if (this._data) { + throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); + } + if (isObject(name)) { + for (const key in name) { + if (hasOwn(name, key)) this.field(key, name[key]); + } + return this; + } + if (Array.isArray(value)) { + for (const i in value) { + if (hasOwn(value, i)) this.field(name, value[i]); + } + return this; + } + + // val should be defined now + if (value === null || undefined === value) { + throw new Error('.field(name, val) val can not be empty'); + } + if (typeof value === 'boolean') { + value = String(value); + } + + // fix https://github.com/ladjs/superagent/issues/1680 + if (options) this._getFormData().append(name, value, options);else this._getFormData().append(name, value); + return this; +}; + +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} request + * @api public + */ +RequestBase.prototype.abort = function () { + if (this._aborted) { + return this; + } + this._aborted = true; + if (this.xhr) this.xhr.abort(); // browser + if (this.req) { + this.req.abort(); // node + } + this.clearTimeout(); + this.emit('abort'); + return this; +}; +RequestBase.prototype._auth = function (user, pass, options, base64Encoder) { + switch (options.type) { + case 'basic': + this.set('Authorization', `Basic ${base64Encoder(`${user}:${pass}`)}`); + break; + case 'auto': + this.username = user; + this.password = pass; + break; + case 'bearer': + // usage would be .auth(accessToken, { type: 'bearer' }) + this.set('Authorization', `Bearer ${user}`); + break; + default: + break; + } + return this; +}; + +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * @param {Boolean} [on=true] - Set 'withCredentials' state + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.withCredentials = function (on) { + // This is browser-only functionality. Node side is no-op. + if (on === undefined) on = true; + this._withCredentials = on; + return this; +}; + +/** + * Set the max redirects to `n`. Does nothing in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.redirects = function (n) { + this._maxRedirects = n; + return this; +}; + +/** + * Maximum size of buffered response body, in bytes. Counts uncompressed size. + * Default 200MB. + * + * @param {Number} n number of bytes + * @return {Request} for chaining + */ +RequestBase.prototype.maxResponseSize = function (n) { + if (typeof n !== 'number') { + throw new TypeError('Invalid argument'); + } + this._maxResponseSize = n; + return this; +}; + +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + +RequestBase.prototype.toJSON = function () { + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; + +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ + +// eslint-disable-next-line complexity +RequestBase.prototype.send = function (data) { + const isObject_ = isObject(data); + let type = this._header['content-type']; + if (this._formData) { + throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); + } + if (isObject_ && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw new Error("Can't merge these send calls"); + } + + // merge + if (isObject_ && isObject(this._data)) { + for (const key in data) { + if (typeof data[key] == 'bigint' && !data[key].toJSON) throw new Error('Cannot serialize BigInt value to json'); + if (hasOwn(data, key)) this._data[key] = data[key]; + } + } else if (typeof data === 'bigint') throw new Error("Cannot send value of type BigInt");else if (typeof data === 'string') { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + if (type) type = type.toLowerCase().trim(); + if (type === 'application/x-www-form-urlencoded') { + this._data = this._data ? `${this._data}&${data}` : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + if (!isObject_ || this._isHost(data)) { + return this; + } + + // default to json + if (!type) this.type('json'); + return this; +}; + +/** + * Sort `querystring` by the sort function + * + * + * Examples: + * + * // default order + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery() + * .end(callback) + * + * // customized sort function + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery(function(a, b){ + * return a.length - b.length; + * }) + * .end(callback) + * + * + * @param {Function} sort + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.sortQuery = function (sort) { + // _sort default to true but otherwise can be a function or boolean + this._sort = typeof sort === 'undefined' ? true : sort; + return this; +}; + +/** + * Compose querystring to append to req.url + * + * @api private + */ +RequestBase.prototype._finalizeQueryString = function () { + const query = this._query.join('&'); + if (query) { + this.url += (this.url.includes('?') ? '&' : '?') + query; + } + this._query.length = 0; // Makes the call idempotent + + if (this._sort) { + const index = this.url.indexOf('?'); + if (index >= 0) { + const queryArray = this.url.slice(index + 1).split('&'); + if (typeof this._sort === 'function') { + queryArray.sort(this._sort); + } else { + queryArray.sort(); + } + this.url = this.url.slice(0, index) + '?' + queryArray.join('&'); + } + } +}; + +// For backwards compat only +RequestBase.prototype._appendQueryString = () => { + console.warn('Unsupported'); +}; + +/** + * Invoke callback with timeout error. + * + * @api private + */ + +RequestBase.prototype._timeoutError = function (reason, timeout, errno) { + if (this._aborted) { + return; + } + const error = new Error(`${reason + timeout}ms exceeded`); + error.timeout = timeout; + error.code = 'ECONNABORTED'; + error.errno = errno; + this.timedout = true; + this.timedoutError = error; + this.abort(); + this.callback(error); +}; +RequestBase.prototype._setTimeouts = function () { + const self = this; + + // deadline + if (this._timeout && !this._timer) { + this._timer = setTimeout(() => { + self._timeoutError('Timeout of ', self._timeout, 'ETIME'); + }, this._timeout); + } + + // response timeout + if (this._responseTimeout && !this._responseTimeoutTimer) { + this._responseTimeoutTimer = setTimeout(() => { + self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); + }, this._responseTimeout); + } +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJpc09iamVjdCIsImhhc093biIsInJlcXVpcmUiLCJtb2R1bGUiLCJleHBvcnRzIiwiUmVxdWVzdEJhc2UiLCJwcm90b3R5cGUiLCJjbGVhclRpbWVvdXQiLCJfdGltZXIiLCJfcmVzcG9uc2VUaW1lb3V0VGltZXIiLCJfdXBsb2FkVGltZW91dFRpbWVyIiwicGFyc2UiLCJmbiIsIl9wYXJzZXIiLCJyZXNwb25zZVR5cGUiLCJ2YWx1ZSIsIl9yZXNwb25zZVR5cGUiLCJzZXJpYWxpemUiLCJfc2VyaWFsaXplciIsInRpbWVvdXQiLCJvcHRpb25zIiwiX3RpbWVvdXQiLCJfcmVzcG9uc2VUaW1lb3V0IiwiX3VwbG9hZFRpbWVvdXQiLCJvcHRpb24iLCJkZWFkbGluZSIsInJlc3BvbnNlIiwidXBsb2FkIiwiY29uc29sZSIsIndhcm4iLCJyZXRyeSIsImNvdW50IiwiYXJndW1lbnRzIiwibGVuZ3RoIiwiX21heFJldHJpZXMiLCJfcmV0cmllcyIsIl9yZXRyeUNhbGxiYWNrIiwiRVJST1JfQ09ERVMiLCJTZXQiLCJTVEFUVVNfQ09ERVMiLCJfc2hvdWxkUmV0cnkiLCJlcnJvciIsInJlcyIsIm92ZXJyaWRlIiwiZXJyIiwic3RhdHVzIiwiaGFzIiwiY29kZSIsImNyb3NzRG9tYWluIiwiX3JldHJ5IiwicmVxIiwicmVxdWV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QyxRQUFRLEVBQUUsT0FBTyxDQUFDO0lBQzNELENBQUMsRUFBRSxJQUFJLENBQUNBLFFBQVEsQ0FBQztFQUNuQjs7RUFFQTtFQUNBLElBQUksSUFBSSxDQUFDQyxnQkFBZ0IsSUFBSSxDQUFDLElBQUksQ0FBQ2IscUJBQXFCLEVBQUU7SUFDeEQsSUFBSSxDQUFDQSxxQkFBcUIsR0FBRytILFVBQVUsQ0FBQyxNQUFNO01BQzVDNUUsSUFBSSxDQUFDd0UsYUFBYSxDQUNoQixzQkFBc0IsRUFDdEJ4RSxJQUFJLENBQUN0QyxnQkFBZ0IsRUFDckIsV0FDRixDQUFDO0lBQ0gsQ0FBQyxFQUFFLElBQUksQ0FBQ0EsZ0JBQWdCLENBQUM7RUFDM0I7QUFDRixDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/response-base.js b/node_modules/superagent/lib/response-base.js new file mode 100644 index 0000000000000000000000000000000000000000..32157bf70e0e11e923a6de4e7e9450504747c252 --- /dev/null +++ b/node_modules/superagent/lib/response-base.js @@ -0,0 +1,120 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const utils = require('./utils'); + +/** + * Expose `ResponseBase`. + */ + +module.exports = ResponseBase; + +/** + * Initialize a new `ResponseBase`. + * + * @api public + */ + +function ResponseBase() {} + +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + +ResponseBase.prototype.get = function (field) { + return this.header[field.toLowerCase()]; +}; + +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + +ResponseBase.prototype._setHeaderProperties = function (header) { + // TODO: moar! + // TODO: make this a util + + // content-type + const ct = header['content-type'] || ''; + this.type = utils.type(ct); + + // params + const parameters = utils.params(ct); + for (const key in parameters) { + if (Object.prototype.hasOwnProperty.call(parameters, key)) this[key] = parameters[key]; + } + this.links = {}; + + // links + try { + if (header.link) { + this.links = utils.parseLinks(header.link); + } + } catch (err) { + // ignore + } +}; + +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + +ResponseBase.prototype._setStatusProperties = function (status) { + const type = Math.trunc(status / 100); + + // status / class + this.statusCode = status; + this.status = this.statusCode; + this.statusType = type; + + // basics + this.info = type === 1; + this.ok = type === 2; + this.redirect = type === 3; + this.clientError = type === 4; + this.serverError = type === 5; + this.error = type === 4 || type === 5 ? this.toError() : false; + + // sugar + this.created = status === 201; + this.accepted = status === 202; + this.noContent = status === 204; + this.badRequest = status === 400; + this.unauthorized = status === 401; + this.notAcceptable = status === 406; + this.forbidden = status === 403; + this.notFound = status === 404; + this.unprocessableEntity = status === 422; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ1dGlscyIsInJlcXVpcmUiLCJtb2R1bGUiLCJleHBvcnRzIiwiUmVzcG9uc2VCYXNlIiwicHJvdG90eXBlIiwiZ2V0IiwiZmllbGQiLCJoZWFkZXIiLCJ0b0xvd2VyQ2FzZSIsIl9zZXRIZWFkZXJQcm9wZXJ0aWVzIiwiY3QiLCJ0eXBlIiwicGFyYW1ldGVycyIsInBhcmFtcyIsImtleSIsIk9iamVjdCIsImhhc093blByb3BlcnR5IiwiY2FsbCIsImxpbmtzIiwibGluayIsInBhcnNlTGlua3MiLCJlcnIiLCJfc2V0U3RhdHVzUHJvcGVydGllcyIsInN0YXR1cyIsIk1hdGgiLCJ0cnVuYyIsInN0YXR1c0NvZGUiLCJzdGF0dXNUeXBlIiw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iLE1BQU0sS0FBSyxHQUFHO0VBQzlCLElBQUksQ0FBQ2MsU0FBUyxHQUFHZCxNQUFNLEtBQUssR0FBRztFQUMvQixJQUFJLENBQUNlLFVBQVUsR0FBR2YsTUFBTSxLQUFLLEdBQUc7RUFDaEMsSUFBSSxDQUFDZ0IsWUFBWSxHQUFHaEIsTUFBTSxLQUFLLEdBQUc7RUFDbEMsSUFBSSxDQUFDaUIsYUFBYSxHQUFHakIsTUFBTSxLQUFLLEdBQUc7RUFDbkMsSUFBSSxDQUFDa0IsU0FBUyxHQUFHbEIsTUFBTSxLQUFLLEdBQUc7RUFDL0IsSUFBSSxDQUFDbUIsUUFBUSxHQUFHbkIsTUFBTSxLQUFLLEdBQUc7RUFDOUIsSUFBSSxDQUFDb0IsbUJBQW1CLEdBQUdwQixNQUFNLEtBQUssR0FBRztBQUMzQyxDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/utils.js b/node_modules/superagent/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..8a1c0bbecbaaa1acc5a56a61bfcd7d7753f79cf5 --- /dev/null +++ b/node_modules/superagent/lib/utils.js @@ -0,0 +1,126 @@ +"use strict"; + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.type = string_ => string_.split(/ *; */).shift(); + +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.params = value => { + const object = {}; + for (const string_ of value.split(/ *; */)) { + const parts = string_.split(/ *= */); + const key = parts.shift(); + const value = parts.shift(); + if (key && value) object[key] = value; + } + return object; +}; + +/** + * Parse Link header fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.parseLinks = value => { + const object = {}; + for (const string_ of value.split(/ *, */)) { + const parts = string_.split(/ *; */); + const url = parts[0].slice(1, -1); + const rel = parts[1].split(/ *= */)[1].slice(1, -1); + object[rel] = url; + } + return object; +}; + +/** + * Strip content related fields from `header`. + * + * @param {Object} header + * @return {Object} header + * @api private + */ + +exports.cleanHeader = (header, changesOrigin) => { + delete header['content-type']; + delete header['content-length']; + delete header['transfer-encoding']; + delete header.host; + // secuirty + if (changesOrigin) { + delete header.authorization; + delete header.cookie; + } + return header; +}; +exports.normalizeHostname = hostname => { + const [, normalized] = hostname.match(/^\[([^\]]+)\]$/) || []; + return normalized || hostname; +}; + +/** + * Check if `obj` is an object. + * + * @param {Object} object + * @return {Boolean} + * @api private + */ +exports.isObject = object => { + return object !== null && typeof object === 'object'; +}; + +/** + * Object.hasOwn fallback/polyfill. + * + * @type {(object: object, property: string) => boolean} object + * @api private + */ +exports.hasOwn = Object.hasOwn || function (object, property) { + if (object == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + return Object.prototype.hasOwnProperty.call(new Object(object), property); +}; +exports.mixin = (target, source) => { + for (const key in source) { + if (exports.hasOwn(source, key)) { + target[key] = source[key]; + } + } +}; + +/** + * Check if the response is compressed using Gzip or Deflate. + * @param {Object} res + * @return {Boolean} + */ + +exports.isGzipOrDeflateEncoding = res => { + return new RegExp(/^\s*(?:deflate|gzip)\s*$/).test(res.headers['content-encoding']); +}; + +/** + * Check if the response is compressed using Brotli. + * @param {Object} res + * @return {Boolean} + */ + +exports.isBrotliEncoding = res => { + return new RegExp(/^\s*(?:br)\s*$/).test(res.headers['content-encoding']); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJleHBvcnRzIiwidHlwZSIsInN0cmluZ18iLCJzcGxpdCIsInNoaWZ0IiwicGFyYW1zIiwidmFsdWUiLCJvYmplY3QiLCJwYXJ0cyIsImtleSIsInBhcnNlTGlua3MiLCJ1cmwiLCJzbGljZSIsInJlbCIsImNsZWFuSGVhZGVyIiwiaGVhZGVyIiwiY2hhbmdlc09yaWdpbiIsImhvc3QiLCJhdXRob3JpemF0aW9uIiwiY29va2llIiwibm9ybWFsaXplSG9zdG5hbWUiLCJob3N0bmFtZSIsIm5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kMsT0FBTyxDQUFDd0MsZ0JBQWdCLEdBQUlKLEdBQUcsSUFBSztFQUNsQyxPQUFPLElBQUlDLE1BQU0sQ0FBQyxnQkFBZ0IsQ0FBQyxDQUFDQyxJQUFJLENBQUNGLEdBQUcsQ0FBQ0csT0FBTyxDQUFDLGtCQUFrQixDQUFDLENBQUM7QUFDM0UsQ0FBQyIsImlnbm9yZUxpc3QiOltdfQ== \ No newline at end of file diff --git a/node_modules/superagent/package.json b/node_modules/superagent/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6485ae89d05f4e4098960fd641667e86f931255e --- /dev/null +++ b/node_modules/superagent/package.json @@ -0,0 +1,132 @@ +{ + "name": "superagent", + "description": "elegant & feature rich browser / node HTTP with a fluent API", + "version": "10.3.0", + "author": "TJ Holowaychuk ", + "browser": { + "./src/node/index.js": "./src/client.js", + "./lib/node/index.js": "./lib/client.js", + "./test/support/server.js": "./test/support/blank.js" + }, + "bugs": { + "url": "https://github.com/ladjs/superagent/issues" + }, + "contributors": [ + "Kornel Lesiński ", + "Peter Lyons ", + "Hunter Loftis ", + "Nick Baugh " + ], + "dependencies": { + "component-emitter": "^1.3.1", + "cookiejar": "^2.1.4", + "debug": "^4.3.7", + "fast-safe-stringify": "^2.1.1", + "form-data": "^4.0.5", + "formidable": "^3.5.4", + "methods": "^1.1.2", + "mime": "2.6.0", + "qs": "^6.14.1" + }, + "devDependencies": { + "@babel/cli": "^7.20.7", + "@babel/core": "^7.20.12", + "@babel/plugin-transform-runtime": "^7.19.6", + "@babel/preset-env": "^7.20.2", + "@babel/runtime": "^7.20.13", + "@commitlint/cli": "^19.8.1", + "@commitlint/config-conventional": "^19.8.1", + "babelify": "^10.0.0", + "Base64": "^1.1.0", + "basic-auth-connect": "^1.0.0", + "body-parser": "^1.20.4", + "browserify": "^17.0.0", + "cookie-parser": "^1.4.7", + "cross-env": "^7.0.3", + "eslint": "^8.32.0", + "eslint-config-xo-lass": "2", + "eslint-plugin-compat": "4.0.2", + "eslint-plugin-node": "^11.1.0", + "express": "^4.18.3", + "express-session": "^1.17.3", + "fixpack": "^4.0.0", + "get-port": "4.2.0", + "husky": "^9.1.7", + "lint-staged": "^15.5.2", + "marked": "^4.2.12", + "mocha": "^6.2.3", + "multer": "1.4.5-lts.1", + "nyc": "^15.1.0", + "remark-cli": "^11.0.0", + "remark-preset-github": "4.0.4", + "rimraf": "3", + "should": "^13.2.3", + "should-http": "^0.1.1", + "tinyify": "3.0.0", + "xo": "^0.53.1", + "zuul": "^3.12.0" + }, + "engines": { + "node": ">=14.18.0" + }, + "files": [ + "dist/*.js", + "lib/**/*.js" + ], + "homepage": "https://github.com/ladjs/superagent", + "jsdelivr": "dist/superagent.min.js", + "keywords": [ + "agent", + "ajax", + "ajax", + "api", + "async", + "await", + "axios", + "cancel", + "client", + "frisbee", + "got", + "http", + "http", + "https", + "ky", + "promise", + "promise", + "promises", + "request", + "request", + "requests", + "response", + "rest", + "retry", + "super", + "superagent", + "timeout", + "transform", + "xhr", + "xmlhttprequest" + ], + "license": "MIT", + "main": "lib/node/index.js", + "repository": { + "type": "git", + "url": "git://github.com/ladjs/superagent.git" + }, + "scripts": { + "browserify": "browserify src/node/index.js -o dist/superagent.js -s superagent -g [ babelify --configFile ./.dist.babelrc ]", + "build": "npm run build:clean && npm run build:lib && npm run build:dist", + "build:clean": "rimraf lib dist", + "build:dist": "npm run browserify && npm run minify", + "build:lib": "babel --config-file ./.lib.babelrc src --out-dir lib", + "build:test": "babel --config-file ./.test.babelrc test --out-dir lib/node/test", + "coverage": "nyc report --reporter=text-lcov > coverage.lcov", + "lint": "eslint -c .eslintrc src test && remark . -qfo && eslint -c .lib.eslintrc lib/**/*.js && eslint -c .dist.eslintrc dist/**/*.js", + "minify": "cross-env NODE_ENV=production browserify src/node/index.js -o dist/superagent.min.js -s superagent -g [ babelify --configFile ./.dist.babelrc ] -p tinyify", + "nyc": "cross-env NODE_ENV=test nyc ava", + "test": "npm run build && npm run lint && make test", + "test-http2": "npm run build && npm run lint && make test-node-http2", + "prepare": "husky" + }, + "unpkg": "dist/superagent.min.js" +} diff --git a/node_modules/supercluster/LICENSE b/node_modules/supercluster/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..631921c40afa67e575bfbdf0d812b54426946cec --- /dev/null +++ b/node_modules/supercluster/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2021, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/supercluster/README.md b/node_modules/supercluster/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6f2061b8febd879a0071f539b005ac006d7ae524 --- /dev/null +++ b/node_modules/supercluster/README.md @@ -0,0 +1,112 @@ +# supercluster [![Simply Awesome](https://img.shields.io/badge/simply-awesome-brightgreen.svg)](https://github.com/mourner/projects) [![Build Status](https://travis-ci.com/mapbox/supercluster.svg?branch=main)](https://travis-ci.com/mapbox/supercluster) + +A very fast JavaScript library for geospatial point clustering for browsers and Node. + +```js +const index = new Supercluster({radius: 40, maxZoom: 16}); +index.load(points); + +const clusters = index.getClusters([-180, -85, 180, 85], 2); +``` + +Clustering 6 million points in Leaflet: + +![clustering demo on an interactive Leaflet map](https://cloud.githubusercontent.com/assets/25395/11857351/43407b46-a40c-11e5-8662-e99ab1cd2cb7.gif) + +Supercluster was built to power clustering in [Mapbox GL JS](https://www.mapbox.com/mapbox-gljs). Read about how it works [on the Mapbox blog](https://blog.mapbox.com/clustering-millions-of-points-on-a-map-with-supercluster-272046ec5c97). + +## Install + +Install using NPM (`npm install supercluster`) or Yarn (`yarn add supercluster`), then: + +```js +// import as a ES module in Node +import Supercluster from 'supercluster'; + +// import from a CDN in the browser: +import Supercluster from 'https://esm.run/supercluster'; +``` + +Or use it with an ordinary script tag in the browser: + +```html + +``` + +## Methods + +#### `load(points)` + +Loads an array of [GeoJSON Feature](https://tools.ietf.org/html/rfc7946#section-3.2) objects. Each feature's `geometry` must be a [GeoJSON Point](https://tools.ietf.org/html/rfc7946#section-3.1.2). Once loaded, index is immutable. + +#### `getClusters(bbox, zoom)` + +For the given `bbox` array (`[westLng, southLat, eastLng, northLat]`) and integer `zoom`, returns an array of clusters and points as [GeoJSON Feature](https://tools.ietf.org/html/rfc7946#section-3.2) objects. + +#### `getTile(z, x, y)` + +For a given zoom and x/y coordinates, returns a [geojson-vt](https://github.com/mapbox/geojson-vt)-compatible JSON tile object with cluster/point features. + +#### `getChildren(clusterId)` + +Returns the children of a cluster (on the next zoom level) given its id (`cluster_id` value from feature properties). + +#### `getLeaves(clusterId, limit = 10, offset = 0)` + +Returns all the points of a cluster (given its `cluster_id`), with pagination support: +`limit` is the number of points to return (set to `Infinity` for all points), +and `offset` is the amount of points to skip (for pagination). + +#### `getClusterExpansionZoom(clusterId)` + +Returns the zoom on which the cluster expands into several children (useful for "click to zoom" feature) given the cluster's `cluster_id`. + +## Options + +| Option | Default | Description | +|------------|---------|-------------------------------------------------------------------| +| minZoom | 0 | Minimum zoom level at which clusters are generated. | +| maxZoom | 16 | Maximum zoom level at which clusters are generated. | +| minPoints | 2 | Minimum number of points to form a cluster. | +| radius | 40 | Cluster radius, in pixels. | +| extent | 512 | (Tiles) Tile extent. Radius is calculated relative to this value. | +| nodeSize | 64 | Size of the KD-tree leaf node. Affects performance. | +| log | false | Whether timing info should be logged. | +| generateId | false | Whether to generate ids for input features in vector tiles. | + +### Property map/reduce options + +In addition to the options above, Supercluster supports property aggregation with the following two options: + +- `map`: a function that returns cluster properties corresponding to a single point. +- `reduce`: a reduce function that merges properties of two clusters into one. + +Example of setting up a `sum` cluster property that accumulates the sum of `myValue` property values: + +```js +const index = new Supercluster({ + map: (props) => ({sum: props.myValue}), + reduce: (accumulated, props) => { accumulated.sum += props.sum; } +}); +``` + +The `map`/`reduce` options must satisfy these conditions to work correctly: + +- `map` must return a new object, not existing `properties` of a point, otherwise it will get overwritten. +- `reduce` must not mutate the second argument (`props`). + +## TypeScript + +Install `@types/supercluster` for the TypeScript type definitions: + +``` +npm install @types/supercluster --save-dev +``` + +## Developing Supercluster + +``` +npm install # install dependencies +npm run build # generate dist/supercluster.js and dist/supercluster.min.js +npm test # run tests +``` diff --git a/node_modules/supercluster/index.js b/node_modules/supercluster/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c56439669b5fb7e54aaf37a1e19840f0f8bedeee --- /dev/null +++ b/node_modules/supercluster/index.js @@ -0,0 +1,424 @@ + +import KDBush from 'kdbush'; + +const defaultOptions = { + minZoom: 0, // min zoom to generate clusters on + maxZoom: 16, // max zoom level to cluster the points on + minPoints: 2, // minimum points to form a cluster + radius: 40, // cluster radius in pixels + extent: 512, // tile extent (radius is calculated relative to it) + nodeSize: 64, // size of the KD-tree leaf node, affects performance + log: false, // whether to log timing info + + // whether to generate numeric ids for input features (in vector tiles) + generateId: false, + + // a reduce function for calculating custom cluster properties + reduce: null, // (accumulated, props) => { accumulated.sum += props.sum; } + + // properties to use for individual points when running the reducer + map: props => props // props => ({sum: props.my_value}) +}; + +const fround = Math.fround || (tmp => ((x) => { tmp[0] = +x; return tmp[0]; }))(new Float32Array(1)); + +const OFFSET_ZOOM = 2; +const OFFSET_ID = 3; +const OFFSET_PARENT = 4; +const OFFSET_NUM = 5; +const OFFSET_PROP = 6; + +export default class Supercluster { + constructor(options) { + this.options = Object.assign(Object.create(defaultOptions), options); + this.trees = new Array(this.options.maxZoom + 1); + this.stride = this.options.reduce ? 7 : 6; + this.clusterProps = []; + } + + load(points) { + const {log, minZoom, maxZoom} = this.options; + + if (log) console.time('total time'); + + const timerId = `prepare ${ points.length } points`; + if (log) console.time(timerId); + + this.points = points; + + // generate a cluster object for each point and index input points into a KD-tree + const data = []; + + for (let i = 0; i < points.length; i++) { + const p = points[i]; + if (!p.geometry) continue; + + const [lng, lat] = p.geometry.coordinates; + const x = fround(lngX(lng)); + const y = fround(latY(lat)); + // store internal point/cluster data in flat numeric arrays for performance + data.push( + x, y, // projected point coordinates + Infinity, // the last zoom the point was processed at + i, // index of the source feature in the original input array + -1, // parent cluster id + 1 // number of points in a cluster + ); + if (this.options.reduce) data.push(0); // noop + } + let tree = this.trees[maxZoom + 1] = this._createTree(data); + + if (log) console.timeEnd(timerId); + + // cluster points on max zoom, then cluster the results on previous zoom, etc.; + // results in a cluster hierarchy across zoom levels + for (let z = maxZoom; z >= minZoom; z--) { + const now = +Date.now(); + + // create a new set of clusters for the zoom and index them with a KD-tree + tree = this.trees[z] = this._createTree(this._cluster(tree, z)); + + if (log) console.log('z%d: %d clusters in %dms', z, tree.numItems, +Date.now() - now); + } + + if (log) console.timeEnd('total time'); + + return this; + } + + getClusters(bbox, zoom) { + let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180; + const minLat = Math.max(-90, Math.min(90, bbox[1])); + let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180; + const maxLat = Math.max(-90, Math.min(90, bbox[3])); + + if (bbox[2] - bbox[0] >= 360) { + minLng = -180; + maxLng = 180; + } else if (minLng > maxLng) { + const easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom); + const westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom); + return easternHem.concat(westernHem); + } + + const tree = this.trees[this._limitZoom(zoom)]; + const ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat)); + const data = tree.data; + const clusters = []; + for (const id of ids) { + const k = this.stride * id; + clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]); + } + return clusters; + } + + getChildren(clusterId) { + const originId = this._getOriginId(clusterId); + const originZoom = this._getOriginZoom(clusterId); + const errorMsg = 'No cluster with the specified id.'; + + const tree = this.trees[originZoom]; + if (!tree) throw new Error(errorMsg); + + const data = tree.data; + if (originId * this.stride >= data.length) throw new Error(errorMsg); + + const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1)); + const x = data[originId * this.stride]; + const y = data[originId * this.stride + 1]; + const ids = tree.within(x, y, r); + const children = []; + for (const id of ids) { + const k = id * this.stride; + if (data[k + OFFSET_PARENT] === clusterId) { + children.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]); + } + } + + if (children.length === 0) throw new Error(errorMsg); + + return children; + } + + getLeaves(clusterId, limit, offset) { + limit = limit || 10; + offset = offset || 0; + + const leaves = []; + this._appendLeaves(leaves, clusterId, limit, offset, 0); + + return leaves; + } + + getTile(z, x, y) { + const tree = this.trees[this._limitZoom(z)]; + const z2 = Math.pow(2, z); + const {extent, radius} = this.options; + const p = radius / extent; + const top = (y - p) / z2; + const bottom = (y + 1 + p) / z2; + + const tile = { + features: [] + }; + + this._addTileFeatures( + tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), + tree.data, x, y, z2, tile); + + if (x === 0) { + this._addTileFeatures( + tree.range(1 - p / z2, top, 1, bottom), + tree.data, z2, y, z2, tile); + } + if (x === z2 - 1) { + this._addTileFeatures( + tree.range(0, top, p / z2, bottom), + tree.data, -1, y, z2, tile); + } + + return tile.features.length ? tile : null; + } + + getClusterExpansionZoom(clusterId) { + let expansionZoom = this._getOriginZoom(clusterId) - 1; + while (expansionZoom <= this.options.maxZoom) { + const children = this.getChildren(clusterId); + expansionZoom++; + if (children.length !== 1) break; + clusterId = children[0].properties.cluster_id; + } + return expansionZoom; + } + + _appendLeaves(result, clusterId, limit, offset, skipped) { + const children = this.getChildren(clusterId); + + for (const child of children) { + const props = child.properties; + + if (props && props.cluster) { + if (skipped + props.point_count <= offset) { + // skip the whole cluster + skipped += props.point_count; + } else { + // enter the cluster + skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped); + // exit the cluster + } + } else if (skipped < offset) { + // skip a single point + skipped++; + } else { + // add a single point + result.push(child); + } + if (result.length === limit) break; + } + + return skipped; + } + + _createTree(data) { + const tree = new KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array); + for (let i = 0; i < data.length; i += this.stride) tree.add(data[i], data[i + 1]); + tree.finish(); + tree.data = data; + return tree; + } + + _addTileFeatures(ids, data, x, y, z2, tile) { + for (const i of ids) { + const k = i * this.stride; + const isCluster = data[k + OFFSET_NUM] > 1; + + let tags, px, py; + if (isCluster) { + tags = getClusterProperties(data, k, this.clusterProps); + px = data[k]; + py = data[k + 1]; + } else { + const p = this.points[data[k + OFFSET_ID]]; + tags = p.properties; + const [lng, lat] = p.geometry.coordinates; + px = lngX(lng); + py = latY(lat); + } + + const f = { + type: 1, + geometry: [[ + Math.round(this.options.extent * (px * z2 - x)), + Math.round(this.options.extent * (py * z2 - y)) + ]], + tags + }; + + // assign id + let id; + if (isCluster || this.options.generateId) { + // optionally generate id for points + id = data[k + OFFSET_ID]; + } else { + // keep id if already assigned + id = this.points[data[k + OFFSET_ID]].id; + } + + if (id !== undefined) f.id = id; + + tile.features.push(f); + } + } + + _limitZoom(z) { + return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1)); + } + + _cluster(tree, zoom) { + const {radius, extent, reduce, minPoints} = this.options; + const r = radius / (extent * Math.pow(2, zoom)); + const data = tree.data; + const nextData = []; + const stride = this.stride; + + // loop through each point + for (let i = 0; i < data.length; i += stride) { + // if we've already visited the point at this zoom level, skip it + if (data[i + OFFSET_ZOOM] <= zoom) continue; + data[i + OFFSET_ZOOM] = zoom; + + // find all nearby points + const x = data[i]; + const y = data[i + 1]; + const neighborIds = tree.within(data[i], data[i + 1], r); + + const numPointsOrigin = data[i + OFFSET_NUM]; + let numPoints = numPointsOrigin; + + // count the number of points in a potential cluster + for (const neighborId of neighborIds) { + const k = neighborId * stride; + // filter out neighbors that are already processed + if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM]; + } + + // if there were neighbors to merge, and there are enough points to form a cluster + if (numPoints > numPointsOrigin && numPoints >= minPoints) { + let wx = x * numPointsOrigin; + let wy = y * numPointsOrigin; + + let clusterProperties; + let clusterPropIndex = -1; + + // encode both zoom and point index on which the cluster originated -- offset by total length of features + const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length; + + for (const neighborId of neighborIds) { + const k = neighborId * stride; + + if (data[k + OFFSET_ZOOM] <= zoom) continue; + data[k + OFFSET_ZOOM] = zoom; // save the zoom (so it doesn't get processed twice) + + const numPoints2 = data[k + OFFSET_NUM]; + wx += data[k] * numPoints2; // accumulate coordinates for calculating weighted center + wy += data[k + 1] * numPoints2; + + data[k + OFFSET_PARENT] = id; + + if (reduce) { + if (!clusterProperties) { + clusterProperties = this._map(data, i, true); + clusterPropIndex = this.clusterProps.length; + this.clusterProps.push(clusterProperties); + } + reduce(clusterProperties, this._map(data, k)); + } + } + + data[i + OFFSET_PARENT] = id; + nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints); + if (reduce) nextData.push(clusterPropIndex); + + } else { // left points as unclustered + for (let j = 0; j < stride; j++) nextData.push(data[i + j]); + + if (numPoints > 1) { + for (const neighborId of neighborIds) { + const k = neighborId * stride; + if (data[k + OFFSET_ZOOM] <= zoom) continue; + data[k + OFFSET_ZOOM] = zoom; + for (let j = 0; j < stride; j++) nextData.push(data[k + j]); + } + } + } + } + + return nextData; + } + + // get index of the point from which the cluster originated + _getOriginId(clusterId) { + return (clusterId - this.points.length) >> 5; + } + + // get zoom of the point from which the cluster originated + _getOriginZoom(clusterId) { + return (clusterId - this.points.length) % 32; + } + + _map(data, i, clone) { + if (data[i + OFFSET_NUM] > 1) { + const props = this.clusterProps[data[i + OFFSET_PROP]]; + return clone ? Object.assign({}, props) : props; + } + const original = this.points[data[i + OFFSET_ID]].properties; + const result = this.options.map(original); + return clone && result === original ? Object.assign({}, result) : result; + } +} + +function getClusterJSON(data, i, clusterProps) { + return { + type: 'Feature', + id: data[i + OFFSET_ID], + properties: getClusterProperties(data, i, clusterProps), + geometry: { + type: 'Point', + coordinates: [xLng(data[i]), yLat(data[i + 1])] + } + }; +} + +function getClusterProperties(data, i, clusterProps) { + const count = data[i + OFFSET_NUM]; + const abbrev = + count >= 10000 ? `${Math.round(count / 1000) }k` : + count >= 1000 ? `${Math.round(count / 100) / 10 }k` : count; + const propIndex = data[i + OFFSET_PROP]; + const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]); + return Object.assign(properties, { + cluster: true, + cluster_id: data[i + OFFSET_ID], + point_count: count, + point_count_abbreviated: abbrev + }); +} + +// longitude/latitude to spherical mercator in [0..1] range +function lngX(lng) { + return lng / 360 + 0.5; +} +function latY(lat) { + const sin = Math.sin(lat * Math.PI / 180); + const y = (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI); + return y < 0 ? 0 : y > 1 ? 1 : y; +} + +// spherical mercator to longitude/latitude +function xLng(x) { + return (x - 0.5) * 360; +} +function yLat(y) { + const y2 = (180 - y * 360) * Math.PI / 180; + return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90; +} diff --git a/node_modules/supercluster/package.json b/node_modules/supercluster/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f0c6554c32f98e19e4bf4e1cbbd177d710422609 --- /dev/null +++ b/node_modules/supercluster/package.json @@ -0,0 +1,57 @@ +{ + "name": "supercluster", + "version": "8.0.1", + "description": "A very fast geospatial point clustering library.", + "main": "dist/supercluster.js", + "type": "module", + "exports": "./index.js", + "module": "index.js", + "jsdelivr": "dist/supercluster.min.js", + "unpkg": "dist/supercluster.min.js", + "sideEffects": false, + "scripts": { + "pretest": "eslint index.js bench.js test/test.js demo/index.js demo/worker.js", + "test": "node test/test.js", + "cov": "c8 npm run test", + "bench": "node --expose-gc bench.js", + "build": "mkdirp dist && rollup -c", + "prepublishOnly": "npm run test && npm run build" + }, + "files": [ + "index.js", + "dist/supercluster.js", + "dist/supercluster.min.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/mapbox/supercluster.git" + }, + "keywords": [ + "clustering", + "geospatial", + "markers" + ], + "author": "Vladimir Agafonkin", + "license": "ISC", + "dependencies": { + "kdbush": "^4.0.2" + }, + "devDependencies": { + "@rollup/plugin-node-resolve": "^15.0.2", + "@rollup/plugin-terser": "^0.4.1", + "c8": "^7.13.0", + "eslint": "^8.39.0", + "eslint-config-mourner": "^3.0.0", + "mkdirp": "^3.0.1", + "rollup": "^3.21.0" + }, + "eslintConfig": { + "extends": "mourner", + "parserOptions": { + "ecmaVersion": 2020 + }, + "rules": { + "camelcase": 0 + } + } +} diff --git a/node_modules/supertest/LICENSE b/node_modules/supertest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..020b1fac6cf419811a3590a693f0a983c5f2890c --- /dev/null +++ b/node_modules/supertest/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk and other +contributors. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/supertest/README.md b/node_modules/supertest/README.md new file mode 100644 index 0000000000000000000000000000000000000000..73e175f2b378097f027e2e75f7ac124b39598825 --- /dev/null +++ b/node_modules/supertest/README.md @@ -0,0 +1,471 @@ +# [supertest](https://forwardemail.github.io/superagent/) + +[![build status](https://github.com/forwardemail/supertest/actions/workflows/ci.yml/badge.svg)](https://github.com/forwardemail/supertest/actions/workflows/ci.yml) +[![code coverage](https://img.shields.io/codecov/c/github/ladjs/supertest.svg)](https://codecov.io/gh/ladjs/supertest) +[![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) +[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) +[![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org) +[![license](https://img.shields.io/github/license/ladjs/supertest.svg)](LICENSE) + +> HTTP assertions made easy via [superagent](http://github.com/ladjs/superagent). Maintained for [Forward Email](https://github.com/forwardemail) and [Lad](https://github.com/ladjs). + +## About + +The motivation with this module is to provide a high-level abstraction for testing +HTTP, while still allowing you to drop down to the [lower-level API](https://forwardemail.github.io/superagent/) provided by superagent. + +## Getting Started + +Install supertest as an npm module and save it to your package.json file as a development dependency: + +```bash +npm install supertest --save-dev +``` + + Once installed it can now be referenced by simply calling ```require('supertest');``` + +## Example + +You may pass an `http.Server`, or a `Function` to `request()` - if the server is not +already listening for connections then it is bound to an ephemeral port for you so +there is no need to keep track of ports. + +supertest works with any test framework, here is an example without using any +test framework at all: + +```js +const request = require('supertest'); +const express = require('express'); + +const app = express(); + +app.get('/user', function(req, res) { + res.status(200).json({ name: 'john' }); +}); + +request(app) + .get('/user') + .expect('Content-Type', /json/) + .expect('Content-Length', '15') + .expect(200) + .end(function(err, res) { + if (err) throw err; + }); +``` + +To enable http2 protocol, simply append an options to `request` or `request.agent`: + +```js +const request = require('supertest'); +const express = require('express'); + +const app = express(); + +app.get('/user', function(req, res) { + res.status(200).json({ name: 'john' }); +}); + +request(app, { http2: true }) + .get('/user') + .expect('Content-Type', /json/) + .expect('Content-Length', '15') + .expect(200) + .end(function(err, res) { + if (err) throw err; + }); + +request.agent(app, { http2: true }) + .get('/user') + .expect('Content-Type', /json/) + .expect('Content-Length', '15') + .expect(200) + .end(function(err, res) { + if (err) throw err; + }); +``` + +Here's an example with mocha, note how you can pass `done` straight to any of the `.expect()` calls: + +```js +describe('GET /user', function() { + it('responds with json', function(done) { + request(app) + .get('/user') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200, done); + }); +}); +``` + +You can use `auth` method to pass HTTP username and password in the same way as in the [superagent](https://forwardemail.github.io/superagent/#authentication): + +```js +describe('GET /user', function() { + it('responds with json', function(done) { + request(app) + .get('/user') + .auth('username', 'password') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200, done); + }); +}); +``` + +One thing to note with the above statement is that superagent now sends any HTTP +error (anything other than a 2XX response code) to the callback as the first argument if +you do not add a status code expect (i.e. `.expect(302)`). + +If you are using the `.end()` method `.expect()` assertions that fail will +not throw - they will return the assertion as an error to the `.end()` callback. In +order to fail the test case, you will need to rethrow or pass `err` to `done()`, as follows: + +```js +describe('POST /users', function() { + it('responds with json', function(done) { + request(app) + .post('/users') + .send({name: 'john'}) + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200) + .end(function(err, res) { + if (err) return done(err); + return done(); + }); + }); +}); +``` + +You can also use promises: + +```js +describe('GET /users', function() { + it('responds with json', function() { + return request(app) + .get('/users') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200) + .then(response => { + expect(response.body.email).toEqual('foo@bar.com'); + }) + }); +}); +``` + +Or async/await syntax: + +```js +describe('GET /users', function() { + it('responds with json', async function() { + const response = await request(app) + .get('/users') + .set('Accept', 'application/json') + expect(response.headers["content-type"]).toMatch(/json/); + expect(response.status).toEqual(200); + expect(response.body.email).toEqual('foo@bar.com'); + }); +}); +``` + +Expectations are run in the order of definition. This characteristic can be used +to modify the response body or headers before executing an assertion. + +```js +describe('POST /user', function() { + it('user.name should be an case-insensitive match for "john"', function(done) { + request(app) + .post('/user') + .send('name=john') // x-www-form-urlencoded upload + .set('Accept', 'application/json') + .expect(function(res) { + res.body.id = 'some fixed id'; + res.body.name = res.body.name.toLowerCase(); + }) + .expect(200, { + id: 'some fixed id', + name: 'john' + }, done); + }); +}); +``` + +Anything you can do with superagent, you can do with supertest - for example multipart file uploads! + +```js +request(app) + .post('/') + .field('name', 'my awesome avatar') + .field('complex_object', '{"attribute": "value"}', {contentType: 'application/json'}) + .attach('avatar', 'test/fixtures/avatar.jpg') + ... +``` + +Passing the app or url each time is not necessary, if you're testing +the same host you may simply re-assign the request variable with the +initialization app or url, a new `Test` is created per `request.VERB()` call. + +```js +request = request('http://localhost:5555'); + +request.get('/').expect(200, function(err){ + console.log(err); +}); + +request.get('/').expect('heya', function(err){ + console.log(err); +}); +``` + +Here's an example with mocha that shows how to persist a request and its cookies: + +```js +const request = require('supertest'); +const should = require('should'); +const express = require('express'); +const cookieParser = require('cookie-parser'); + +describe('request.agent(app)', function() { + const app = express(); + app.use(cookieParser()); + + app.get('/', function(req, res) { + res.cookie('cookie', 'hey'); + res.send(); + }); + + app.get('/return', function(req, res) { + if (req.cookies.cookie) res.send(req.cookies.cookie); + else res.send(':(') + }); + + const agent = request.agent(app); + + it('should save cookies', function(done) { + agent + .get('/') + .expect('set-cookie', 'cookie=hey; Path=/', done); + }); + + it('should send cookies', function(done) { + agent + .get('/return') + .expect('hey', done); + }); +}); +``` + +There is another example that is introduced by the file [agency.js](https://github.com/ladjs/superagent/blob/master/test/node/agency.js) + +Here is an example where 2 cookies are set on the request. + +```js +agent(app) + .get('/api/content') + .set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo']) + .send() + .expect(200) + .end((err, res) => { + if (err) { + return done(err); + } + expect(res.text).to.be.equal('hey'); + return done(); + }); +``` + +## API + +You may use any [superagent](http://github.com/ladjs/superagent) methods, +including `.write()`, `.pipe()` etc and perform assertions in the `.end()` callback +for lower-level needs. + +### .expect(status[, fn]) + +Assert response `status` code. + +### .expect(status, body[, fn]) + +Assert response `status` code and `body`. + +### .expect(body[, fn]) + +Assert response `body` text with a string, regular expression, or +parsed body object. + +### .expect(field, value[, fn]) + +Assert header `field` `value` with a string or regular expression. + +### .expect(function(res) {}) + +Pass a custom assertion function. It'll be given the response object to check. If the check fails, throw an error. + +```js +request(app) + .get('/') + .expect(hasPreviousAndNextKeys) + .end(done); + +function hasPreviousAndNextKeys(res) { + if (!('next' in res.body)) throw new Error("missing next key"); + if (!('prev' in res.body)) throw new Error("missing prev key"); +} +``` + +### .end(fn) + +Perform the request and invoke `fn(err, res)`. + +## Cookies + +Here is an example of using the `set` and `not` cookie assertions: + +```js +// setup super-test +const request = require('supertest'); +const express = require('express'); +const cookies = request.cookies; + +// setup express test service +const app = express(); + +app.get('/users', function(req, res) { + res.cookie('alpha', 'one', { domain: 'domain.com', path: '/', httpOnly: true }); + res.send(200, { name: 'tobi' }); +}); + +// test request to service +request(app) + .get('/users') + .expect('Content-Type', /json/) + .expect('Content-Length', '15') + .expect(200) + // assert 'alpha' cookie is set with domain, path, and httpOnly options + .expect(cookies.set({ name: 'alpha', options: ['domain', 'path', 'httponly'] })) + // assert 'bravo' cookie is NOT set + .expect(cookies.not('set', { name: 'bravo' })) + .end(function(err, res) { + if (err) { + throw err; + } + }); +``` + +It is also possible to chain assertions: + +```js +cookies.set({/* ... */}).not('set', {/* ... */}) +``` + +### Cookie assertions + +Functions and methods are chainable. + +#### cookies([secret], [asserts]) + +Get assertion function for [super-test](https://github.com/visionmedia/supertest) `.expect()` method. + +*Arguments* + +- `secret` - String or array of strings. Cookie signature secrets. +- `asserts(req, res)` - Function or array of functions. Failed custom assertions should throw. + +#### .set(expects, [assert]) + +Assert that cookie and options are set. + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. + - `options` - *Optional* array of options. +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .reset(expects, [assert]) + +Assert that cookie is set and was already set (in request headers). + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .new(expects, [assert]) + +Assert that cookie is set and was NOT already set (NOT in request headers). + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .renew(expects, [assert]) + +Assert that cookie is set with a strictly greater `expires` or `max-age` than the given value. + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. + - `options` - Object of options. `use one of two options below` + - `options`.`expires` - String UTC expiration for original cookie (in request headers). + - `options`.`max-age` - Integer ttl in seconds for original cookie (in request headers). +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .contain(expects, [assert]) + +Assert that cookie is set with value and contains options. + +Requires `cookies(secret)` initialization if cookie is signed. + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. + - `value` - *Optional* string unsigned value of cookie. + - `options` - *Optional* object of options. + - `options`.`domain` - *Optional* string domain. + - `options`.`path` - *Optional* string path. + - `options`.`expires` - *Optional* string UTC expiration. + - `options`.`max-age` - *Optional* integer ttl, in seconds. + - `options`.`secure` - *Optional* boolean secure flag. + - `options`.`httponly` - *Optional* boolean httpOnly flag. +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .not(method, expects) + +Call any cookies assertion method with "assert true" modifier set to `false`. + +Syntactic sugar. + +*Arguments* + +- `method` - String method name. Arguments of method name apply in `expects`. +- `expects` - Object or array of objects. + - `name` - String name of cookie. + - `value` - *Optional* string unsigned value of cookie. + - `options` - *Optional* object of options. + +## Notes + +Inspired by [api-easy](https://github.com/flatiron/api-easy) minus vows coupling. + +## License + +MIT + +[coverage-badge]: https://img.shields.io/codecov/c/github/ladjs/supertest.svg +[coverage]: https://codecov.io/gh/ladjs/supertest +[travis-badge]: https://travis-ci.org/ladjs/supertest.svg?branch=master +[travis]: https://travis-ci.org/ladjs/supertest +[dependencies-badge]: https://david-dm.org/ladjs/supertest/status.svg +[dependencies]: https://david-dm.org/ladjs/supertest +[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square +[prs]: http://makeapullrequest.com +[license-badge]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square +[license]: https://github.com/ladjs/supertest/blob/master/LICENSE diff --git a/node_modules/supertest/index.js b/node_modules/supertest/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7575a39d5b50a1f6975bb0db2a1bd803d143ddfd --- /dev/null +++ b/node_modules/supertest/index.js @@ -0,0 +1,67 @@ +'use strict'; + +/** + * Module dependencies. + */ +const methods = require('methods'); +let http2; +try { + http2 = require('http2'); // eslint-disable-line global-require +} catch (_) { + // eslint-disable-line no-empty +} +const Test = require('./lib/test.js'); +const agent = require('./lib/agent.js'); +const cookies = require('./lib/cookies'); + +/** + * Test against the given `app`, + * returning a new `Test`. + * + * @param {Function|Server|String} app + * @return {Test} + * @api public + */ +module.exports = function(app, options = {}) { + const obj = {}; + + if (typeof app === 'function') { + if (options.http2) { + if (!http2) { + throw new Error( + 'supertest: this version of Node.js does not support http2' + ); + } + } + } + + methods.forEach(function(method) { + obj[method] = function(url) { + var test = new Test(app, method, url, options.http2); + if (options.http2) { + test.http2(); + } + return test; + }; + }); + + // Support previous use of del + obj.del = obj.delete; + + return obj; +}; + +/** + * Expose `Test` + */ +module.exports.Test = Test; + +/** + * Expose the agent function + */ +module.exports.agent = agent; + +/** + * Expose cookie assertions + */ +module.exports.cookies = cookies; diff --git a/node_modules/supertest/lib/agent.js b/node_modules/supertest/lib/agent.js new file mode 100644 index 0000000000000000000000000000000000000000..eee7159d3c5e313b93634dd9246b3ae75e530f93 --- /dev/null +++ b/node_modules/supertest/lib/agent.js @@ -0,0 +1,100 @@ +'use strict'; + +/** + * Module dependencies. + */ + +const { agent: Agent } = require('superagent'); +const methods = require('methods'); +const http = require('http'); +let http2; +try { + http2 = require('http2'); // eslint-disable-line global-require +} catch (_) { + // eslint-disable-line no-empty +} +const Test = require('./test.js'); + +/** + * Initialize a new `TestAgent`. + * + * @param {Function|Server} app + * @param {Object} options + * @api public + */ + +function TestAgent(app, options = {}) { + if (!(this instanceof TestAgent)) return new TestAgent(app, options); + + const agent = new Agent(options); + Object.assign(this, agent); + + this._options = options; + + if (typeof app === 'function') { + if (options.http2) { + if (!http2) { + throw new Error( + 'supertest: this version of Node.js does not support http2' + ); + } + app = http2.createServer(app); // eslint-disable-line no-param-reassign + } else { + app = http.createServer(app); // eslint-disable-line no-param-reassign + } + } + this.app = app; +} + +/** + * Inherits from `Agent.prototype`. + */ + +Object.setPrototypeOf(TestAgent.prototype, Agent.prototype); + +// Preserve the original query method before overriding HTTP methods +const originalQuery = Agent.prototype.query; + +// set a host name +TestAgent.prototype.host = function(host) { + this._host = host; + return this; +}; + +// override HTTP verb methods +methods.forEach(function(method) { + // Skip 'query' method to prevent overwriting superagent's query functionality + if (method === 'query') { + return; + } + + TestAgent.prototype[method] = function(url, fn) { // eslint-disable-line no-unused-vars + const req = new Test(this.app, method.toUpperCase(), url); + if (this._options.http2) { + req.http2(); + } + + if (this._host) { + req.set('host', this._host); + } + + req.on('response', this._saveCookies.bind(this)); + req.on('redirect', this._saveCookies.bind(this)); + req.on('redirect', this._attachCookies.bind(this, req)); + this._setDefaults(req); + this._attachCookies(req); + + return req; + }; +}); + +// Restore the original query method +TestAgent.prototype.query = originalQuery; + +TestAgent.prototype.del = TestAgent.prototype.delete; + +/** + * Expose `Agent`. + */ + +module.exports = TestAgent; diff --git a/node_modules/supertest/lib/cookies/assertion.js b/node_modules/supertest/lib/cookies/assertion.js new file mode 100644 index 0000000000000000000000000000000000000000..1d5b890d7268ed2380abcdafcfc357d19195c236 --- /dev/null +++ b/node_modules/supertest/lib/cookies/assertion.js @@ -0,0 +1,497 @@ +/** Copyright 2015 Gregory Langlais. See LICENSE.txt. */ + +'use strict'; + +const signature = require('cookie-signature'); + +/** + * Assert that an object has specific properties (supports array of keys or object) + * + * @param {object} obj + * @param {object|array} props + */ +function assertHasProperties(obj, props) { + if (Array.isArray(props)) { + props.forEach(function (key) { + if (!(key in obj)) { + throw new Error('expected object to have property ' + key); + } + }); + } else { + Object.keys(props).forEach(function (key) { + if (!(key in obj)) { + throw new Error('expected object to have property ' + key); + } + }); + } +} + +/** + * Assert that an object does not have specific properties (supports array of keys or object) + * When checking with empty props, throws if object exists (matches should.js behavior) + * + * @param {object} obj + * @param {object|array} props + */ +function assertNotHasProperties(obj, props) { + if (Array.isArray(props)) { + // When empty array is passed, should.js throws 'false negative fail' if object exists + if (props.length === 0) { + throw new Error('expected object to not have properties (false negative fail)'); + } + props.forEach(function (key) { + if (key in obj) { + throw new Error('expected object to not have property ' + key); + } + }); + } else { + // When empty object is passed, should.js throws 'false negative fail' if object exists + let keys = Object.keys(props); + if (keys.length === 0) { + throw new Error('expected object to not have properties (false negative fail)'); + } + keys.forEach(function (key) { + if (key in obj) { + throw new Error('expected object to not have property ' + key); + } + }); + } +} + +/** + * Assert that two values are equal + * + * @param {*} actual + * @param {*} expected + */ +function assertEqual(actual, expected) { + if (actual !== expected) { + throw new Error( + 'expected ' + JSON.stringify(actual) + ' to equal ' + JSON.stringify(expected) + ); + } +} + +/** + * Assert that two values are not equal + * + * @param {*} actual + * @param {*} expected + */ +function assertNotEqual(actual, expected) { + if (actual === expected) { + throw new Error( + 'expected ' + JSON.stringify(actual) + ' to not equal ' + JSON.stringify(expected) + ); + } +} + +/** + * Build Assertion function + * + * {object|object[]} expects cookies + * {string} expects. and value of cookie + * {object} expects.options + * {string} [expects.options.domain] + * {string} [expects.options.path] + * {string} [expects.options.expires] UTC string using date.toUTCString() + * {number} [expects.options.max-age] + * {boolean} [expects.options.secure] + * {boolean} [expects.options.httponly] + * {string|string[]} [expects.secret] + * + * @param {null|string|string[]} [secret] + * @param {function|function[]} [asserts] + * @returns {Assertion} + */ +module.exports = function (secret, asserts) { + let assertions = []; + + if (typeof secret === 'string') secret = [secret]; // eslint-disable-line no-param-reassign + else if (!Array.isArray(secret)) secret = []; // eslint-disable-line no-param-reassign + + if (Array.isArray(asserts)) assertions = asserts; + else if (typeof asserts === 'function') assertions.push(asserts); + + /** + * Assertion function with static chainable methods + * + * @param {object} res + * @returns {undefined|string} + * @constructor + */ + function Assertion(res) { + if (typeof res !== 'object') throw new Error('res argument must be object'); + + // request and response object initialization + let request = { + headers: res.req.getHeaders(), + cookies: [] + }; + + let response = { + headers: res.headers, + cookies: [] + }; + + // build assertions request object + if (request.headers.cookie) { + const cookies = String(request.headers.cookie); + cookies.split(/; */).forEach(function (cookie) { + request.cookies.push(Assertion.parse(cookie)); + }); + } + + // build assertions response object + if ( + Array.isArray(response.headers['set-cookie']) + && response.headers['set-cookie'].length > 0 + ) { + response.headers['set-cookie'].forEach(function (val) { + response.cookies.push(Assertion.parse(val)); + }); + } + + // run assertions + let result; + assertions.every(function (assertion) { + result = assertion(request, response); + return (typeof (result) !== 'string'); + }); + + return result; + } + + /** + * Find cookie in stack/array + * + * @param {string} name + * @param {array} stack + * @returns {object|undefined} cookie + */ + Assertion.find = function (name, stack) { + let cookie; + + stack.every(function (val) { + if (name !== val.name) return true; + cookie = val; + return false; + }); + + return cookie; + }; + + /** + * Parse cookie string + * + * @param {string} str + * @param {object} [options] + * @param {function} [options.decode] uri + * @param {undefined|boolean} [options.request] headers + * @returns {object} + */ + Assertion.parse = function (str, options) { + if (typeof str !== 'string') throw new TypeError('argument str must be a string'); + + if (typeof options !== 'object') options = {}; // eslint-disable-line no-param-reassign + + let decode = options.decode || decodeURIComponent; + + let parts = str.split(/; */); + + let cookie = {}; + + parts.forEach(function (part, i) { + if (i === 1) cookie.options = {}; + + let equalsIndex = part.indexOf('='); + + // things that don't look like key=value get true flag + if (equalsIndex < 0) { + cookie.options[part.trim().toLowerCase()] = true; + return; + } + + const key = part.substr(0, equalsIndex).trim().toLowerCase(); + // only assign once + if (typeof cookie[key] !== 'undefined') return; + + equalsIndex += 1; + let val = part.substr(equalsIndex, part.length).trim(); + // quoted values + if (val[0] === '"') val = val.slice(1, -1); + + let value; + try { + value = decode(val); + } catch (e) { + value = val; + } + + if (i > 0) { + cookie.options[key] = value; + return; + } + + cookie.name = key; + cookie.value = decode(val); + }); + + if (typeof cookie.options === 'undefined') cookie.options = {}; + + return cookie; + }; + + /** + * Iterate expects + * + * @param {object|object[]} expects + * @param {boolean|function} hasValues + * @param {function} [cb] + */ + Assertion.expects = function (expects, hasValues, cb) { + if (!Array.isArray(expects) && typeof expects === 'object') expects = [expects]; // eslint-disable-line no-param-reassign + + let resolvedCb; + let resolvedHasValues; + if (typeof cb === 'undefined' && typeof hasValues === 'function') { + resolvedCb = hasValues; + resolvedHasValues = false; + } else { + resolvedCb = cb; + resolvedHasValues = hasValues; + } + + expects.forEach(function (expect) { + let options = expect.options; + if (typeof options !== 'object' && !Array.isArray(options)) { + options = (resolvedHasValues) ? {} : []; + } + + resolvedCb(Object.assign({}, expect, { options })); + }); + }; + + /** + * Assert cookies and options are set + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.set = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, function (expect) { + assertions.push(function (req, res) { + // get expectation cookie + const cookie = Assertion.find(expect.name, res.cookies); + + if (assert && !cookie) throw new Error('expected: ' + expect.name + ' cookie to be set'); + + if (assert) assertHasProperties(cookie.options, expect.options); + else if (cookie) assertNotHasProperties(cookie.options, expect.options); + }); + }); + + return Assertion; + }; + + /** + * Assert cookies has been reset + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.reset = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, function (expect) { + assertions.push(function (req, res) { + // get sent cookie + const cookieReq = Assertion.find(expect.name, req.cookies); + // get expectation cookie + const cookieRes = Assertion.find(expect.name, res.cookies); + + if (assert && (!cookieReq || !cookieRes)) { + throw new Error('expected: ' + expect.name + ' cookie to be set'); + } else if (!assert && cookieReq && cookieRes) { + throw new Error('expected: ' + expect.name + ' cookie to be set'); + } + }); + }); + + return Assertion; + }; + + /** + * Assert cookies is set and new + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.new = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, function (expect) { + assertions.push(function (req, res) { + // get sent cookie + const cookieReq = Assertion.find(expect.name, req.cookies); + // get expectation cookie + const cookieRes = Assertion.find(expect.name, res.cookies); + + if (assert) { + if (!cookieRes) throw new Error('expected: ' + expect.name + ' cookie to be set'); + if (cookieReq && cookieRes) { + throw new Error('expected: ' + expect.name + ' cookie to NOT already be set'); + } + } else if (!cookieReq || !cookieRes) { + throw new Error('expected: ' + expect.name + ' cookie to be set'); + } + }); + }); + + return Assertion; + }; + + /** + * Assert cookies expires or max-age has increased + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.renew = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, true, function (expect) { + const expectExpires = new Date(expect.options.expires); + const expectMaxAge = parseFloat(expect.options['max-age']); + + let baseMessage = 'expected: ' + expect.name; + if (!expectExpires.getTime() && !expectMaxAge) { + throw new Error(baseMessage + ' expects to have expires or max-age option'); + } + + assertions.push(function (req, res) { + // get sent cookie + const cookieReq = Assertion.find(expect.name, req.cookies); + // get expectation cookie + const cookieRes = Assertion.find(expect.name, res.cookies); + + const cookieMaxAge = (expectMaxAge && cookieRes) + ? parseFloat(cookieRes.options['max-age']) + : undefined; + const cookieExpires = (expectExpires.getTime() && cookieRes) + ? new Date(cookieRes.options.expires) + : undefined; + + if (assert) { + if (!cookieReq || !cookieRes) { + throw new Error(baseMessage + ' cookie to be set'); + } + if (expectMaxAge && (!cookieMaxAge || cookieMaxAge <= expectMaxAge)) { + throw new Error(baseMessage + ' cookie max-age to be greater than existing value'); + } + + if ( + expectExpires.getTime() + && (!cookieExpires.getTime() || cookieExpires <= expectExpires) + ) { + throw new Error(baseMessage + ' cookie expires to be greater than existing value'); + } + } else if (cookieRes) { + if (expectMaxAge && cookieMaxAge > expectMaxAge) { + throw new Error( + baseMessage + ' cookie max-age to be less than or equal to existing value' + ); + } + + if (expectExpires.getTime() && cookieExpires > expectExpires) { + throw new Error( + baseMessage + ' cookie expires to be less than or equal to existing value' + ); + } + } + }); + }); + + return Assertion; + }; + + /** + * Assert cookies contains values + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.contain = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, function (expect) { + const keys = Object.keys(expect.options); + + assertions.push(function (req, res) { + // get expectation cookie + const cookie = Assertion.find(expect.name, res.cookies); + + if (!cookie) throw new Error('expected: ' + expect.name + ' cookie to be set'); + + // check cookie values are equal + if ('value' in expect) { + try { + if (assert) assertEqual(cookie.value, expect.value); + else assertNotEqual(cookie.value, expect.value); + } catch (e) { + if (secret.length) { + let value; + secret.every(function (sec) { + value = signature.unsign(cookie.value.slice(2), sec); + return !(value && value === expect.value); + }); + + if (assert && !value) { + throw new Error('expected: ' + expect.name + ' value to equal ' + expect.value); + } else if (!assert && value) { + throw new Error('expected: ' + expect.name + ' value to NOT equal ' + expect.value); + } + } else throw e; + } + } + + keys.forEach(function (key) { + const expected = ( + key === 'max-age' + ? expect.options[key].toString() + : expect.options[key] + ); + if (assert) assertEqual(cookie.options[key], expected); + else assertNotEqual(cookie.options[key], expected); + }); + }); + }); + + return Assertion; + }; + + /** + * Assert NOT modifier + * + * @param {function} method + * @param {...*} + */ + Assertion.not = function (method) { + let args = []; + + for (let i = 1; i < arguments.length; i += 1) args.push(arguments[i]); + + args.push(false); + + return Assertion[method].apply(Assertion, args); + }; + + return Assertion; +}; diff --git a/node_modules/supertest/lib/cookies/index.js b/node_modules/supertest/lib/cookies/index.js new file mode 100644 index 0000000000000000000000000000000000000000..889dee0e371297eaba3bfb4ec1290b48f30c23e4 --- /dev/null +++ b/node_modules/supertest/lib/cookies/index.js @@ -0,0 +1,32 @@ +/** Copyright 2015 Gregory Langlais. See LICENSE.txt. */ + +'use strict'; + +const Assertion = require('./assertion'); + +/** + * Construct cookies assertion (function) + * + * @param {null|string|string[]} [secret] + * @param {function(req, res)[]} [asserts] ran within returned assertion function + * @returns {function} assertion + * @constructor + */ +function ExpectCookies(secret, asserts) { + return Assertion(secret, asserts); +} + +// build ExpectCookies proxy methods +const assertion = Assertion(); +const methods = Object.getOwnPropertyNames(assertion); + +methods.forEach(function(method) { + if (typeof assertion[method] === 'function' && typeof Function[method] === 'undefined') { + ExpectCookies[method] = function() { + const newAssertion = Assertion(); + return newAssertion[method].apply(newAssertion, arguments); + }; + } +}); + +module.exports = ExpectCookies; diff --git a/node_modules/supertest/lib/test.js b/node_modules/supertest/lib/test.js new file mode 100644 index 0000000000000000000000000000000000000000..f83008811ab1aee6242d60b8b6fcc09b93e8396c --- /dev/null +++ b/node_modules/supertest/lib/test.js @@ -0,0 +1,403 @@ +'use strict'; + +/** + * Module dependencies. + */ + +const { inspect } = require('util'); +const http = require('http'); +const { STATUS_CODES } = require('http'); +const { Server } = require('tls'); +const { deepStrictEqual } = require('assert'); +const { Request } = require('superagent'); +let http2; +try { + http2 = require('http2'); // eslint-disable-line global-require +} catch (_) { + // eslint-disable-line no-empty +} + +/** @typedef {import('superagent').Response} Response */ + +class Test extends Request { + /** + * Initialize a new `Test` with the given `app`, + * request `method` and `path`. + * + * @param {Server} app + * @param {String} method + * @param {String} path + * @api public + */ + constructor (app, method, path, optHttp2) { + super(method.toUpperCase(), path); + + if (typeof app === 'function') { + if (optHttp2) { + app = http2.createServer(app); // eslint-disable-line no-param-reassign + } else { + app = http.createServer(app); // eslint-disable-line no-param-reassign + } + } + + this.redirects(0); + this.buffer(); + this.app = app; + this._asserts = []; + this.url = typeof app === 'string' + ? app + path + : this.serverAddress(app, path); + } + + /** + * Returns a URL, extracted from a server. + * + * @param {Server} app + * @param {String} path + * @returns {String} URL address + * @api private + */ + serverAddress(app, path) { + const addr = app.address(); + + if (!addr) this._server = app.listen(0); + // } else { + // this._server = app; + // } + const port = app.address().port; + const protocol = app instanceof Server ? 'https' : 'http'; + return protocol + '://127.0.0.1:' + port + path; + } + + /** + * Expectations: + * + * .expect(200) + * .expect(200, fn) + * .expect(200, body) + * .expect('Some body') + * .expect('Some body', fn) + * .expect(['json array body', { key: 'val' }]) + * .expect('Content-Type', 'application/json') + * .expect('Content-Type', 'application/json', fn) + * .expect(fn) + * .expect([200, 404]) + * + * @return {Test} + * @api public + */ + expect(a, b, c) { + // callback + if (typeof a === 'function') { + this._asserts.push(wrapAssertFn(a)); + return this; + } + if (typeof b === 'function') this.end(b); + if (typeof c === 'function') this.end(c); + + // status + if (typeof a === 'number') { + this._asserts.push(wrapAssertFn(this._assertStatus.bind(this, a))); + // body + if (typeof b !== 'function' && arguments.length > 1) { + this._asserts.push(wrapAssertFn(this._assertBody.bind(this, b))); + } + return this; + } + + // multiple statuses + if (Array.isArray(a) && a.length > 0 && a.every(val => typeof val === 'number')) { + this._asserts.push(wrapAssertFn(this._assertStatusArray.bind(this, a))); + return this; + } + + // header field + if (typeof b === 'string' || typeof b === 'number' || b instanceof RegExp) { + this._asserts.push(wrapAssertFn(this._assertHeader.bind(this, { name: '' + a, value: b }))); + return this; + } + + // body + this._asserts.push(wrapAssertFn(this._assertBody.bind(this, a))); + + return this; + } + + /** + * Defer invoking superagent's `.end()` until + * the server is listening. + * + * @param {?Function} fn + * @api public + */ + end(fn) { + const server = this._server; + + super.end((err, res) => { + const localAssert = () => { + this.assert(err, res, fn); + }; + + if (server && server._handle) { + // Handle server closing with error handling for already closed servers + return server.close((closeError) => { + // Ignore ERR_SERVER_NOT_RUNNING errors as the server is already closed + if (closeError && closeError.code === 'ERR_SERVER_NOT_RUNNING') { + return localAssert(); + } + // For other errors, pass them through + if (closeError) { + return localAssert(); + } + localAssert(); + }); + } + + localAssert(); + }); + + return this; + } + + /** + * Perform assertions and invoke `fn(err, res)`. + * + * @param {?Error} resError + * @param {Response} res + * @param {Function} fn + * @api private + */ + assert(resError, res, fn) { + let errorObj; + + // check for unexpected network errors or server not running/reachable errors + // when there is no response and superagent sends back a System Error + // do not check further for other asserts, if any, in such case + // https://nodejs.org/api/errors.html#errors_common_system_errors + const sysErrors = { + ECONNREFUSED: 'Connection refused', + ECONNRESET: 'Connection reset by peer', + EPIPE: 'Broken pipe', + ETIMEDOUT: 'Operation timed out' + }; + + if (!res && resError) { + if (resError instanceof Error && resError.syscall === 'connect' + && Object.getOwnPropertyNames(sysErrors).indexOf(resError.code) >= 0) { + errorObj = new Error(resError.code + ': ' + sysErrors[resError.code]); + } else { + errorObj = resError; + } + } + + // asserts + for (let i = 0; i < this._asserts.length && !errorObj; i += 1) { + errorObj = this._assertFunction(this._asserts[i], res); + } + + // set unexpected superagent error if no other error has occurred. + if (!errorObj && resError instanceof Error && (!res || resError.status !== res.status)) { + errorObj = resError; + } + + if (fn) { + fn.call(this, errorObj || null, res); + } + } + + /* + * Adds a set Authorization Bearer + * + * @param {Bearer} Bearer Token + * Shortcut for .set('Authorization', `Bearer ${token}`) + */ + + bearer(token) { + this.set('Authorization', `Bearer ${token}`); + return this; + } + + /* + * Adds a set Authorization Bearer + * + * @param {Bearer} Bearer Token + * Shortcut for .set('Authorization', `Bearer ${token}`) + */ + + bearer(token) { + this.set('Authorization', `Bearer ${token}`); + return this; + } + + /** + * Perform assertions on a response body and return an Error upon failure. + * + * @param {Mixed} body + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertBody(body, res) { + const isRegexp = body instanceof RegExp; + + // parsed + if (typeof body === 'object' && !isRegexp) { + try { + deepStrictEqual(body, res.body); + } catch (err) { + const a = inspect(body); + const b = inspect(res.body); + return error('expected ' + a + ' response body, got ' + b, body, res.body); + } + } else if (body !== res.text) { + // string + const a = inspect(body); + const b = inspect(res.text); + + // regexp + if (isRegexp) { + if (!body.test(res.text)) { + return error('expected body ' + b + ' to match ' + body, body, res.body); + } + } else { + return error('expected ' + a + ' response body, got ' + b, body, res.body); + } + } + } + + /** + * Perform assertions on a response header and return an Error upon failure. + * + * @param {Object} header + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertHeader(header, res) { + const field = header.name; + const actual = res.header[field.toLowerCase()]; + const fieldExpected = header.value; + + if (typeof actual === 'undefined') return new Error('expected "' + field + '" header field'); + // This check handles header values that may be a String or single element Array + if ((Array.isArray(actual) && actual.toString() === fieldExpected) + || fieldExpected === actual) { + return; + } + if (fieldExpected instanceof RegExp) { + if (!fieldExpected.test(actual)) { + return new Error('expected "' + field + '" matching ' + + fieldExpected + ', got "' + actual + '"'); + } + } else { + return new Error('expected "' + field + '" of "' + fieldExpected + '", got "' + actual + '"'); + } + } + + /** + * Perform assertions on the response status and return an Error upon failure. + * + * @param {Number} status + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertStatus(status, res) { + if (res.status !== status) { + const a = STATUS_CODES[status]; + const b = STATUS_CODES[res.status]; + return new Error('expected ' + status + ' "' + a + '", got ' + res.status + ' "' + b + '"'); + } + } + + /** + * Perform assertions on the response status and return an Error upon failure. + * + * @param {Array} statusArray + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertStatusArray(statusArray, res) { + if (!statusArray.includes(res.status)) { + const b = STATUS_CODES[res.status]; + const expectedList = statusArray.join(', '); + return new Error( + 'expected one of "' + expectedList + '", got ' + res.status + ' "' + b + '"' + ); + } + } + + /** + * Performs an assertion by calling a function and return an Error upon failure. + * + * @param {Function} fn + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertFunction(fn, res) { + let err; + try { + err = fn(res); + } catch (e) { + err = e; + } + if (err instanceof Error) return err; + } +} + +/** + * Wraps an assert function into another. + * The wrapper function edit the stack trace of any assertion error, prepending a more useful stack to it. + * + * @param {Function} assertFn + * @returns {Function} wrapped assert function + */ + +function wrapAssertFn(assertFn) { + const savedStack = new Error().stack.split('\n').slice(3); + + return function(res) { + let badStack; + let err; + try { + err = assertFn(res); + } catch (e) { + err = e; + } + if (err instanceof Error && err.stack) { + badStack = err.stack.replace(err.message, '').split('\n').slice(1); + err.stack = [err.toString()] + .concat(savedStack) + .concat('----') + .concat(badStack) + .join('\n'); + } + return err; + }; +} + +/** + * Return an `Error` with `msg` and results properties. + * + * @param {String} msg + * @param {Mixed} expected + * @param {Mixed} actual + * @return {Error} + * @api private + */ + +function error(msg, expected, actual) { + const err = new Error(msg); + err.expected = expected; + err.actual = actual; + err.showDiff = true; + return err; +} + +/** + * Expose `Test`. + */ + +module.exports = Test; diff --git a/node_modules/supertest/package.json b/node_modules/supertest/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ec8f250facf40c3658e7b05f4490dfbc31aed1ad --- /dev/null +++ b/node_modules/supertest/package.json @@ -0,0 +1,57 @@ +{ + "name": "supertest", + "description": "SuperAgent driven library for testing HTTP servers", + "version": "7.2.2", + "author": "TJ Holowaychuk", + "contributors": [], + "dependencies": { + "methods": "^1.1.2", + "superagent": "^10.3.0", + "cookie-signature": "^1.2.2" + }, + "devDependencies": { + "@commitlint/cli": "17", + "@commitlint/config-conventional": "17", + "body-parser": "^1.20.3", + "cookie-parser": "^1.4.7", + "eslint": "^8.32.0", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-plugin-import": "^2.27.5", + "express": "^4.18.3", + "mocha": "^10.2.0", + "nock": "^13.3.8", + "nyc": "^15.1.0", + "proxyquire": "^2.1.3", + "should": "^13.2.3", + "sinon": "20.0.0" + }, + "engines": { + "node": ">=14.18.0" + }, + "files": [ + "index.js", + "lib" + ], + "keywords": [ + "bdd", + "http", + "request", + "superagent", + "tdd", + "test", + "testing" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/ladjs/supertest.git" + }, + "scripts": { + "coverage": "nyc report --reporter=text-lcov > coverage.lcov", + "lint": "eslint lib/**/*.js test/**/*.js index.js", + "lint:fix": "eslint --fix lib/**/*.js test/**/*.js index.js", + "pretest": "npm run lint --if-present", + "test": "nyc --reporter=html --reporter=text mocha --exit --require should --reporter spec --check-leaks" + } +} diff --git a/node_modules/supports-color/browser.d.ts b/node_modules/supports-color/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e8a9ccb8665265a0b38d98f5f08c60c3d347c24 --- /dev/null +++ b/node_modules/supports-color/browser.d.ts @@ -0,0 +1 @@ +export {default} from './index.js'; diff --git a/node_modules/supports-color/browser.js b/node_modules/supports-color/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..f9008d8e713572cdf836f8ad4d54f2afe66b96c8 --- /dev/null +++ b/node_modules/supports-color/browser.js @@ -0,0 +1,35 @@ +/* eslint-env browser */ +/* eslint-disable n/no-unsupported-features/node-builtins */ + +const level = (() => { + if (!('navigator' in globalThis)) { + return 0; + } + + if (globalThis.navigator.userAgentData) { + const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium'); + if (brand?.version > 93) { + return 3; + } + } + + if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) { + return 1; + } + + return 0; +})(); + +const colorSupport = level !== 0 && { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, +}; + +const supportsColor = { + stdout: colorSupport, + stderr: colorSupport, +}; + +export default supportsColor; diff --git a/node_modules/supports-color/index.d.ts b/node_modules/supports-color/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..db44a785196f345cf7e41265aa3d388e9905d5fd --- /dev/null +++ b/node_modules/supports-color/index.d.ts @@ -0,0 +1,55 @@ +import type {WriteStream} from 'node:tty'; + +export type Options = { + /** + Whether `process.argv` should be sniffed for `--color` and `--no-color` flags. + + @default true + */ + readonly sniffFlags?: boolean; +}; + +/** +Levels: +- `0` - All colors disabled. +- `1` - Basic 16 colors support. +- `2` - ANSI 256 colors support. +- `3` - Truecolor 16 million colors support. +*/ +export type ColorSupportLevel = 0 | 1 | 2 | 3; + +/** +Detect whether the terminal supports color. +*/ +export type ColorSupport = { + /** + The color level. + */ + level: ColorSupportLevel; + + /** + Whether basic 16 colors are supported. + */ + hasBasic: boolean; + + /** + Whether ANSI 256 colors are supported. + */ + has256: boolean; + + /** + Whether Truecolor 16 million colors are supported. + */ + has16m: boolean; +}; + +export type ColorInfo = ColorSupport | false; + +export function createSupportsColor(stream?: WriteStream, options?: Options): ColorInfo; + +declare const supportsColor: { + stdout: ColorInfo; + stderr: ColorInfo; +}; + +export default supportsColor; diff --git a/node_modules/supports-color/index.js b/node_modules/supports-color/index.js new file mode 100644 index 0000000000000000000000000000000000000000..906a6f9b83224e75daf5d5d6a8cda554a6b1e996 --- /dev/null +++ b/node_modules/supports-color/index.js @@ -0,0 +1,202 @@ +import process from 'node:process'; +import os from 'node:os'; +import tty from 'node:tty'; + +// From: https://github.com/sindresorhus/has-flag/blob/main/index.js +/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) { +function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +} + +const {env} = process; + +let flagForceColor; +if ( + hasFlag('no-color') + || hasFlag('no-colors') + || hasFlag('color=false') + || hasFlag('color=never') +) { + flagForceColor = 0; +} else if ( + hasFlag('color') + || hasFlag('colors') + || hasFlag('color=true') + || hasFlag('color=always') +) { + flagForceColor = 1; +} + +function envForceColor() { + if (!('FORCE_COLOR' in env)) { + return; + } + + if (env.FORCE_COLOR === 'true') { + return 1; + } + + if (env.FORCE_COLOR === 'false') { + return 0; + } + + if (env.FORCE_COLOR.length === 0) { + return 1; + } + + const level = Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); + + if (![0, 1, 2, 3].includes(level)) { + return; + } + + return level; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== undefined) { + flagForceColor = noFlagForceColor; + } + + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + + if (forceColor === 0) { + return 0; + } + + if (sniffFlags) { + if (hasFlag('color=16m') + || hasFlag('color=full') + || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + } + + // Check for Azure DevOps pipelines. + // Has to be above the `!streamIsTTY` check. + if ('TF_BUILD' in env && 'AGENT_NAME' in env) { + return 1; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 + && Number(osRelease[2]) >= 10_586 + ) { + return Number(osRelease[2]) >= 14_931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) { + return 3; + } + + if (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if (env.TERM === 'xterm-kitty') { + return 3; + } + + if (env.TERM === 'xterm-ghostty') { + return 3; + } + + if (env.TERM === 'wezterm') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': { + return version >= 3 ? 3 : 2; + } + + case 'Apple_Terminal': { + return 2; + } + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +export function createSupportsColor(stream, options = {}) { + const level = _supportsColor(stream, { + streamIsTTY: stream && stream.isTTY, + ...options, + }); + + return translateLevel(level); +} + +const supportsColor = { + stdout: createSupportsColor({isTTY: tty.isatty(1)}), + stderr: createSupportsColor({isTTY: tty.isatty(2)}), +}; + +export default supportsColor; diff --git a/node_modules/supports-color/license b/node_modules/supports-color/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/supports-color/package.json b/node_modules/supports-color/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8915597ab45a0b35dc50bc2d08b64ea9382c9546 --- /dev/null +++ b/node_modules/supports-color/package.json @@ -0,0 +1,64 @@ +{ + "name": "supports-color", + "version": "10.2.2", + "description": "Detect whether a terminal supports color", + "license": "MIT", + "repository": "chalk/supports-color", + "funding": "https://github.com/chalk/supports-color?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + "types": "./index.d.ts", + "node": "./index.js", + "default": "./browser.js" + }, + "sideEffects": false, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "browser.js", + "browser.d.ts" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "devDependencies": { + "@types/node": "^22.10.2", + "ava": "^6.2.0", + "tsd": "^0.31.2", + "xo": "^0.60.0" + }, + "ava": { + "serial": true, + "workerThreads": false + } +} diff --git a/node_modules/supports-color/readme.md b/node_modules/supports-color/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..5c192719b39f7b5eb3e80aa99b938533ee966ab6 --- /dev/null +++ b/node_modules/supports-color/readme.md @@ -0,0 +1,75 @@ +# supports-color + +> Detect whether a terminal supports color + +## Install + +```sh +npm install supports-color +``` + +## Usage + +```js +import supportsColor from 'supports-color'; + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + +## API + +Returns an `object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + +### Custom instance + +The package also exposes the named export `createSupportColor` function that takes an arbitrary write stream (for example, `process.stdout`) and an optional options object to (re-)evaluate color support for an arbitrary stream. + +```js +import {createSupportsColor} from 'supports-color'; + +const stdoutSupportsColor = createSupportsColor(process.stdout); + +if (stdoutSupportsColor) { + console.log('Terminal stdout supports color'); +} + +// `stdoutSupportsColor` is the same as `supportsColor.stdout` +``` + +The options object supports a single boolean property `sniffFlags`. By default it is `true`, which instructs the detection to sniff `process.argv` for the multitude of `--color` flags (see _Info_ below). If `false`, then `process.argv` is not considered when determining color support. + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right +- [is-unicode-supported](https://github.com/sindresorhus/is-unicode-supported) - Detect whether the terminal supports Unicode +- [is-interactive](https://github.com/sindresorhus/is-interactive) - Check if stdout or stderr is interactive + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) diff --git a/node_modules/supports-preserve-symlinks-flag/.eslintrc b/node_modules/supports-preserve-symlinks-flag/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..346ffeca87d3784723773d39f9e52b8c6d12f8c3 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/.eslintrc @@ -0,0 +1,14 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "browser": true, + "node": true, + }, + + "rules": { + "id-length": "off", + }, +} diff --git a/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml b/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..e8d64f37e5fc43885727dc3d086050af7dcc4bb1 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/supports-preserve-symlink-flag +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/supports-preserve-symlinks-flag/.nycrc b/node_modules/supports-preserve-symlinks-flag/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md b/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..61f607f4894beba4e0693c72a6446bf3497bb318 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2022-01-02 + +### Commits + +- Tests [`e2f59ad`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/e2f59ad74e2ae0f5f4899fcde6a6f693ab7cc074) +- Initial commit [`dc222aa`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/dc222aad3c0b940d8d3af1ca9937d108bd2dc4b9) +- [meta] do not publish workflow files [`5ef77f7`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/5ef77f7cb6946d16ee38672be9ec0f1bbdf63262) +- npm init [`992b068`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/992b068503a461f7e8676f40ca2aab255fd8d6ff) +- read me [`6c9afa9`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/6c9afa9fabc8eaf0814aaed6dd01e6df0931b76d) +- Initial implementation [`2f98925`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/2f9892546396d4ab0ad9f1ff83e76c3f01234ae8) +- [meta] add `auto-changelog` [`6c476ae`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/6c476ae1ed7ce68b0480344f090ac2844f35509d) +- [Dev Deps] add `eslint`, `@ljharb/eslint-config` [`d0fffc8`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/d0fffc886d25fba119355520750a909d64da0087) +- Only apps should have lockfiles [`ab318ed`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/ab318ed7ae62f6c2c0e80a50398d40912afd8f69) +- [meta] add `safe-publish-latest` [`2bb23b3`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/2bb23b3ebab02dc4135c4cdf0217db82835b9fca) +- [meta] add `sideEffects` flag [`600223b`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/600223ba24f30779f209d9097721eff35ed62741) diff --git a/node_modules/supports-preserve-symlinks-flag/LICENSE b/node_modules/supports-preserve-symlinks-flag/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2e7b9a3eacf263cb418f4c16b087290ef78c39b2 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/supports-preserve-symlinks-flag/README.md b/node_modules/supports-preserve-symlinks-flag/README.md new file mode 100644 index 0000000000000000000000000000000000000000..eb05b124ca68ba0312c98834f282a2cd6ce568b5 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/README.md @@ -0,0 +1,42 @@ +# node-supports-preserve-symlinks-flag [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Determine if the current node version supports the `--preserve-symlinks` flag. + +## Example + +```js +var supportsPreserveSymlinks = require('node-supports-preserve-symlinks-flag'); +var assert = require('assert'); + +assert.equal(supportsPreserveSymlinks, null); // in a browser +assert.equal(supportsPreserveSymlinks, false); // in node < v6.2 +assert.equal(supportsPreserveSymlinks, true); // in node v6.2+ +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/node-supports-preserve-symlinks-flag +[npm-version-svg]: https://versionbadg.es/inspect-js/node-supports-preserve-symlinks-flag.svg +[deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag.svg +[deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag +[dev-deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/node-supports-preserve-symlinks-flag.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/node-supports-preserve-symlinks-flag.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/node-supports-preserve-symlinks-flag.svg +[downloads-url]: https://npm-stat.com/charts.html?package=node-supports-preserve-symlinks-flag +[codecov-image]: https://codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/node-supports-preserve-symlinks-flag +[actions-url]: https://github.com/inspect-js/node-supports-preserve-symlinks-flag/actions diff --git a/node_modules/supports-preserve-symlinks-flag/browser.js b/node_modules/supports-preserve-symlinks-flag/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..087be1fe9fda8930ca66a68204bd0112b9d8710b --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/browser.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = null; diff --git a/node_modules/supports-preserve-symlinks-flag/index.js b/node_modules/supports-preserve-symlinks-flag/index.js new file mode 100644 index 0000000000000000000000000000000000000000..86fd5d331c4a4d44e9a92d46fbb637165cea78d5 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/index.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = ( +// node 12+ + process.allowedNodeEnvironmentFlags && process.allowedNodeEnvironmentFlags.has('--preserve-symlinks') +) || ( +// node v6.2 - v11 + String(module.constructor._findPath).indexOf('preserveSymlinks') >= 0 // eslint-disable-line no-underscore-dangle +); diff --git a/node_modules/supports-preserve-symlinks-flag/package.json b/node_modules/supports-preserve-symlinks-flag/package.json new file mode 100644 index 0000000000000000000000000000000000000000..56edadcaad850fa1f348aeb0988e98d16eb14a84 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/package.json @@ -0,0 +1,70 @@ +{ + "name": "supports-preserve-symlinks-flag", + "version": "1.0.0", + "description": "Determine if the current node version supports the `--preserve-symlinks` flag.", + "main": "./index.js", + "browser": "./browser.js", + "exports": { + ".": [ + { + "browser": "./browser.js", + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/node-supports-preserve-symlinks-flag.git" + }, + "keywords": [ + "node", + "flag", + "symlink", + "symlinks", + "preserve-symlinks" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/node-supports-preserve-symlinks-flag/issues" + }, + "homepage": "https://github.com/inspect-js/node-supports-preserve-symlinks-flag#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.1.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "eslint": "^8.6.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "semver": "^6.3.0", + "tape": "^5.4.0" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/supports-preserve-symlinks-flag/test/index.js b/node_modules/supports-preserve-symlinks-flag/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9938d671691790a75bacefc6100b39d6e4ab937a --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/test/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); +var semver = require('semver'); + +var supportsPreserveSymlinks = require('../'); +var browser = require('../browser'); + +test('supportsPreserveSymlinks', function (t) { + t.equal(typeof supportsPreserveSymlinks, 'boolean', 'is a boolean'); + + t.equal(browser, null, 'browser file is `null`'); + t.equal( + supportsPreserveSymlinks, + null, + 'in a browser, is null', + { skip: typeof window === 'undefined' } + ); + + var expected = semver.satisfies(process.version, '>= 6.2'); + t.equal( + supportsPreserveSymlinks, + expected, + 'is true in node v6.2+, false otherwise (actual: ' + supportsPreserveSymlinks + ', expected ' + expected + ')', + { skip: typeof window !== 'undefined' } + ); + + t.end(); +}); diff --git a/node_modules/svg-arc-to-cubic-bezier/LICENSE.md b/node_modules/svg-arc-to-cubic-bezier/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..6e59fa5a817cc1ae3e3aff73b2cc63fdb8175905 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/LICENSE.md @@ -0,0 +1,16 @@ +Internet Systems Consortium license +=================================== + +Copyright (c) `2017`, `Colin Meinke` + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/svg-arc-to-cubic-bezier/README.md b/node_modules/svg-arc-to-cubic-bezier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f4d8f8192d17bce665d547a9ae6ac498b22b30d1 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/README.md @@ -0,0 +1,75 @@ +# SVG arc to cubic bezier + +A function that takes an SVG arc curve as input, and maps it to +one or more cubic bezier curves. + +I extracted the `a2c` function from +[SVG path](https://github.com/fontello/svgpath), as I wanted to use it on its own. + +All credit, thanks and respect goes to: + +- Sergey Batishchev – [@snb2013](https://github.com/snb2013) +- Vitaly Puzrin – [@puzrin](https://github.com/puzrin) +- Alex Kocharin – [@rlidwka](https://github.com/rlidwka) + +It blew my mind. Thank you! + +## Installation + +``` +npm install svg-arc-to-cubic-bezier +``` + +## Usage + +```js +import arcToBezier from 'svg-arc-to-cubic-bezier'; + +const previousPoint = { x: 100, y: 100 } + +const currentPoint = { + x: 700, + y: 100, + curve: { + type: 'arc', + rx: 300, + ry: 200, + largeArcFlag: 30, + sweepFlag: 0, + xAxisRotation: 0, + }, +}; + +const curves = arcToBezier({ + px: previousPoint.x, + py: previousPoint.y, + cx: currentPoint.x, + cy: currentPoint.y, + rx: currentPoint.curve.rx, + ry: currentPoint.curve.ry, + xAxisRotation: currentPoint.curve.xAxisRotation, + largeArcFlag: currentPoint.curve.largeArcFlag, + sweepFlag: currentPoint.curve.sweepFlag, +}); + +curves.forEach( c => console.log( c )); + +// [ +// { +// x1: 159.7865795437111, +// y1: 244.97474575043722, +// x2: 342.5677510865157, +// y2: 362.49999701503634, +// x: 508.253174689854, +// y: 362.4999967447917, +// }, +// { +// x1: 673.9385982931924, +// y1: 362.49999647454695, +// x2: 759.7865756485664, +// y2: 244.97474477179443, +// x: 699.9999995964145, +// y: 99.99999902135724, +// }, +// ] +``` diff --git a/node_modules/svg-arc-to-cubic-bezier/cjs/index.js b/node_modules/svg-arc-to-cubic-bezier/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..11bcabc67c03cca97f9c8f108d9d6ed0bf6e0f13 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/cjs/index.js @@ -0,0 +1,190 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); + +var TAU = Math.PI * 2; + +var mapToEllipse = function mapToEllipse(_ref, rx, ry, cosphi, sinphi, centerx, centery) { + var x = _ref.x, + y = _ref.y; + + x *= rx; + y *= ry; + + var xp = cosphi * x - sinphi * y; + var yp = sinphi * x + cosphi * y; + + return { + x: xp + centerx, + y: yp + centery + }; +}; + +var approxUnitArc = function approxUnitArc(ang1, ang2) { + // If 90 degree circular arc, use a constant + // as derived from http://spencermortensen.com/articles/bezier-circle + var a = ang2 === 1.5707963267948966 ? 0.551915024494 : ang2 === -1.5707963267948966 ? -0.551915024494 : 4 / 3 * Math.tan(ang2 / 4); + + var x1 = Math.cos(ang1); + var y1 = Math.sin(ang1); + var x2 = Math.cos(ang1 + ang2); + var y2 = Math.sin(ang1 + ang2); + + return [{ + x: x1 - y1 * a, + y: y1 + x1 * a + }, { + x: x2 + y2 * a, + y: y2 - x2 * a + }, { + x: x2, + y: y2 + }]; +}; + +var vectorAngle = function vectorAngle(ux, uy, vx, vy) { + var sign = ux * vy - uy * vx < 0 ? -1 : 1; + + var dot = ux * vx + uy * vy; + + if (dot > 1) { + dot = 1; + } + + if (dot < -1) { + dot = -1; + } + + return sign * Math.acos(dot); +}; + +var getArcCenter = function getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) { + var rxsq = Math.pow(rx, 2); + var rysq = Math.pow(ry, 2); + var pxpsq = Math.pow(pxp, 2); + var pypsq = Math.pow(pyp, 2); + + var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq; + + if (radicant < 0) { + radicant = 0; + } + + radicant /= rxsq * pypsq + rysq * pxpsq; + radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1); + + var centerxp = radicant * rx / ry * pyp; + var centeryp = radicant * -ry / rx * pxp; + + var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2; + var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2; + + var vx1 = (pxp - centerxp) / rx; + var vy1 = (pyp - centeryp) / ry; + var vx2 = (-pxp - centerxp) / rx; + var vy2 = (-pyp - centeryp) / ry; + + var ang1 = vectorAngle(1, 0, vx1, vy1); + var ang2 = vectorAngle(vx1, vy1, vx2, vy2); + + if (sweepFlag === 0 && ang2 > 0) { + ang2 -= TAU; + } + + if (sweepFlag === 1 && ang2 < 0) { + ang2 += TAU; + } + + return [centerx, centery, ang1, ang2]; +}; + +var arcToBezier = function arcToBezier(_ref2) { + var px = _ref2.px, + py = _ref2.py, + cx = _ref2.cx, + cy = _ref2.cy, + rx = _ref2.rx, + ry = _ref2.ry, + _ref2$xAxisRotation = _ref2.xAxisRotation, + xAxisRotation = _ref2$xAxisRotation === undefined ? 0 : _ref2$xAxisRotation, + _ref2$largeArcFlag = _ref2.largeArcFlag, + largeArcFlag = _ref2$largeArcFlag === undefined ? 0 : _ref2$largeArcFlag, + _ref2$sweepFlag = _ref2.sweepFlag, + sweepFlag = _ref2$sweepFlag === undefined ? 0 : _ref2$sweepFlag; + + var curves = []; + + if (rx === 0 || ry === 0) { + return []; + } + + var sinphi = Math.sin(xAxisRotation * TAU / 360); + var cosphi = Math.cos(xAxisRotation * TAU / 360); + + var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2; + var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2; + + if (pxp === 0 && pyp === 0) { + return []; + } + + rx = Math.abs(rx); + ry = Math.abs(ry); + + var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2); + + if (lambda > 1) { + rx *= Math.sqrt(lambda); + ry *= Math.sqrt(lambda); + } + + var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), + _getArcCenter2 = _slicedToArray(_getArcCenter, 4), + centerx = _getArcCenter2[0], + centery = _getArcCenter2[1], + ang1 = _getArcCenter2[2], + ang2 = _getArcCenter2[3]; + + // If 'ang2' == 90.0000000001, then `ratio` will evaluate to + // 1.0000000001. This causes `segments` to be greater than one, which is an + // unecessary split, and adds extra points to the bezier curve. To alleviate + // this issue, we round to 1.0 when the ratio is close to 1.0. + + + var ratio = Math.abs(ang2) / (TAU / 4); + if (Math.abs(1.0 - ratio) < 0.0000001) { + ratio = 1.0; + } + + var segments = Math.max(Math.ceil(ratio), 1); + + ang2 /= segments; + + for (var i = 0; i < segments; i++) { + curves.push(approxUnitArc(ang1, ang2)); + ang1 += ang2; + } + + return curves.map(function (curve) { + var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), + x1 = _mapToEllipse.x, + y1 = _mapToEllipse.y; + + var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), + x2 = _mapToEllipse2.x, + y2 = _mapToEllipse2.y; + + var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), + x = _mapToEllipse3.x, + y = _mapToEllipse3.y; + + return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }; + }); +}; + +exports.default = arcToBezier; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/svg-arc-to-cubic-bezier/modules/index.js b/node_modules/svg-arc-to-cubic-bezier/modules/index.js new file mode 100644 index 0000000000000000000000000000000000000000..61541f14d39e3203133d26bb337d86f0b82c823b --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/modules/index.js @@ -0,0 +1,183 @@ +var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); + +var TAU = Math.PI * 2; + +var mapToEllipse = function mapToEllipse(_ref, rx, ry, cosphi, sinphi, centerx, centery) { + var x = _ref.x, + y = _ref.y; + + x *= rx; + y *= ry; + + var xp = cosphi * x - sinphi * y; + var yp = sinphi * x + cosphi * y; + + return { + x: xp + centerx, + y: yp + centery + }; +}; + +var approxUnitArc = function approxUnitArc(ang1, ang2) { + // If 90 degree circular arc, use a constant + // as derived from http://spencermortensen.com/articles/bezier-circle + var a = ang2 === 1.5707963267948966 ? 0.551915024494 : ang2 === -1.5707963267948966 ? -0.551915024494 : 4 / 3 * Math.tan(ang2 / 4); + + var x1 = Math.cos(ang1); + var y1 = Math.sin(ang1); + var x2 = Math.cos(ang1 + ang2); + var y2 = Math.sin(ang1 + ang2); + + return [{ + x: x1 - y1 * a, + y: y1 + x1 * a + }, { + x: x2 + y2 * a, + y: y2 - x2 * a + }, { + x: x2, + y: y2 + }]; +}; + +var vectorAngle = function vectorAngle(ux, uy, vx, vy) { + var sign = ux * vy - uy * vx < 0 ? -1 : 1; + + var dot = ux * vx + uy * vy; + + if (dot > 1) { + dot = 1; + } + + if (dot < -1) { + dot = -1; + } + + return sign * Math.acos(dot); +}; + +var getArcCenter = function getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) { + var rxsq = Math.pow(rx, 2); + var rysq = Math.pow(ry, 2); + var pxpsq = Math.pow(pxp, 2); + var pypsq = Math.pow(pyp, 2); + + var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq; + + if (radicant < 0) { + radicant = 0; + } + + radicant /= rxsq * pypsq + rysq * pxpsq; + radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1); + + var centerxp = radicant * rx / ry * pyp; + var centeryp = radicant * -ry / rx * pxp; + + var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2; + var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2; + + var vx1 = (pxp - centerxp) / rx; + var vy1 = (pyp - centeryp) / ry; + var vx2 = (-pxp - centerxp) / rx; + var vy2 = (-pyp - centeryp) / ry; + + var ang1 = vectorAngle(1, 0, vx1, vy1); + var ang2 = vectorAngle(vx1, vy1, vx2, vy2); + + if (sweepFlag === 0 && ang2 > 0) { + ang2 -= TAU; + } + + if (sweepFlag === 1 && ang2 < 0) { + ang2 += TAU; + } + + return [centerx, centery, ang1, ang2]; +}; + +var arcToBezier = function arcToBezier(_ref2) { + var px = _ref2.px, + py = _ref2.py, + cx = _ref2.cx, + cy = _ref2.cy, + rx = _ref2.rx, + ry = _ref2.ry, + _ref2$xAxisRotation = _ref2.xAxisRotation, + xAxisRotation = _ref2$xAxisRotation === undefined ? 0 : _ref2$xAxisRotation, + _ref2$largeArcFlag = _ref2.largeArcFlag, + largeArcFlag = _ref2$largeArcFlag === undefined ? 0 : _ref2$largeArcFlag, + _ref2$sweepFlag = _ref2.sweepFlag, + sweepFlag = _ref2$sweepFlag === undefined ? 0 : _ref2$sweepFlag; + + var curves = []; + + if (rx === 0 || ry === 0) { + return []; + } + + var sinphi = Math.sin(xAxisRotation * TAU / 360); + var cosphi = Math.cos(xAxisRotation * TAU / 360); + + var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2; + var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2; + + if (pxp === 0 && pyp === 0) { + return []; + } + + rx = Math.abs(rx); + ry = Math.abs(ry); + + var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2); + + if (lambda > 1) { + rx *= Math.sqrt(lambda); + ry *= Math.sqrt(lambda); + } + + var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), + _getArcCenter2 = _slicedToArray(_getArcCenter, 4), + centerx = _getArcCenter2[0], + centery = _getArcCenter2[1], + ang1 = _getArcCenter2[2], + ang2 = _getArcCenter2[3]; + + // If 'ang2' == 90.0000000001, then `ratio` will evaluate to + // 1.0000000001. This causes `segments` to be greater than one, which is an + // unecessary split, and adds extra points to the bezier curve. To alleviate + // this issue, we round to 1.0 when the ratio is close to 1.0. + + + var ratio = Math.abs(ang2) / (TAU / 4); + if (Math.abs(1.0 - ratio) < 0.0000001) { + ratio = 1.0; + } + + var segments = Math.max(Math.ceil(ratio), 1); + + ang2 /= segments; + + for (var i = 0; i < segments; i++) { + curves.push(approxUnitArc(ang1, ang2)); + ang1 += ang2; + } + + return curves.map(function (curve) { + var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), + x1 = _mapToEllipse.x, + y1 = _mapToEllipse.y; + + var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), + x2 = _mapToEllipse2.x, + y2 = _mapToEllipse2.y; + + var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), + x = _mapToEllipse3.x, + y = _mapToEllipse3.y; + + return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }; + }); +}; + +export default arcToBezier; \ No newline at end of file diff --git a/node_modules/svg-arc-to-cubic-bezier/package.json b/node_modules/svg-arc-to-cubic-bezier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dfe75de54df748d5422645f087d6a5171f8c62b4 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/package.json @@ -0,0 +1,106 @@ +{ + "author": { + "name": "Colin Meinke", + "email": "hello@colinmeinke.com", + "url": "https://colinmeinke.com" + }, + "babel": { + "env": { + "cjs": { + "plugins": [ + "transform-object-rest-spread", + "add-module-exports" + ], + "presets": [ + "es2015" + ] + }, + "modules": { + "plugins": [ + "transform-object-rest-spread" + ], + "presets": [ + [ + "es2015", + { + "modules": false + } + ] + ] + }, + "umd": { + "plugins": [ + "transform-object-rest-spread" + ], + "presets": [ + [ + "es2015", + { + "modules": false + } + ] + ] + } + } + }, + "bugs": { + "url": "https://github.com/colinmeinke/svg-arc-to-cubic-bezier/issues" + }, + "config": { + "commitizen": { + "path": "node_modules/cz-conventional-changelog" + } + }, + "description": "A function that takes an SVG arc curve as input, and maps it to one or more cubic bezier curves", + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-core": "^6.26.3", + "babel-plugin-add-module-exports": "^0.3.3", + "babel-plugin-transform-object-rest-spread": "^6.26.0", + "babel-preset-es2015": "^6.24.1", + "commitizen": "^3.1.1", + "cz-conventional-changelog": "^2.1.0", + "rimraf": "^2.6.3", + "rollup": "^1.16.6", + "rollup-plugin-babel": "^3.0.7", + "rollup-plugin-commonjs": "^10.0.1", + "rollup-plugin-uglify": "^6.0.2", + "snazzy": "^8.0.0", + "standard": "^12.0.1", + "travis-deploy-once": "^5.0.11", + "semantic-release": "^15.13.18" + }, + "keywords": [ + "arc", + "bezier", + "convert", + "cubic", + "curve", + "path", + "svg" + ], + "license": "ISC", + "main": "cjs/index.js", + "module": "modules/index.js", + "name": "svg-arc-to-cubic-bezier", + "repository": { + "type": "git", + "url": "https://github.com/colinmeinke/svg-arc-to-cubic-bezier" + }, + "scripts": { + "build": "npm run build:modules && npm run build:cjs && npm run build:umd", + "build:cjs": "BABEL_ENV=cjs babel src --out-dir cjs", + "build:modules": "BABEL_ENV=modules babel src --out-dir modules", + "build:umd": "npm run build:umd:dev && npm run build:umd:pro", + "build:umd:dev": "BABEL_ENV=umd rollup -c", + "build:umd:pro": "NODE_ENV=production BABEL_ENV=umd rollup -c", + "commit": "git-cz", + "fix": "standard --fix", + "lint": "standard --verbose | snazzy", + "prepublish": "npm run tidy && npm run build", + "semantic-release": "semantic-release", + "tidy": "rimraf modules cjs dist", + "travis-deploy-once": "travis-deploy-once" + }, + "version": "3.2.0" +} diff --git a/node_modules/svg-arc-to-cubic-bezier/src/index.js b/node_modules/svg-arc-to-cubic-bezier/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fb3219838ecf0ad211a2dde8b1ced51a165e83fa --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/src/index.js @@ -0,0 +1,196 @@ +const TAU = Math.PI * 2 + +const mapToEllipse = ({ x, y }, rx, ry, cosphi, sinphi, centerx, centery) => { + x *= rx + y *= ry + + const xp = cosphi * x - sinphi * y + const yp = sinphi * x + cosphi * y + + return { + x: xp + centerx, + y: yp + centery + } +} + +const approxUnitArc = (ang1, ang2) => { + // If 90 degree circular arc, use a constant + // as derived from http://spencermortensen.com/articles/bezier-circle + const a = ang2 === 1.5707963267948966 + ? 0.551915024494 + : ang2 === -1.5707963267948966 + ? -0.551915024494 + : 4 / 3 * Math.tan(ang2 / 4) + + const x1 = Math.cos(ang1) + const y1 = Math.sin(ang1) + const x2 = Math.cos(ang1 + ang2) + const y2 = Math.sin(ang1 + ang2) + + return [ + { + x: x1 - y1 * a, + y: y1 + x1 * a + }, + { + x: x2 + y2 * a, + y: y2 - x2 * a + }, + { + x: x2, + y: y2 + } + ] +} + +const vectorAngle = (ux, uy, vx, vy) => { + const sign = (ux * vy - uy * vx < 0) ? -1 : 1 + + let dot = ux * vx + uy * vy + + if (dot > 1) { + dot = 1 + } + + if (dot < -1) { + dot = -1 + } + + return sign * Math.acos(dot) +} + +const getArcCenter = ( + px, + py, + cx, + cy, + rx, + ry, + largeArcFlag, + sweepFlag, + sinphi, + cosphi, + pxp, + pyp +) => { + const rxsq = Math.pow(rx, 2) + const rysq = Math.pow(ry, 2) + const pxpsq = Math.pow(pxp, 2) + const pypsq = Math.pow(pyp, 2) + + let radicant = (rxsq * rysq) - (rxsq * pypsq) - (rysq * pxpsq) + + if (radicant < 0) { + radicant = 0 + } + + radicant /= (rxsq * pypsq) + (rysq * pxpsq) + radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1) + + const centerxp = radicant * rx / ry * pyp + const centeryp = radicant * -ry / rx * pxp + + const centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2 + const centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2 + + const vx1 = (pxp - centerxp) / rx + const vy1 = (pyp - centeryp) / ry + const vx2 = (-pxp - centerxp) / rx + const vy2 = (-pyp - centeryp) / ry + + let ang1 = vectorAngle(1, 0, vx1, vy1) + let ang2 = vectorAngle(vx1, vy1, vx2, vy2) + + if (sweepFlag === 0 && ang2 > 0) { + ang2 -= TAU + } + + if (sweepFlag === 1 && ang2 < 0) { + ang2 += TAU + } + + return [ centerx, centery, ang1, ang2 ] +} + +const arcToBezier = ({ + px, + py, + cx, + cy, + rx, + ry, + xAxisRotation = 0, + largeArcFlag = 0, + sweepFlag = 0 +}) => { + const curves = [] + + if (rx === 0 || ry === 0) { + return [] + } + + const sinphi = Math.sin(xAxisRotation * TAU / 360) + const cosphi = Math.cos(xAxisRotation * TAU / 360) + + const pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2 + const pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2 + + if (pxp === 0 && pyp === 0) { + return [] + } + + rx = Math.abs(rx) + ry = Math.abs(ry) + + const lambda = + Math.pow(pxp, 2) / Math.pow(rx, 2) + + Math.pow(pyp, 2) / Math.pow(ry, 2) + + if (lambda > 1) { + rx *= Math.sqrt(lambda) + ry *= Math.sqrt(lambda) + } + + let [ centerx, centery, ang1, ang2 ] = getArcCenter( + px, + py, + cx, + cy, + rx, + ry, + largeArcFlag, + sweepFlag, + sinphi, + cosphi, + pxp, + pyp + ) + + // If 'ang2' == 90.0000000001, then `ratio` will evaluate to + // 1.0000000001. This causes `segments` to be greater than one, which is an + // unecessary split, and adds extra points to the bezier curve. To alleviate + // this issue, we round to 1.0 when the ratio is close to 1.0. + let ratio = Math.abs(ang2) / (TAU / 4) + if (Math.abs(1.0 - ratio) < 0.0000001) { + ratio = 1.0 + } + + const segments = Math.max(Math.ceil(ratio), 1) + + ang2 /= segments + + for (let i = 0; i < segments; i++) { + curves.push(approxUnitArc(ang1, ang2)) + ang1 += ang2 + } + + return curves.map(curve => { + const { x: x1, y: y1 } = mapToEllipse(curve[ 0 ], rx, ry, cosphi, sinphi, centerx, centery) + const { x: x2, y: y2 } = mapToEllipse(curve[ 1 ], rx, ry, cosphi, sinphi, centerx, centery) + const { x, y } = mapToEllipse(curve[ 2 ], rx, ry, cosphi, sinphi, centerx, centery) + + return { x1, y1, x2, y2, x, y } + }) +} + +export default arcToBezier diff --git a/node_modules/symbol-tree/LICENSE b/node_modules/symbol-tree/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9b5796d43e2d07312e3c88d947a4e9ff72a0f432 --- /dev/null +++ b/node_modules/symbol-tree/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Joris van der Wel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/symbol-tree/README.md b/node_modules/symbol-tree/README.md new file mode 100644 index 0000000000000000000000000000000000000000..972db1adafd2b8ac4175fd0bb02198bd65e8897d --- /dev/null +++ b/node_modules/symbol-tree/README.md @@ -0,0 +1,545 @@ +symbol-tree +=========== +[![Travis CI Build Status](https://api.travis-ci.org/jsdom/js-symbol-tree.svg?branch=master)](https://travis-ci.org/jsdom/js-symbol-tree) [![Coverage Status](https://coveralls.io/repos/github/jsdom/js-symbol-tree/badge.svg?branch=master)](https://coveralls.io/github/jsdom/js-symbol-tree?branch=master) + +Turn any collection of objects into its own efficient tree or linked list using `Symbol`. + +This library has been designed to provide an efficient backing data structure for DOM trees. You can also use this library as an efficient linked list. Any meta data is stored on your objects directly, which ensures any kind of insertion or deletion is performed in constant time. Because an ES6 `Symbol` is used, the meta data does not interfere with your object in any way. + +Node.js 4+, io.js and modern browsers are supported. + +Example +------- +A linked list: + +```javascript +const SymbolTree = require('symbol-tree'); +const tree = new SymbolTree(); + +let a = {foo: 'bar'}; // or `new Whatever()` +let b = {foo: 'baz'}; +let c = {foo: 'qux'}; + +tree.insertBefore(b, a); // insert a before b +tree.insertAfter(b, c); // insert c after b + +console.log(tree.nextSibling(a) === b); +console.log(tree.nextSibling(b) === c); +console.log(tree.previousSibling(c) === b); + +tree.remove(b); +console.log(tree.nextSibling(a) === c); +``` + +A tree: + +```javascript +const SymbolTree = require('symbol-tree'); +const tree = new SymbolTree(); + +let parent = {}; +let a = {}; +let b = {}; +let c = {}; + +tree.prependChild(parent, a); // insert a as the first child +tree.appendChild(parent,c ); // insert c as the last child +tree.insertAfter(a, b); // insert b after a, it now has the same parent as a + +console.log(tree.firstChild(parent) === a); +console.log(tree.nextSibling(tree.firstChild(parent)) === b); +console.log(tree.lastChild(parent) === c); + +let grandparent = {}; +tree.prependChild(grandparent, parent); +console.log(tree.firstChild(tree.firstChild(grandparent)) === a); +``` + +See [api.md](api.md) for more documentation. + +Testing +------- +Make sure you install the dependencies first: + + npm install + +You can now run the unit tests by executing: + + npm test + +The line and branch coverage should be 100%. + +API Documentation +----------------- + + +## symbol-tree +**Author**: Joris van der Wel + +* [symbol-tree](#module_symbol-tree) + * [SymbolTree](#exp_module_symbol-tree--SymbolTree) ⏏ + * [new SymbolTree([description])](#new_module_symbol-tree--SymbolTree_new) + * [.initialize(object)](#module_symbol-tree--SymbolTree+initialize) ⇒ Object + * [.hasChildren(object)](#module_symbol-tree--SymbolTree+hasChildren) ⇒ Boolean + * [.firstChild(object)](#module_symbol-tree--SymbolTree+firstChild) ⇒ Object + * [.lastChild(object)](#module_symbol-tree--SymbolTree+lastChild) ⇒ Object + * [.previousSibling(object)](#module_symbol-tree--SymbolTree+previousSibling) ⇒ Object + * [.nextSibling(object)](#module_symbol-tree--SymbolTree+nextSibling) ⇒ Object + * [.parent(object)](#module_symbol-tree--SymbolTree+parent) ⇒ Object + * [.lastInclusiveDescendant(object)](#module_symbol-tree--SymbolTree+lastInclusiveDescendant) ⇒ Object + * [.preceding(object, [options])](#module_symbol-tree--SymbolTree+preceding) ⇒ Object + * [.following(object, [options])](#module_symbol-tree--SymbolTree+following) ⇒ Object + * [.childrenToArray(parent, [options])](#module_symbol-tree--SymbolTree+childrenToArray) ⇒ Array.<Object> + * [.ancestorsToArray(object, [options])](#module_symbol-tree--SymbolTree+ancestorsToArray) ⇒ Array.<Object> + * [.treeToArray(root, [options])](#module_symbol-tree--SymbolTree+treeToArray) ⇒ Array.<Object> + * [.childrenIterator(parent, [options])](#module_symbol-tree--SymbolTree+childrenIterator) ⇒ Object + * [.previousSiblingsIterator(object)](#module_symbol-tree--SymbolTree+previousSiblingsIterator) ⇒ Object + * [.nextSiblingsIterator(object)](#module_symbol-tree--SymbolTree+nextSiblingsIterator) ⇒ Object + * [.ancestorsIterator(object)](#module_symbol-tree--SymbolTree+ancestorsIterator) ⇒ Object + * [.treeIterator(root, options)](#module_symbol-tree--SymbolTree+treeIterator) ⇒ Object + * [.index(child)](#module_symbol-tree--SymbolTree+index) ⇒ Number + * [.childrenCount(parent)](#module_symbol-tree--SymbolTree+childrenCount) ⇒ Number + * [.compareTreePosition(left, right)](#module_symbol-tree--SymbolTree+compareTreePosition) ⇒ Number + * [.remove(removeObject)](#module_symbol-tree--SymbolTree+remove) ⇒ Object + * [.insertBefore(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertBefore) ⇒ Object + * [.insertAfter(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertAfter) ⇒ Object + * [.prependChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+prependChild) ⇒ Object + * [.appendChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+appendChild) ⇒ Object + + + +### SymbolTree ⏏ +**Kind**: Exported class + + +#### new SymbolTree([description]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [description] | string | "'SymbolTree data'" | Description used for the Symbol | + + + +#### symbolTree.initialize(object) ⇒ Object +You can use this function to (optionally) initialize an object right after its creation, +to take advantage of V8's fast properties. Also useful if you would like to +freeze your object. + +`O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - object + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.hasChildren(object) ⇒ Boolean +Returns `true` if the object has any children. Otherwise it returns `false`. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.firstChild(object) ⇒ Object +Returns the first child of the given object. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.lastChild(object) ⇒ Object +Returns the last child of the given object. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.previousSibling(object) ⇒ Object +Returns the previous sibling of the given object. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.nextSibling(object) ⇒ Object +Returns the next sibling of the given object. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.parent(object) ⇒ Object +Return the parent of the given object. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.lastInclusiveDescendant(object) ⇒ Object +Find the inclusive descendant that is last in tree order of the given object. + +* `O(n)` (worst case) where `n` is the depth of the subtree of `object` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.preceding(object, [options]) ⇒ Object +Find the preceding object (A) of the given object (B). +An object A is preceding an object B if A and B are in the same tree +and A comes before B in tree order. + +* `O(n)` (worst case) +* `O(1)` (amortized when walking the entire tree) + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | Description | +| --- | --- | --- | +| object | Object | | +| [options] | Object | | +| [options.root] | Object | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` | + + + +#### symbolTree.following(object, [options]) ⇒ Object +Find the following object (A) of the given object (B). +An object A is following an object B if A and B are in the same tree +and A comes after B in tree order. + +* `O(n)` (worst case) where `n` is the amount of objects in the entire tree +* `O(1)` (amortized when walking the entire tree) + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| object | Object | | | +| [options] | Object | | | +| [options.root] | Object | | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` | +| [options.skipChildren] | Boolean | false | If set, ignore the children of `object` | + + + +#### symbolTree.childrenToArray(parent, [options]) ⇒ Array.<Object> +Append all children of the given object to an array. + +* `O(n)` where `n` is the amount of children of the given `parent` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| parent | Object | | | +| [options] | Object | | | +| [options.array] | Array.<Object> | [] | | +| [options.filter] | function | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. | +| [options.thisArg] | \* | | Value to use as `this` when executing `filter`. | + + + +#### symbolTree.ancestorsToArray(object, [options]) ⇒ Array.<Object> +Append all inclusive ancestors of the given object to an array. + +* `O(n)` where `n` is the amount of ancestors of the given `object` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| object | Object | | | +| [options] | Object | | | +| [options.array] | Array.<Object> | [] | | +| [options.filter] | function | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. | +| [options.thisArg] | \* | | Value to use as `this` when executing `filter`. | + + + +#### symbolTree.treeToArray(root, [options]) ⇒ Array.<Object> +Append all descendants of the given object to an array (in tree order). + +* `O(n)` where `n` is the amount of objects in the sub-tree of the given `object` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| root | Object | | | +| [options] | Object | | | +| [options.array] | Array.<Object> | [] | | +| [options.filter] | function | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. | +| [options.thisArg] | \* | | Value to use as `this` when executing `filter`. | + + + +#### symbolTree.childrenIterator(parent, [options]) ⇒ Object +Iterate over all children of the given object + +* `O(1)` for a single iteration + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - An iterable iterator (ES6) + +| Param | Type | Default | +| --- | --- | --- | +| parent | Object | | +| [options] | Object | | +| [options.reverse] | Boolean | false | + + + +#### symbolTree.previousSiblingsIterator(object) ⇒ Object +Iterate over all the previous siblings of the given object. (in reverse tree order) + +* `O(1)` for a single iteration + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - An iterable iterator (ES6) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.nextSiblingsIterator(object) ⇒ Object +Iterate over all the next siblings of the given object. (in tree order) + +* `O(1)` for a single iteration + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - An iterable iterator (ES6) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.ancestorsIterator(object) ⇒ Object +Iterate over all inclusive ancestors of the given object + +* `O(1)` for a single iteration + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - An iterable iterator (ES6) + +| Param | Type | +| --- | --- | +| object | Object | + + + +#### symbolTree.treeIterator(root, options) ⇒ Object +Iterate over all descendants of the given object (in tree order). + +Where `n` is the amount of objects in the sub-tree of the given `root`: + +* `O(n)` (worst case for a single iteration) +* `O(n)` (amortized, when completing the iterator) + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - An iterable iterator (ES6) + +| Param | Type | Default | +| --- | --- | --- | +| root | Object | | +| options | Object | | +| [options.reverse] | Boolean | false | + + + +#### symbolTree.index(child) ⇒ Number +Find the index of the given object (the number of preceding siblings). + +* `O(n)` where `n` is the amount of preceding siblings +* `O(1)` (amortized, if the tree is not modified) + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Number - The number of preceding siblings, or -1 if the object has no parent + +| Param | Type | +| --- | --- | +| child | Object | + + + +#### symbolTree.childrenCount(parent) ⇒ Number +Calculate the number of children. + +* `O(n)` where `n` is the amount of children +* `O(1)` (amortized, if the tree is not modified) + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | +| --- | --- | +| parent | Object | + + + +#### symbolTree.compareTreePosition(left, right) ⇒ Number +Compare the position of an object relative to another object. A bit set is returned: + +
    +
  • DISCONNECTED : 1
  • +
  • PRECEDING : 2
  • +
  • FOLLOWING : 4
  • +
  • CONTAINS : 8
  • +
  • CONTAINED_BY : 16
  • +
+ +The semantics are the same as compareDocumentPosition in DOM, with the exception that +DISCONNECTED never occurs with any other bit. + +where `n` and `m` are the amount of ancestors of `left` and `right`; +where `o` is the amount of children of the lowest common ancestor of `left` and `right`: + +* `O(n + m + o)` (worst case) +* `O(n + m)` (amortized, if the tree is not modified) + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) + +| Param | Type | +| --- | --- | +| left | Object | +| right | Object | + + + +#### symbolTree.remove(removeObject) ⇒ Object +Remove the object from this tree. +Has no effect if already removed. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - removeObject + +| Param | Type | +| --- | --- | +| removeObject | Object | + + + +#### symbolTree.insertBefore(referenceObject, newObject) ⇒ Object +Insert the given object before the reference object. +`newObject` is now the previous sibling of `referenceObject`. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - newObject +**Throws**: + +- Error If the newObject is already present in this SymbolTree + + +| Param | Type | +| --- | --- | +| referenceObject | Object | +| newObject | Object | + + + +#### symbolTree.insertAfter(referenceObject, newObject) ⇒ Object +Insert the given object after the reference object. +`newObject` is now the next sibling of `referenceObject`. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - newObject +**Throws**: + +- Error If the newObject is already present in this SymbolTree + + +| Param | Type | +| --- | --- | +| referenceObject | Object | +| newObject | Object | + + + +#### symbolTree.prependChild(referenceObject, newObject) ⇒ Object +Insert the given object as the first child of the given reference object. +`newObject` is now the first child of `referenceObject`. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - newObject +**Throws**: + +- Error If the newObject is already present in this SymbolTree + + +| Param | Type | +| --- | --- | +| referenceObject | Object | +| newObject | Object | + + + +#### symbolTree.appendChild(referenceObject, newObject) ⇒ Object +Insert the given object as the last child of the given reference object. +`newObject` is now the last child of `referenceObject`. + +* `O(1)` + +**Kind**: instance method of [SymbolTree](#exp_module_symbol-tree--SymbolTree) +**Returns**: Object - newObject +**Throws**: + +- Error If the newObject is already present in this SymbolTree + + +| Param | Type | +| --- | --- | +| referenceObject | Object | +| newObject | Object | + diff --git a/node_modules/symbol-tree/lib/SymbolTree.js b/node_modules/symbol-tree/lib/SymbolTree.js new file mode 100644 index 0000000000000000000000000000000000000000..b2b8f2efb0fd8563db6be65af3091c988c2cdd1f --- /dev/null +++ b/node_modules/symbol-tree/lib/SymbolTree.js @@ -0,0 +1,838 @@ +'use strict'; + +/** + * @module symbol-tree + * @author Joris van der Wel + */ + +const SymbolTreeNode = require('./SymbolTreeNode'); +const TreePosition = require('./TreePosition'); +const TreeIterator = require('./TreeIterator'); + +function returnTrue() { + return true; +} + +function reverseArrayIndex(array, reverseIndex) { + return array[array.length - 1 - reverseIndex]; // no need to check `index >= 0` +} + +class SymbolTree { + + /** + * @constructor + * @alias module:symbol-tree + * @param {string} [description='SymbolTree data'] Description used for the Symbol + */ + constructor(description) { + this.symbol = Symbol(description || 'SymbolTree data'); + } + + /** + * You can use this function to (optionally) initialize an object right after its creation, + * to take advantage of V8's fast properties. Also useful if you would like to + * freeze your object. + * + * `O(1)` + * + * @method + * @alias module:symbol-tree#initialize + * @param {Object} object + * @return {Object} object + */ + initialize(object) { + this._node(object); + + return object; + } + + _node(object) { + if (!object) { + return null; + } + + const node = object[this.symbol]; + + if (node) { + return node; + } + + return (object[this.symbol] = new SymbolTreeNode()); + } + + /** + * Returns `true` if the object has any children. Otherwise it returns `false`. + * + * * `O(1)` + * + * @method hasChildren + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Boolean} + */ + hasChildren(object) { + return this._node(object).hasChildren; + } + + /** + * Returns the first child of the given object. + * + * * `O(1)` + * + * @method firstChild + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Object} + */ + firstChild(object) { + return this._node(object).firstChild; + } + + /** + * Returns the last child of the given object. + * + * * `O(1)` + * + * @method lastChild + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Object} + */ + lastChild(object) { + return this._node(object).lastChild; + } + + /** + * Returns the previous sibling of the given object. + * + * * `O(1)` + * + * @method previousSibling + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Object} + */ + previousSibling(object) { + return this._node(object).previousSibling; + } + + /** + * Returns the next sibling of the given object. + * + * * `O(1)` + * + * @method nextSibling + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Object} + */ + nextSibling(object) { + return this._node(object).nextSibling; + } + + /** + * Return the parent of the given object. + * + * * `O(1)` + * + * @method parent + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Object} + */ + parent(object) { + return this._node(object).parent; + } + + /** + * Find the inclusive descendant that is last in tree order of the given object. + * + * * `O(n)` (worst case) where `n` is the depth of the subtree of `object` + * + * @method lastInclusiveDescendant + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Object} + */ + lastInclusiveDescendant(object) { + let lastChild; + let current = object; + + while ((lastChild = this._node(current).lastChild)) { + current = lastChild; + } + + return current; + } + + /** + * Find the preceding object (A) of the given object (B). + * An object A is preceding an object B if A and B are in the same tree + * and A comes before B in tree order. + * + * * `O(n)` (worst case) + * * `O(1)` (amortized when walking the entire tree) + * + * @method preceding + * @memberOf module:symbol-tree# + * @param {Object} object + * @param {Object} [options] + * @param {Object} [options.root] If set, `root` must be an inclusive ancestor + * of the return value (or else null is returned). This check _assumes_ + * that `root` is also an inclusive ancestor of the given `object` + * @return {?Object} + */ + preceding(object, options) { + const treeRoot = options && options.root; + + if (object === treeRoot) { + return null; + } + + const previousSibling = this._node(object).previousSibling; + + if (previousSibling) { + return this.lastInclusiveDescendant(previousSibling); + } + + // if there is no previous sibling return the parent (might be null) + return this._node(object).parent; + } + + /** + * Find the following object (A) of the given object (B). + * An object A is following an object B if A and B are in the same tree + * and A comes after B in tree order. + * + * * `O(n)` (worst case) where `n` is the amount of objects in the entire tree + * * `O(1)` (amortized when walking the entire tree) + * + * @method following + * @memberOf module:symbol-tree# + * @param {!Object} object + * @param {Object} [options] + * @param {Object} [options.root] If set, `root` must be an inclusive ancestor + * of the return value (or else null is returned). This check _assumes_ + * that `root` is also an inclusive ancestor of the given `object` + * @param {Boolean} [options.skipChildren=false] If set, ignore the children of `object` + * @return {?Object} + */ + following(object, options) { + const treeRoot = options && options.root; + const skipChildren = options && options.skipChildren; + + const firstChild = !skipChildren && this._node(object).firstChild; + + if (firstChild) { + return firstChild; + } + + let current = object; + + do { + if (current === treeRoot) { + return null; + } + + const nextSibling = this._node(current).nextSibling; + + if (nextSibling) { + return nextSibling; + } + + current = this._node(current).parent; + } while (current); + + return null; + } + + /** + * Append all children of the given object to an array. + * + * * `O(n)` where `n` is the amount of children of the given `parent` + * + * @method childrenToArray + * @memberOf module:symbol-tree# + * @param {Object} parent + * @param {Object} [options] + * @param {Object[]} [options.array=[]] + * @param {Function} [options.filter] Function to test each object before it is added to the array. + * Invoked with arguments (object). Should return `true` if an object + * is to be included. + * @param {*} [options.thisArg] Value to use as `this` when executing `filter`. + * @return {Object[]} + */ + childrenToArray(parent, options) { + const array = (options && options.array) || []; + const filter = (options && options.filter) || returnTrue; + const thisArg = (options && options.thisArg) || undefined; + + const parentNode = this._node(parent); + let object = parentNode.firstChild; + let index = 0; + + while (object) { + const node = this._node(object); + node.setCachedIndex(parentNode, index); + + if (filter.call(thisArg, object)) { + array.push(object); + } + + object = node.nextSibling; + ++index; + } + + return array; + } + + /** + * Append all inclusive ancestors of the given object to an array. + * + * * `O(n)` where `n` is the amount of ancestors of the given `object` + * + * @method ancestorsToArray + * @memberOf module:symbol-tree# + * @param {Object} object + * @param {Object} [options] + * @param {Object[]} [options.array=[]] + * @param {Function} [options.filter] Function to test each object before it is added to the array. + * Invoked with arguments (object). Should return `true` if an object + * is to be included. + * @param {*} [options.thisArg] Value to use as `this` when executing `filter`. + * @return {Object[]} + */ + ancestorsToArray(object, options) { + const array = (options && options.array) || []; + const filter = (options && options.filter) || returnTrue; + const thisArg = (options && options.thisArg) || undefined; + + let ancestor = object; + + while (ancestor) { + if (filter.call(thisArg, ancestor)) { + array.push(ancestor); + } + ancestor = this._node(ancestor).parent; + } + + return array; + } + + /** + * Append all descendants of the given object to an array (in tree order). + * + * * `O(n)` where `n` is the amount of objects in the sub-tree of the given `object` + * + * @method treeToArray + * @memberOf module:symbol-tree# + * @param {Object} root + * @param {Object} [options] + * @param {Object[]} [options.array=[]] + * @param {Function} [options.filter] Function to test each object before it is added to the array. + * Invoked with arguments (object). Should return `true` if an object + * is to be included. + * @param {*} [options.thisArg] Value to use as `this` when executing `filter`. + * @return {Object[]} + */ + treeToArray(root, options) { + const array = (options && options.array) || []; + const filter = (options && options.filter) || returnTrue; + const thisArg = (options && options.thisArg) || undefined; + + let object = root; + + while (object) { + if (filter.call(thisArg, object)) { + array.push(object); + } + object = this.following(object, {root: root}); + } + + return array; + } + + /** + * Iterate over all children of the given object + * + * * `O(1)` for a single iteration + * + * @method childrenIterator + * @memberOf module:symbol-tree# + * @param {Object} parent + * @param {Object} [options] + * @param {Boolean} [options.reverse=false] + * @return {Object} An iterable iterator (ES6) + */ + childrenIterator(parent, options) { + const reverse = options && options.reverse; + const parentNode = this._node(parent); + + return new TreeIterator( + this, + parent, + reverse ? parentNode.lastChild : parentNode.firstChild, + reverse ? TreeIterator.PREV : TreeIterator.NEXT + ); + } + + /** + * Iterate over all the previous siblings of the given object. (in reverse tree order) + * + * * `O(1)` for a single iteration + * + * @method previousSiblingsIterator + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Object} An iterable iterator (ES6) + */ + previousSiblingsIterator(object) { + return new TreeIterator( + this, + object, + this._node(object).previousSibling, + TreeIterator.PREV + ); + } + + /** + * Iterate over all the next siblings of the given object. (in tree order) + * + * * `O(1)` for a single iteration + * + * @method nextSiblingsIterator + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Object} An iterable iterator (ES6) + */ + nextSiblingsIterator(object) { + return new TreeIterator( + this, + object, + this._node(object).nextSibling, + TreeIterator.NEXT + ); + } + + /** + * Iterate over all inclusive ancestors of the given object + * + * * `O(1)` for a single iteration + * + * @method ancestorsIterator + * @memberOf module:symbol-tree# + * @param {Object} object + * @return {Object} An iterable iterator (ES6) + */ + ancestorsIterator(object) { + return new TreeIterator( + this, + object, + object, + TreeIterator.PARENT + ); + } + + /** + * Iterate over all descendants of the given object (in tree order). + * + * Where `n` is the amount of objects in the sub-tree of the given `root`: + * + * * `O(n)` (worst case for a single iteration) + * * `O(n)` (amortized, when completing the iterator) + * + * @method treeIterator + * @memberOf module:symbol-tree# + * @param {Object} root + * @param {Object} options + * @param {Boolean} [options.reverse=false] + * @return {Object} An iterable iterator (ES6) + */ + treeIterator(root, options) { + const reverse = options && options.reverse; + + return new TreeIterator( + this, + root, + reverse ? this.lastInclusiveDescendant(root) : root, + reverse ? TreeIterator.PRECEDING : TreeIterator.FOLLOWING + ); + } + + /** + * Find the index of the given object (the number of preceding siblings). + * + * * `O(n)` where `n` is the amount of preceding siblings + * * `O(1)` (amortized, if the tree is not modified) + * + * @method index + * @memberOf module:symbol-tree# + * @param {Object} child + * @return {Number} The number of preceding siblings, or -1 if the object has no parent + */ + index(child) { + const childNode = this._node(child); + const parentNode = this._node(childNode.parent); + + if (!parentNode) { + // In principal, you could also find out the number of preceding siblings + // for objects that do not have a parent. This method limits itself only to + // objects that have a parent because that lets us optimize more. + return -1; + } + + let currentIndex = childNode.getCachedIndex(parentNode); + + if (currentIndex >= 0) { + return currentIndex; + } + + currentIndex = 0; + let object = parentNode.firstChild; + + if (parentNode.childIndexCachedUpTo) { + const cachedUpToNode = this._node(parentNode.childIndexCachedUpTo); + object = cachedUpToNode.nextSibling; + currentIndex = cachedUpToNode.getCachedIndex(parentNode) + 1; + } + + while (object) { + const node = this._node(object); + node.setCachedIndex(parentNode, currentIndex); + + if (object === child) { + break; + } + + ++currentIndex; + object = node.nextSibling; + } + + parentNode.childIndexCachedUpTo = child; + + return currentIndex; + } + + /** + * Calculate the number of children. + * + * * `O(n)` where `n` is the amount of children + * * `O(1)` (amortized, if the tree is not modified) + * + * @method childrenCount + * @memberOf module:symbol-tree# + * @param {Object} parent + * @return {Number} + */ + childrenCount(parent) { + const parentNode = this._node(parent); + + if (!parentNode.lastChild) { + return 0; + } + + return this.index(parentNode.lastChild) + 1; + } + + /** + * Compare the position of an object relative to another object. A bit set is returned: + * + *
    + *
  • DISCONNECTED : 1
  • + *
  • PRECEDING : 2
  • + *
  • FOLLOWING : 4
  • + *
  • CONTAINS : 8
  • + *
  • CONTAINED_BY : 16
  • + *
+ * + * The semantics are the same as compareDocumentPosition in DOM, with the exception that + * DISCONNECTED never occurs with any other bit. + * + * where `n` and `m` are the amount of ancestors of `left` and `right`; + * where `o` is the amount of children of the lowest common ancestor of `left` and `right`: + * + * * `O(n + m + o)` (worst case) + * * `O(n + m)` (amortized, if the tree is not modified) + * + * @method compareTreePosition + * @memberOf module:symbol-tree# + * @param {Object} left + * @param {Object} right + * @return {Number} + */ + compareTreePosition(left, right) { + // In DOM terms: + // left = reference / context object + // right = other + + if (left === right) { + return 0; + } + + /* jshint -W016 */ + + const leftAncestors = []; { // inclusive + let leftAncestor = left; + + while (leftAncestor) { + if (leftAncestor === right) { + return TreePosition.CONTAINS | TreePosition.PRECEDING; + // other is ancestor of reference + } + + leftAncestors.push(leftAncestor); + leftAncestor = this.parent(leftAncestor); + } + } + + + const rightAncestors = []; { + let rightAncestor = right; + + while (rightAncestor) { + if (rightAncestor === left) { + return TreePosition.CONTAINED_BY | TreePosition.FOLLOWING; + } + + rightAncestors.push(rightAncestor); + rightAncestor = this.parent(rightAncestor); + } + } + + + const root = reverseArrayIndex(leftAncestors, 0); + + if (!root || root !== reverseArrayIndex(rightAncestors, 0)) { + // note: unlike DOM, preceding / following is not set here + return TreePosition.DISCONNECTED; + } + + // find the lowest common ancestor + let commonAncestorIndex = 0; + const ancestorsMinLength = Math.min(leftAncestors.length, rightAncestors.length); + + for (let i = 0; i < ancestorsMinLength; ++i) { + const leftAncestor = reverseArrayIndex(leftAncestors, i); + const rightAncestor = reverseArrayIndex(rightAncestors, i); + + if (leftAncestor !== rightAncestor) { + break; + } + + commonAncestorIndex = i; + } + + // indexes within the common ancestor + const leftIndex = this.index(reverseArrayIndex(leftAncestors, commonAncestorIndex + 1)); + const rightIndex = this.index(reverseArrayIndex(rightAncestors, commonAncestorIndex + 1)); + + return rightIndex < leftIndex + ? TreePosition.PRECEDING + : TreePosition.FOLLOWING; + } + + /** + * Remove the object from this tree. + * Has no effect if already removed. + * + * * `O(1)` + * + * @method remove + * @memberOf module:symbol-tree# + * @param {Object} removeObject + * @return {Object} removeObject + */ + remove(removeObject) { + const removeNode = this._node(removeObject); + const parentNode = this._node(removeNode.parent); + const prevNode = this._node(removeNode.previousSibling); + const nextNode = this._node(removeNode.nextSibling); + + if (parentNode) { + if (parentNode.firstChild === removeObject) { + parentNode.firstChild = removeNode.nextSibling; + } + + if (parentNode.lastChild === removeObject) { + parentNode.lastChild = removeNode.previousSibling; + } + } + + if (prevNode) { + prevNode.nextSibling = removeNode.nextSibling; + } + + if (nextNode) { + nextNode.previousSibling = removeNode.previousSibling; + } + + removeNode.parent = null; + removeNode.previousSibling = null; + removeNode.nextSibling = null; + removeNode.cachedIndex = -1; + removeNode.cachedIndexVersion = NaN; + + if (parentNode) { + parentNode.childrenChanged(); + } + + return removeObject; + } + + /** + * Insert the given object before the reference object. + * `newObject` is now the previous sibling of `referenceObject`. + * + * * `O(1)` + * + * @method insertBefore + * @memberOf module:symbol-tree# + * @param {Object} referenceObject + * @param {Object} newObject + * @throws {Error} If the newObject is already present in this SymbolTree + * @return {Object} newObject + */ + insertBefore(referenceObject, newObject) { + const referenceNode = this._node(referenceObject); + const prevNode = this._node(referenceNode.previousSibling); + const newNode = this._node(newObject); + const parentNode = this._node(referenceNode.parent); + + if (newNode.isAttached) { + throw Error('Given object is already present in this SymbolTree, remove it first'); + } + + newNode.parent = referenceNode.parent; + newNode.previousSibling = referenceNode.previousSibling; + newNode.nextSibling = referenceObject; + referenceNode.previousSibling = newObject; + + if (prevNode) { + prevNode.nextSibling = newObject; + } + + if (parentNode && parentNode.firstChild === referenceObject) { + parentNode.firstChild = newObject; + } + + if (parentNode) { + parentNode.childrenChanged(); + } + + return newObject; + } + + /** + * Insert the given object after the reference object. + * `newObject` is now the next sibling of `referenceObject`. + * + * * `O(1)` + * + * @method insertAfter + * @memberOf module:symbol-tree# + * @param {Object} referenceObject + * @param {Object} newObject + * @throws {Error} If the newObject is already present in this SymbolTree + * @return {Object} newObject + */ + insertAfter(referenceObject, newObject) { + const referenceNode = this._node(referenceObject); + const nextNode = this._node(referenceNode.nextSibling); + const newNode = this._node(newObject); + const parentNode = this._node(referenceNode.parent); + + if (newNode.isAttached) { + throw Error('Given object is already present in this SymbolTree, remove it first'); + } + + newNode.parent = referenceNode.parent; + newNode.previousSibling = referenceObject; + newNode.nextSibling = referenceNode.nextSibling; + referenceNode.nextSibling = newObject; + + if (nextNode) { + nextNode.previousSibling = newObject; + } + + if (parentNode && parentNode.lastChild === referenceObject) { + parentNode.lastChild = newObject; + } + + if (parentNode) { + parentNode.childrenChanged(); + } + + return newObject; + } + + /** + * Insert the given object as the first child of the given reference object. + * `newObject` is now the first child of `referenceObject`. + * + * * `O(1)` + * + * @method prependChild + * @memberOf module:symbol-tree# + * @param {Object} referenceObject + * @param {Object} newObject + * @throws {Error} If the newObject is already present in this SymbolTree + * @return {Object} newObject + */ + prependChild(referenceObject, newObject) { + const referenceNode = this._node(referenceObject); + const newNode = this._node(newObject); + + if (newNode.isAttached) { + throw Error('Given object is already present in this SymbolTree, remove it first'); + } + + if (referenceNode.hasChildren) { + this.insertBefore(referenceNode.firstChild, newObject); + } + else { + newNode.parent = referenceObject; + referenceNode.firstChild = newObject; + referenceNode.lastChild = newObject; + referenceNode.childrenChanged(); + } + + return newObject; + } + + /** + * Insert the given object as the last child of the given reference object. + * `newObject` is now the last child of `referenceObject`. + * + * * `O(1)` + * + * @method appendChild + * @memberOf module:symbol-tree# + * @param {Object} referenceObject + * @param {Object} newObject + * @throws {Error} If the newObject is already present in this SymbolTree + * @return {Object} newObject + */ + appendChild(referenceObject, newObject) { + const referenceNode = this._node(referenceObject); + const newNode = this._node(newObject); + + if (newNode.isAttached) { + throw Error('Given object is already present in this SymbolTree, remove it first'); + } + + if (referenceNode.hasChildren) { + this.insertAfter(referenceNode.lastChild, newObject); + } + else { + newNode.parent = referenceObject; + referenceNode.firstChild = newObject; + referenceNode.lastChild = newObject; + referenceNode.childrenChanged(); + } + + return newObject; + } +} + +module.exports = SymbolTree; +SymbolTree.TreePosition = TreePosition; diff --git a/node_modules/symbol-tree/lib/SymbolTreeNode.js b/node_modules/symbol-tree/lib/SymbolTreeNode.js new file mode 100644 index 0000000000000000000000000000000000000000..cae7f9ade12371fd38eaa323926c42f473e639e3 --- /dev/null +++ b/node_modules/symbol-tree/lib/SymbolTreeNode.js @@ -0,0 +1,54 @@ +'use strict'; + +module.exports = class SymbolTreeNode { + constructor() { + this.parent = null; + this.previousSibling = null; + this.nextSibling = null; + + this.firstChild = null; + this.lastChild = null; + + /** This value is incremented anytime a children is added or removed */ + this.childrenVersion = 0; + /** The last child object which has a cached index */ + this.childIndexCachedUpTo = null; + + /** This value represents the cached node index, as long as + * cachedIndexVersion matches with the childrenVersion of the parent */ + this.cachedIndex = -1; + this.cachedIndexVersion = NaN; // NaN is never equal to anything + } + + get isAttached() { + return Boolean(this.parent || this.previousSibling || this.nextSibling); + } + + get hasChildren() { + return Boolean(this.firstChild); + } + + childrenChanged() { + /* jshint -W016 */ + // integer wrap around + this.childrenVersion = (this.childrenVersion + 1) & 0xFFFFFFFF; + this.childIndexCachedUpTo = null; + } + + getCachedIndex(parentNode) { + // (assumes parentNode is actually the parent) + if (this.cachedIndexVersion !== parentNode.childrenVersion) { + this.cachedIndexVersion = NaN; + // cachedIndex is no longer valid + return -1; + } + + return this.cachedIndex; // -1 if not cached + } + + setCachedIndex(parentNode, index) { + // (assumes parentNode is actually the parent) + this.cachedIndexVersion = parentNode.childrenVersion; + this.cachedIndex = index; + } +}; diff --git a/node_modules/symbol-tree/lib/TreeIterator.js b/node_modules/symbol-tree/lib/TreeIterator.js new file mode 100644 index 0000000000000000000000000000000000000000..f9d621764e20d596d447df4ecb595862e7199c3f --- /dev/null +++ b/node_modules/symbol-tree/lib/TreeIterator.js @@ -0,0 +1,69 @@ +'use strict'; + +const TREE = Symbol(); +const ROOT = Symbol(); +const NEXT = Symbol(); +const ITERATE_FUNC = Symbol(); + +class TreeIterator { + constructor(tree, root, firstResult, iterateFunction) { + this[TREE] = tree; + this[ROOT] = root; + this[NEXT] = firstResult; + this[ITERATE_FUNC] = iterateFunction; + } + + next() { + const tree = this[TREE]; + const iterateFunc = this[ITERATE_FUNC]; + const root = this[ROOT]; + + if (!this[NEXT]) { + return { + done: true, + value: root, + }; + } + + const value = this[NEXT]; + + if (iterateFunc === 1) { + this[NEXT] = tree._node(value).previousSibling; + } + else if (iterateFunc === 2) { + this[NEXT] = tree._node(value).nextSibling; + } + else if (iterateFunc === 3) { + this[NEXT] = tree._node(value).parent; + } + else if (iterateFunc === 4) { + this[NEXT] = tree.preceding(value, {root: root}); + } + else /* if (iterateFunc === 5)*/ { + this[NEXT] = tree.following(value, {root: root}); + } + + return { + done: false, + value: value, + }; + } +} + +Object.defineProperty(TreeIterator.prototype, Symbol.iterator, { + value: function() { + return this; + }, + writable: false, +}); + +TreeIterator.PREV = 1; +TreeIterator.NEXT = 2; +TreeIterator.PARENT = 3; +TreeIterator.PRECEDING = 4; +TreeIterator.FOLLOWING = 5; + +Object.freeze(TreeIterator); +Object.freeze(TreeIterator.prototype); + +module.exports = TreeIterator; diff --git a/node_modules/symbol-tree/lib/TreePosition.js b/node_modules/symbol-tree/lib/TreePosition.js new file mode 100644 index 0000000000000000000000000000000000000000..fd2b6ed8fbd8335f2952e71727a805358dcce596 --- /dev/null +++ b/node_modules/symbol-tree/lib/TreePosition.js @@ -0,0 +1,11 @@ +'use strict'; + +/* eslint-disable sort-keys */ +module.exports = Object.freeze({ + // same as DOM DOCUMENT_POSITION_ + DISCONNECTED: 1, + PRECEDING: 2, + FOLLOWING: 4, + CONTAINS: 8, + CONTAINED_BY: 16, +}); diff --git a/node_modules/symbol-tree/package.json b/node_modules/symbol-tree/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dfaefddaf2e66362fdec270cc433ddb740d81aee --- /dev/null +++ b/node_modules/symbol-tree/package.json @@ -0,0 +1,47 @@ +{ + "name": "symbol-tree", + "version": "3.2.4", + "description": "Turn any collection of objects into its own efficient tree or linked list using Symbol", + "main": "lib/SymbolTree.js", + "scripts": { + "lint": "eslint lib test", + "test": "istanbul cover test/SymbolTree.js", + "posttest": "npm run lint", + "ci": "istanbul cover test/SymbolTree.js --report lcovonly && cat ./coverage/lcov.info | coveralls", + "postci": "npm run posttest", + "predocumentation": "cp readme-header.md README.md", + "documentation": "jsdoc2md --files lib/SymbolTree.js >> README.md" + }, + "repository": { + "type": "git", + "url": "https://github.com/jsdom/js-symbol-tree.git" + }, + "keywords": [ + "list", + "queue", + "stack", + "linked-list", + "tree", + "es6", + "dom", + "symbol" + ], + "files": [ + "lib" + ], + "author": "Joris van der Wel ", + "license": "MIT", + "bugs": { + "url": "https://github.com/jsdom/js-symbol-tree/issues" + }, + "homepage": "https://github.com/jsdom/js-symbol-tree#symbol-tree", + "devDependencies": { + "babel-eslint": "^10.0.1", + "coveralls": "^3.0.0", + "eslint": "^5.16.0", + "eslint-plugin-import": "^2.2.0", + "istanbul": "^0.4.5", + "jsdoc-to-markdown": "^5.0.0", + "tape": "^4.0.0" + } +} diff --git a/node_modules/synckit/LICENSE b/node_modules/synckit/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b93398b949d1a4c86369ce7588cffa60837204e8 --- /dev/null +++ b/node_modules/synckit/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 UnTS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/synckit/README.md b/node_modules/synckit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..69a808f1acc68851fb0fd836a311f93912bd352a --- /dev/null +++ b/node_modules/synckit/README.md @@ -0,0 +1,256 @@ +# synckit + +[![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/un-ts/synckit/ci.yml?branch=main)](https://github.com/un-ts/synckit/actions/workflows/ci.yml?query=branch%3Amain) +[![Codecov](https://img.shields.io/codecov/c/github/un-ts/synckit.svg)](https://codecov.io/gh/un-ts/synckit) +[![type-coverage](https://img.shields.io/badge/dynamic/json.svg?label=type-coverage&prefix=%E2%89%A5&suffix=%&query=$.typeCoverage.atLeast&uri=https%3A%2F%2Fraw.githubusercontent.com%2Fun-ts%2Fsynckit%2Fmain%2Fpackage.json)](https://github.com/plantain-00/type-coverage) +[![CodeRabbit Pull Request Reviews](https://img.shields.io/coderabbit/prs/github/un-ts/synckit)](https://coderabbit.ai) +[![npm](https://img.shields.io/npm/v/synckit.svg)](https://www.npmjs.com/package/synckit) +[![GitHub Release](https://img.shields.io/github/release/un-ts/synckit)](https://github.com/un-ts/synckit/releases) + +[![Conventional Commits](https://img.shields.io/badge/conventional%20commits-1.0.0-yellow.svg)](https://conventionalcommits.org) +[![Renovate enabled](https://img.shields.io/badge/renovate-enabled-brightgreen.svg)](https://renovatebot.com) +[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) +[![Code Style: Prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier) +[![changesets](https://img.shields.io/badge/maintained%20with-changesets-176de3.svg)](https://github.com/changesets/changesets) + +Perform async work synchronously in Node.js/Bun using `worker_threads` with first-class TypeScript and Yarn P'n'P support. + +## TOC + +- [Usage](#usage) + - [Install](#install) + - [API](#api) + - [Types](#types) + - [Options](#options) + - [Envs](#envs) + - [TypeScript](#typescript) + - [`node` (Default, Node 22.6+)](#node-default-node-226) + - [`bun` (Default, Bun)](#bun-default-bun) + - [`ts-node` (Default)](#ts-node-default) + - [`esbuild-register`](#esbuild-register) + - [`esbuild-runner`](#esbuild-runner) + - [`oxc`](#oxc) + - [`swc`](#swc) + - [`tsx`](#tsx) +- [Benchmark](#benchmark) +- [Sponsors](#sponsors) +- [Backers](#backers) +- [Who are using `synckit`](#who-are-using-synckit) +- [Acknowledgements](#acknowledgements) +- [Changelog](#changelog) +- [License](#license) + +## Usage + +### Install + +```sh +# yarn +yarn add synckit + +# npm +npm i synckit +``` + +### API + +```js +// runner.js +import { createSyncFn } from 'synckit' + +// the worker path must be absolute +const syncFn = createSyncFn(require.resolve('./worker'), { + tsRunner: 'tsx', // optional, can be `'node' | 'ts-node' | 'esbuild-register' | 'esbuild-runner' | 'tsx'` +}) + +// do whatever you want, you will get the result synchronously! +const result = syncFn(...args) +``` + +```js +// worker.js +import { runAsWorker } from 'synckit' + +runAsWorker(async (...args) => { + // do expensive work + return result +}) +``` + +You must make sure, the `result` is serializable by [`Structured Clone Algorithm`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) + +### Types + +````ts +export interface GlobalShim { + moduleName: string + /** `undefined` means side effect only */ + globalName?: string + /** + * 1. `undefined` or empty string means `default`, for example: + * + * ```js + * import globalName from 'module-name' + * ``` + * + * 2. `null` means namespaced, for example: + * + * ```js + * import * as globalName from 'module-name' + * ``` + */ + named?: string | null + /** + * If not `false`, the shim will only be applied when the original + * `globalName` unavailable, for example you may only want polyfill + * `globalThis.fetch` when it's unavailable natively: + * + * ```js + * import fetch from 'node-fetch' + * + * if (!globalThis.fetch) { + * globalThis.fetch = fetch + * } + * ``` + */ + conditional?: boolean +} +```` + +### Options + +1. `execArgv` same as env `SYNCKIT_EXEC_ARGV` +2. `globalShims`: Similar like env `SYNCKIT_GLOBAL_SHIMS` but much more flexible which can be a `GlobalShim` `Array`, see `GlobalShim`'s [definition](#types) for more details +3. `timeout` same as env `SYNCKIT_TIMEOUT` +4. `transferList`: Please refer Node.js [`worker_threads`](https://nodejs.org/api/worker_threads.html#:~:text=Default%3A%20true.-,transferList,-%3CObject%5B%5D%3E%20If) documentation +5. `tsRunner` same as env `SYNCKIT_TS_RUNNER` + +### Envs + +1. `SYNCKIT_EXEC_ARGV`: List of node CLI options passed to the worker, split with comma `,`. (default as `[]`), see also [`node` docs](https://nodejs.org/api/worker_threads.html) +2. `SYNCKIT_GLOBAL_SHIMS`: Whether to enable the default `DEFAULT_GLOBAL_SHIMS_PRESET` as `globalShims` +3. `SYNCKIT_TIMEOUT`: `timeout` for performing the async job (no default) +4. `SYNCKIT_TS_RUNNER`: Which TypeScript runner to be used, it could be very useful for development, could be `'node' | 'ts-node' | 'esbuild-register' | 'esbuild-runner' | 'oxc' | 'swc' | 'tsx'`, `node` or `ts-node` will be used by default accordingly, make sure you have installed them already + +### TypeScript + +#### `node` (Default, Node 22.6+) + +On recent `Node` versions, you may select this runner to execute your worker file (a `.ts` file) in the native runtime. + +As of `Node` v23.6, this feature is supported out of the box. For `Node` `>=22.6 <23.6`, this feature is supported via `--experimental-strip-types` flag. Visit the [documentation](https://nodejs.org/docs/latest/api/typescript.html#type-stripping) to learn more. + +When `synckit` detects the process to be running with supported `Node` versions (>=22.6), it will execute the worker file with the `node` runner by default, you can disable this behavior by setting `--no-experimental-strip-types` flag via `NODE_OPTIONS` env or cli arg. + +#### `bun` (Default, Bun) + +[`Bun`](https://bun.sh/docs/typescript) supports `TypeScript` natively. + +When `synckit` detects the process to be running with `Bun`, it will execute the worker file with the `bun` runner by default. + +In this case, `synckit` doesn't do anything to the worker itself, it just passes through the worker directly. + +#### `ts-node` (Default) + +Prior to Node v22.6, you may want to use `ts-node` to execute your worker file (a `.ts` file). + +If you want to use a custom tsconfig as project instead of default `tsconfig.json`, use `TS_NODE_PROJECT` env. Please view [ts-node](https://github.com/TypeStrong/ts-node#tsconfig) for more details. + +If you want to integrate with [tsconfig-paths](https://www.npmjs.com/package/tsconfig-paths), please view [ts-node](https://github.com/TypeStrong/ts-node#paths-and-baseurl) for more details. + +#### `esbuild-register` + +Please view [`esbuild-register`][] for its document + +#### `esbuild-runner` + +Please view [`esbuild-runner`][] for its document + +#### `oxc` + +Please view [`@oxc-node/core`][] for its document + +#### `swc` + +Please view [`@swc-node/register`][] for its document + +#### `tsx` + +Please view [`tsx`][] for its document + +## Benchmark + +The following are the benchmark results of `synckit` against other libraries with Node.js v20.19.0 on my personal MacBook Pro with 64G M1 Max: + +```sh +# cjs +┌───────────┬────────────┬──────────────┬───────────────────┬─────────────┬────────────────┬───────────────────┬────────────────────────┬───────────┬─────────────────┐ +│ (index) │ synckit │ sync-threads │ perf sync-threads │ deasync │ perf deasync │ make-synchronized │ perf make-synchronized │ native │ perf native │ +├───────────┼────────────┼──────────────┼───────────────────┼─────────────┼────────────────┼───────────────────┼────────────────────────┼───────────┼─────────────────┤ +│ loadTime │ '17.26ms' │ '1.49ms' │ '11.57x slower' │ '146.55ms' │ '8.49x faster' │ '1025.77ms' │ '59.42x faster' │ '0.29ms' │ '59.71x slower' │ +│ runTime │ '143.12ms' │ '3689.15ms' │ '25.78x faster' │ '1221.11ms' │ '8.53x faster' │ '2842.50ms' │ '19.86x faster' │ '12.64ms' │ '11.33x slower' │ +│ totalTime │ '160.38ms' │ '3690.64ms' │ '23.01x faster' │ '1367.66ms' │ '8.53x faster' │ '3868.27ms' │ '24.12x faster' │ '12.93ms' │ '12.41x slower' │ +└───────────┴────────────┴──────────────┴───────────────────┴─────────────┴────────────────┴───────────────────┴────────────────────────┴───────────┴─────────────────┘ +``` + +```sh +# esm +┌───────────┬────────────┬──────────────┬───────────────────┬─────────────┬────────────────┬───────────────────┬────────────────────────┬───────────┬─────────────────┐ +│ (index) │ synckit │ sync-threads │ perf sync-threads │ deasync │ perf deasync │ make-synchronized │ perf make-synchronized │ native │ perf native │ +├───────────┼────────────┼──────────────┼───────────────────┼─────────────┼────────────────┼───────────────────┼────────────────────────┼───────────┼─────────────────┤ +│ loadTime │ '23.88ms' │ '2.03ms' │ '11.75x slower' │ '70.95ms' │ '2.97x faster' │ '400.24ms' │ '16.76x faster' │ '0.44ms' │ '54.70x slower' │ +│ runTime │ '139.56ms' │ '3570.12ms' │ '25.58x faster' │ '1150.99ms' │ '8.25x faster' │ '3484.04ms' │ '24.96x faster' │ '12.98ms' │ '10.75x slower' │ +│ totalTime │ '163.44ms' │ '3572.15ms' │ '21.86x faster' │ '1221.93ms' │ '7.48x faster' │ '3884.28ms' │ '23.77x faster' │ '13.42ms' │ '12.18x slower' │ +└───────────┴────────────┴──────────────┴───────────────────┴─────────────┴────────────────┴───────────────────┴────────────────────────┴───────────┴─────────────────┘ +``` + +See [benchmark.cjs](./benchmarks/benchmark.cjs.txt) and [benchmark.esm](./benchmarks/benchmark.esm.txt) for more details. + +You can try it with running `yarn benchmark` by yourself. [Here](./benchmarks/benchmark.js) is the benchmark source code. + +## Sponsors and Backers + +[![Sponsors and Backers](https://raw.githubusercontent.com/1stG/static/master/sponsors.svg)](https://github.com/sponsors/JounQin) + +### Sponsors + +| 1stG | RxTS | UnTS | +| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| [![1stG Open Collective sponsors](https://opencollective.com/1stG/organizations.svg)](https://opencollective.com/1stG) | [![RxTS Open Collective sponsors](https://opencollective.com/rxts/organizations.svg)](https://opencollective.com/rxts) | [![UnTS Open Collective sponsors](https://opencollective.com/unts/organizations.svg)](https://opencollective.com/unts) | + +### Backers + +| 1stG | RxTS | UnTS | +| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | +| [![1stG Open Collective backers](https://opencollective.com/1stG/individuals.svg)](https://opencollective.com/1stG) | [![RxTS Open Collective backers](https://opencollective.com/rxts/individuals.svg)](https://opencollective.com/rxts) | [![UnTS Open Collective backers](https://opencollective.com/unts/individuals.svg)](https://opencollective.com/unts) | + +## Who are using `synckit` + +- [`@cspell/eslint-plugin`](https://github.com/streetsidesoftware/cspell/blob/ec04bcee0c90ff4e2a9fb5ef4421714796fb58ba/packages/cspell-eslint-plugin/package.json#L80) +- [`astrojs-compiler-sync`](https://github.com/ota-meshi/astrojs-compiler-sync/blob/da4e86fd601755e40599d7f5121bc83d08255c42/package.json#L52) +- [`eslint-plugin-prettier`](https://github.com/prettier/eslint-plugin-prettier/blob/ca5eb3ec11c4ae511e1da22736c73b253210b73b/package.json#L67) +- [`eslint-plugin-prettier-vue`](https://github.com/meteorlxy/eslint-plugin-prettier-vue/blob/d3f6722303d66a2b223df2f750982e33c1143d5d/package.json#L40) +- [`eslint-mdx`](https://github.com/mdx-js/eslint-mdx/blob/4623359cc9784d3e38bd917ed001c5d7d826f990/packages/eslint-mdx/package.json#L40) +- [`prettier-plugin-packagejson`](https://github.com/matzkoh/prettier-plugin-packagejson/blob/eb7ade2a048d6d163cf8ef37e098ee273f72c585/package.json#L31) +- [`jest-snapshot`](https://github.com/jestjs/jest/blob/4e7d916ec6a16de5548273c17b5d2c5761b0aebb/packages/jest-snapshot/package.json#L42) + +## Acknowledgements + +This package is original inspired by [`esbuild`](https://github.com/evanw/esbuild) and [`sync-threads`](https://github.com/lambci/sync-threads). + +## Changelog + +Detailed changes for each release are documented in [CHANGELOG.md](./CHANGELOG.md). + +## License + +[MIT][] © [JounQin][]@[1stG.me][] + +[`esbuild-register`]: https://github.com/egoist/esbuild-register +[`esbuild-runner`]: https://github.com/folke/esbuild-runner +[`@oxc-node/core`]: https://github.com/oxc-project/oxc-node +[`@swc-node/register`]: https://github.com/swc-project/swc-node/tree/master/packages/register +[`tsx`]: https://github.com/esbuild-kit/tsx +[1stG.me]: https://www.1stG.me +[JounQin]: https://github.com/JounQin +[MIT]: http://opensource.org/licenses/MIT diff --git a/node_modules/synckit/lib/common.d.ts b/node_modules/synckit/lib/common.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8804f0291c3a43aa3b9473e70ea4ce246a4d613a --- /dev/null +++ b/node_modules/synckit/lib/common.d.ts @@ -0,0 +1,5 @@ +export declare const hasFlag: (flag: string) => boolean; +export declare const parseVersion: (version: string) => number[]; +export declare const compareVersion: (version1: string, version2: string) => 1 | -1 | 0; +export declare const NODE_VERSION: string; +export declare const compareNodeVersion: (version: string) => 1 | -1 | 0; diff --git a/node_modules/synckit/lib/common.js b/node_modules/synckit/lib/common.js new file mode 100644 index 0000000000000000000000000000000000000000..f6c6a1a17b8566ff014c5d37de3bd1d8400565e1 --- /dev/null +++ b/node_modules/synckit/lib/common.js @@ -0,0 +1,22 @@ +const NODE_OPTIONS = process.env.NODE_OPTIONS?.split(/\s+/); +export const hasFlag = (flag) => NODE_OPTIONS?.includes(flag) || process.argv.includes(flag); +export const parseVersion = (version) => version.split('.').map(Number.parseFloat); +export const compareVersion = (version1, version2) => { + const versions1 = parseVersion(version1); + const versions2 = parseVersion(version2); + const length = Math.max(versions1.length, versions2.length); + for (let i = 0; i < length; i++) { + const v1 = versions1[i] || 0; + const v2 = versions2[i] || 0; + if (v1 > v2) { + return 1; + } + if (v1 < v2) { + return -1; + } + } + return 0; +}; +export const NODE_VERSION = process.versions.node; +export const compareNodeVersion = (version) => compareVersion(NODE_VERSION, version); +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/synckit/lib/common.js.map b/node_modules/synckit/lib/common.js.map new file mode 100644 index 0000000000000000000000000000000000000000..a5240d55dd6aed6d0a69f6d4ed8333a39455fd66 --- /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,CAAA;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAA;AAEjD,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,OAAe,EAAE,EAAE,CACpD,cAAc,CAAC,YAAY,EAAE,OAAO,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/synckit/lib/constants.d.ts b/node_modules/synckit/lib/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..819fb5967ff172837b7a39c4e86171817a1f25eb --- /dev/null +++ b/node_modules/synckit/lib/constants.d.ts @@ -0,0 +1,38 @@ +import type { GlobalShim, ValueOf } from './types.js'; +export declare const TsRunner: { + readonly Node: "node"; + readonly Bun: "bun"; + readonly TsNode: "ts-node"; + readonly EsbuildRegister: "esbuild-register"; + readonly EsbuildRunner: "esbuild-runner"; + readonly OXC: "oxc"; + readonly SWC: "swc"; + readonly TSX: "tsx"; +}; +export type TsRunner = ValueOf; +export declare const TS_ESM_PARTIAL_SUPPORTED: boolean; +export declare const MTS_SUPPORTED: boolean; +export declare const MODULE_REGISTER_SUPPORTED: boolean; +export declare const STRIP_TYPES_NODE_VERSION = "22.6"; +export declare const TRANSFORM_TYPES_NODE_VERSION = "22.7"; +export declare const FEATURE_TYPESCRIPT_NODE_VERSION = "22.10"; +export declare const DEFAULT_TYPES_NODE_VERSION = "23.6"; +export declare const STRIP_TYPES_FLAG = "--experimental-strip-types"; +export declare const TRANSFORM_TYPES_FLAG = "--experimental-transform-types"; +export declare const NO_STRIP_TYPES_FLAG = "--no-experimental-strip-types"; +export declare const NODE_OPTIONS: string[]; +export declare const NO_STRIP_TYPES: boolean; +export declare const DEFAULT_TIMEOUT: number | undefined; +export declare const DEFAULT_EXEC_ARGV: string[]; +export declare const DEFAULT_TS_RUNNER: TsRunner | undefined; +export declare const DEFAULT_GLOBAL_SHIMS: boolean; +export declare const DEFAULT_GLOBAL_SHIMS_PRESET: GlobalShim[]; +export declare const IMPORT_FLAG = "--import"; +export declare const REQUIRE_FLAG = "--require"; +export declare const REQUIRE_ABBR_FLAG = "-r"; +export declare const REQUIRE_FLAGS: Set; +export declare const LOADER_FLAG = "--loader"; +export declare const EXPERIMENTAL_LOADER_FLAG = "--experimental-loader"; +export declare const LOADER_FLAGS: Set; +export declare const IMPORT_FLAG_SUPPORTED: boolean; +export declare const INT32_BYTES = 4; diff --git a/node_modules/synckit/lib/constants.js b/node_modules/synckit/lib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..ecfb3985685d92db1fb6fa37b252341729b15d57 --- /dev/null +++ b/node_modules/synckit/lib/constants.js @@ -0,0 +1,54 @@ +import { compareNodeVersion, hasFlag } from './common.js'; +export const TsRunner = { + Node: 'node', + Bun: 'bun', + TsNode: 'ts-node', + EsbuildRegister: 'esbuild-register', + EsbuildRunner: 'esbuild-runner', + OXC: 'oxc', + SWC: 'swc', + TSX: 'tsx', +}; +const { NODE_OPTIONS: NODE_OPTIONS_ = '', SYNCKIT_EXEC_ARGV = '', SYNCKIT_GLOBAL_SHIMS, SYNCKIT_TIMEOUT, SYNCKIT_TS_RUNNER, } = process.env; +export const TS_ESM_PARTIAL_SUPPORTED = compareNodeVersion('16') >= 0 && + compareNodeVersion('18.19') < 0; +export const MTS_SUPPORTED = compareNodeVersion('20.8') >= 0; +export const MODULE_REGISTER_SUPPORTED = MTS_SUPPORTED || + compareNodeVersion('18.19') >= 0; +export const STRIP_TYPES_NODE_VERSION = '22.6'; +export const TRANSFORM_TYPES_NODE_VERSION = '22.7'; +export const FEATURE_TYPESCRIPT_NODE_VERSION = '22.10'; +export const DEFAULT_TYPES_NODE_VERSION = '23.6'; +export const STRIP_TYPES_FLAG = '--experimental-strip-types'; +export const TRANSFORM_TYPES_FLAG = '--experimental-transform-types'; +export const NO_STRIP_TYPES_FLAG = '--no-experimental-strip-types'; +export const NODE_OPTIONS = NODE_OPTIONS_.split(/\s+/); +export const NO_STRIP_TYPES = hasFlag(NO_STRIP_TYPES_FLAG) && + (compareNodeVersion(FEATURE_TYPESCRIPT_NODE_VERSION) >= 0 + ? process.features.typescript === false + : !hasFlag(STRIP_TYPES_FLAG) && !hasFlag(TRANSFORM_TYPES_FLAG)); +export const DEFAULT_TIMEOUT = SYNCKIT_TIMEOUT ? +SYNCKIT_TIMEOUT : undefined; +export const DEFAULT_EXEC_ARGV = SYNCKIT_EXEC_ARGV.split(','); +export const DEFAULT_TS_RUNNER = SYNCKIT_TS_RUNNER; +export const DEFAULT_GLOBAL_SHIMS = ['1', 'true'].includes(SYNCKIT_GLOBAL_SHIMS); +export const DEFAULT_GLOBAL_SHIMS_PRESET = [ + { + moduleName: 'node-fetch', + globalName: 'fetch', + }, + { + moduleName: 'node:perf_hooks', + globalName: 'performance', + named: 'performance', + }, +]; +export const IMPORT_FLAG = '--import'; +export const REQUIRE_FLAG = '--require'; +export const REQUIRE_ABBR_FLAG = '-r'; +export const REQUIRE_FLAGS = new Set([REQUIRE_FLAG, REQUIRE_ABBR_FLAG]); +export const LOADER_FLAG = '--loader'; +export const EXPERIMENTAL_LOADER_FLAG = '--experimental-loader'; +export const LOADER_FLAGS = new Set([LOADER_FLAG, EXPERIMENTAL_LOADER_FLAG]); +export const IMPORT_FLAG_SUPPORTED = compareNodeVersion('20.6') >= 0; +export const INT32_BYTES = 4; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/synckit/lib/constants.js.map b/node_modules/synckit/lib/constants.js.map new file mode 100644 index 0000000000000000000000000000000000000000..66334e2d67f6c3a13005e7a000a1743ceda43c86 --- /dev/null +++ b/node_modules/synckit/lib/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAGzD,MAAM,CAAC,MAAM,QAAQ,GAAG;IAEtB,IAAI,EAAE,MAAM;IAEZ,GAAG,EAAE,KAAK;IAEV,MAAM,EAAE,SAAS;IA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--git a/node_modules/synckit/lib/helpers.d.ts b/node_modules/synckit/lib/helpers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7973bccde9849cfaff9c70e55ee77a61eb37729 --- /dev/null +++ b/node_modules/synckit/lib/helpers.d.ts @@ -0,0 +1,27 @@ +import { TsRunner } from './constants.js'; +import type { AnyFn, GlobalShim, StdioChunk, SynckitOptions } from './types.js'; +export declare const isFile: (path: string) => boolean; +export declare const dataUrl: (code: string) => import("url").URL; +export declare const hasRequireFlag: (execArgv: string[]) => boolean; +export declare const hasImportFlag: (execArgv: string[]) => boolean; +export declare const hasLoaderFlag: (execArgv: string[]) => boolean; +export declare const setupTsRunner: (workerPath: string, { execArgv, tsRunner, }?: { + execArgv?: string[]; + tsRunner?: TsRunner; +}) => { + ext: string; + isTs: boolean; + jsUseEsm: boolean; + tsRunner: TsRunner | undefined; + tsUseEsm: boolean; + workerPath: string; + pnpLoaderPath: string | undefined; + execArgv: string[]; +}; +export declare const md5Hash: (text: string) => string; +export declare const encodeImportModule: (moduleNameOrGlobalShim: GlobalShim | string, type?: "import" | "require") => string; +export declare const generateGlobals: (workerPath: string, globalShims: GlobalShim[], type?: "import" | "require") => string; +export declare function extractProperties(object: T): T; +export declare function extractProperties(object?: T): T | undefined; +export declare function startWorkerThread>>(workerPath: string, { timeout, execArgv, tsRunner, transferList, globalShims, }?: SynckitOptions): (...args: Parameters) => R; +export declare const overrideStdio: (stdio: StdioChunk[]) => void; diff --git a/node_modules/synckit/lib/helpers.js b/node_modules/synckit/lib/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..865e8efc7447b0c4e949ffcd1db10c3b8220c102 --- /dev/null +++ b/node_modules/synckit/lib/helpers.js @@ -0,0 +1,411 @@ +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { MessageChannel, Worker, receiveMessageOnPort, } from 'node:worker_threads'; +import { tryExtensions, findUp, cjsRequire, isPkgAvailable } from '@pkgr/core'; +import { compareNodeVersion } from './common.js'; +import { DEFAULT_EXEC_ARGV, DEFAULT_GLOBAL_SHIMS, DEFAULT_GLOBAL_SHIMS_PRESET, DEFAULT_TIMEOUT, DEFAULT_TS_RUNNER, DEFAULT_TYPES_NODE_VERSION, IMPORT_FLAG, IMPORT_FLAG_SUPPORTED, INT32_BYTES, LOADER_FLAG, LOADER_FLAGS, MTS_SUPPORTED, NO_STRIP_TYPES, NO_STRIP_TYPES_FLAG, NODE_OPTIONS, REQUIRE_ABBR_FLAG, REQUIRE_FLAGS, STRIP_TYPES_FLAG, STRIP_TYPES_NODE_VERSION, TRANSFORM_TYPES_FLAG, TRANSFORM_TYPES_NODE_VERSION, TS_ESM_PARTIAL_SUPPORTED, TsRunner, } from './constants.js'; +export const isFile = (path) => { + try { + return !!fs.statSync(path, { throwIfNoEntry: false })?.isFile(); + } + catch { + return false; + } +}; +export const dataUrl = (code) => new URL(`data:text/javascript,${encodeURIComponent(code)}`); +export const hasRequireFlag = (execArgv) => execArgv.some(execArg => REQUIRE_FLAGS.has(execArg)); +export const hasImportFlag = (execArgv) => execArgv.includes(IMPORT_FLAG); +export const hasLoaderFlag = (execArgv) => execArgv.some(execArg => LOADER_FLAGS.has(execArg)); +export const setupTsRunner = (workerPath, { execArgv = DEFAULT_EXEC_ARGV, tsRunner, } = {}) => { + let ext = path.extname(workerPath); + if (!/([/\\])node_modules\1/.test(workerPath) && + (!ext || /^\.[cm]?js$/.test(ext))) { + const workPathWithoutExt = ext + ? workerPath.slice(0, -ext.length) + : workerPath; + let extensions; + switch (ext) { + case '.cjs': { + extensions = ['.cts', '.cjs']; + break; + } + case '.mjs': { + extensions = ['.mts', '.mjs']; + break; + } + default: { + extensions = ['.ts', '.js']; + break; + } + } + const found = tryExtensions(workPathWithoutExt, extensions); + let differentExt; + if (found && (!ext || (differentExt = found !== workPathWithoutExt))) { + workerPath = found; + if (differentExt) { + ext = path.extname(workerPath); + } + } + } + const isTs = /\.[cm]?ts$/.test(workerPath); + let jsUseEsm = ext === '.mjs'; + let tsUseEsm = ext === '.mts'; + if (isTs) { + if (!tsUseEsm && ext !== '.cts') { + const pkg = findUp(workerPath); + if (pkg) { + tsUseEsm = cjsRequire(pkg).type === 'module'; + } + } + const stripTypesIndex = execArgv.indexOf(STRIP_TYPES_FLAG); + const transformTypesIndex = execArgv.indexOf(TRANSFORM_TYPES_FLAG); + const noStripTypesIndex = execArgv.indexOf(NO_STRIP_TYPES_FLAG); + const execArgvNoStripTypes = noStripTypesIndex > stripTypesIndex || + noStripTypesIndex > transformTypesIndex; + const noStripTypes = execArgvNoStripTypes || + (stripTypesIndex === -1 && transformTypesIndex === -1 && NO_STRIP_TYPES); + if (tsRunner == null) { + if (process.versions.bun) { + tsRunner = TsRunner.Bun; + } + else if (!noStripTypes && + compareNodeVersion(STRIP_TYPES_NODE_VERSION) >= 0) { + tsRunner = TsRunner.Node; + } + else if (isPkgAvailable(TsRunner.TsNode)) { + tsRunner = TsRunner.TsNode; + } + } + switch (tsRunner) { + case TsRunner.Bun: { + break; + } + case TsRunner.Node: { + if (compareNodeVersion(STRIP_TYPES_NODE_VERSION) < 0) { + throw new Error('type stripping is not supported in this node version'); + } + if (noStripTypes) { + throw new Error('type stripping is disabled explicitly'); + } + if (compareNodeVersion(DEFAULT_TYPES_NODE_VERSION) >= 0) { + break; + } + if (compareNodeVersion(TRANSFORM_TYPES_NODE_VERSION) >= 0 && + !execArgv.includes(TRANSFORM_TYPES_FLAG)) { + execArgv = [TRANSFORM_TYPES_FLAG, ...execArgv]; + } + else if (compareNodeVersion(STRIP_TYPES_NODE_VERSION) >= 0 && + !execArgv.includes(STRIP_TYPES_FLAG)) { + execArgv = [STRIP_TYPES_FLAG, ...execArgv]; + } + break; + } + case TsRunner.TsNode: { + if (tsUseEsm) { + if (!execArgv.includes(LOADER_FLAG)) { + execArgv = [LOADER_FLAG, `${TsRunner.TsNode}/esm`, ...execArgv]; + } + } + else if (!hasRequireFlag(execArgv)) { + execArgv = [ + REQUIRE_ABBR_FLAG, + `${TsRunner.TsNode}/register`, + ...execArgv, + ]; + } + break; + } + case TsRunner.EsbuildRegister: { + if (tsUseEsm) { + if (!hasLoaderFlag(execArgv)) { + execArgv = [ + LOADER_FLAG, + `${TsRunner.EsbuildRegister}/loader`, + ...execArgv, + ]; + } + } + else if (!hasRequireFlag(execArgv)) { + execArgv = [REQUIRE_ABBR_FLAG, TsRunner.EsbuildRegister, ...execArgv]; + } + break; + } + case TsRunner.EsbuildRunner: { + if (!hasRequireFlag(execArgv)) { + execArgv = [ + REQUIRE_ABBR_FLAG, + `${TsRunner.EsbuildRunner}/register`, + ...execArgv, + ]; + } + break; + } + case TsRunner.OXC: { + if (!execArgv.includes(IMPORT_FLAG)) { + execArgv = [ + IMPORT_FLAG, + `@${TsRunner.OXC}-node/core/register`, + ...execArgv, + ]; + } + break; + } + case TsRunner.SWC: { + if (tsUseEsm) { + if (IMPORT_FLAG_SUPPORTED) { + if (!hasImportFlag(execArgv)) { + execArgv = [ + IMPORT_FLAG, + `@${TsRunner.SWC}-node/register/esm-register`, + ...execArgv, + ]; + } + } + else if (!hasLoaderFlag(execArgv)) { + execArgv = [ + LOADER_FLAG, + `@${TsRunner.SWC}-node/register/esm`, + ...execArgv, + ]; + } + } + else if (!hasRequireFlag(execArgv)) { + execArgv = [ + REQUIRE_ABBR_FLAG, + `@${TsRunner.SWC}-node/register`, + ...execArgv, + ]; + } + break; + } + case TsRunner.TSX: { + if (IMPORT_FLAG_SUPPORTED) { + if (!execArgv.includes(IMPORT_FLAG)) { + execArgv = [IMPORT_FLAG, TsRunner.TSX, ...execArgv]; + } + } + else if (!execArgv.includes(LOADER_FLAG)) { + execArgv = [LOADER_FLAG, TsRunner.TSX, ...execArgv]; + } + break; + } + default: { + throw new Error(`Unknown ts runner: ${String(tsRunner)}`); + } + } + } + else if (!jsUseEsm && ext !== '.cjs') { + const pkg = findUp(workerPath); + if (pkg) { + jsUseEsm = cjsRequire(pkg).type === 'module'; + } + } + let resolvedPnpLoaderPath; + if (process.versions.pnp) { + let pnpApiPath; + try { + pnpApiPath = cjsRequire.resolve('pnpapi'); + } + catch { } + if (pnpApiPath && + !NODE_OPTIONS.some((option, index) => REQUIRE_FLAGS.has(option) && + pnpApiPath === cjsRequire.resolve(NODE_OPTIONS[index + 1])) && + !execArgv.includes(pnpApiPath)) { + execArgv = [REQUIRE_ABBR_FLAG, pnpApiPath, ...execArgv]; + const pnpLoaderPath = path.resolve(pnpApiPath, '../.pnp.loader.mjs'); + if (isFile(pnpLoaderPath)) { + resolvedPnpLoaderPath = pathToFileURL(pnpLoaderPath).href; + execArgv = [LOADER_FLAG, resolvedPnpLoaderPath, ...execArgv]; + } + } + } + return { + ext, + isTs, + jsUseEsm, + tsRunner, + tsUseEsm, + workerPath, + pnpLoaderPath: resolvedPnpLoaderPath, + execArgv, + }; +}; +export const md5Hash = (text) => createHash('md5').update(text).digest('hex'); +export const encodeImportModule = (moduleNameOrGlobalShim, type = 'import') => { + const { moduleName, globalName, named, conditional } = typeof moduleNameOrGlobalShim === 'string' + ? { moduleName: moduleNameOrGlobalShim } + : moduleNameOrGlobalShim; + const importStatement = type === 'import' + ? `import${globalName + ? ' ' + + (named === null + ? '* as ' + globalName + : named?.trim() + ? `{${named}}` + : globalName) + + ' from' + : ''} '${path.isAbsolute(moduleName) + ? String(pathToFileURL(moduleName)) + : moduleName}'` + : `${globalName + ? 'const ' + (named?.trim() ? `{${named}}` : globalName) + '=' + : ''}require('${moduleName + .replace(/\\/g, '\\\\')}')`; + if (!globalName) { + return importStatement; + } + const overrideStatement = `globalThis.${globalName}=${named?.trim() ? named : globalName}`; + return (importStatement + + (conditional === false + ? `;${overrideStatement}` + : `;if(!globalThis.${globalName})${overrideStatement}`)); +}; +export const _generateGlobals = (globalShims, type) => globalShims.reduce((acc, shim) => `${acc}${acc ? ';' : ''}${encodeImportModule(shim, type)}`, ''); +let globalsCache; +let tmpdir; +const _dirname = typeof __dirname === 'undefined' + ? path.dirname(fileURLToPath(import.meta.url)) + : __dirname; +export const generateGlobals = (workerPath, globalShims, type = 'import') => { + if (globalShims.length === 0) { + return ''; + } + globalsCache ?? (globalsCache = new Map()); + const cached = globalsCache.get(workerPath); + if (cached) { + const [content, filepath] = cached; + if ((type === 'require' && !filepath) || + (type === 'import' && filepath && isFile(filepath))) { + return content; + } + } + const globals = _generateGlobals(globalShims, type); + let content = globals; + let filepath; + if (type === 'import') { + if (!tmpdir) { + tmpdir = path.resolve(findUp(_dirname), '../node_modules/.synckit'); + } + fs.mkdirSync(tmpdir, { recursive: true }); + filepath = path.resolve(tmpdir, md5Hash(workerPath) + '.mjs'); + content = encodeImportModule(filepath); + fs.writeFileSync(filepath, globals); + } + globalsCache.set(workerPath, [content, filepath]); + return content; +}; +export function extractProperties(object) { + if (object && typeof object === 'object') { + const properties = {}; + for (const key in object) { + properties[key] = object[key]; + } + return properties; + } +} +let sharedBuffer; +let sharedBufferView; +export function startWorkerThread(workerPath, { timeout = DEFAULT_TIMEOUT, execArgv = DEFAULT_EXEC_ARGV, tsRunner = DEFAULT_TS_RUNNER, transferList = [], globalShims = DEFAULT_GLOBAL_SHIMS, } = {}) { + const { port1: mainPort, port2: workerPort } = new MessageChannel(); + const { isTs, ext, jsUseEsm, tsUseEsm, tsRunner: finalTsRunner, workerPath: finalWorkerPath, pnpLoaderPath, execArgv: finalExecArgv, } = setupTsRunner(workerPath, { execArgv, tsRunner }); + const workerPathUrl = pathToFileURL(finalWorkerPath); + if (/\.[cm]ts$/.test(finalWorkerPath)) { + const isTsxSupported = !tsUseEsm || TS_ESM_PARTIAL_SUPPORTED; + if (!finalTsRunner) { + throw new Error('No ts runner specified, ts worker path is not supported'); + } + else if ([ + TsRunner.EsbuildRegister, + TsRunner.EsbuildRunner, + ...(TS_ESM_PARTIAL_SUPPORTED + ? [ + TsRunner.OXC, + TsRunner.SWC, + ] + : []), + ...(isTsxSupported ? [] : [TsRunner.TSX]), + ].includes(finalTsRunner)) { + throw new Error(`${finalTsRunner} is not supported for ${ext} files yet` + + (isTsxSupported + ? ', you can try [tsx](https://github.com/esbuild-kit/tsx) instead' + : MTS_SUPPORTED + ? ', you can try [oxc](https://github.com/oxc-project/oxc-node) or [swc](https://github.com/swc-project/swc-node/tree/master/packages/register) instead' + : '')); + } + } + const finalGlobalShims = (globalShims === true + ? DEFAULT_GLOBAL_SHIMS_PRESET + : Array.isArray(globalShims) + ? globalShims + : []).filter(({ moduleName }) => isPkgAvailable(moduleName)); + sharedBufferView ?? (sharedBufferView = new Int32Array((sharedBuffer ?? (sharedBuffer = new SharedArrayBuffer(INT32_BYTES))), 0, 1)); + const useGlobals = finalGlobalShims.length > 0; + const useEval = isTs ? !tsUseEsm : !jsUseEsm && useGlobals; + const worker = new Worker((jsUseEsm && useGlobals) || (tsUseEsm && finalTsRunner === TsRunner.TsNode) + ? dataUrl(`${generateGlobals(finalWorkerPath, finalGlobalShims)};import '${String(workerPathUrl)}'`) + : useEval + ? `${generateGlobals(finalWorkerPath, finalGlobalShims, 'require')};${encodeImportModule(finalWorkerPath, 'require')}` + : workerPathUrl, { + eval: useEval, + workerData: { sharedBufferView, workerPort, pnpLoaderPath }, + transferList: [workerPort, ...transferList], + execArgv: finalExecArgv, + }); + let nextID = 0; + const receiveMessageWithId = (port, expectedId, waitingTimeout) => { + const start = Date.now(); + const status = Atomics.wait(sharedBufferView, 0, 0, waitingTimeout); + Atomics.store(sharedBufferView, 0, 0); + if (!['ok', 'not-equal'].includes(status)) { + const abortMsg = { + id: expectedId, + cmd: 'abort', + }; + port.postMessage(abortMsg); + throw new Error('Internal error: Atomics.wait() failed: ' + status); + } + const result = receiveMessageOnPort(mainPort); + const msg = result?.message; + if (msg?.id == null || msg.id < expectedId) { + const waitingTime = Date.now() - start; + return receiveMessageWithId(port, expectedId, waitingTimeout ? waitingTimeout - waitingTime : undefined); + } + const { id, ...message } = msg; + if (expectedId !== id) { + throw new Error(`Internal error: Expected id ${expectedId} but got id ${id}`); + } + return { id, ...message }; + }; + const syncFn = (...args) => { + const id = nextID++; + const msg = { id, args }; + worker.postMessage(msg); + const { result, error, properties, stdio } = receiveMessageWithId(mainPort, id, timeout); + for (const { type, chunk, encoding } of stdio) { + process[type].write(chunk, encoding); + } + if (error) { + throw Object.assign(error, properties); + } + return result; + }; + worker.unref(); + return syncFn; +} +export const overrideStdio = (stdio) => { + for (const type of ['stdout', 'stderr']) { + process[type]._writev = (chunks, callback) => { + for (const { chunk, encoding, } of chunks) { + stdio.push({ + type, + chunk, + encoding, + }); + } + callback(); + }; + } +}; +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/synckit/lib/helpers.js.map b/node_modules/synckit/lib/helpers.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cab73555e8f9efccfc21211deb4f3f319cae3904 --- /dev/null +++ b/node_modules/synckit/lib/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACvD,OAAO,EAEL,cAAc,EACd,MAAM,EACN,oBAAoB,GACrB,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAE9E,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAChD,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,2BAA2B,EAC3B,eAAe,EACf,iBAAiB,EACjB,0BAA0B,EAC1B,WAAW,EACX,qBAAqB,EACrB,WAAW,EACX,WAAW,EACX,YAAY,EACZ,aAAa,EACb,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,iBAAiB,EACjB,aAAa,EAC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;IACH,CAAC;AACH,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/synckit/lib/index.cjs b/node_modules/synckit/lib/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..4a4c7bf02ba46f42a1605bc3c90b02bb35839a68 --- /dev/null +++ b/node_modules/synckit/lib/index.cjs @@ -0,0 +1,588 @@ +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion +const node_path = __toESM(require("node:path")); +const node_url = __toESM(require("node:url")); +const node_worker_threads = __toESM(require("node:worker_threads")); +const node_crypto = __toESM(require("node:crypto")); +const node_fs = __toESM(require("node:fs")); +const __pkgr_core = __toESM(require("@pkgr/core")); + +//#region src/common.ts +var _process$env$NODE_OPT; +const NODE_OPTIONS$1 = (_process$env$NODE_OPT = process.env.NODE_OPTIONS) === null || _process$env$NODE_OPT === void 0 ? void 0 : _process$env$NODE_OPT.split(/\s+/); +const hasFlag = (flag) => (NODE_OPTIONS$1 === null || NODE_OPTIONS$1 === void 0 ? void 0 : NODE_OPTIONS$1.includes(flag)) || process.argv.includes(flag); +const parseVersion = (version) => version.split(".").map(Number.parseFloat); +const compareVersion = (version1, version2) => { + const versions1 = parseVersion(version1); + const versions2 = parseVersion(version2); + const length = Math.max(versions1.length, versions2.length); + for (let i = 0; i < length; i++) { + const v1 = versions1[i] || 0; + const v2 = versions2[i] || 0; + if (v1 > v2) return 1; + if (v1 < v2) return -1; + } + return 0; +}; +const NODE_VERSION = process.versions.node; +const compareNodeVersion = (version) => compareVersion(NODE_VERSION, version); + +//#endregion +//#region src/constants.ts +const TsRunner = { + Node: "node", + Bun: "bun", + TsNode: "ts-node", + EsbuildRegister: "esbuild-register", + EsbuildRunner: "esbuild-runner", + OXC: "oxc", + SWC: "swc", + TSX: "tsx" +}; +const { NODE_OPTIONS: NODE_OPTIONS_ = "", SYNCKIT_EXEC_ARGV = "", SYNCKIT_GLOBAL_SHIMS, SYNCKIT_TIMEOUT, SYNCKIT_TS_RUNNER } = process.env; +const TS_ESM_PARTIAL_SUPPORTED = compareNodeVersion("16") >= 0 && compareNodeVersion("18.19") < 0; +const MTS_SUPPORTED = compareNodeVersion("20.8") >= 0; +const MODULE_REGISTER_SUPPORTED = MTS_SUPPORTED || compareNodeVersion("18.19") >= 0; +const STRIP_TYPES_NODE_VERSION = "22.6"; +const TRANSFORM_TYPES_NODE_VERSION = "22.7"; +const FEATURE_TYPESCRIPT_NODE_VERSION = "22.10"; +const DEFAULT_TYPES_NODE_VERSION = "23.6"; +const STRIP_TYPES_FLAG = "--experimental-strip-types"; +const TRANSFORM_TYPES_FLAG = "--experimental-transform-types"; +const NO_STRIP_TYPES_FLAG = "--no-experimental-strip-types"; +const NODE_OPTIONS = NODE_OPTIONS_.split(/\s+/); +const NO_STRIP_TYPES = hasFlag(NO_STRIP_TYPES_FLAG) && (compareNodeVersion(FEATURE_TYPESCRIPT_NODE_VERSION) >= 0 ? process.features.typescript === false : !hasFlag(STRIP_TYPES_FLAG) && !hasFlag(TRANSFORM_TYPES_FLAG)); +const DEFAULT_TIMEOUT = SYNCKIT_TIMEOUT ? +SYNCKIT_TIMEOUT : void 0; +const DEFAULT_EXEC_ARGV = SYNCKIT_EXEC_ARGV.split(","); +const DEFAULT_TS_RUNNER = SYNCKIT_TS_RUNNER; +const DEFAULT_GLOBAL_SHIMS = ["1", "true"].includes(SYNCKIT_GLOBAL_SHIMS); +const DEFAULT_GLOBAL_SHIMS_PRESET = [{ + moduleName: "node-fetch", + globalName: "fetch" +}, { + moduleName: "node:perf_hooks", + globalName: "performance", + named: "performance" +}]; +const IMPORT_FLAG = "--import"; +const REQUIRE_FLAG = "--require"; +const REQUIRE_ABBR_FLAG = "-r"; +const REQUIRE_FLAGS = new Set([REQUIRE_FLAG, REQUIRE_ABBR_FLAG]); +const LOADER_FLAG = "--loader"; +const EXPERIMENTAL_LOADER_FLAG = "--experimental-loader"; +const LOADER_FLAGS = new Set([LOADER_FLAG, EXPERIMENTAL_LOADER_FLAG]); +const IMPORT_FLAG_SUPPORTED = compareNodeVersion("20.6") >= 0; +const INT32_BYTES = 4; + +//#endregion +//#region src/helpers.ts +const isFile = (path$2) => { + try { + var _fs$statSync; + return !!((_fs$statSync = node_fs.default.statSync(path$2, { throwIfNoEntry: false })) === null || _fs$statSync === void 0 ? void 0 : _fs$statSync.isFile()); + } catch { + /* istanbul ignore next */ + return false; + } +}; +const dataUrl = (code) => new URL(`data:text/javascript,${encodeURIComponent(code)}`); +const hasRequireFlag = (execArgv) => execArgv.some((execArg) => REQUIRE_FLAGS.has(execArg)); +const hasImportFlag = (execArgv) => execArgv.includes(IMPORT_FLAG); +const hasLoaderFlag = (execArgv) => execArgv.some((execArg) => LOADER_FLAGS.has(execArg)); +const setupTsRunner = (workerPath, { execArgv = DEFAULT_EXEC_ARGV, tsRunner } = {}) => { + let ext = node_path.default.extname(workerPath); + if (!/([/\\])node_modules\1/.test(workerPath) && (!ext || /^\.[cm]?js$/.test(ext))) { + const workPathWithoutExt = ext ? workerPath.slice(0, -ext.length) : workerPath; + let extensions; + switch (ext) { + case ".cjs": { + extensions = [".cts", ".cjs"]; + break; + } + case ".mjs": { + extensions = [".mts", ".mjs"]; + break; + } + default: { + extensions = [".ts", ".js"]; + break; + } + } + const found = (0, __pkgr_core.tryExtensions)(workPathWithoutExt, extensions); + let differentExt; + if (found && (!ext || (differentExt = found !== workPathWithoutExt))) { + workerPath = found; + if (differentExt) ext = node_path.default.extname(workerPath); + } + } + const isTs = /\.[cm]?ts$/.test(workerPath); + let jsUseEsm = ext === ".mjs"; + let tsUseEsm = ext === ".mts"; + if (isTs) { + if (!tsUseEsm && ext !== ".cts") { + const pkg = (0, __pkgr_core.findUp)(workerPath); + if (pkg) tsUseEsm = (0, __pkgr_core.cjsRequire)(pkg).type === "module"; + } + const stripTypesIndex = execArgv.indexOf(STRIP_TYPES_FLAG); + const transformTypesIndex = execArgv.indexOf(TRANSFORM_TYPES_FLAG); + const noStripTypesIndex = execArgv.indexOf(NO_STRIP_TYPES_FLAG); + const execArgvNoStripTypes = noStripTypesIndex > stripTypesIndex || noStripTypesIndex > transformTypesIndex; + const noStripTypes = execArgvNoStripTypes || stripTypesIndex === -1 && transformTypesIndex === -1 && NO_STRIP_TYPES; + if (tsRunner == null) { + if (process.versions.bun) tsRunner = TsRunner.Bun; + else if (!noStripTypes && compareNodeVersion(STRIP_TYPES_NODE_VERSION) >= 0) tsRunner = TsRunner.Node; + else if ((0, __pkgr_core.isPkgAvailable)(TsRunner.TsNode)) tsRunner = TsRunner.TsNode; + } + switch (tsRunner) { + case TsRunner.Bun: break; + case TsRunner.Node: { + if (compareNodeVersion(STRIP_TYPES_NODE_VERSION) < 0) throw new Error("type stripping is not supported in this node version"); + if (noStripTypes) throw new Error("type stripping is disabled explicitly"); + if (compareNodeVersion(DEFAULT_TYPES_NODE_VERSION) >= 0) break; + if (compareNodeVersion(TRANSFORM_TYPES_NODE_VERSION) >= 0 && !execArgv.includes(TRANSFORM_TYPES_FLAG)) execArgv = [TRANSFORM_TYPES_FLAG, ...execArgv]; + else if (compareNodeVersion(STRIP_TYPES_NODE_VERSION) >= 0 && !execArgv.includes(STRIP_TYPES_FLAG)) execArgv = [STRIP_TYPES_FLAG, ...execArgv]; + break; + } + case TsRunner.TsNode: { + if (tsUseEsm) { + if (!execArgv.includes(LOADER_FLAG)) execArgv = [ + LOADER_FLAG, + `${TsRunner.TsNode}/esm`, + ...execArgv + ]; + } else if (!hasRequireFlag(execArgv)) execArgv = [ + REQUIRE_ABBR_FLAG, + `${TsRunner.TsNode}/register`, + ...execArgv + ]; + break; + } + case TsRunner.EsbuildRegister: { + if (tsUseEsm) { + if (!hasLoaderFlag(execArgv)) execArgv = [ + LOADER_FLAG, + `${TsRunner.EsbuildRegister}/loader`, + ...execArgv + ]; + } else if (!hasRequireFlag(execArgv)) execArgv = [ + REQUIRE_ABBR_FLAG, + TsRunner.EsbuildRegister, + ...execArgv + ]; + break; + } + case TsRunner.EsbuildRunner: { + if (!hasRequireFlag(execArgv)) execArgv = [ + REQUIRE_ABBR_FLAG, + `${TsRunner.EsbuildRunner}/register`, + ...execArgv + ]; + break; + } + case TsRunner.OXC: { + if (!execArgv.includes(IMPORT_FLAG)) execArgv = [ + IMPORT_FLAG, + `@${TsRunner.OXC}-node/core/register`, + ...execArgv + ]; + break; + } + case TsRunner.SWC: { + if (tsUseEsm) { + if (IMPORT_FLAG_SUPPORTED) { + if (!hasImportFlag(execArgv)) execArgv = [ + IMPORT_FLAG, + `@${TsRunner.SWC}-node/register/esm-register`, + ...execArgv + ]; + } else if (!hasLoaderFlag(execArgv)) execArgv = [ + LOADER_FLAG, + `@${TsRunner.SWC}-node/register/esm`, + ...execArgv + ]; + } else if (!hasRequireFlag(execArgv)) execArgv = [ + REQUIRE_ABBR_FLAG, + `@${TsRunner.SWC}-node/register`, + ...execArgv + ]; + break; + } + case TsRunner.TSX: { + if (IMPORT_FLAG_SUPPORTED) { + if (!execArgv.includes(IMPORT_FLAG)) execArgv = [ + IMPORT_FLAG, + TsRunner.TSX, + ...execArgv + ]; + } else if (!execArgv.includes(LOADER_FLAG)) execArgv = [ + LOADER_FLAG, + TsRunner.TSX, + ...execArgv + ]; + break; + } + default: throw new Error(`Unknown ts runner: ${String(tsRunner)}`); + } + } else if (!jsUseEsm && ext !== ".cjs") { + const pkg = (0, __pkgr_core.findUp)(workerPath); + if (pkg) jsUseEsm = (0, __pkgr_core.cjsRequire)(pkg).type === "module"; + } + let resolvedPnpLoaderPath; + /* istanbul ignore if -- https://github.com/facebook/jest/issues/5274 */ + if (process.versions.pnp) { + let pnpApiPath; + try { + /** @see https://github.com/facebook/jest/issues/9543 */ + pnpApiPath = __pkgr_core.cjsRequire.resolve("pnpapi"); + } catch {} + if (pnpApiPath && !NODE_OPTIONS.some((option, index) => REQUIRE_FLAGS.has(option) && pnpApiPath === __pkgr_core.cjsRequire.resolve(NODE_OPTIONS[index + 1])) && !execArgv.includes(pnpApiPath)) { + execArgv = [ + REQUIRE_ABBR_FLAG, + pnpApiPath, + ...execArgv + ]; + const pnpLoaderPath = node_path.default.resolve(pnpApiPath, "../.pnp.loader.mjs"); + if (isFile(pnpLoaderPath)) { + resolvedPnpLoaderPath = (0, node_url.pathToFileURL)(pnpLoaderPath).href; + execArgv = [ + LOADER_FLAG, + resolvedPnpLoaderPath, + ...execArgv + ]; + } + } + } + return { + ext, + isTs, + jsUseEsm, + tsRunner, + tsUseEsm, + workerPath, + pnpLoaderPath: resolvedPnpLoaderPath, + execArgv + }; +}; +const md5Hash = (text) => (0, node_crypto.createHash)("md5").update(text).digest("hex"); +const encodeImportModule = (moduleNameOrGlobalShim, type = "import") => { + const { moduleName, globalName, named, conditional } = typeof moduleNameOrGlobalShim === "string" ? { moduleName: moduleNameOrGlobalShim } : moduleNameOrGlobalShim; + const importStatement = type === "import" ? `import${globalName ? " " + (named === null ? "* as " + globalName : (named === null || named === void 0 ? void 0 : named.trim()) ? `{${named}}` : globalName) + " from" : ""} '${node_path.default.isAbsolute(moduleName) ? String((0, node_url.pathToFileURL)(moduleName)) : moduleName}'` : `${globalName ? "const " + ((named === null || named === void 0 ? void 0 : named.trim()) ? `{${named}}` : globalName) + "=" : ""}require('${moduleName.replace(/\\/g, "\\\\")}')`; + if (!globalName) return importStatement; + const overrideStatement = `globalThis.${globalName}=${(named === null || named === void 0 ? void 0 : named.trim()) ? named : globalName}`; + return importStatement + (conditional === false ? `;${overrideStatement}` : `;if(!globalThis.${globalName})${overrideStatement}`); +}; +/** @internal */ +const _generateGlobals = (globalShims, type) => globalShims.reduce((acc, shim) => `${acc}${acc ? ";" : ""}${encodeImportModule(shim, type)}`, ""); +let globalsCache; +let tmpdir; +const _dirname = typeof __dirname === "undefined" ? node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href)) : __dirname; +const generateGlobals = (workerPath, globalShims, type = "import") => { + if (globalShims.length === 0) return ""; + globalsCache ?? (globalsCache = new Map()); + const cached = globalsCache.get(workerPath); + if (cached) { + const [content$1, filepath$1] = cached; + if (type === "require" && !filepath$1 || type === "import" && filepath$1 && isFile(filepath$1)) return content$1; + } + const globals = _generateGlobals(globalShims, type); + let content = globals; + let filepath; + if (type === "import") { + if (!tmpdir) tmpdir = node_path.default.resolve((0, __pkgr_core.findUp)(_dirname), "../node_modules/.synckit"); + node_fs.default.mkdirSync(tmpdir, { recursive: true }); + filepath = node_path.default.resolve(tmpdir, md5Hash(workerPath) + ".mjs"); + content = encodeImportModule(filepath); + node_fs.default.writeFileSync(filepath, globals); + } + globalsCache.set(workerPath, [content, filepath]); + return content; +}; +/** +* Creates a shallow copy of the enumerable properties from the provided object. +* +* @param object - An optional object whose properties are to be extracted. +* @returns A new object containing the enumerable properties of the input, or +* undefined if no valid object is provided. +*/ +function extractProperties(object) { + if (object && typeof object === "object") { + const properties = {}; + for (const key in object) properties[key] = object[key]; + return properties; + } +} +let sharedBuffer; +let sharedBufferView; +/** +* Spawns a worker thread and returns a synchronous function to dispatch tasks. +* +* The function initializes a worker thread with the specified script and +* configuration, setting up a dedicated message channel for bidirectional +* communication. It applies TypeScript runner settings, execution arguments, +* and global shims as needed. The returned function sends tasks to the worker, +* waits synchronously for a response using shared memory synchronization, and +* then returns the computed result. +* +* @param workerPath - The file path of the worker script to execute. +* @param options - An object containing configuration parameters: +* +* - Timeout: Maximum time in milliseconds to wait for the worker's response. +* - ExecArgv: Array of Node.js execution arguments for the worker. +* - TsRunner: Specifies the TypeScript runner to use if the worker script is +* TypeScript. +* - TransferList: List of additional transferable objects to pass to the worker. +* - GlobalShims: Modules to import as global shims; if true, a default preset is +* used. +* +* @returns A synchronous function that accepts task arguments intended for the +* worker thread and returns its result. +* @throws {Error} If a TypeScript runner is required but not specified, or if +* an unsupported TypeScript runner is used for the file type. +* @throws {Error} If internal synchronization fails or if the message +* identifier does not match the expected value. +*/ +function startWorkerThread(workerPath, { timeout = DEFAULT_TIMEOUT, execArgv = DEFAULT_EXEC_ARGV, tsRunner = DEFAULT_TS_RUNNER, transferList = [], globalShims = DEFAULT_GLOBAL_SHIMS } = {}) { + const { port1: mainPort, port2: workerPort } = new node_worker_threads.MessageChannel(); + const { isTs, ext, jsUseEsm, tsUseEsm, tsRunner: finalTsRunner, workerPath: finalWorkerPath, pnpLoaderPath, execArgv: finalExecArgv } = setupTsRunner(workerPath, { + execArgv, + tsRunner + }); + const workerPathUrl = (0, node_url.pathToFileURL)(finalWorkerPath); + if (/\.[cm]ts$/.test(finalWorkerPath)) { + const isTsxSupported = !tsUseEsm || TS_ESM_PARTIAL_SUPPORTED; + /* istanbul ignore if */ + if (!finalTsRunner) throw new Error("No ts runner specified, ts worker path is not supported"); + else if ([ + TsRunner.EsbuildRegister, + TsRunner.EsbuildRunner, + ...TS_ESM_PARTIAL_SUPPORTED ? [TsRunner.OXC, TsRunner.SWC] : [], + ...isTsxSupported ? [] : [TsRunner.TSX] + ].includes(finalTsRunner)) throw new Error(`${finalTsRunner} is not supported for ${ext} files yet` + (isTsxSupported ? ", you can try [tsx](https://github.com/esbuild-kit/tsx) instead" : MTS_SUPPORTED ? ", you can try [oxc](https://github.com/oxc-project/oxc-node) or [swc](https://github.com/swc-project/swc-node/tree/master/packages/register) instead" : "")); + } + const finalGlobalShims = (globalShims === true ? DEFAULT_GLOBAL_SHIMS_PRESET : Array.isArray(globalShims) ? globalShims : []).filter(({ moduleName }) => (0, __pkgr_core.isPkgAvailable)(moduleName)); + sharedBufferView ?? (sharedBufferView = new Int32Array(sharedBuffer ?? (sharedBuffer = new SharedArrayBuffer(INT32_BYTES)), 0, 1)); + const useGlobals = finalGlobalShims.length > 0; + const useEval = isTs ? !tsUseEsm : !jsUseEsm && useGlobals; + const worker = new node_worker_threads.Worker(jsUseEsm && useGlobals || tsUseEsm && finalTsRunner === TsRunner.TsNode ? dataUrl(`${generateGlobals(finalWorkerPath, finalGlobalShims)};import '${String(workerPathUrl)}'`) : useEval ? `${generateGlobals(finalWorkerPath, finalGlobalShims, "require")};${encodeImportModule(finalWorkerPath, "require")}` : workerPathUrl, { + eval: useEval, + workerData: { + sharedBufferView, + workerPort, + pnpLoaderPath + }, + transferList: [workerPort, ...transferList], + execArgv: finalExecArgv + }); + let nextID = 0; + const receiveMessageWithId = (port, expectedId, waitingTimeout) => { + const start = Date.now(); + const status = Atomics.wait(sharedBufferView, 0, 0, waitingTimeout); + Atomics.store(sharedBufferView, 0, 0); + if (!["ok", "not-equal"].includes(status)) { + const abortMsg = { + id: expectedId, + cmd: "abort" + }; + port.postMessage(abortMsg); + throw new Error("Internal error: Atomics.wait() failed: " + status); + } + const result = (0, node_worker_threads.receiveMessageOnPort)(mainPort); + const msg = result === null || result === void 0 ? void 0 : result.message; + if ((msg === null || msg === void 0 ? void 0 : msg.id) == null || msg.id < expectedId) { + const waitingTime = Date.now() - start; + return receiveMessageWithId(port, expectedId, waitingTimeout ? waitingTimeout - waitingTime : void 0); + } + const { id,...message } = msg; + if (expectedId !== id) throw new Error(`Internal error: Expected id ${expectedId} but got id ${id}`); + return { + id, + ...message + }; + }; + const syncFn = (...args) => { + const id = nextID++; + const msg = { + id, + args + }; + worker.postMessage(msg); + const { result, error, properties, stdio } = receiveMessageWithId(mainPort, id, timeout); + for (const { type, chunk, encoding } of stdio) process[type].write(chunk, encoding); + if (error) throw Object.assign(error, properties); + return result; + }; + worker.unref(); + return syncFn; +} +const overrideStdio = (stdio) => { + for (const type of ["stdout", "stderr"]) process[type]._writev = (chunks, callback) => { + for (const { chunk, encoding } of chunks) stdio.push({ + type, + chunk, + encoding + }); + callback(); + }; +}; + +//#endregion +//#region src/index.ts +let syncFnCache; +/** +* Creates a synchronous worker function. +* +* Converts the provided worker path (URL or string) to an absolute file path, +* retrieves a cached synchronous function if one exists, or starts a new worker +* thread to handle task execution. The resulting function is cached to avoid +* redundant initialization. +* +* @param workerPath - The absolute file path or URL of the worker script. If +* given as a URL, it is converted to a file path. +* @param timeoutOrOptions - Optional timeout in milliseconds or an options +* object to configure the worker thread. +* @returns A synchronous function that executes tasks on the specified worker +* thread. +* @throws {Error} If the resulting worker path is not absolute. +*/ +function createSyncFn(workerPath, timeoutOrOptions) { + syncFnCache ?? (syncFnCache = new Map()); + if (typeof workerPath !== "string" || workerPath.startsWith("file://")) workerPath = (0, node_url.fileURLToPath)(workerPath); + const cachedSyncFn = syncFnCache.get(workerPath); + if (cachedSyncFn) return cachedSyncFn; + if (!node_path.default.isAbsolute(workerPath)) throw new Error("`workerPath` must be absolute"); + const syncFn = startWorkerThread( + workerPath, + /* istanbul ignore next */ + typeof timeoutOrOptions === "number" ? { timeout: timeoutOrOptions } : timeoutOrOptions + ); + syncFnCache.set(workerPath, syncFn); + return syncFn; +} +/* istanbul ignore next */ +/** +* Configures the worker thread to listen for messages from the parent process +* and execute a provided function. +* +* If the worker is not initialized with the required data, the function exits +* without further action. Otherwise, it optionally registers a custom module +* loader when a valid loader path is provided and captures output generated +* during execution. It listens for messages containing an identifier and +* arguments, then invokes the supplied function asynchronously with those +* arguments. If an abort command is received for the same message, the response +* is suppressed. Upon completing execution, it posts a message back with either +* the result or error details, including extracted error properties. +* +* @param fn - The function to execute when a message is received. +*/ +function runAsWorker(fn) { + if (!node_worker_threads.workerData) return; + const stdio = []; + overrideStdio(stdio); + const { workerPort, sharedBufferView: sharedBufferView$1 } = node_worker_threads.workerData; + node_worker_threads.parentPort.on("message", ({ id, args }) => { + (async () => { + let isAborted = false; + const handleAbortMessage = (msg$1) => { + if (msg$1.id === id && msg$1.cmd === "abort") isAborted = true; + }; + workerPort.on("message", handleAbortMessage); + let msg; + try { + msg = { + id, + stdio, + result: await fn(...args) + }; + } catch (error) { + msg = { + id, + stdio, + error, + properties: extractProperties(error) + }; + } + workerPort.off("message", handleAbortMessage); + if (isAborted) { + stdio.length = 0; + return; + } + try { + workerPort.postMessage(msg); + Atomics.add(sharedBufferView$1, 0, 1); + Atomics.notify(sharedBufferView$1, 0); + } finally { + stdio.length = 0; + } + })(); + }); +} + +//#endregion +exports.DEFAULT_EXEC_ARGV = DEFAULT_EXEC_ARGV; +exports.DEFAULT_GLOBAL_SHIMS = DEFAULT_GLOBAL_SHIMS; +exports.DEFAULT_GLOBAL_SHIMS_PRESET = DEFAULT_GLOBAL_SHIMS_PRESET; +exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; +exports.DEFAULT_TS_RUNNER = DEFAULT_TS_RUNNER; +exports.DEFAULT_TYPES_NODE_VERSION = DEFAULT_TYPES_NODE_VERSION; +exports.EXPERIMENTAL_LOADER_FLAG = EXPERIMENTAL_LOADER_FLAG; +exports.FEATURE_TYPESCRIPT_NODE_VERSION = FEATURE_TYPESCRIPT_NODE_VERSION; +exports.IMPORT_FLAG = IMPORT_FLAG; +exports.IMPORT_FLAG_SUPPORTED = IMPORT_FLAG_SUPPORTED; +exports.INT32_BYTES = INT32_BYTES; +exports.LOADER_FLAG = LOADER_FLAG; +exports.LOADER_FLAGS = LOADER_FLAGS; +exports.MODULE_REGISTER_SUPPORTED = MODULE_REGISTER_SUPPORTED; +exports.MTS_SUPPORTED = MTS_SUPPORTED; +exports.NODE_OPTIONS = NODE_OPTIONS; +exports.NODE_VERSION = NODE_VERSION; +exports.NO_STRIP_TYPES = NO_STRIP_TYPES; +exports.NO_STRIP_TYPES_FLAG = NO_STRIP_TYPES_FLAG; +exports.REQUIRE_ABBR_FLAG = REQUIRE_ABBR_FLAG; +exports.REQUIRE_FLAG = REQUIRE_FLAG; +exports.REQUIRE_FLAGS = REQUIRE_FLAGS; +exports.STRIP_TYPES_FLAG = STRIP_TYPES_FLAG; +exports.STRIP_TYPES_NODE_VERSION = STRIP_TYPES_NODE_VERSION; +exports.TRANSFORM_TYPES_FLAG = TRANSFORM_TYPES_FLAG; +exports.TRANSFORM_TYPES_NODE_VERSION = TRANSFORM_TYPES_NODE_VERSION; +exports.TS_ESM_PARTIAL_SUPPORTED = TS_ESM_PARTIAL_SUPPORTED; +exports.TsRunner = TsRunner; +exports._generateGlobals = _generateGlobals; +exports.compareNodeVersion = compareNodeVersion; +exports.compareVersion = compareVersion; +exports.createSyncFn = createSyncFn; +exports.dataUrl = dataUrl; +exports.encodeImportModule = encodeImportModule; +exports.extractProperties = extractProperties; +exports.generateGlobals = generateGlobals; +exports.hasFlag = hasFlag; +exports.hasImportFlag = hasImportFlag; +exports.hasLoaderFlag = hasLoaderFlag; +exports.hasRequireFlag = hasRequireFlag; +exports.isFile = isFile; +exports.md5Hash = md5Hash; +exports.overrideStdio = overrideStdio; +exports.parseVersion = parseVersion; +exports.runAsWorker = runAsWorker; +exports.setupTsRunner = setupTsRunner; +exports.startWorkerThread = startWorkerThread; \ No newline at end of file diff --git a/node_modules/synckit/lib/index.d.cts b/node_modules/synckit/lib/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..48bd9ac3aafc6d6e4ec9385de7a6f81604029e16 --- /dev/null +++ b/node_modules/synckit/lib/index.d.cts @@ -0,0 +1,138 @@ +import { MessagePort, TransferListItem } from "node:worker_threads"; +import * as url0 from "url"; + +//#region src/constants.d.ts +declare const TsRunner: { + readonly Node: "node"; + readonly Bun: "bun"; + readonly TsNode: "ts-node"; + readonly EsbuildRegister: "esbuild-register"; + readonly EsbuildRunner: "esbuild-runner"; + readonly OXC: "oxc"; + readonly SWC: "swc"; + readonly TSX: "tsx"; +}; +type TsRunner = ValueOf; +declare const TS_ESM_PARTIAL_SUPPORTED: boolean; +declare const MTS_SUPPORTED: boolean; +declare const MODULE_REGISTER_SUPPORTED: boolean; +declare const STRIP_TYPES_NODE_VERSION = "22.6"; +declare const TRANSFORM_TYPES_NODE_VERSION = "22.7"; +declare const FEATURE_TYPESCRIPT_NODE_VERSION = "22.10"; +declare const DEFAULT_TYPES_NODE_VERSION = "23.6"; +declare const STRIP_TYPES_FLAG = "--experimental-strip-types"; +declare const TRANSFORM_TYPES_FLAG = "--experimental-transform-types"; +declare const NO_STRIP_TYPES_FLAG = "--no-experimental-strip-types"; +declare const NODE_OPTIONS: string[]; +declare const NO_STRIP_TYPES: boolean; +declare const DEFAULT_TIMEOUT: number | undefined; +declare const DEFAULT_EXEC_ARGV: string[]; +declare const DEFAULT_TS_RUNNER: TsRunner | undefined; +declare const DEFAULT_GLOBAL_SHIMS: boolean; +declare const DEFAULT_GLOBAL_SHIMS_PRESET: GlobalShim[]; +declare const IMPORT_FLAG = "--import"; +declare const REQUIRE_FLAG = "--require"; +declare const REQUIRE_ABBR_FLAG = "-r"; +declare const REQUIRE_FLAGS: Set; +declare const LOADER_FLAG = "--loader"; +declare const EXPERIMENTAL_LOADER_FLAG = "--experimental-loader"; +declare const LOADER_FLAGS: Set; +declare const IMPORT_FLAG_SUPPORTED: boolean; +declare const INT32_BYTES = 4; +//#endregion +//#region src/types.d.ts +type AnyFn = (...args: T) => R; +type Syncify = (...args: Parameters) => Awaited>; +type ValueOf = T[keyof T]; +interface MainToWorkerMessage { + id: number; + args: T; +} +interface MainToWorkerCommandMessage { + id: number; + cmd: string; +} +interface WorkerData { + sharedBufferView: Int32Array; + workerPort: MessagePort; + pnpLoaderPath: string | undefined; +} +interface DataMessage { + result?: T; + error?: unknown; + properties?: unknown; +} +interface StdioChunk { + type: 'stderr' | 'stdout'; + chunk: Uint8Array | string; + encoding: BufferEncoding; +} +interface WorkerToMainMessage extends DataMessage { + id: number; + stdio: StdioChunk[]; +} +interface GlobalShim { + moduleName: string; + globalName?: string; + named?: string | null; + conditional?: boolean; +} +interface PackageJson { + type?: 'commonjs' | 'module'; +} +interface SynckitOptions { + execArgv?: string[]; + globalShims?: GlobalShim[] | boolean; + timeout?: number; + transferList?: TransferListItem[]; + tsRunner?: TsRunner; +} +//#endregion +//#region src/common.d.ts +declare const hasFlag: (flag: string) => boolean; +declare const parseVersion: (version: string) => number[]; +declare const compareVersion: (version1: string, version2: string) => 1 | -1 | 0; +declare const NODE_VERSION: string; +declare const compareNodeVersion: (version: string) => 1 | -1 | 0; +//#endregion +//#region src/helpers.d.ts +declare const isFile: (path: string) => boolean; +declare const dataUrl: (code: string) => url0.URL; +declare const hasRequireFlag: (execArgv: string[]) => boolean; +declare const hasImportFlag: (execArgv: string[]) => boolean; +declare const hasLoaderFlag: (execArgv: string[]) => boolean; +declare const setupTsRunner: (workerPath: string, { + execArgv, + tsRunner +}?: { + execArgv?: string[]; + tsRunner?: TsRunner; +}) => { + ext: string; + isTs: boolean; + jsUseEsm: boolean; + tsRunner: TsRunner | undefined; + tsUseEsm: boolean; + workerPath: string; + pnpLoaderPath: string | undefined; + execArgv: string[]; +}; +declare const md5Hash: (text: string) => string; +declare const encodeImportModule: (moduleNameOrGlobalShim: GlobalShim | string, type?: "import" | "require") => string; +declare const generateGlobals: (workerPath: string, globalShims: GlobalShim[], type?: "import" | "require") => string; +declare function extractProperties(object: T): T; +declare function extractProperties(object?: T): T | undefined; +declare function startWorkerThread>>(workerPath: string, { + timeout, + execArgv, + tsRunner, + transferList, + globalShims +}?: SynckitOptions): (...args: Parameters) => R; +declare const overrideStdio: (stdio: StdioChunk[]) => void; +//#endregion +//#region src/index.d.ts +declare function createSyncFn(workerPath: URL | string, timeoutOrOptions?: SynckitOptions | number): Syncify; +declare function runAsWorker | R>, R = ReturnType>(fn: T): void; +//#endregion +export { AnyFn, DEFAULT_EXEC_ARGV, DEFAULT_GLOBAL_SHIMS, DEFAULT_GLOBAL_SHIMS_PRESET, DEFAULT_TIMEOUT, DEFAULT_TS_RUNNER, DEFAULT_TYPES_NODE_VERSION, DataMessage, EXPERIMENTAL_LOADER_FLAG, FEATURE_TYPESCRIPT_NODE_VERSION, GlobalShim, IMPORT_FLAG, IMPORT_FLAG_SUPPORTED, INT32_BYTES, LOADER_FLAG, LOADER_FLAGS, MODULE_REGISTER_SUPPORTED, MTS_SUPPORTED, MainToWorkerCommandMessage, MainToWorkerMessage, NODE_OPTIONS, NODE_VERSION, NO_STRIP_TYPES, NO_STRIP_TYPES_FLAG, PackageJson, REQUIRE_ABBR_FLAG, REQUIRE_FLAG, REQUIRE_FLAGS, STRIP_TYPES_FLAG, STRIP_TYPES_NODE_VERSION, StdioChunk, Syncify, SynckitOptions, TRANSFORM_TYPES_FLAG, TRANSFORM_TYPES_NODE_VERSION, TS_ESM_PARTIAL_SUPPORTED, TsRunner, ValueOf, WorkerData, WorkerToMainMessage, compareNodeVersion, compareVersion, createSyncFn, dataUrl, encodeImportModule, extractProperties, generateGlobals, hasFlag, hasImportFlag, hasLoaderFlag, hasRequireFlag, isFile, md5Hash, overrideStdio, parseVersion, runAsWorker, setupTsRunner, startWorkerThread }; \ No newline at end of file diff --git a/node_modules/synckit/lib/index.d.ts b/node_modules/synckit/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e769011d6d40dbe58603afa1d1caa458c43965c --- /dev/null +++ b/node_modules/synckit/lib/index.d.ts @@ -0,0 +1,7 @@ +import type { AnyFn, Syncify, SynckitOptions } from './types.js'; +export * from './common.js'; +export * from './constants.js'; +export * from './helpers.js'; +export * from './types.js'; +export declare function createSyncFn(workerPath: URL | string, timeoutOrOptions?: SynckitOptions | number): Syncify; +export declare function runAsWorker | R>, R = ReturnType>(fn: T): void; diff --git a/node_modules/synckit/lib/index.js b/node_modules/synckit/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0e23cb4e570aa83f5fe5b901808be23aadba8554 --- /dev/null +++ b/node_modules/synckit/lib/index.js @@ -0,0 +1,68 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parentPort, workerData, } from 'node:worker_threads'; +import { extractProperties, overrideStdio, startWorkerThread, } from './helpers.js'; +export * from './common.js'; +export * from './constants.js'; +export * from './helpers.js'; +export * from './types.js'; +let syncFnCache; +export function createSyncFn(workerPath, timeoutOrOptions) { + syncFnCache ?? (syncFnCache = new Map()); + if (typeof workerPath !== 'string' || workerPath.startsWith('file://')) { + workerPath = fileURLToPath(workerPath); + } + const cachedSyncFn = syncFnCache.get(workerPath); + if (cachedSyncFn) { + return cachedSyncFn; + } + if (!path.isAbsolute(workerPath)) { + throw new Error('`workerPath` must be absolute'); + } + const syncFn = startWorkerThread(workerPath, typeof timeoutOrOptions === 'number' + ? { timeout: timeoutOrOptions } + : timeoutOrOptions); + syncFnCache.set(workerPath, syncFn); + return syncFn; +} +export function runAsWorker(fn) { + if (!workerData) { + return; + } + const stdio = []; + overrideStdio(stdio); + const { workerPort, sharedBufferView } = workerData; + parentPort.on('message', ({ id, args }) => { + ; + (async () => { + let isAborted = false; + const handleAbortMessage = (msg) => { + if (msg.id === id && msg.cmd === 'abort') { + isAborted = true; + } + }; + workerPort.on('message', handleAbortMessage); + let msg; + try { + msg = { id, stdio, result: await fn(...args) }; + } + catch (error) { + msg = { id, stdio, error, properties: extractProperties(error) }; + } + workerPort.off('message', handleAbortMessage); + if (isAborted) { + stdio.length = 0; + return; + } + try { + workerPort.postMessage(msg); + Atomics.add(sharedBufferView, 0, 1); + Atomics.notify(sharedBufferView, 0); + } + finally { + stdio.length = 0; + } + })(); + }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/synckit/lib/index.js.map b/node_modules/synckit/lib/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..d983d86ccb45edc04939e9a4b854021fd53e8a61 --- /dev/null +++ b/node_modules/synckit/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts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,MAAM,CAAC,gBAAgB,EAAE,CAAC,CAAC,CAAA;YACrC,CAAC;oBAAS,CAAC;gBACT,KAAK,CAAC,MAAM,GAAG,CAAC,CAAA;YAClB,CAAC;QACH,CAAC,CAAC,EAAE,CAAA;IACN,CAAC,CACF,CAAA;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/synckit/lib/types.d.ts b/node_modules/synckit/lib/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfb2296e87ab620ec1e32a4d56e2e453ad57bef5 --- /dev/null +++ b/node_modules/synckit/lib/types.d.ts @@ -0,0 +1,48 @@ +import type { MessagePort, TransferListItem } from 'node:worker_threads'; +import type { TsRunner } from './constants.ts'; +export type AnyFn = (...args: T) => R; +export type Syncify = (...args: Parameters) => Awaited>; +export type ValueOf = T[keyof T]; +export interface MainToWorkerMessage { + id: number; + args: T; +} +export interface MainToWorkerCommandMessage { + id: number; + cmd: string; +} +export interface WorkerData { + sharedBufferView: Int32Array; + workerPort: MessagePort; + pnpLoaderPath: string | undefined; +} +export interface DataMessage { + result?: T; + error?: unknown; + properties?: unknown; +} +export interface StdioChunk { + type: 'stderr' | 'stdout'; + chunk: Uint8Array | string; + encoding: BufferEncoding; +} +export interface WorkerToMainMessage extends DataMessage { + id: number; + stdio: StdioChunk[]; +} +export interface GlobalShim { + moduleName: string; + globalName?: string; + named?: string | null; + conditional?: boolean; +} +export interface PackageJson { + type?: 'commonjs' | 'module'; +} +export interface SynckitOptions { + execArgv?: string[]; + globalShims?: GlobalShim[] | boolean; + timeout?: number; + transferList?: TransferListItem[]; + tsRunner?: TsRunner; +} diff --git a/node_modules/synckit/lib/types.js b/node_modules/synckit/lib/types.js new file mode 100644 index 0000000000000000000000000000000000000000..718fd38ae40c67ea23b242517cf9919f602c5a3e --- /dev/null +++ b/node_modules/synckit/lib/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/node_modules/synckit/lib/types.js.map b/node_modules/synckit/lib/types.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c768b79002615c0e69cc6efdcad6a509c1abaaec --- /dev/null +++ b/node_modules/synckit/lib/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/synckit/package.json b/node_modules/synckit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2da4cd3ab69eaa05a6704ef13ee6256912593942 --- /dev/null +++ b/node_modules/synckit/package.json @@ -0,0 +1,45 @@ +{ + "name": "synckit", + "version": "0.11.13", + "type": "module", + "description": "Perform async work synchronously in Node.js using `worker_threads` with first-class TypeScript support.", + "repository": "https://github.com/un-ts/synckit.git", + "author": "JounQin (https://www.1stG.me)", + "funding": "https://opencollective.com/synckit", + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "main": "./lib/index.cjs", + "types": "./lib/index.d.cts", + "module": "./lib/index.js", + "exports": { + "import": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "require": { + "types": "./lib/index.d.cts", + "default": "./lib/index.cjs" + } + }, + "files": [ + "index.d.cts", + "lib", + "!**/*.tsbuildinfo" + ], + "keywords": [ + "deasync", + "make-synchronized", + "make-synchronous", + "sync", + "sync-exec", + "sync-rpc", + "sync-threads", + "synchronize", + "synckit" + ], + "dependencies": { + "@pkgr/core": "^0.3.6" + } +} \ No newline at end of file diff --git a/node_modules/tagged-tag/index.d.ts b/node_modules/tagged-tag/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d68b8568273eecccc4972fffb0d0069dd20ea841 --- /dev/null +++ b/node_modules/tagged-tag/index.d.ts @@ -0,0 +1,3 @@ +declare const tag: unique symbol; + +export default tag; diff --git a/node_modules/tagged-tag/license b/node_modules/tagged-tag/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/tagged-tag/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/tagged-tag/package.json b/node_modules/tagged-tag/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6d714abc122cac6e30f9373cf9978362ea29dd99 --- /dev/null +++ b/node_modules/tagged-tag/package.json @@ -0,0 +1,36 @@ +{ + "name": "tagged-tag", + "version": "1.0.0", + "description": "Unique tag for use in the type-fest Tagged type", + "license": "MIT", + "repository": "sindresorhus/tagged-tag", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + "types": "./index.d.ts" + }, + "engines": { + "node": ">=20" + }, + "scripts": { + "test": "tsc index.d.ts" + }, + "files": [ + "index.d.ts" + ], + "keywords": [ + "tagged", + "tag", + "unique", + "symbol", + "type-fest" + ], + "devDependencies": { + "typescript": "^5.8.3" + } +} diff --git a/node_modules/tagged-tag/readme.md b/node_modules/tagged-tag/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..33ccacfcf1c09bc57aad1ee2310beec42795c88c --- /dev/null +++ b/node_modules/tagged-tag/readme.md @@ -0,0 +1,5 @@ +# tagged-tag + +> Unique tag used in the [type-fest](https://github.com/sindresorhus/type-fest) [`Tagged`](https://github.com/sindresorhus/type-fest/blob/a6612048e1bf4c6e787b1a10007dd90c5c9f34e7/source/opaque.d.ts#L122-L184) type + +This package provides a singular, unified tag to prevent the duplication of tag symbols when multiple versions of type-fest coexist in a project's dependency tree. Such duplication could lead to ambiguity when using the `Tagged` type. Because of this, this package will never have another major version. diff --git a/node_modules/tailwindcss/LICENSE b/node_modules/tailwindcss/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d6a82290738a9f78946cbcb4594535d6984086dd --- /dev/null +++ b/node_modules/tailwindcss/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/tailwindcss/README.md b/node_modules/tailwindcss/README.md new file mode 100644 index 0000000000000000000000000000000000000000..14c29a3c0a434c7da5a35a3ac4161f9813d5dd51 --- /dev/null +++ b/node_modules/tailwindcss/README.md @@ -0,0 +1,40 @@ +

+ + + + + Tailwind CSS + + +

+ +

+ A utility-first CSS framework for rapidly building custom user interfaces. +

+ +

+ Build Status + Total Downloads + Latest Release + License +

+ +--- + +## Documentation + +For full documentation, visit [tailwindcss.com](https://tailwindcss.com/). + +## Community + +For help, discussion about best practices, or any other conversation that would benefit from being searchable: + +[Discuss Tailwind CSS on GitHub](https://github.com/tailwindcss/tailwindcss/discussions) + +For casual chit-chat with others using the framework: + +[Join the Tailwind CSS Discord Server](https://discord.gg/7NF8GNe) + +## Contributing + +If you're interested in contributing to Tailwind CSS, please read our [contributing docs](https://github.com/tailwindcss/tailwindcss/blob/main/.github/CONTRIBUTING.md) **before submitting a pull request**. diff --git a/node_modules/tailwindcss/base.css b/node_modules/tailwindcss/base.css new file mode 100644 index 0000000000000000000000000000000000000000..2f02db53f6e3a2b20e7c29a0e64f983de6a3bfff --- /dev/null +++ b/node_modules/tailwindcss/base.css @@ -0,0 +1 @@ +@tailwind base; diff --git a/node_modules/tailwindcss/colors.d.ts b/node_modules/tailwindcss/colors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d85ab869a0b73dd925450274e34fe808bd78edeb --- /dev/null +++ b/node_modules/tailwindcss/colors.d.ts @@ -0,0 +1,3 @@ +import type { DefaultColors } from './types/generated/colors' +declare const colors: DefaultColors +export = colors diff --git a/node_modules/tailwindcss/colors.js b/node_modules/tailwindcss/colors.js new file mode 100644 index 0000000000000000000000000000000000000000..c6f914958841a8b9b1632e0b8c978cf2d4a445bc --- /dev/null +++ b/node_modules/tailwindcss/colors.js @@ -0,0 +1,2 @@ +let colors = require('./lib/public/colors') +module.exports = (colors.__esModule ? colors : { default: colors }).default diff --git a/node_modules/tailwindcss/components.css b/node_modules/tailwindcss/components.css new file mode 100644 index 0000000000000000000000000000000000000000..020aabafdeaa0f5f0e098755a4e3afb1e550fa52 --- /dev/null +++ b/node_modules/tailwindcss/components.css @@ -0,0 +1 @@ +@tailwind components; diff --git a/node_modules/tailwindcss/defaultConfig.d.ts b/node_modules/tailwindcss/defaultConfig.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c2bccf2c4ccc2e012ef3b750d0c9a50ab142217 --- /dev/null +++ b/node_modules/tailwindcss/defaultConfig.d.ts @@ -0,0 +1,3 @@ +import type { Config } from './types/config' +declare const config: Config +export = config diff --git a/node_modules/tailwindcss/defaultConfig.js b/node_modules/tailwindcss/defaultConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..7b635875d255b680396e8b49c23f92263f948e0a --- /dev/null +++ b/node_modules/tailwindcss/defaultConfig.js @@ -0,0 +1,2 @@ +let defaultConfig = require('./lib/public/default-config') +module.exports = (defaultConfig.__esModule ? defaultConfig : { default: defaultConfig }).default diff --git a/node_modules/tailwindcss/defaultTheme.d.ts b/node_modules/tailwindcss/defaultTheme.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2bc9dc718b0c7384b2129cb936ce7faf6bcd6c5f --- /dev/null +++ b/node_modules/tailwindcss/defaultTheme.d.ts @@ -0,0 +1,4 @@ +import type { Config } from './types/config' +import { DefaultTheme } from './types/generated/default-theme' +declare const theme: Config['theme'] & DefaultTheme +export = theme diff --git a/node_modules/tailwindcss/defaultTheme.js b/node_modules/tailwindcss/defaultTheme.js new file mode 100644 index 0000000000000000000000000000000000000000..991526d7bf2f368020259cc87b182dbe5a144dad --- /dev/null +++ b/node_modules/tailwindcss/defaultTheme.js @@ -0,0 +1,2 @@ +let defaultTheme = require('./lib/public/default-theme') +module.exports = (defaultTheme.__esModule ? defaultTheme : { default: defaultTheme }).default diff --git a/node_modules/tailwindcss/lib/cli-peer-dependencies.js b/node_modules/tailwindcss/lib/cli-peer-dependencies.js new file mode 100644 index 0000000000000000000000000000000000000000..4b64be28d5c5fb104ac03b855f69606112501785 --- /dev/null +++ b/node_modules/tailwindcss/lib/cli-peer-dependencies.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + lazyPostcss: function() { + return lazyPostcss; + }, + lazyPostcssImport: function() { + return lazyPostcssImport; + }, + lazyAutoprefixer: function() { + return lazyAutoprefixer; + }, + lazyCssnano: function() { + return lazyCssnano; + } +}); +function lazyPostcss() { + return require("postcss"); +} +function lazyPostcssImport() { + return require("postcss-import"); +} +function lazyAutoprefixer() { + return require("autoprefixer"); +} +function lazyCssnano() { + return require("cssnano"); +} diff --git a/node_modules/tailwindcss/lib/cli.js b/node_modules/tailwindcss/lib/cli.js new file mode 100644 index 0000000000000000000000000000000000000000..1cdfd6ebc031d4e9a46b28094cb5b90ebffafb77 --- /dev/null +++ b/node_modules/tailwindcss/lib/cli.js @@ -0,0 +1,3 @@ +#!/usr/bin/env node +"use strict"; +module.exports = require("./cli/index"); diff --git a/node_modules/tailwindcss/lib/cli/build/deps.js b/node_modules/tailwindcss/lib/cli/build/deps.js new file mode 100644 index 0000000000000000000000000000000000000000..1aa8116365aaaea5697382c8cabef9f17486a24b --- /dev/null +++ b/node_modules/tailwindcss/lib/cli/build/deps.js @@ -0,0 +1,62 @@ +// @ts-check +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + loadPostcss: function() { + return loadPostcss; + }, + loadPostcssImport: function() { + return loadPostcssImport; + }, + loadCssNano: function() { + return loadCssNano; + }, + loadAutoprefixer: function() { + return loadAutoprefixer; + } +}); +const _index = require("../../../peers/index.js"); +function loadPostcss() { + // Try to load a local `postcss` version first + try { + return require("postcss"); + } catch {} + return (0, _index.lazyPostcss)(); +} +function loadPostcssImport() { + // Try to load a local `postcss-import` version first + try { + return require("postcss-import"); + } catch {} + return (0, _index.lazyPostcssImport)(); +} +function loadCssNano() { + let options = { + preset: [ + "default", + { + cssDeclarationSorter: false + } + ] + }; + // Try to load a local `cssnano` version first + try { + return require("cssnano"); + } catch {} + return (0, _index.lazyCssnano)()(options); +} +function loadAutoprefixer() { + // Try to load a local `autoprefixer` version first + try { + return require("autoprefixer"); + } catch {} + return (0, _index.lazyAutoprefixer)(); +} diff --git a/node_modules/tailwindcss/lib/cli/build/index.js b/node_modules/tailwindcss/lib/cli/build/index.js new file mode 100644 index 0000000000000000000000000000000000000000..60304f69673670c1828dc0816986bb11cabd5f23 --- /dev/null +++ b/node_modules/tailwindcss/lib/cli/build/index.js @@ -0,0 +1,54 @@ +// @ts-check +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "build", { + enumerable: true, + get: function() { + return build; + } +}); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _resolveConfigPath = require("../../util/resolveConfigPath.js"); +const _plugin = require("./plugin.js"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +async function build(args) { + let input = args["--input"]; + let shouldWatch = args["--watch"]; + // TODO: Deprecate this in future versions + if (!input && args["_"][1]) { + console.error("[deprecation] Running tailwindcss without -i, please provide an input file."); + input = args["--input"] = args["_"][1]; + } + if (input && input !== "-" && !_fs.default.existsSync(input = _path.default.resolve(input))) { + console.error(`Specified input file ${args["--input"]} does not exist.`); + process.exit(9); + } + if (args["--config"] && !_fs.default.existsSync(args["--config"] = _path.default.resolve(args["--config"]))) { + console.error(`Specified config file ${args["--config"]} does not exist.`); + process.exit(9); + } + // TODO: Reference the @config path here if exists + let configPath = args["--config"] ? args["--config"] : (0, _resolveConfigPath.resolveDefaultConfigPath)(); + let processor = await (0, _plugin.createProcessor)(args, configPath); + if (shouldWatch) { + // Abort the watcher if stdin is closed to avoid zombie processes + // You can disable this behavior with --watch=always + if (args["--watch"] !== "always") { + process.stdin.on("end", ()=>process.exit(0)); + } + process.stdin.resume(); + await processor.watch(); + } else { + await processor.build().catch((e)=>{ + console.error(e); + process.exit(1); + }); + } +} diff --git a/node_modules/tailwindcss/lib/cli/build/plugin.js b/node_modules/tailwindcss/lib/cli/build/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..5714067bdf922ea972e0f2d45d45c60478363c60 --- /dev/null +++ b/node_modules/tailwindcss/lib/cli/build/plugin.js @@ -0,0 +1,376 @@ +// @ts-check +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "createProcessor", { + enumerable: true, + get: function() { + return createProcessor; + } +}); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _postcssloadconfig = /*#__PURE__*/ _interop_require_default(require("postcss-load-config")); +const _lilconfig = require("lilconfig"); +const _plugins = /*#__PURE__*/ _interop_require_default(require("postcss-load-config/src/plugins" // Little bit scary, looking at private/internal API +)); +const _options = /*#__PURE__*/ _interop_require_default(require("postcss-load-config/src/options" // Little bit scary, looking at private/internal API +)); +const _processTailwindFeatures = /*#__PURE__*/ _interop_require_default(require("../../processTailwindFeatures")); +const _deps = require("./deps"); +const _utils = require("./utils"); +const _sharedState = require("../../lib/sharedState"); +const _resolveConfig = /*#__PURE__*/ _interop_require_default(require("../../../resolveConfig.js")); +const _content = require("../../lib/content.js"); +const _watching = require("./watching.js"); +const _fastglob = /*#__PURE__*/ _interop_require_default(require("fast-glob")); +const _findAtConfigPath = require("../../lib/findAtConfigPath.js"); +const _log = /*#__PURE__*/ _interop_require_default(require("../../util/log")); +const _loadconfig = require("../../lib/load-config"); +const _getModuleDependencies = /*#__PURE__*/ _interop_require_default(require("../../lib/getModuleDependencies")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +/** + * + * @param {string} [customPostCssPath ] + * @returns + */ async function loadPostCssPlugins(customPostCssPath) { + let config = customPostCssPath ? await (async ()=>{ + let file = _path.default.resolve(customPostCssPath); + // Implementation, see: https://unpkg.com/browse/postcss-load-config@3.1.0/src/index.js + // @ts-ignore + let { config ={} } = await (0, _lilconfig.lilconfig)("postcss").load(file); + if (typeof config === "function") { + config = config(); + } else { + config = Object.assign({}, config); + } + if (!config.plugins) { + config.plugins = []; + } + // We have to await these because in v5 and v6 of postcss-load-config + // these functions return promises while they don't in v4. Awaiting a + // non-promise is basically a no-op so this is safe to do. + return { + file, + plugins: await (0, _plugins.default)(config, file), + options: await (0, _options.default)(config, file) + }; + })() : await (0, _postcssloadconfig.default)(); + let configPlugins = config.plugins; + let configPluginTailwindIdx = configPlugins.findIndex((plugin)=>{ + if (typeof plugin === "function" && plugin.name === "tailwindcss") { + return true; + } + if (typeof plugin === "object" && plugin !== null && plugin.postcssPlugin === "tailwindcss") { + return true; + } + return false; + }); + let beforePlugins = configPluginTailwindIdx === -1 ? [] : configPlugins.slice(0, configPluginTailwindIdx); + let afterPlugins = configPluginTailwindIdx === -1 ? configPlugins : configPlugins.slice(configPluginTailwindIdx + 1); + return [ + beforePlugins, + afterPlugins, + config.options + ]; +} +function loadBuiltinPostcssPlugins() { + let postcss = (0, _deps.loadPostcss)(); + let IMPORT_COMMENT = "__TAILWIND_RESTORE_IMPORT__: "; + return [ + [ + (root)=>{ + root.walkAtRules("import", (rule)=>{ + if (rule.params.slice(1).startsWith("tailwindcss/")) { + rule.after(postcss.comment({ + text: IMPORT_COMMENT + rule.params + })); + rule.remove(); + } + }); + }, + (0, _deps.loadPostcssImport)(), + (root)=>{ + root.walkComments((rule)=>{ + if (rule.text.startsWith(IMPORT_COMMENT)) { + rule.after(postcss.atRule({ + name: "import", + params: rule.text.replace(IMPORT_COMMENT, "") + })); + rule.remove(); + } + }); + } + ], + [], + {} + ]; +} +let state = { + /** @type {any} */ context: null, + /** @type {ReturnType | null} */ watcher: null, + /** @type {{content: string, extension: string}[]} */ changedContent: [], + /** @type {ReturnType | null} */ configBag: null, + contextDependencies: new Set(), + /** @type {import('../../lib/content.js').ContentPath[]} */ contentPaths: [], + refreshContentPaths () { + var _this_context; + this.contentPaths = (0, _content.parseCandidateFiles)(this.context, (_this_context = this.context) === null || _this_context === void 0 ? void 0 : _this_context.tailwindConfig); + }, + get config () { + return this.context.tailwindConfig; + }, + get contentPatterns () { + return { + all: this.contentPaths.map((contentPath)=>contentPath.pattern), + dynamic: this.contentPaths.filter((contentPath)=>contentPath.glob !== undefined).map((contentPath)=>contentPath.pattern) + }; + }, + loadConfig (configPath, content) { + if (this.watcher && configPath) { + this.refreshConfigDependencies(); + } + let config = (0, _loadconfig.loadConfig)(configPath); + let dependencies = (0, _getModuleDependencies.default)(configPath); + this.configBag = { + config, + dependencies, + dispose () { + for (let file of dependencies){ + delete require.cache[require.resolve(file)]; + } + } + }; + // @ts-ignore + this.configBag.config = (0, _resolveConfig.default)(this.configBag.config, { + content: { + files: [] + } + }); + // Override content files if `--content` has been passed explicitly + if ((content === null || content === void 0 ? void 0 : content.length) > 0) { + this.configBag.config.content.files = content; + } + return this.configBag.config; + }, + refreshConfigDependencies () { + var _this_configBag; + _sharedState.env.DEBUG && console.time("Module dependencies"); + (_this_configBag = this.configBag) === null || _this_configBag === void 0 ? void 0 : _this_configBag.dispose(); + _sharedState.env.DEBUG && console.timeEnd("Module dependencies"); + }, + readContentPaths () { + let content = []; + // Resolve globs from the content config + // TODO: When we make the postcss plugin async-capable this can become async + let files = _fastglob.default.sync(this.contentPatterns.all); + let checkBroadPattern = (0, _content.createBroadPatternCheck)(this.contentPatterns.all); + for (let file of files){ + checkBroadPattern(file); + content.push({ + content: _fs.default.readFileSync(_path.default.resolve(file), "utf8"), + extension: _path.default.extname(file).slice(1) + }); + } + // Resolve raw content in the tailwind config + let rawContent = this.config.content.files.filter((file)=>{ + return file !== null && typeof file === "object"; + }); + for (let { raw: htmlContent , extension ="html" } of rawContent){ + content.push({ + content: htmlContent, + extension + }); + } + return content; + }, + getContext ({ createContext , cliConfigPath , root , result , content }) { + _sharedState.env.DEBUG && console.time("Searching for config"); + var _findAtConfigPath1; + let configPath = (_findAtConfigPath1 = (0, _findAtConfigPath.findAtConfigPath)(root, result)) !== null && _findAtConfigPath1 !== void 0 ? _findAtConfigPath1 : cliConfigPath; + _sharedState.env.DEBUG && console.timeEnd("Searching for config"); + if (this.context) { + this.context.changedContent = this.changedContent.splice(0); + return this.context; + } + _sharedState.env.DEBUG && console.time("Loading config"); + let config = this.loadConfig(configPath, content); + _sharedState.env.DEBUG && console.timeEnd("Loading config"); + _sharedState.env.DEBUG && console.time("Creating context"); + this.context = createContext(config, []); + Object.assign(this.context, { + userConfigPath: configPath + }); + _sharedState.env.DEBUG && console.timeEnd("Creating context"); + _sharedState.env.DEBUG && console.time("Resolving content paths"); + this.refreshContentPaths(); + _sharedState.env.DEBUG && console.timeEnd("Resolving content paths"); + if (this.watcher) { + _sharedState.env.DEBUG && console.time("Watch new files"); + this.watcher.refreshWatchedFiles(); + _sharedState.env.DEBUG && console.timeEnd("Watch new files"); + } + for (let file of this.readContentPaths()){ + this.context.changedContent.push(file); + } + return this.context; + } +}; +async function createProcessor(args, cliConfigPath) { + var _args_content; + let postcss = (0, _deps.loadPostcss)(); + let input = args["--input"]; + let output = args["--output"]; + let includePostCss = args["--postcss"]; + let customPostCssPath = typeof args["--postcss"] === "string" ? args["--postcss"] : undefined; + let [beforePlugins, afterPlugins, postcssOptions] = includePostCss ? await loadPostCssPlugins(customPostCssPath) : loadBuiltinPostcssPlugins(); + if (args["--purge"]) { + _log.default.warn("purge-flag-deprecated", [ + "The `--purge` flag has been deprecated.", + "Please use `--content` instead." + ]); + if (!args["--content"]) { + args["--content"] = args["--purge"]; + } + } + var _args_content_split; + let content = (_args_content_split = (_args_content = args["--content"]) === null || _args_content === void 0 ? void 0 : _args_content.split(/(?{ + return { + postcssPlugin: "tailwindcss", + async Once (root, { result }) { + _sharedState.env.DEBUG && console.time("Compiling CSS"); + await (0, _processTailwindFeatures.default)(({ createContext })=>{ + console.error(); + console.error("Rebuilding..."); + return ()=>{ + return state.getContext({ + createContext, + cliConfigPath, + root, + result, + content + }); + }; + })(root, result); + _sharedState.env.DEBUG && console.timeEnd("Compiling CSS"); + } + }; + }; + tailwindPlugin.postcss = true; + let plugins = [ + ...beforePlugins, + tailwindPlugin, + !args["--minify"] && _utils.formatNodes, + ...afterPlugins, + !args["--no-autoprefixer"] && (0, _deps.loadAutoprefixer)(), + args["--minify"] && (0, _deps.loadCssNano)() + ].filter(Boolean); + /** @type {import('postcss').Processor} */ // @ts-ignore + let processor = postcss(plugins); + async function readInput() { + // Piping in data, let's drain the stdin + if (input === "-") { + return (0, _utils.drainStdin)(); + } + // Input file has been provided + if (input) { + return _fs.default.promises.readFile(_path.default.resolve(input), "utf8"); + } + // No input file provided, fallback to default at-rules + return "@tailwind base; @tailwind components; @tailwind utilities"; + } + async function build() { + let start = process.hrtime.bigint(); + return readInput().then((css)=>processor.process(css, { + ...postcssOptions, + from: input, + to: output + })).then((result)=>{ + if (!state.watcher) { + return result; + } + _sharedState.env.DEBUG && console.time("Recording PostCSS dependencies"); + for (let message of result.messages){ + if (message.type === "dependency") { + state.contextDependencies.add(message.file); + } + } + _sharedState.env.DEBUG && console.timeEnd("Recording PostCSS dependencies"); + // TODO: This needs to be in a different spot + _sharedState.env.DEBUG && console.time("Watch new files"); + state.watcher.refreshWatchedFiles(); + _sharedState.env.DEBUG && console.timeEnd("Watch new files"); + return result; + }).then((result)=>{ + if (!output) { + process.stdout.write(result.css); + return; + } + return Promise.all([ + (0, _utils.outputFile)(result.opts.to, result.css), + result.map && (0, _utils.outputFile)(result.opts.to + ".map", result.map.toString()) + ]); + }).then(()=>{ + let end = process.hrtime.bigint(); + console.error(); + console.error("Done in", (end - start) / BigInt(1e6) + "ms."); + }).then(()=>{}, (err)=>{ + // TODO: If an initial build fails we can't easily pick up any PostCSS dependencies + // that were collected before the error occurred + // The result is not stored on the error so we have to store it externally + // and pull the messages off of it here somehow + // This results in a less than ideal DX because the watcher will not pick up + // changes to imported CSS if one of them caused an error during the initial build + // If you fix it and then save the main CSS file so there's no error + // The watcher will start watching the imported CSS files and will be + // resilient to future errors. + if (state.watcher) { + console.error(err); + } else { + return Promise.reject(err); + } + }); + } + /** + * @param {{file: string, content(): Promise, extension: string}[]} changes + */ async function parseChanges(changes) { + return Promise.all(changes.map(async (change)=>({ + content: await change.content(), + extension: change.extension + }))); + } + if (input !== undefined && input !== "-") { + state.contextDependencies.add(_path.default.resolve(input)); + } + return { + build, + watch: async ()=>{ + state.watcher = (0, _watching.createWatcher)(args, { + state, + /** + * @param {{file: string, content(): Promise, extension: string}[]} changes + */ async rebuild (changes) { + let needsNewContext = changes.some((change)=>{ + var _state_configBag; + return ((_state_configBag = state.configBag) === null || _state_configBag === void 0 ? void 0 : _state_configBag.dependencies.has(change.file)) || state.contextDependencies.has(change.file); + }); + if (needsNewContext) { + state.context = null; + } else { + for (let change of (await parseChanges(changes))){ + state.changedContent.push(change); + } + } + return build(); + } + }); + await build(); + } + }; +} diff --git a/node_modules/tailwindcss/lib/cli/build/utils.js b/node_modules/tailwindcss/lib/cli/build/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..3bed06041d7abf44044256b5fc2a807b8205587f --- /dev/null +++ b/node_modules/tailwindcss/lib/cli/build/utils.js @@ -0,0 +1,88 @@ +// @ts-check +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + indentRecursive: function() { + return indentRecursive; + }, + formatNodes: function() { + return formatNodes; + }, + readFileWithRetries: function() { + return readFileWithRetries; + }, + drainStdin: function() { + return drainStdin; + }, + outputFile: function() { + return outputFile; + } +}); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function indentRecursive(node, indent = 0) { + node.each && node.each((child, i)=>{ + if (!child.raws.before || !child.raws.before.trim() || child.raws.before.includes("\n")) { + child.raws.before = `\n${node.type !== "rule" && i > 0 ? "\n" : ""}${" ".repeat(indent)}`; + } + child.raws.after = `\n${" ".repeat(indent)}`; + indentRecursive(child, indent + 1); + }); +} +function formatNodes(root) { + indentRecursive(root); + if (root.first) { + root.first.raws.before = ""; + } +} +async function readFileWithRetries(path, tries = 5) { + for(let n = 0; n <= tries; n++){ + try { + return await _fs.default.promises.readFile(path, "utf8"); + } catch (err) { + if (n !== tries) { + if (err.code === "ENOENT" || err.code === "EBUSY") { + await new Promise((resolve)=>setTimeout(resolve, 10)); + continue; + } + } + throw err; + } + } +} +function drainStdin() { + return new Promise((resolve, reject)=>{ + let result = ""; + process.stdin.on("data", (chunk)=>{ + result += chunk; + }); + process.stdin.on("end", ()=>resolve(result)); + process.stdin.on("error", (err)=>reject(err)); + }); +} +async function outputFile(file, newContents) { + try { + let currentContents = await _fs.default.promises.readFile(file, "utf8"); + if (currentContents === newContents) { + return; // Skip writing the file + } + } catch {} + // Write the file + await _fs.default.promises.mkdir(_path.default.dirname(file), { + recursive: true + }); + await _fs.default.promises.writeFile(file, newContents, "utf8"); +} diff --git a/node_modules/tailwindcss/lib/cli/build/watching.js b/node_modules/tailwindcss/lib/cli/build/watching.js new file mode 100644 index 0000000000000000000000000000000000000000..83639bdcb0bdb961f722657e587ab719f384d435 --- /dev/null +++ b/node_modules/tailwindcss/lib/cli/build/watching.js @@ -0,0 +1,182 @@ +// @ts-check +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "createWatcher", { + enumerable: true, + get: function() { + return createWatcher; + } +}); +const _chokidar = /*#__PURE__*/ _interop_require_default(require("chokidar")); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _micromatch = /*#__PURE__*/ _interop_require_default(require("micromatch")); +const _normalizepath = /*#__PURE__*/ _interop_require_default(require("normalize-path")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _utils = require("./utils.js"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function createWatcher(args, { state , rebuild }) { + let shouldPoll = args["--poll"]; + let shouldCoalesceWriteEvents = shouldPoll || process.platform === "win32"; + // Polling interval in milliseconds + // Used only when polling or coalescing add/change events on Windows + let pollInterval = 10; + let watcher = _chokidar.default.watch([], { + // Force checking for atomic writes in all situations + // This causes chokidar to wait up to 100ms for a file to re-added after it's been unlinked + // This only works when watching directories though + atomic: true, + usePolling: shouldPoll, + interval: shouldPoll ? pollInterval : undefined, + ignoreInitial: true, + awaitWriteFinish: shouldCoalesceWriteEvents ? { + stabilityThreshold: 50, + pollInterval: pollInterval + } : false + }); + // A queue of rebuilds, file reads, etc… to run + let chain = Promise.resolve(); + /** + * A list of files that have been changed since the last rebuild + * + * @type {{file: string, content: () => Promise, extension: string}[]} + */ let changedContent = []; + /** + * A list of files for which a rebuild has already been queued. + * This is used to prevent duplicate rebuilds when multiple events are fired for the same file. + * The rebuilt file is cleared from this list when it's associated rebuild has _started_ + * This is because if the file is changed during a rebuild it won't trigger a new rebuild which it should + **/ let pendingRebuilds = new Set(); + let _timer; + let _reject; + /** + * Rebuilds the changed files and resolves when the rebuild is + * complete regardless of whether it was successful or not + */ async function rebuildAndContinue() { + let changes = changedContent.splice(0); + // There are no changes to rebuild so we can just do nothing + if (changes.length === 0) { + return Promise.resolve(); + } + // Clear all pending rebuilds for the about-to-be-built files + changes.forEach((change)=>pendingRebuilds.delete(change.file)); + // Resolve the promise even when the rebuild fails + return rebuild(changes).then(()=>{}, (e)=>{ + console.error(e.toString()); + }); + } + /** + * + * @param {*} file + * @param {(() => Promise) | null} content + * @param {boolean} skipPendingCheck + * @returns {Promise} + */ function recordChangedFile(file, content = null, skipPendingCheck = false) { + file = _path.default.resolve(file); + // Applications like Vim/Neovim fire both rename and change events in succession for atomic writes + // In that case rebuild has already been queued by rename, so can be skipped in change + if (pendingRebuilds.has(file) && !skipPendingCheck) { + return Promise.resolve(); + } + // Mark that a rebuild of this file is going to happen + // It MUST happen synchronously before the rebuild is queued for this to be effective + pendingRebuilds.add(file); + changedContent.push({ + file, + content: content !== null && content !== void 0 ? content : ()=>_fs.default.promises.readFile(file, "utf8"), + extension: _path.default.extname(file).slice(1) + }); + if (_timer) { + clearTimeout(_timer); + _reject(); + } + // If a rebuild is already in progress we don't want to start another one until the 10ms timer has expired + chain = chain.then(()=>new Promise((resolve, reject)=>{ + _timer = setTimeout(resolve, 10); + _reject = reject; + })); + // Resolves once this file has been rebuilt (or the rebuild for this file has failed) + // This queues as many rebuilds as there are changed files + // But those rebuilds happen after some delay + // And will immediately resolve if there are no changes + chain = chain.then(rebuildAndContinue, rebuildAndContinue); + return chain; + } + watcher.on("change", (file)=>recordChangedFile(file)); + watcher.on("add", (file)=>recordChangedFile(file)); + // Restore watching any files that are "removed" + // This can happen when a file is pseudo-atomically replaced (a copy is created, overwritten, the old one is unlinked, and the new one is renamed) + // TODO: An an optimization we should allow removal when the config changes + watcher.on("unlink", (file)=>{ + file = (0, _normalizepath.default)(file); + // Only re-add the file if it's not covered by a dynamic pattern + if (!_micromatch.default.some([ + file + ], state.contentPatterns.dynamic)) { + watcher.add(file); + } + }); + // Some applications such as Visual Studio (but not VS Code) + // will only fire a rename event for atomic writes and not a change event + // This is very likely a chokidar bug but it's one we need to work around + // We treat this as a change event and rebuild the CSS + watcher.on("raw", (evt, filePath, meta)=>{ + if (evt !== "rename" || filePath === null) { + return; + } + let watchedPath = meta.watchedPath; + // Watched path might be the file itself + // Or the directory it is in + filePath = watchedPath.endsWith(filePath) ? watchedPath : _path.default.join(watchedPath, filePath); + // Skip this event since the files it is for does not match any of the registered content globs + if (!_micromatch.default.some([ + filePath + ], state.contentPatterns.all)) { + return; + } + // Skip since we've already queued a rebuild for this file that hasn't happened yet + if (pendingRebuilds.has(filePath)) { + return; + } + // We'll go ahead and add the file to the pending rebuilds list here + // It'll be removed when the rebuild starts unless the read fails + // which will be taken care of as well + pendingRebuilds.add(filePath); + async function enqueue() { + try { + // We need to read the file as early as possible outside of the chain + // because it may be gone by the time we get to it. doing the read + // immediately increases the chance that the file is still there + let content = await (0, _utils.readFileWithRetries)(_path.default.resolve(filePath)); + if (content === undefined) { + return; + } + // This will push the rebuild onto the chain + // We MUST skip the rebuild check here otherwise the rebuild will never happen on Linux + // This is because the order of events and timing is different on Linux + // @ts-ignore: TypeScript isn't picking up that content is a string here + await recordChangedFile(filePath, ()=>content, true); + } catch { + // If reading the file fails, it's was probably a deleted temporary file + // So we can ignore it and no rebuild is needed + } + } + enqueue().then(()=>{ + // If the file read fails we still need to make sure the file isn't stuck in the pending rebuilds list + pendingRebuilds.delete(filePath); + }); + }); + return { + fswatcher: watcher, + refreshWatchedFiles () { + watcher.add(Array.from(state.contextDependencies)); + watcher.add(Array.from(state.configBag.dependencies)); + watcher.add(state.contentPatterns.all); + } + }; +} diff --git a/node_modules/tailwindcss/lib/cli/help/index.js b/node_modules/tailwindcss/lib/cli/help/index.js new file mode 100644 index 0000000000000000000000000000000000000000..030997fab28d0f2b570f43898f1fd9c74b7486a9 --- /dev/null +++ b/node_modules/tailwindcss/lib/cli/help/index.js @@ -0,0 +1,73 @@ +// @ts-check +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "help", { + enumerable: true, + get: function() { + return help; + } +}); +const _packagejson = /*#__PURE__*/ _interop_require_default(require("../../../package.json")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function help({ message , usage , commands , options }) { + let indent = 2; + // Render header + console.log(); + console.log(`${_packagejson.default.name} v${_packagejson.default.version}`); + // Render message + if (message) { + console.log(); + for (let msg of message.split("\n")){ + console.log(msg); + } + } + // Render usage + if (usage && usage.length > 0) { + console.log(); + console.log("Usage:"); + for (let example of usage){ + console.log(" ".repeat(indent), example); + } + } + // Render commands + if (commands && commands.length > 0) { + console.log(); + console.log("Commands:"); + for (let command of commands){ + console.log(" ".repeat(indent), command); + } + } + // Render options + if (options) { + let groupedOptions = {}; + for (let [key, value] of Object.entries(options)){ + if (typeof value === "object") { + groupedOptions[key] = { + ...value, + flags: [ + key + ] + }; + } else { + groupedOptions[value].flags.push(key); + } + } + console.log(); + console.log("Options:"); + for (let { flags , description , deprecated } of Object.values(groupedOptions)){ + if (deprecated) continue; + if (flags.length === 1) { + console.log(" ".repeat(indent + 4 /* 4 = "-i, ".length */ ), flags.slice().reverse().join(", ").padEnd(20, " "), description); + } else { + console.log(" ".repeat(indent), flags.slice().reverse().join(", ").padEnd(24, " "), description); + } + } + } + console.log(); +} diff --git a/node_modules/tailwindcss/lib/cli/index.js b/node_modules/tailwindcss/lib/cli/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e6e2e27c78fea167c19fcdada6a2e8d4065e27ca --- /dev/null +++ b/node_modules/tailwindcss/lib/cli/index.js @@ -0,0 +1,230 @@ +#!/usr/bin/env node +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _arg = /*#__PURE__*/ _interop_require_default(require("arg")); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _build = require("./build"); +const _help = require("./help"); +const _init = require("./init"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function oneOf(...options) { + return Object.assign((value = true)=>{ + for (let option of options){ + let parsed = option(value); + if (parsed === value) { + return parsed; + } + } + throw new Error("..."); + }, { + manualParsing: true + }); +} +let commands = { + init: { + run: _init.init, + args: { + "--esm": { + type: Boolean, + description: `Initialize configuration file as ESM` + }, + "--ts": { + type: Boolean, + description: `Initialize configuration file as TypeScript` + }, + "--postcss": { + type: Boolean, + description: `Initialize a \`postcss.config.js\` file` + }, + "--full": { + type: Boolean, + description: `Include the default values for all options in the generated configuration file` + }, + "-f": "--full", + "-p": "--postcss" + } + }, + build: { + run: _build.build, + args: { + "--input": { + type: String, + description: "Input file" + }, + "--output": { + type: String, + description: "Output file" + }, + "--watch": { + type: oneOf(String, Boolean), + description: "Watch for changes and rebuild as needed" + }, + "--poll": { + type: Boolean, + description: "Use polling instead of filesystem events when watching" + }, + "--content": { + type: String, + description: "Content paths to use for removing unused classes" + }, + "--purge": { + type: String, + deprecated: true + }, + "--postcss": { + type: oneOf(String, Boolean), + description: "Load custom PostCSS configuration" + }, + "--minify": { + type: Boolean, + description: "Minify the output" + }, + "--config": { + type: String, + description: "Path to a custom config file" + }, + "--no-autoprefixer": { + type: Boolean, + description: "Disable autoprefixer" + }, + "-c": "--config", + "-i": "--input", + "-o": "--output", + "-m": "--minify", + "-w": "--watch", + "-p": "--poll" + } + } +}; +let sharedFlags = { + "--help": { + type: Boolean, + description: "Display usage information" + }, + "-h": "--help" +}; +if (process.stdout.isTTY /* Detect redirecting output to a file */ && (process.argv[2] === undefined || process.argv.slice(2).every((flag)=>sharedFlags[flag] !== undefined))) { + (0, _help.help)({ + usage: [ + "tailwindcss [--input input.css] [--output output.css] [--watch] [options...]", + "tailwindcss init [--full] [--postcss] [options...]" + ], + commands: Object.keys(commands).filter((command)=>command !== "build").map((command)=>`${command} [options]`), + options: { + ...commands.build.args, + ...sharedFlags + } + }); + process.exit(0); +} +let command = ((arg = "")=>arg.startsWith("-") ? undefined : arg)(process.argv[2]) || "build"; +if (commands[command] === undefined) { + if (_fs.default.existsSync(_path.default.resolve(command))) { + // TODO: Deprecate this in future versions + // Check if non-existing command, might be a file. + command = "build"; + } else { + (0, _help.help)({ + message: `Invalid command: ${command}`, + usage: [ + "tailwindcss [options]" + ], + commands: Object.keys(commands).filter((command)=>command !== "build").map((command)=>`${command} [options]`), + options: sharedFlags + }); + process.exit(1); + } +} +// Execute command +let { args: flags , run } = commands[command]; +let args = (()=>{ + try { + let result = (0, _arg.default)(Object.fromEntries(Object.entries({ + ...flags, + ...sharedFlags + }).filter(([_key, value])=>{ + var _value_type; + return !(value === null || value === void 0 ? void 0 : (_value_type = value.type) === null || _value_type === void 0 ? void 0 : _value_type.manualParsing); + }).map(([key, value])=>[ + key, + typeof value === "object" ? value.type : value + ])), { + permissive: true + }); + // Manual parsing of flags to allow for special flags like oneOf(Boolean, String) + for(let i = result["_"].length - 1; i >= 0; --i){ + let flag = result["_"][i]; + if (!flag.startsWith("-")) continue; + let [flagName, flagValue] = flag.split("="); + let handler = flags[flagName]; + // Resolve flagName & handler + while(typeof handler === "string"){ + flagName = handler; + handler = flags[handler]; + } + if (!handler) continue; + let args = []; + let offset = i + 1; + // --flag value syntax was used so we need to pull `value` from `args` + if (flagValue === undefined) { + // Parse args for current flag + while(result["_"][offset] && !result["_"][offset].startsWith("-")){ + args.push(result["_"][offset++]); + } + // Cleanup manually parsed flags + args + result["_"].splice(i, 1 + args.length); + // No args were provided, use default value defined in handler + // One arg was provided, use that directly + // Multiple args were provided so pass them all in an array + flagValue = args.length === 0 ? undefined : args.length === 1 ? args[0] : args; + } else { + // Remove the whole flag from the args array + result["_"].splice(i, 1); + } + // Set the resolved value in the `result` object + result[flagName] = handler.type(flagValue, flagName); + } + // Ensure that the `command` is always the first argument in the `args`. + // This is important so that we don't have to check if a default command + // (build) was used or not from within each plugin. + // + // E.g.: tailwindcss input.css -> _: ['build', 'input.css'] + // E.g.: tailwindcss build input.css -> _: ['build', 'input.css'] + if (result["_"][0] !== command) { + result["_"].unshift(command); + } + return result; + } catch (err) { + if (err.code === "ARG_UNKNOWN_OPTION") { + (0, _help.help)({ + message: err.message, + usage: [ + "tailwindcss [options]" + ], + options: sharedFlags + }); + process.exit(1); + } + throw err; + } +})(); +if (args["--help"]) { + (0, _help.help)({ + options: { + ...flags, + ...sharedFlags + }, + usage: [ + `tailwindcss ${command} [options]` + ] + }); + process.exit(0); +} +run(args); diff --git a/node_modules/tailwindcss/lib/cli/init/index.js b/node_modules/tailwindcss/lib/cli/init/index.js new file mode 100644 index 0000000000000000000000000000000000000000..47caf30abcbd11043b2f8f1f36893e5e51271552 --- /dev/null +++ b/node_modules/tailwindcss/lib/cli/init/index.js @@ -0,0 +1,63 @@ +// @ts-check +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "init", { + enumerable: true, + get: function() { + return init; + } +}); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function isESM() { + const pkgPath = _path.default.resolve("./package.json"); + try { + let pkg = JSON.parse(_fs.default.readFileSync(pkgPath, "utf8")); + return pkg.type && pkg.type === "module"; + } catch (err) { + return false; + } +} +function init(args) { + let messages = []; + let isProjectESM = args["--ts"] || args["--esm"] || isESM(); + let syntax = args["--ts"] ? "ts" : isProjectESM ? "js" : "cjs"; + let extension = args["--ts"] ? "ts" : "js"; + var _args___; + let tailwindConfigLocation = _path.default.resolve((_args___ = args["_"][1]) !== null && _args___ !== void 0 ? _args___ : `./tailwind.config.${extension}`); + if (_fs.default.existsSync(tailwindConfigLocation)) { + messages.push(`${_path.default.basename(tailwindConfigLocation)} already exists.`); + } else { + let stubContentsFile = _fs.default.readFileSync(args["--full"] ? _path.default.resolve(__dirname, "../../../stubs/config.full.js") : _path.default.resolve(__dirname, "../../../stubs/config.simple.js"), "utf8"); + let stubFile = _fs.default.readFileSync(_path.default.resolve(__dirname, `../../../stubs/tailwind.config.${syntax}`), "utf8"); + // Change colors import + stubContentsFile = stubContentsFile.replace("../colors", "tailwindcss/colors"); + // Replace contents of {ts,js,cjs} file with the stub {simple,full}. + stubFile = stubFile.replace("__CONFIG__", stubContentsFile.replace("module.exports =", "").trim()).trim() + "\n\n"; + _fs.default.writeFileSync(tailwindConfigLocation, stubFile, "utf8"); + messages.push(`Created Tailwind CSS config file: ${_path.default.basename(tailwindConfigLocation)}`); + } + if (args["--postcss"]) { + let postcssConfigLocation = _path.default.resolve("./postcss.config.js"); + if (_fs.default.existsSync(postcssConfigLocation)) { + messages.push(`${_path.default.basename(postcssConfigLocation)} already exists.`); + } else { + let stubFile = _fs.default.readFileSync(isProjectESM ? _path.default.resolve(__dirname, "../../../stubs/postcss.config.js") : _path.default.resolve(__dirname, "../../../stubs/postcss.config.cjs"), "utf8"); + _fs.default.writeFileSync(postcssConfigLocation, stubFile, "utf8"); + messages.push(`Created PostCSS config file: ${_path.default.basename(postcssConfigLocation)}`); + } + } + if (messages.length > 0) { + console.log(); + for (let message of messages){ + console.log(message); + } + } +} diff --git a/node_modules/tailwindcss/lib/corePluginList.js b/node_modules/tailwindcss/lib/corePluginList.js new file mode 100644 index 0000000000000000000000000000000000000000..552934bd13a63eab0bf8173625e25b6520598ccf --- /dev/null +++ b/node_modules/tailwindcss/lib/corePluginList.js @@ -0,0 +1,191 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _default = [ + "preflight", + "container", + "accessibility", + "pointerEvents", + "visibility", + "position", + "inset", + "isolation", + "zIndex", + "order", + "gridColumn", + "gridColumnStart", + "gridColumnEnd", + "gridRow", + "gridRowStart", + "gridRowEnd", + "float", + "clear", + "margin", + "boxSizing", + "lineClamp", + "display", + "aspectRatio", + "size", + "height", + "maxHeight", + "minHeight", + "width", + "minWidth", + "maxWidth", + "flex", + "flexShrink", + "flexGrow", + "flexBasis", + "tableLayout", + "captionSide", + "borderCollapse", + "borderSpacing", + "transformOrigin", + "translate", + "rotate", + "skew", + "scale", + "transform", + "animation", + "cursor", + "touchAction", + "userSelect", + "resize", + "scrollSnapType", + "scrollSnapAlign", + "scrollSnapStop", + "scrollMargin", + "scrollPadding", + "listStylePosition", + "listStyleType", + "listStyleImage", + "appearance", + "columns", + "breakBefore", + "breakInside", + "breakAfter", + "gridAutoColumns", + "gridAutoFlow", + "gridAutoRows", + "gridTemplateColumns", + "gridTemplateRows", + "flexDirection", + "flexWrap", + "placeContent", + "placeItems", + "alignContent", + "alignItems", + "justifyContent", + "justifyItems", + "gap", + "space", + "divideWidth", + "divideStyle", + "divideColor", + "divideOpacity", + "placeSelf", + "alignSelf", + "justifySelf", + "overflow", + "overscrollBehavior", + "scrollBehavior", + "textOverflow", + "hyphens", + "whitespace", + "textWrap", + "wordBreak", + "borderRadius", + "borderWidth", + "borderStyle", + "borderColor", + "borderOpacity", + "backgroundColor", + "backgroundOpacity", + "backgroundImage", + "gradientColorStops", + "boxDecorationBreak", + "backgroundSize", + "backgroundAttachment", + "backgroundClip", + "backgroundPosition", + "backgroundRepeat", + "backgroundOrigin", + "fill", + "stroke", + "strokeWidth", + "objectFit", + "objectPosition", + "padding", + "textAlign", + "textIndent", + "verticalAlign", + "fontFamily", + "fontSize", + "fontWeight", + "textTransform", + "fontStyle", + "fontVariantNumeric", + "lineHeight", + "letterSpacing", + "textColor", + "textOpacity", + "textDecoration", + "textDecorationColor", + "textDecorationStyle", + "textDecorationThickness", + "textUnderlineOffset", + "fontSmoothing", + "placeholderColor", + "placeholderOpacity", + "caretColor", + "accentColor", + "opacity", + "backgroundBlendMode", + "mixBlendMode", + "boxShadow", + "boxShadowColor", + "outlineStyle", + "outlineWidth", + "outlineOffset", + "outlineColor", + "ringWidth", + "ringColor", + "ringOpacity", + "ringOffsetWidth", + "ringOffsetColor", + "blur", + "brightness", + "contrast", + "dropShadow", + "grayscale", + "hueRotate", + "invert", + "saturate", + "sepia", + "filter", + "backdropBlur", + "backdropBrightness", + "backdropContrast", + "backdropGrayscale", + "backdropHueRotate", + "backdropInvert", + "backdropOpacity", + "backdropSaturate", + "backdropSepia", + "backdropFilter", + "transitionProperty", + "transitionDelay", + "transitionDuration", + "transitionTimingFunction", + "willChange", + "contain", + "content", + "forcedColorAdjust" +]; diff --git a/node_modules/tailwindcss/lib/corePlugins.js b/node_modules/tailwindcss/lib/corePlugins.js new file mode 100644 index 0000000000000000000000000000000000000000..bf5d0835e3e6839faa47ca7314b4a4a901ca2a36 --- /dev/null +++ b/node_modules/tailwindcss/lib/corePlugins.js @@ -0,0 +1,4339 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + variantPlugins: function() { + return variantPlugins; + }, + corePlugins: function() { + return corePlugins; + } +}); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _path = /*#__PURE__*/ _interop_require_wildcard(require("path")); +const _postcss = /*#__PURE__*/ _interop_require_default(require("postcss")); +const _createUtilityPlugin = /*#__PURE__*/ _interop_require_default(require("./util/createUtilityPlugin")); +const _buildMediaQuery = /*#__PURE__*/ _interop_require_default(require("./util/buildMediaQuery")); +const _escapeClassName = /*#__PURE__*/ _interop_require_default(require("./util/escapeClassName")); +const _parseAnimationValue = /*#__PURE__*/ _interop_require_default(require("./util/parseAnimationValue")); +const _flattenColorPalette = /*#__PURE__*/ _interop_require_default(require("./util/flattenColorPalette")); +const _withAlphaVariable = /*#__PURE__*/ _interop_require_wildcard(require("./util/withAlphaVariable")); +const _toColorValue = /*#__PURE__*/ _interop_require_default(require("./util/toColorValue")); +const _isPlainObject = /*#__PURE__*/ _interop_require_default(require("./util/isPlainObject")); +const _transformThemeValue = /*#__PURE__*/ _interop_require_default(require("./util/transformThemeValue")); +const _packagejson = require("../package.json"); +const _log = /*#__PURE__*/ _interop_require_default(require("./util/log")); +const _normalizeScreens = require("./util/normalizeScreens"); +const _parseBoxShadowValue = require("./util/parseBoxShadowValue"); +const _removeAlphaVariables = require("./util/removeAlphaVariables"); +const _featureFlags = require("./featureFlags"); +const _dataTypes = require("./util/dataTypes"); +const _setupContextUtils = require("./lib/setupContextUtils"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +let variantPlugins = { + childVariant: ({ addVariant })=>{ + addVariant("*", "& > *"); + }, + pseudoElementVariants: ({ addVariant })=>{ + addVariant("first-letter", "&::first-letter"); + addVariant("first-line", "&::first-line"); + addVariant("marker", [ + ({ container })=>{ + (0, _removeAlphaVariables.removeAlphaVariables)(container, [ + "--tw-text-opacity" + ]); + return "& *::marker"; + }, + ({ container })=>{ + (0, _removeAlphaVariables.removeAlphaVariables)(container, [ + "--tw-text-opacity" + ]); + return "&::marker"; + } + ]); + addVariant("selection", [ + "& *::selection", + "&::selection" + ]); + addVariant("file", "&::file-selector-button"); + addVariant("placeholder", "&::placeholder"); + addVariant("backdrop", "&::backdrop"); + addVariant("before", ({ container })=>{ + container.walkRules((rule)=>{ + let foundContent = false; + rule.walkDecls("content", ()=>{ + foundContent = true; + }); + if (!foundContent) { + rule.prepend(_postcss.default.decl({ + prop: "content", + value: "var(--tw-content)" + })); + } + }); + return "&::before"; + }); + addVariant("after", ({ container })=>{ + container.walkRules((rule)=>{ + let foundContent = false; + rule.walkDecls("content", ()=>{ + foundContent = true; + }); + if (!foundContent) { + rule.prepend(_postcss.default.decl({ + prop: "content", + value: "var(--tw-content)" + })); + } + }); + return "&::after"; + }); + }, + pseudoClassVariants: ({ addVariant , matchVariant , config , prefix })=>{ + let pseudoVariants = [ + // Positional + [ + "first", + "&:first-child" + ], + [ + "last", + "&:last-child" + ], + [ + "only", + "&:only-child" + ], + [ + "odd", + "&:nth-child(odd)" + ], + [ + "even", + "&:nth-child(even)" + ], + "first-of-type", + "last-of-type", + "only-of-type", + // State + [ + "visited", + ({ container })=>{ + (0, _removeAlphaVariables.removeAlphaVariables)(container, [ + "--tw-text-opacity", + "--tw-border-opacity", + "--tw-bg-opacity" + ]); + return "&:visited"; + } + ], + "target", + [ + "open", + "&[open]" + ], + // Forms + "default", + "checked", + "indeterminate", + "placeholder-shown", + "autofill", + "optional", + "required", + "valid", + "invalid", + "in-range", + "out-of-range", + "read-only", + // Content + "empty", + // Interactive + "focus-within", + [ + "hover", + !(0, _featureFlags.flagEnabled)(config(), "hoverOnlyWhenSupported") ? "&:hover" : "@media (hover: hover) and (pointer: fine) { &:hover }" + ], + "focus", + "focus-visible", + "active", + "enabled", + "disabled" + ].map((variant)=>Array.isArray(variant) ? variant : [ + variant, + `&:${variant}` + ]); + for (let [variantName, state] of pseudoVariants){ + addVariant(variantName, (ctx)=>{ + let result = typeof state === "function" ? state(ctx) : state; + return result; + }); + } + let variants = { + group: (_, { modifier })=>modifier ? [ + `:merge(${prefix(".group")}\\/${(0, _escapeClassName.default)(modifier)})`, + " &" + ] : [ + `:merge(${prefix(".group")})`, + " &" + ], + peer: (_, { modifier })=>modifier ? [ + `:merge(${prefix(".peer")}\\/${(0, _escapeClassName.default)(modifier)})`, + " ~ &" + ] : [ + `:merge(${prefix(".peer")})`, + " ~ &" + ] + }; + for (let [name, fn] of Object.entries(variants)){ + matchVariant(name, (value = "", extra)=>{ + let result = (0, _dataTypes.normalize)(typeof value === "function" ? value(extra) : value); + if (!result.includes("&")) result = "&" + result; + let [a, b] = fn("", extra); + let start = null; + let end = null; + let quotes = 0; + for(let i = 0; i < result.length; ++i){ + let c = result[i]; + if (c === "&") { + start = i; + } else if (c === "'" || c === '"') { + quotes += 1; + } else if (start !== null && c === " " && !quotes) { + end = i; + } + } + if (start !== null && end === null) { + end = result.length; + } + // Basically this but can handle quotes: + // result.replace(/&(\S+)?/g, (_, pseudo = '') => a + pseudo + b) + return result.slice(0, start) + a + result.slice(start + 1, end) + b + result.slice(end); + }, { + values: Object.fromEntries(pseudoVariants), + [_setupContextUtils.INTERNAL_FEATURES]: { + respectPrefix: false + } + }); + } + }, + directionVariants: ({ addVariant })=>{ + addVariant("ltr", '&:where([dir="ltr"], [dir="ltr"] *)'); + addVariant("rtl", '&:where([dir="rtl"], [dir="rtl"] *)'); + }, + reducedMotionVariants: ({ addVariant })=>{ + addVariant("motion-safe", "@media (prefers-reduced-motion: no-preference)"); + addVariant("motion-reduce", "@media (prefers-reduced-motion: reduce)"); + }, + darkVariants: ({ config , addVariant })=>{ + let [mode, selector = ".dark"] = [].concat(config("darkMode", "media")); + if (mode === false) { + mode = "media"; + _log.default.warn("darkmode-false", [ + "The `darkMode` option in your Tailwind CSS configuration is set to `false`, which now behaves the same as `media`.", + "Change `darkMode` to `media` or remove it entirely.", + "https://tailwindcss.com/docs/upgrade-guide#remove-dark-mode-configuration" + ]); + } + if (mode === "variant") { + let formats; + if (Array.isArray(selector)) { + formats = selector; + } else if (typeof selector === "function") { + formats = selector; + } else if (typeof selector === "string") { + formats = [ + selector + ]; + } + // TODO: We could also add these warnings if the user passes a function that returns string | string[] + // But this is an advanced enough use case that it's probably not necessary + if (Array.isArray(formats)) { + for (let format of formats){ + if (format === ".dark") { + mode = false; + _log.default.warn("darkmode-variant-without-selector", [ + "When using `variant` for `darkMode`, you must provide a selector.", + 'Example: `darkMode: ["variant", ".your-selector &"]`' + ]); + } else if (!format.includes("&")) { + mode = false; + _log.default.warn("darkmode-variant-without-ampersand", [ + "When using `variant` for `darkMode`, your selector must contain `&`.", + 'Example `darkMode: ["variant", ".your-selector &"]`' + ]); + } + } + } + selector = formats; + } + if (mode === "selector") { + // New preferred behavior + addVariant("dark", `&:where(${selector}, ${selector} *)`); + } else if (mode === "media") { + addVariant("dark", "@media (prefers-color-scheme: dark)"); + } else if (mode === "variant") { + addVariant("dark", selector); + } else if (mode === "class") { + // Old behavior + addVariant("dark", `&:is(${selector} *)`); + } + }, + printVariant: ({ addVariant })=>{ + addVariant("print", "@media print"); + }, + screenVariants: ({ theme , addVariant , matchVariant })=>{ + var _theme; + let rawScreens = (_theme = theme("screens")) !== null && _theme !== void 0 ? _theme : {}; + let areSimpleScreens = Object.values(rawScreens).every((v)=>typeof v === "string"); + let screens = (0, _normalizeScreens.normalizeScreens)(theme("screens")); + /** @type {Set} */ let unitCache = new Set([]); + /** @param {string} value */ function units(value) { + var _value_match; + var _value_match_; + return (_value_match_ = (_value_match = value.match(/(\D+)$/)) === null || _value_match === void 0 ? void 0 : _value_match[1]) !== null && _value_match_ !== void 0 ? _value_match_ : "(none)"; + } + /** @param {string} value */ function recordUnits(value) { + if (value !== undefined) { + unitCache.add(units(value)); + } + } + /** @param {string} value */ function canUseUnits(value) { + recordUnits(value); + // If the cache was empty it'll become 1 because we've just added the current unit + // If the cache was not empty and the units are the same the size doesn't change + // Otherwise, if the units are different from what is already known the size will always be > 1 + return unitCache.size === 1; + } + for (const screen of screens){ + for (const value of screen.values){ + recordUnits(value.min); + recordUnits(value.max); + } + } + let screensUseConsistentUnits = unitCache.size <= 1; + /** + * @typedef {import('./util/normalizeScreens').Screen} Screen + */ /** + * @param {'min' | 'max'} type + * @returns {Record} + */ function buildScreenValues(type) { + return Object.fromEntries(screens.filter((screen)=>(0, _normalizeScreens.isScreenSortable)(screen).result).map((screen)=>{ + let { min , max } = screen.values[0]; + if (type === "min" && min !== undefined) { + return screen; + } else if (type === "min" && max !== undefined) { + return { + ...screen, + not: !screen.not + }; + } else if (type === "max" && max !== undefined) { + return screen; + } else if (type === "max" && min !== undefined) { + return { + ...screen, + not: !screen.not + }; + } + }).map((screen)=>[ + screen.name, + screen + ])); + } + /** + * @param {'min' | 'max'} type + * @returns {(a: { value: string | Screen }, z: { value: string | Screen }) => number} + */ function buildSort(type) { + return (a, z)=>(0, _normalizeScreens.compareScreens)(type, a.value, z.value); + } + let maxSort = buildSort("max"); + let minSort = buildSort("min"); + /** @param {'min'|'max'} type */ function buildScreenVariant(type) { + return (value)=>{ + if (!areSimpleScreens) { + _log.default.warn("complex-screen-config", [ + "The `min-*` and `max-*` variants are not supported with a `screens` configuration containing objects." + ]); + return []; + } else if (!screensUseConsistentUnits) { + _log.default.warn("mixed-screen-units", [ + "The `min-*` and `max-*` variants are not supported with a `screens` configuration containing mixed units." + ]); + return []; + } else if (typeof value === "string" && !canUseUnits(value)) { + _log.default.warn("minmax-have-mixed-units", [ + "The `min-*` and `max-*` variants are not supported with a `screens` configuration containing mixed units." + ]); + return []; + } + return [ + `@media ${(0, _buildMediaQuery.default)((0, _normalizeScreens.toScreen)(value, type))}` + ]; + }; + } + matchVariant("max", buildScreenVariant("max"), { + sort: maxSort, + values: areSimpleScreens ? buildScreenValues("max") : {} + }); + // screens and min-* are sorted together when they can be + let id = "min-screens"; + for (let screen of screens){ + addVariant(screen.name, `@media ${(0, _buildMediaQuery.default)(screen)}`, { + id, + sort: areSimpleScreens && screensUseConsistentUnits ? minSort : undefined, + value: screen + }); + } + matchVariant("min", buildScreenVariant("min"), { + id, + sort: minSort + }); + }, + supportsVariants: ({ matchVariant , theme })=>{ + var _theme; + matchVariant("supports", (value = "")=>{ + let check = value.startsWith("--") ? value : (0, _dataTypes.normalize)(value); + let isRaw = /^[\w-]*\s*\(/.test(check); + // Chrome has a bug where `(condition1)or(condition2)` is not valid + // But `(condition1) or (condition2)` is supported. + check = isRaw ? check.replace(/\b(and|or|not)\b/g, " $1 ") : check; + if (isRaw) { + return `@supports ${check}`; + } + if (!check.includes(":")) { + check = `${check}: var(--tw)`; + } + if (!(check.startsWith("(") && check.endsWith(")"))) { + check = `(${check})`; + } + return `@supports ${check}`; + }, { + values: (_theme = theme("supports")) !== null && _theme !== void 0 ? _theme : {} + }); + }, + hasVariants: ({ matchVariant , prefix })=>{ + matchVariant("has", (value)=>`&:has(${(0, _dataTypes.normalize)(value)})`, { + values: {}, + [_setupContextUtils.INTERNAL_FEATURES]: { + respectPrefix: false + } + }); + matchVariant("group-has", (value, { modifier })=>modifier ? `:merge(${prefix(".group")}\\/${modifier}):has(${(0, _dataTypes.normalize)(value)}) &` : `:merge(${prefix(".group")}):has(${(0, _dataTypes.normalize)(value)}) &`, { + values: {}, + [_setupContextUtils.INTERNAL_FEATURES]: { + respectPrefix: false + } + }); + matchVariant("peer-has", (value, { modifier })=>modifier ? `:merge(${prefix(".peer")}\\/${modifier}):has(${(0, _dataTypes.normalize)(value)}) ~ &` : `:merge(${prefix(".peer")}):has(${(0, _dataTypes.normalize)(value)}) ~ &`, { + values: {}, + [_setupContextUtils.INTERNAL_FEATURES]: { + respectPrefix: false + } + }); + }, + ariaVariants: ({ matchVariant , theme })=>{ + var _theme; + matchVariant("aria", (value)=>`&[aria-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}]`, { + values: (_theme = theme("aria")) !== null && _theme !== void 0 ? _theme : {} + }); + var _theme1; + matchVariant("group-aria", (value, { modifier })=>modifier ? `:merge(.group\\/${modifier})[aria-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}] &` : `:merge(.group)[aria-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}] &`, { + values: (_theme1 = theme("aria")) !== null && _theme1 !== void 0 ? _theme1 : {} + }); + var _theme2; + matchVariant("peer-aria", (value, { modifier })=>modifier ? `:merge(.peer\\/${modifier})[aria-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}] ~ &` : `:merge(.peer)[aria-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}] ~ &`, { + values: (_theme2 = theme("aria")) !== null && _theme2 !== void 0 ? _theme2 : {} + }); + }, + dataVariants: ({ matchVariant , theme })=>{ + var _theme; + matchVariant("data", (value)=>`&[data-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}]`, { + values: (_theme = theme("data")) !== null && _theme !== void 0 ? _theme : {} + }); + var _theme1; + matchVariant("group-data", (value, { modifier })=>modifier ? `:merge(.group\\/${modifier})[data-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}] &` : `:merge(.group)[data-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}] &`, { + values: (_theme1 = theme("data")) !== null && _theme1 !== void 0 ? _theme1 : {} + }); + var _theme2; + matchVariant("peer-data", (value, { modifier })=>modifier ? `:merge(.peer\\/${modifier})[data-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}] ~ &` : `:merge(.peer)[data-${(0, _dataTypes.normalizeAttributeSelectors)((0, _dataTypes.normalize)(value))}] ~ &`, { + values: (_theme2 = theme("data")) !== null && _theme2 !== void 0 ? _theme2 : {} + }); + }, + orientationVariants: ({ addVariant })=>{ + addVariant("portrait", "@media (orientation: portrait)"); + addVariant("landscape", "@media (orientation: landscape)"); + }, + prefersContrastVariants: ({ addVariant })=>{ + addVariant("contrast-more", "@media (prefers-contrast: more)"); + addVariant("contrast-less", "@media (prefers-contrast: less)"); + }, + forcedColorsVariants: ({ addVariant })=>{ + addVariant("forced-colors", "@media (forced-colors: active)"); + } +}; +let cssTransformValue = [ + "translate(var(--tw-translate-x), var(--tw-translate-y))", + "rotate(var(--tw-rotate))", + "skewX(var(--tw-skew-x))", + "skewY(var(--tw-skew-y))", + "scaleX(var(--tw-scale-x))", + "scaleY(var(--tw-scale-y))" +].join(" "); +let cssFilterValue = [ + "var(--tw-blur)", + "var(--tw-brightness)", + "var(--tw-contrast)", + "var(--tw-grayscale)", + "var(--tw-hue-rotate)", + "var(--tw-invert)", + "var(--tw-saturate)", + "var(--tw-sepia)", + "var(--tw-drop-shadow)" +].join(" "); +let cssBackdropFilterValue = [ + "var(--tw-backdrop-blur)", + "var(--tw-backdrop-brightness)", + "var(--tw-backdrop-contrast)", + "var(--tw-backdrop-grayscale)", + "var(--tw-backdrop-hue-rotate)", + "var(--tw-backdrop-invert)", + "var(--tw-backdrop-opacity)", + "var(--tw-backdrop-saturate)", + "var(--tw-backdrop-sepia)" +].join(" "); +let corePlugins = { + preflight: ({ addBase })=>{ + let preflightStyles = _postcss.default.parse(_fs.default.readFileSync(_path.join(__dirname, "./css/preflight.css"), "utf8")); + addBase([ + _postcss.default.comment({ + text: `! tailwindcss v${_packagejson.version} | MIT License | https://tailwindcss.com` + }), + ...preflightStyles.nodes + ]); + }, + container: (()=>{ + function extractMinWidths(breakpoints = []) { + return breakpoints.flatMap((breakpoint)=>breakpoint.values.map((breakpoint)=>breakpoint.min)).filter((v)=>v !== undefined); + } + function mapMinWidthsToPadding(minWidths, screens, paddings) { + if (typeof paddings === "undefined") { + return []; + } + if (!(typeof paddings === "object" && paddings !== null)) { + return [ + { + screen: "DEFAULT", + minWidth: 0, + padding: paddings + } + ]; + } + let mapping = []; + if (paddings.DEFAULT) { + mapping.push({ + screen: "DEFAULT", + minWidth: 0, + padding: paddings.DEFAULT + }); + } + for (let minWidth of minWidths){ + for (let screen of screens){ + for (let { min } of screen.values){ + if (min === minWidth) { + mapping.push({ + minWidth, + padding: paddings[screen.name] + }); + } + } + } + } + return mapping; + } + return function({ addComponents , theme }) { + let screens = (0, _normalizeScreens.normalizeScreens)(theme("container.screens", theme("screens"))); + let minWidths = extractMinWidths(screens); + let paddings = mapMinWidthsToPadding(minWidths, screens, theme("container.padding")); + let generatePaddingFor = (minWidth)=>{ + let paddingConfig = paddings.find((padding)=>padding.minWidth === minWidth); + if (!paddingConfig) { + return {}; + } + return { + paddingRight: paddingConfig.padding, + paddingLeft: paddingConfig.padding + }; + }; + let atRules = Array.from(new Set(minWidths.slice().sort((a, z)=>parseInt(a) - parseInt(z)))).map((minWidth)=>({ + [`@media (min-width: ${minWidth})`]: { + ".container": { + "max-width": minWidth, + ...generatePaddingFor(minWidth) + } + } + })); + addComponents([ + { + ".container": Object.assign({ + width: "100%" + }, theme("container.center", false) ? { + marginRight: "auto", + marginLeft: "auto" + } : {}, generatePaddingFor(0)) + }, + ...atRules + ]); + }; + })(), + accessibility: ({ addUtilities })=>{ + addUtilities({ + ".sr-only": { + position: "absolute", + width: "1px", + height: "1px", + padding: "0", + margin: "-1px", + overflow: "hidden", + clip: "rect(0, 0, 0, 0)", + whiteSpace: "nowrap", + borderWidth: "0" + }, + ".not-sr-only": { + position: "static", + width: "auto", + height: "auto", + padding: "0", + margin: "0", + overflow: "visible", + clip: "auto", + whiteSpace: "normal" + } + }); + }, + pointerEvents: ({ addUtilities })=>{ + addUtilities({ + ".pointer-events-none": { + "pointer-events": "none" + }, + ".pointer-events-auto": { + "pointer-events": "auto" + } + }); + }, + visibility: ({ addUtilities })=>{ + addUtilities({ + ".visible": { + visibility: "visible" + }, + ".invisible": { + visibility: "hidden" + }, + ".collapse": { + visibility: "collapse" + } + }); + }, + position: ({ addUtilities })=>{ + addUtilities({ + ".static": { + position: "static" + }, + ".fixed": { + position: "fixed" + }, + ".absolute": { + position: "absolute" + }, + ".relative": { + position: "relative" + }, + ".sticky": { + position: "sticky" + } + }); + }, + inset: (0, _createUtilityPlugin.default)("inset", [ + [ + "inset", + [ + "inset" + ] + ], + [ + [ + "inset-x", + [ + "left", + "right" + ] + ], + [ + "inset-y", + [ + "top", + "bottom" + ] + ] + ], + [ + [ + "start", + [ + "inset-inline-start" + ] + ], + [ + "end", + [ + "inset-inline-end" + ] + ], + [ + "top", + [ + "top" + ] + ], + [ + "right", + [ + "right" + ] + ], + [ + "bottom", + [ + "bottom" + ] + ], + [ + "left", + [ + "left" + ] + ] + ] + ], { + supportsNegativeValues: true + }), + isolation: ({ addUtilities })=>{ + addUtilities({ + ".isolate": { + isolation: "isolate" + }, + ".isolation-auto": { + isolation: "auto" + } + }); + }, + zIndex: (0, _createUtilityPlugin.default)("zIndex", [ + [ + "z", + [ + "zIndex" + ] + ] + ], { + supportsNegativeValues: true + }), + order: (0, _createUtilityPlugin.default)("order", undefined, { + supportsNegativeValues: true + }), + gridColumn: (0, _createUtilityPlugin.default)("gridColumn", [ + [ + "col", + [ + "gridColumn" + ] + ] + ]), + gridColumnStart: (0, _createUtilityPlugin.default)("gridColumnStart", [ + [ + "col-start", + [ + "gridColumnStart" + ] + ] + ], { + supportsNegativeValues: true + }), + gridColumnEnd: (0, _createUtilityPlugin.default)("gridColumnEnd", [ + [ + "col-end", + [ + "gridColumnEnd" + ] + ] + ], { + supportsNegativeValues: true + }), + gridRow: (0, _createUtilityPlugin.default)("gridRow", [ + [ + "row", + [ + "gridRow" + ] + ] + ]), + gridRowStart: (0, _createUtilityPlugin.default)("gridRowStart", [ + [ + "row-start", + [ + "gridRowStart" + ] + ] + ], { + supportsNegativeValues: true + }), + gridRowEnd: (0, _createUtilityPlugin.default)("gridRowEnd", [ + [ + "row-end", + [ + "gridRowEnd" + ] + ] + ], { + supportsNegativeValues: true + }), + float: ({ addUtilities })=>{ + addUtilities({ + ".float-start": { + float: "inline-start" + }, + ".float-end": { + float: "inline-end" + }, + ".float-right": { + float: "right" + }, + ".float-left": { + float: "left" + }, + ".float-none": { + float: "none" + } + }); + }, + clear: ({ addUtilities })=>{ + addUtilities({ + ".clear-start": { + clear: "inline-start" + }, + ".clear-end": { + clear: "inline-end" + }, + ".clear-left": { + clear: "left" + }, + ".clear-right": { + clear: "right" + }, + ".clear-both": { + clear: "both" + }, + ".clear-none": { + clear: "none" + } + }); + }, + margin: (0, _createUtilityPlugin.default)("margin", [ + [ + "m", + [ + "margin" + ] + ], + [ + [ + "mx", + [ + "margin-left", + "margin-right" + ] + ], + [ + "my", + [ + "margin-top", + "margin-bottom" + ] + ] + ], + [ + [ + "ms", + [ + "margin-inline-start" + ] + ], + [ + "me", + [ + "margin-inline-end" + ] + ], + [ + "mt", + [ + "margin-top" + ] + ], + [ + "mr", + [ + "margin-right" + ] + ], + [ + "mb", + [ + "margin-bottom" + ] + ], + [ + "ml", + [ + "margin-left" + ] + ] + ] + ], { + supportsNegativeValues: true + }), + boxSizing: ({ addUtilities })=>{ + addUtilities({ + ".box-border": { + "box-sizing": "border-box" + }, + ".box-content": { + "box-sizing": "content-box" + } + }); + }, + lineClamp: ({ matchUtilities , addUtilities , theme })=>{ + matchUtilities({ + "line-clamp": (value)=>({ + overflow: "hidden", + display: "-webkit-box", + "-webkit-box-orient": "vertical", + "-webkit-line-clamp": `${value}` + }) + }, { + values: theme("lineClamp") + }); + addUtilities({ + ".line-clamp-none": { + overflow: "visible", + display: "block", + "-webkit-box-orient": "horizontal", + "-webkit-line-clamp": "none" + } + }); + }, + display: ({ addUtilities })=>{ + addUtilities({ + ".block": { + display: "block" + }, + ".inline-block": { + display: "inline-block" + }, + ".inline": { + display: "inline" + }, + ".flex": { + display: "flex" + }, + ".inline-flex": { + display: "inline-flex" + }, + ".table": { + display: "table" + }, + ".inline-table": { + display: "inline-table" + }, + ".table-caption": { + display: "table-caption" + }, + ".table-cell": { + display: "table-cell" + }, + ".table-column": { + display: "table-column" + }, + ".table-column-group": { + display: "table-column-group" + }, + ".table-footer-group": { + display: "table-footer-group" + }, + ".table-header-group": { + display: "table-header-group" + }, + ".table-row-group": { + display: "table-row-group" + }, + ".table-row": { + display: "table-row" + }, + ".flow-root": { + display: "flow-root" + }, + ".grid": { + display: "grid" + }, + ".inline-grid": { + display: "inline-grid" + }, + ".contents": { + display: "contents" + }, + ".list-item": { + display: "list-item" + }, + ".hidden": { + display: "none" + } + }); + }, + aspectRatio: (0, _createUtilityPlugin.default)("aspectRatio", [ + [ + "aspect", + [ + "aspect-ratio" + ] + ] + ]), + size: (0, _createUtilityPlugin.default)("size", [ + [ + "size", + [ + "width", + "height" + ] + ] + ]), + height: (0, _createUtilityPlugin.default)("height", [ + [ + "h", + [ + "height" + ] + ] + ]), + maxHeight: (0, _createUtilityPlugin.default)("maxHeight", [ + [ + "max-h", + [ + "maxHeight" + ] + ] + ]), + minHeight: (0, _createUtilityPlugin.default)("minHeight", [ + [ + "min-h", + [ + "minHeight" + ] + ] + ]), + width: (0, _createUtilityPlugin.default)("width", [ + [ + "w", + [ + "width" + ] + ] + ]), + minWidth: (0, _createUtilityPlugin.default)("minWidth", [ + [ + "min-w", + [ + "minWidth" + ] + ] + ]), + maxWidth: (0, _createUtilityPlugin.default)("maxWidth", [ + [ + "max-w", + [ + "maxWidth" + ] + ] + ]), + flex: (0, _createUtilityPlugin.default)("flex"), + flexShrink: (0, _createUtilityPlugin.default)("flexShrink", [ + [ + "flex-shrink", + [ + "flex-shrink" + ] + ], + [ + "shrink", + [ + "flex-shrink" + ] + ] + ]), + flexGrow: (0, _createUtilityPlugin.default)("flexGrow", [ + [ + "flex-grow", + [ + "flex-grow" + ] + ], + [ + "grow", + [ + "flex-grow" + ] + ] + ]), + flexBasis: (0, _createUtilityPlugin.default)("flexBasis", [ + [ + "basis", + [ + "flex-basis" + ] + ] + ]), + tableLayout: ({ addUtilities })=>{ + addUtilities({ + ".table-auto": { + "table-layout": "auto" + }, + ".table-fixed": { + "table-layout": "fixed" + } + }); + }, + captionSide: ({ addUtilities })=>{ + addUtilities({ + ".caption-top": { + "caption-side": "top" + }, + ".caption-bottom": { + "caption-side": "bottom" + } + }); + }, + borderCollapse: ({ addUtilities })=>{ + addUtilities({ + ".border-collapse": { + "border-collapse": "collapse" + }, + ".border-separate": { + "border-collapse": "separate" + } + }); + }, + borderSpacing: ({ addDefaults , matchUtilities , theme })=>{ + addDefaults("border-spacing", { + "--tw-border-spacing-x": 0, + "--tw-border-spacing-y": 0 + }); + matchUtilities({ + "border-spacing": (value)=>{ + return { + "--tw-border-spacing-x": value, + "--tw-border-spacing-y": value, + "@defaults border-spacing": {}, + "border-spacing": "var(--tw-border-spacing-x) var(--tw-border-spacing-y)" + }; + }, + "border-spacing-x": (value)=>{ + return { + "--tw-border-spacing-x": value, + "@defaults border-spacing": {}, + "border-spacing": "var(--tw-border-spacing-x) var(--tw-border-spacing-y)" + }; + }, + "border-spacing-y": (value)=>{ + return { + "--tw-border-spacing-y": value, + "@defaults border-spacing": {}, + "border-spacing": "var(--tw-border-spacing-x) var(--tw-border-spacing-y)" + }; + } + }, { + values: theme("borderSpacing") + }); + }, + transformOrigin: (0, _createUtilityPlugin.default)("transformOrigin", [ + [ + "origin", + [ + "transformOrigin" + ] + ] + ]), + translate: (0, _createUtilityPlugin.default)("translate", [ + [ + [ + "translate-x", + [ + [ + "@defaults transform", + {} + ], + "--tw-translate-x", + [ + "transform", + cssTransformValue + ] + ] + ], + [ + "translate-y", + [ + [ + "@defaults transform", + {} + ], + "--tw-translate-y", + [ + "transform", + cssTransformValue + ] + ] + ] + ] + ], { + supportsNegativeValues: true + }), + rotate: (0, _createUtilityPlugin.default)("rotate", [ + [ + "rotate", + [ + [ + "@defaults transform", + {} + ], + "--tw-rotate", + [ + "transform", + cssTransformValue + ] + ] + ] + ], { + supportsNegativeValues: true + }), + skew: (0, _createUtilityPlugin.default)("skew", [ + [ + [ + "skew-x", + [ + [ + "@defaults transform", + {} + ], + "--tw-skew-x", + [ + "transform", + cssTransformValue + ] + ] + ], + [ + "skew-y", + [ + [ + "@defaults transform", + {} + ], + "--tw-skew-y", + [ + "transform", + cssTransformValue + ] + ] + ] + ] + ], { + supportsNegativeValues: true + }), + scale: (0, _createUtilityPlugin.default)("scale", [ + [ + "scale", + [ + [ + "@defaults transform", + {} + ], + "--tw-scale-x", + "--tw-scale-y", + [ + "transform", + cssTransformValue + ] + ] + ], + [ + [ + "scale-x", + [ + [ + "@defaults transform", + {} + ], + "--tw-scale-x", + [ + "transform", + cssTransformValue + ] + ] + ], + [ + "scale-y", + [ + [ + "@defaults transform", + {} + ], + "--tw-scale-y", + [ + "transform", + cssTransformValue + ] + ] + ] + ] + ], { + supportsNegativeValues: true + }), + transform: ({ addDefaults , addUtilities })=>{ + addDefaults("transform", { + "--tw-translate-x": "0", + "--tw-translate-y": "0", + "--tw-rotate": "0", + "--tw-skew-x": "0", + "--tw-skew-y": "0", + "--tw-scale-x": "1", + "--tw-scale-y": "1" + }); + addUtilities({ + ".transform": { + "@defaults transform": {}, + transform: cssTransformValue + }, + ".transform-cpu": { + transform: cssTransformValue + }, + ".transform-gpu": { + transform: cssTransformValue.replace("translate(var(--tw-translate-x), var(--tw-translate-y))", "translate3d(var(--tw-translate-x), var(--tw-translate-y), 0)") + }, + ".transform-none": { + transform: "none" + } + }); + }, + animation: ({ matchUtilities , theme , config })=>{ + let prefixName = (name)=>(0, _escapeClassName.default)(config("prefix") + name); + var _theme; + let keyframes = Object.fromEntries(Object.entries((_theme = theme("keyframes")) !== null && _theme !== void 0 ? _theme : {}).map(([key, value])=>{ + return [ + key, + { + [`@keyframes ${prefixName(key)}`]: value + } + ]; + })); + matchUtilities({ + animate: (value)=>{ + let animations = (0, _parseAnimationValue.default)(value); + return [ + ...animations.flatMap((animation)=>keyframes[animation.name]), + { + animation: animations.map(({ name , value })=>{ + if (name === undefined || keyframes[name] === undefined) { + return value; + } + return value.replace(name, prefixName(name)); + }).join(", ") + } + ]; + } + }, { + values: theme("animation") + }); + }, + cursor: (0, _createUtilityPlugin.default)("cursor"), + touchAction: ({ addDefaults , addUtilities })=>{ + addDefaults("touch-action", { + "--tw-pan-x": " ", + "--tw-pan-y": " ", + "--tw-pinch-zoom": " " + }); + let cssTouchActionValue = "var(--tw-pan-x) var(--tw-pan-y) var(--tw-pinch-zoom)"; + addUtilities({ + ".touch-auto": { + "touch-action": "auto" + }, + ".touch-none": { + "touch-action": "none" + }, + ".touch-pan-x": { + "@defaults touch-action": {}, + "--tw-pan-x": "pan-x", + "touch-action": cssTouchActionValue + }, + ".touch-pan-left": { + "@defaults touch-action": {}, + "--tw-pan-x": "pan-left", + "touch-action": cssTouchActionValue + }, + ".touch-pan-right": { + "@defaults touch-action": {}, + "--tw-pan-x": "pan-right", + "touch-action": cssTouchActionValue + }, + ".touch-pan-y": { + "@defaults touch-action": {}, + "--tw-pan-y": "pan-y", + "touch-action": cssTouchActionValue + }, + ".touch-pan-up": { + "@defaults touch-action": {}, + "--tw-pan-y": "pan-up", + "touch-action": cssTouchActionValue + }, + ".touch-pan-down": { + "@defaults touch-action": {}, + "--tw-pan-y": "pan-down", + "touch-action": cssTouchActionValue + }, + ".touch-pinch-zoom": { + "@defaults touch-action": {}, + "--tw-pinch-zoom": "pinch-zoom", + "touch-action": cssTouchActionValue + }, + ".touch-manipulation": { + "touch-action": "manipulation" + } + }); + }, + userSelect: ({ addUtilities })=>{ + addUtilities({ + ".select-none": { + "user-select": "none" + }, + ".select-text": { + "user-select": "text" + }, + ".select-all": { + "user-select": "all" + }, + ".select-auto": { + "user-select": "auto" + } + }); + }, + resize: ({ addUtilities })=>{ + addUtilities({ + ".resize-none": { + resize: "none" + }, + ".resize-y": { + resize: "vertical" + }, + ".resize-x": { + resize: "horizontal" + }, + ".resize": { + resize: "both" + } + }); + }, + scrollSnapType: ({ addDefaults , addUtilities })=>{ + addDefaults("scroll-snap-type", { + "--tw-scroll-snap-strictness": "proximity" + }); + addUtilities({ + ".snap-none": { + "scroll-snap-type": "none" + }, + ".snap-x": { + "@defaults scroll-snap-type": {}, + "scroll-snap-type": "x var(--tw-scroll-snap-strictness)" + }, + ".snap-y": { + "@defaults scroll-snap-type": {}, + "scroll-snap-type": "y var(--tw-scroll-snap-strictness)" + }, + ".snap-both": { + "@defaults scroll-snap-type": {}, + "scroll-snap-type": "both var(--tw-scroll-snap-strictness)" + }, + ".snap-mandatory": { + "--tw-scroll-snap-strictness": "mandatory" + }, + ".snap-proximity": { + "--tw-scroll-snap-strictness": "proximity" + } + }); + }, + scrollSnapAlign: ({ addUtilities })=>{ + addUtilities({ + ".snap-start": { + "scroll-snap-align": "start" + }, + ".snap-end": { + "scroll-snap-align": "end" + }, + ".snap-center": { + "scroll-snap-align": "center" + }, + ".snap-align-none": { + "scroll-snap-align": "none" + } + }); + }, + scrollSnapStop: ({ addUtilities })=>{ + addUtilities({ + ".snap-normal": { + "scroll-snap-stop": "normal" + }, + ".snap-always": { + "scroll-snap-stop": "always" + } + }); + }, + scrollMargin: (0, _createUtilityPlugin.default)("scrollMargin", [ + [ + "scroll-m", + [ + "scroll-margin" + ] + ], + [ + [ + "scroll-mx", + [ + "scroll-margin-left", + "scroll-margin-right" + ] + ], + [ + "scroll-my", + [ + "scroll-margin-top", + "scroll-margin-bottom" + ] + ] + ], + [ + [ + "scroll-ms", + [ + "scroll-margin-inline-start" + ] + ], + [ + "scroll-me", + [ + "scroll-margin-inline-end" + ] + ], + [ + "scroll-mt", + [ + "scroll-margin-top" + ] + ], + [ + "scroll-mr", + [ + "scroll-margin-right" + ] + ], + [ + "scroll-mb", + [ + "scroll-margin-bottom" + ] + ], + [ + "scroll-ml", + [ + "scroll-margin-left" + ] + ] + ] + ], { + supportsNegativeValues: true + }), + scrollPadding: (0, _createUtilityPlugin.default)("scrollPadding", [ + [ + "scroll-p", + [ + "scroll-padding" + ] + ], + [ + [ + "scroll-px", + [ + "scroll-padding-left", + "scroll-padding-right" + ] + ], + [ + "scroll-py", + [ + "scroll-padding-top", + "scroll-padding-bottom" + ] + ] + ], + [ + [ + "scroll-ps", + [ + "scroll-padding-inline-start" + ] + ], + [ + "scroll-pe", + [ + "scroll-padding-inline-end" + ] + ], + [ + "scroll-pt", + [ + "scroll-padding-top" + ] + ], + [ + "scroll-pr", + [ + "scroll-padding-right" + ] + ], + [ + "scroll-pb", + [ + "scroll-padding-bottom" + ] + ], + [ + "scroll-pl", + [ + "scroll-padding-left" + ] + ] + ] + ]), + listStylePosition: ({ addUtilities })=>{ + addUtilities({ + ".list-inside": { + "list-style-position": "inside" + }, + ".list-outside": { + "list-style-position": "outside" + } + }); + }, + listStyleType: (0, _createUtilityPlugin.default)("listStyleType", [ + [ + "list", + [ + "listStyleType" + ] + ] + ]), + listStyleImage: (0, _createUtilityPlugin.default)("listStyleImage", [ + [ + "list-image", + [ + "listStyleImage" + ] + ] + ]), + appearance: ({ addUtilities })=>{ + addUtilities({ + ".appearance-none": { + appearance: "none" + }, + ".appearance-auto": { + appearance: "auto" + } + }); + }, + columns: (0, _createUtilityPlugin.default)("columns", [ + [ + "columns", + [ + "columns" + ] + ] + ]), + breakBefore: ({ addUtilities })=>{ + addUtilities({ + ".break-before-auto": { + "break-before": "auto" + }, + ".break-before-avoid": { + "break-before": "avoid" + }, + ".break-before-all": { + "break-before": "all" + }, + ".break-before-avoid-page": { + "break-before": "avoid-page" + }, + ".break-before-page": { + "break-before": "page" + }, + ".break-before-left": { + "break-before": "left" + }, + ".break-before-right": { + "break-before": "right" + }, + ".break-before-column": { + "break-before": "column" + } + }); + }, + breakInside: ({ addUtilities })=>{ + addUtilities({ + ".break-inside-auto": { + "break-inside": "auto" + }, + ".break-inside-avoid": { + "break-inside": "avoid" + }, + ".break-inside-avoid-page": { + "break-inside": "avoid-page" + }, + ".break-inside-avoid-column": { + "break-inside": "avoid-column" + } + }); + }, + breakAfter: ({ addUtilities })=>{ + addUtilities({ + ".break-after-auto": { + "break-after": "auto" + }, + ".break-after-avoid": { + "break-after": "avoid" + }, + ".break-after-all": { + "break-after": "all" + }, + ".break-after-avoid-page": { + "break-after": "avoid-page" + }, + ".break-after-page": { + "break-after": "page" + }, + ".break-after-left": { + "break-after": "left" + }, + ".break-after-right": { + "break-after": "right" + }, + ".break-after-column": { + "break-after": "column" + } + }); + }, + gridAutoColumns: (0, _createUtilityPlugin.default)("gridAutoColumns", [ + [ + "auto-cols", + [ + "gridAutoColumns" + ] + ] + ]), + gridAutoFlow: ({ addUtilities })=>{ + addUtilities({ + ".grid-flow-row": { + gridAutoFlow: "row" + }, + ".grid-flow-col": { + gridAutoFlow: "column" + }, + ".grid-flow-dense": { + gridAutoFlow: "dense" + }, + ".grid-flow-row-dense": { + gridAutoFlow: "row dense" + }, + ".grid-flow-col-dense": { + gridAutoFlow: "column dense" + } + }); + }, + gridAutoRows: (0, _createUtilityPlugin.default)("gridAutoRows", [ + [ + "auto-rows", + [ + "gridAutoRows" + ] + ] + ]), + gridTemplateColumns: (0, _createUtilityPlugin.default)("gridTemplateColumns", [ + [ + "grid-cols", + [ + "gridTemplateColumns" + ] + ] + ]), + gridTemplateRows: (0, _createUtilityPlugin.default)("gridTemplateRows", [ + [ + "grid-rows", + [ + "gridTemplateRows" + ] + ] + ]), + flexDirection: ({ addUtilities })=>{ + addUtilities({ + ".flex-row": { + "flex-direction": "row" + }, + ".flex-row-reverse": { + "flex-direction": "row-reverse" + }, + ".flex-col": { + "flex-direction": "column" + }, + ".flex-col-reverse": { + "flex-direction": "column-reverse" + } + }); + }, + flexWrap: ({ addUtilities })=>{ + addUtilities({ + ".flex-wrap": { + "flex-wrap": "wrap" + }, + ".flex-wrap-reverse": { + "flex-wrap": "wrap-reverse" + }, + ".flex-nowrap": { + "flex-wrap": "nowrap" + } + }); + }, + placeContent: ({ addUtilities })=>{ + addUtilities({ + ".place-content-center": { + "place-content": "center" + }, + ".place-content-start": { + "place-content": "start" + }, + ".place-content-end": { + "place-content": "end" + }, + ".place-content-between": { + "place-content": "space-between" + }, + ".place-content-around": { + "place-content": "space-around" + }, + ".place-content-evenly": { + "place-content": "space-evenly" + }, + ".place-content-baseline": { + "place-content": "baseline" + }, + ".place-content-stretch": { + "place-content": "stretch" + } + }); + }, + placeItems: ({ addUtilities })=>{ + addUtilities({ + ".place-items-start": { + "place-items": "start" + }, + ".place-items-end": { + "place-items": "end" + }, + ".place-items-center": { + "place-items": "center" + }, + ".place-items-baseline": { + "place-items": "baseline" + }, + ".place-items-stretch": { + "place-items": "stretch" + } + }); + }, + alignContent: ({ addUtilities })=>{ + addUtilities({ + ".content-normal": { + "align-content": "normal" + }, + ".content-center": { + "align-content": "center" + }, + ".content-start": { + "align-content": "flex-start" + }, + ".content-end": { + "align-content": "flex-end" + }, + ".content-between": { + "align-content": "space-between" + }, + ".content-around": { + "align-content": "space-around" + }, + ".content-evenly": { + "align-content": "space-evenly" + }, + ".content-baseline": { + "align-content": "baseline" + }, + ".content-stretch": { + "align-content": "stretch" + } + }); + }, + alignItems: ({ addUtilities })=>{ + addUtilities({ + ".items-start": { + "align-items": "flex-start" + }, + ".items-end": { + "align-items": "flex-end" + }, + ".items-center": { + "align-items": "center" + }, + ".items-baseline": { + "align-items": "baseline" + }, + ".items-stretch": { + "align-items": "stretch" + } + }); + }, + justifyContent: ({ addUtilities })=>{ + addUtilities({ + ".justify-normal": { + "justify-content": "normal" + }, + ".justify-start": { + "justify-content": "flex-start" + }, + ".justify-end": { + "justify-content": "flex-end" + }, + ".justify-center": { + "justify-content": "center" + }, + ".justify-between": { + "justify-content": "space-between" + }, + ".justify-around": { + "justify-content": "space-around" + }, + ".justify-evenly": { + "justify-content": "space-evenly" + }, + ".justify-stretch": { + "justify-content": "stretch" + } + }); + }, + justifyItems: ({ addUtilities })=>{ + addUtilities({ + ".justify-items-start": { + "justify-items": "start" + }, + ".justify-items-end": { + "justify-items": "end" + }, + ".justify-items-center": { + "justify-items": "center" + }, + ".justify-items-stretch": { + "justify-items": "stretch" + } + }); + }, + gap: (0, _createUtilityPlugin.default)("gap", [ + [ + "gap", + [ + "gap" + ] + ], + [ + [ + "gap-x", + [ + "columnGap" + ] + ], + [ + "gap-y", + [ + "rowGap" + ] + ] + ] + ]), + space: ({ matchUtilities , addUtilities , theme })=>{ + matchUtilities({ + "space-x": (value)=>{ + value = value === "0" ? "0px" : value; + return { + "& > :not([hidden]) ~ :not([hidden])": { + "--tw-space-x-reverse": "0", + "margin-right": `calc(${value} * var(--tw-space-x-reverse))`, + "margin-left": `calc(${value} * calc(1 - var(--tw-space-x-reverse)))` + } + }; + }, + "space-y": (value)=>{ + value = value === "0" ? "0px" : value; + return { + "& > :not([hidden]) ~ :not([hidden])": { + "--tw-space-y-reverse": "0", + "margin-top": `calc(${value} * calc(1 - var(--tw-space-y-reverse)))`, + "margin-bottom": `calc(${value} * var(--tw-space-y-reverse))` + } + }; + } + }, { + values: theme("space"), + supportsNegativeValues: true + }); + addUtilities({ + ".space-y-reverse > :not([hidden]) ~ :not([hidden])": { + "--tw-space-y-reverse": "1" + }, + ".space-x-reverse > :not([hidden]) ~ :not([hidden])": { + "--tw-space-x-reverse": "1" + } + }); + }, + divideWidth: ({ matchUtilities , addUtilities , theme })=>{ + matchUtilities({ + "divide-x": (value)=>{ + value = value === "0" ? "0px" : value; + return { + "& > :not([hidden]) ~ :not([hidden])": { + "@defaults border-width": {}, + "--tw-divide-x-reverse": "0", + "border-right-width": `calc(${value} * var(--tw-divide-x-reverse))`, + "border-left-width": `calc(${value} * calc(1 - var(--tw-divide-x-reverse)))` + } + }; + }, + "divide-y": (value)=>{ + value = value === "0" ? "0px" : value; + return { + "& > :not([hidden]) ~ :not([hidden])": { + "@defaults border-width": {}, + "--tw-divide-y-reverse": "0", + "border-top-width": `calc(${value} * calc(1 - var(--tw-divide-y-reverse)))`, + "border-bottom-width": `calc(${value} * var(--tw-divide-y-reverse))` + } + }; + } + }, { + values: theme("divideWidth"), + type: [ + "line-width", + "length", + "any" + ] + }); + addUtilities({ + ".divide-y-reverse > :not([hidden]) ~ :not([hidden])": { + "@defaults border-width": {}, + "--tw-divide-y-reverse": "1" + }, + ".divide-x-reverse > :not([hidden]) ~ :not([hidden])": { + "@defaults border-width": {}, + "--tw-divide-x-reverse": "1" + } + }); + }, + divideStyle: ({ addUtilities })=>{ + addUtilities({ + ".divide-solid > :not([hidden]) ~ :not([hidden])": { + "border-style": "solid" + }, + ".divide-dashed > :not([hidden]) ~ :not([hidden])": { + "border-style": "dashed" + }, + ".divide-dotted > :not([hidden]) ~ :not([hidden])": { + "border-style": "dotted" + }, + ".divide-double > :not([hidden]) ~ :not([hidden])": { + "border-style": "double" + }, + ".divide-none > :not([hidden]) ~ :not([hidden])": { + "border-style": "none" + } + }); + }, + divideColor: ({ matchUtilities , theme , corePlugins })=>{ + matchUtilities({ + divide: (value)=>{ + if (!corePlugins("divideOpacity")) { + return { + ["& > :not([hidden]) ~ :not([hidden])"]: { + "border-color": (0, _toColorValue.default)(value) + } + }; + } + return { + ["& > :not([hidden]) ~ :not([hidden])"]: (0, _withAlphaVariable.default)({ + color: value, + property: "border-color", + variable: "--tw-divide-opacity" + }) + }; + } + }, { + values: (({ DEFAULT: _ , ...colors })=>colors)((0, _flattenColorPalette.default)(theme("divideColor"))), + type: [ + "color", + "any" + ] + }); + }, + divideOpacity: ({ matchUtilities , theme })=>{ + matchUtilities({ + "divide-opacity": (value)=>{ + return { + [`& > :not([hidden]) ~ :not([hidden])`]: { + "--tw-divide-opacity": value + } + }; + } + }, { + values: theme("divideOpacity") + }); + }, + placeSelf: ({ addUtilities })=>{ + addUtilities({ + ".place-self-auto": { + "place-self": "auto" + }, + ".place-self-start": { + "place-self": "start" + }, + ".place-self-end": { + "place-self": "end" + }, + ".place-self-center": { + "place-self": "center" + }, + ".place-self-stretch": { + "place-self": "stretch" + } + }); + }, + alignSelf: ({ addUtilities })=>{ + addUtilities({ + ".self-auto": { + "align-self": "auto" + }, + ".self-start": { + "align-self": "flex-start" + }, + ".self-end": { + "align-self": "flex-end" + }, + ".self-center": { + "align-self": "center" + }, + ".self-stretch": { + "align-self": "stretch" + }, + ".self-baseline": { + "align-self": "baseline" + } + }); + }, + justifySelf: ({ addUtilities })=>{ + addUtilities({ + ".justify-self-auto": { + "justify-self": "auto" + }, + ".justify-self-start": { + "justify-self": "start" + }, + ".justify-self-end": { + "justify-self": "end" + }, + ".justify-self-center": { + "justify-self": "center" + }, + ".justify-self-stretch": { + "justify-self": "stretch" + } + }); + }, + overflow: ({ addUtilities })=>{ + addUtilities({ + ".overflow-auto": { + overflow: "auto" + }, + ".overflow-hidden": { + overflow: "hidden" + }, + ".overflow-clip": { + overflow: "clip" + }, + ".overflow-visible": { + overflow: "visible" + }, + ".overflow-scroll": { + overflow: "scroll" + }, + ".overflow-x-auto": { + "overflow-x": "auto" + }, + ".overflow-y-auto": { + "overflow-y": "auto" + }, + ".overflow-x-hidden": { + "overflow-x": "hidden" + }, + ".overflow-y-hidden": { + "overflow-y": "hidden" + }, + ".overflow-x-clip": { + "overflow-x": "clip" + }, + ".overflow-y-clip": { + "overflow-y": "clip" + }, + ".overflow-x-visible": { + "overflow-x": "visible" + }, + ".overflow-y-visible": { + "overflow-y": "visible" + }, + ".overflow-x-scroll": { + "overflow-x": "scroll" + }, + ".overflow-y-scroll": { + "overflow-y": "scroll" + } + }); + }, + overscrollBehavior: ({ addUtilities })=>{ + addUtilities({ + ".overscroll-auto": { + "overscroll-behavior": "auto" + }, + ".overscroll-contain": { + "overscroll-behavior": "contain" + }, + ".overscroll-none": { + "overscroll-behavior": "none" + }, + ".overscroll-y-auto": { + "overscroll-behavior-y": "auto" + }, + ".overscroll-y-contain": { + "overscroll-behavior-y": "contain" + }, + ".overscroll-y-none": { + "overscroll-behavior-y": "none" + }, + ".overscroll-x-auto": { + "overscroll-behavior-x": "auto" + }, + ".overscroll-x-contain": { + "overscroll-behavior-x": "contain" + }, + ".overscroll-x-none": { + "overscroll-behavior-x": "none" + } + }); + }, + scrollBehavior: ({ addUtilities })=>{ + addUtilities({ + ".scroll-auto": { + "scroll-behavior": "auto" + }, + ".scroll-smooth": { + "scroll-behavior": "smooth" + } + }); + }, + textOverflow: ({ addUtilities })=>{ + addUtilities({ + ".truncate": { + overflow: "hidden", + "text-overflow": "ellipsis", + "white-space": "nowrap" + }, + ".overflow-ellipsis": { + "text-overflow": "ellipsis" + }, + ".text-ellipsis": { + "text-overflow": "ellipsis" + }, + ".text-clip": { + "text-overflow": "clip" + } + }); + }, + hyphens: ({ addUtilities })=>{ + addUtilities({ + ".hyphens-none": { + hyphens: "none" + }, + ".hyphens-manual": { + hyphens: "manual" + }, + ".hyphens-auto": { + hyphens: "auto" + } + }); + }, + whitespace: ({ addUtilities })=>{ + addUtilities({ + ".whitespace-normal": { + "white-space": "normal" + }, + ".whitespace-nowrap": { + "white-space": "nowrap" + }, + ".whitespace-pre": { + "white-space": "pre" + }, + ".whitespace-pre-line": { + "white-space": "pre-line" + }, + ".whitespace-pre-wrap": { + "white-space": "pre-wrap" + }, + ".whitespace-break-spaces": { + "white-space": "break-spaces" + } + }); + }, + textWrap: ({ addUtilities })=>{ + addUtilities({ + ".text-wrap": { + "text-wrap": "wrap" + }, + ".text-nowrap": { + "text-wrap": "nowrap" + }, + ".text-balance": { + "text-wrap": "balance" + }, + ".text-pretty": { + "text-wrap": "pretty" + } + }); + }, + wordBreak: ({ addUtilities })=>{ + addUtilities({ + ".break-normal": { + "overflow-wrap": "normal", + "word-break": "normal" + }, + ".break-words": { + "overflow-wrap": "break-word" + }, + ".break-all": { + "word-break": "break-all" + }, + ".break-keep": { + "word-break": "keep-all" + } + }); + }, + borderRadius: (0, _createUtilityPlugin.default)("borderRadius", [ + [ + "rounded", + [ + "border-radius" + ] + ], + [ + [ + "rounded-s", + [ + "border-start-start-radius", + "border-end-start-radius" + ] + ], + [ + "rounded-e", + [ + "border-start-end-radius", + "border-end-end-radius" + ] + ], + [ + "rounded-t", + [ + "border-top-left-radius", + "border-top-right-radius" + ] + ], + [ + "rounded-r", + [ + "border-top-right-radius", + "border-bottom-right-radius" + ] + ], + [ + "rounded-b", + [ + "border-bottom-right-radius", + "border-bottom-left-radius" + ] + ], + [ + "rounded-l", + [ + "border-top-left-radius", + "border-bottom-left-radius" + ] + ] + ], + [ + [ + "rounded-ss", + [ + "border-start-start-radius" + ] + ], + [ + "rounded-se", + [ + "border-start-end-radius" + ] + ], + [ + "rounded-ee", + [ + "border-end-end-radius" + ] + ], + [ + "rounded-es", + [ + "border-end-start-radius" + ] + ], + [ + "rounded-tl", + [ + "border-top-left-radius" + ] + ], + [ + "rounded-tr", + [ + "border-top-right-radius" + ] + ], + [ + "rounded-br", + [ + "border-bottom-right-radius" + ] + ], + [ + "rounded-bl", + [ + "border-bottom-left-radius" + ] + ] + ] + ]), + borderWidth: (0, _createUtilityPlugin.default)("borderWidth", [ + [ + "border", + [ + [ + "@defaults border-width", + {} + ], + "border-width" + ] + ], + [ + [ + "border-x", + [ + [ + "@defaults border-width", + {} + ], + "border-left-width", + "border-right-width" + ] + ], + [ + "border-y", + [ + [ + "@defaults border-width", + {} + ], + "border-top-width", + "border-bottom-width" + ] + ] + ], + [ + [ + "border-s", + [ + [ + "@defaults border-width", + {} + ], + "border-inline-start-width" + ] + ], + [ + "border-e", + [ + [ + "@defaults border-width", + {} + ], + "border-inline-end-width" + ] + ], + [ + "border-t", + [ + [ + "@defaults border-width", + {} + ], + "border-top-width" + ] + ], + [ + "border-r", + [ + [ + "@defaults border-width", + {} + ], + "border-right-width" + ] + ], + [ + "border-b", + [ + [ + "@defaults border-width", + {} + ], + "border-bottom-width" + ] + ], + [ + "border-l", + [ + [ + "@defaults border-width", + {} + ], + "border-left-width" + ] + ] + ] + ], { + type: [ + "line-width", + "length" + ] + }), + borderStyle: ({ addUtilities })=>{ + addUtilities({ + ".border-solid": { + "border-style": "solid" + }, + ".border-dashed": { + "border-style": "dashed" + }, + ".border-dotted": { + "border-style": "dotted" + }, + ".border-double": { + "border-style": "double" + }, + ".border-hidden": { + "border-style": "hidden" + }, + ".border-none": { + "border-style": "none" + } + }); + }, + borderColor: ({ matchUtilities , theme , corePlugins })=>{ + matchUtilities({ + border: (value)=>{ + if (!corePlugins("borderOpacity")) { + return { + "border-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "border-color", + variable: "--tw-border-opacity" + }); + } + }, { + values: (({ DEFAULT: _ , ...colors })=>colors)((0, _flattenColorPalette.default)(theme("borderColor"))), + type: [ + "color", + "any" + ] + }); + matchUtilities({ + "border-x": (value)=>{ + if (!corePlugins("borderOpacity")) { + return { + "border-left-color": (0, _toColorValue.default)(value), + "border-right-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: [ + "border-left-color", + "border-right-color" + ], + variable: "--tw-border-opacity" + }); + }, + "border-y": (value)=>{ + if (!corePlugins("borderOpacity")) { + return { + "border-top-color": (0, _toColorValue.default)(value), + "border-bottom-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: [ + "border-top-color", + "border-bottom-color" + ], + variable: "--tw-border-opacity" + }); + } + }, { + values: (({ DEFAULT: _ , ...colors })=>colors)((0, _flattenColorPalette.default)(theme("borderColor"))), + type: [ + "color", + "any" + ] + }); + matchUtilities({ + "border-s": (value)=>{ + if (!corePlugins("borderOpacity")) { + return { + "border-inline-start-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "border-inline-start-color", + variable: "--tw-border-opacity" + }); + }, + "border-e": (value)=>{ + if (!corePlugins("borderOpacity")) { + return { + "border-inline-end-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "border-inline-end-color", + variable: "--tw-border-opacity" + }); + }, + "border-t": (value)=>{ + if (!corePlugins("borderOpacity")) { + return { + "border-top-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "border-top-color", + variable: "--tw-border-opacity" + }); + }, + "border-r": (value)=>{ + if (!corePlugins("borderOpacity")) { + return { + "border-right-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "border-right-color", + variable: "--tw-border-opacity" + }); + }, + "border-b": (value)=>{ + if (!corePlugins("borderOpacity")) { + return { + "border-bottom-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "border-bottom-color", + variable: "--tw-border-opacity" + }); + }, + "border-l": (value)=>{ + if (!corePlugins("borderOpacity")) { + return { + "border-left-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "border-left-color", + variable: "--tw-border-opacity" + }); + } + }, { + values: (({ DEFAULT: _ , ...colors })=>colors)((0, _flattenColorPalette.default)(theme("borderColor"))), + type: [ + "color", + "any" + ] + }); + }, + borderOpacity: (0, _createUtilityPlugin.default)("borderOpacity", [ + [ + "border-opacity", + [ + "--tw-border-opacity" + ] + ] + ]), + backgroundColor: ({ matchUtilities , theme , corePlugins })=>{ + matchUtilities({ + bg: (value)=>{ + if (!corePlugins("backgroundOpacity")) { + return { + "background-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "background-color", + variable: "--tw-bg-opacity" + }); + } + }, { + values: (0, _flattenColorPalette.default)(theme("backgroundColor")), + type: [ + "color", + "any" + ] + }); + }, + backgroundOpacity: (0, _createUtilityPlugin.default)("backgroundOpacity", [ + [ + "bg-opacity", + [ + "--tw-bg-opacity" + ] + ] + ]), + backgroundImage: (0, _createUtilityPlugin.default)("backgroundImage", [ + [ + "bg", + [ + "background-image" + ] + ] + ], { + type: [ + "lookup", + "image", + "url" + ] + }), + gradientColorStops: (()=>{ + function transparentTo(value) { + return (0, _withAlphaVariable.withAlphaValue)(value, 0, "rgb(255 255 255 / 0)"); + } + return function({ matchUtilities , theme , addDefaults }) { + addDefaults("gradient-color-stops", { + "--tw-gradient-from-position": " ", + "--tw-gradient-via-position": " ", + "--tw-gradient-to-position": " " + }); + let options = { + values: (0, _flattenColorPalette.default)(theme("gradientColorStops")), + type: [ + "color", + "any" + ] + }; + let positionOptions = { + values: theme("gradientColorStopPositions"), + type: [ + "length", + "percentage" + ] + }; + matchUtilities({ + from: (value)=>{ + let transparentToValue = transparentTo(value); + return { + "@defaults gradient-color-stops": {}, + "--tw-gradient-from": `${(0, _toColorValue.default)(value)} var(--tw-gradient-from-position)`, + "--tw-gradient-to": `${transparentToValue} var(--tw-gradient-to-position)`, + "--tw-gradient-stops": `var(--tw-gradient-from), var(--tw-gradient-to)` + }; + } + }, options); + matchUtilities({ + from: (value)=>{ + return { + "--tw-gradient-from-position": value + }; + } + }, positionOptions); + matchUtilities({ + via: (value)=>{ + let transparentToValue = transparentTo(value); + return { + "@defaults gradient-color-stops": {}, + "--tw-gradient-to": `${transparentToValue} var(--tw-gradient-to-position)`, + "--tw-gradient-stops": `var(--tw-gradient-from), ${(0, _toColorValue.default)(value)} var(--tw-gradient-via-position), var(--tw-gradient-to)` + }; + } + }, options); + matchUtilities({ + via: (value)=>{ + return { + "--tw-gradient-via-position": value + }; + } + }, positionOptions); + matchUtilities({ + to: (value)=>({ + "@defaults gradient-color-stops": {}, + "--tw-gradient-to": `${(0, _toColorValue.default)(value)} var(--tw-gradient-to-position)` + }) + }, options); + matchUtilities({ + to: (value)=>{ + return { + "--tw-gradient-to-position": value + }; + } + }, positionOptions); + }; + })(), + boxDecorationBreak: ({ addUtilities })=>{ + addUtilities({ + ".decoration-slice": { + "box-decoration-break": "slice" + }, + ".decoration-clone": { + "box-decoration-break": "clone" + }, + ".box-decoration-slice": { + "box-decoration-break": "slice" + }, + ".box-decoration-clone": { + "box-decoration-break": "clone" + } + }); + }, + backgroundSize: (0, _createUtilityPlugin.default)("backgroundSize", [ + [ + "bg", + [ + "background-size" + ] + ] + ], { + type: [ + "lookup", + "length", + "percentage", + "size" + ] + }), + backgroundAttachment: ({ addUtilities })=>{ + addUtilities({ + ".bg-fixed": { + "background-attachment": "fixed" + }, + ".bg-local": { + "background-attachment": "local" + }, + ".bg-scroll": { + "background-attachment": "scroll" + } + }); + }, + backgroundClip: ({ addUtilities })=>{ + addUtilities({ + ".bg-clip-border": { + "background-clip": "border-box" + }, + ".bg-clip-padding": { + "background-clip": "padding-box" + }, + ".bg-clip-content": { + "background-clip": "content-box" + }, + ".bg-clip-text": { + "background-clip": "text" + } + }); + }, + backgroundPosition: (0, _createUtilityPlugin.default)("backgroundPosition", [ + [ + "bg", + [ + "background-position" + ] + ] + ], { + type: [ + "lookup", + [ + "position", + { + preferOnConflict: true + } + ] + ] + }), + backgroundRepeat: ({ addUtilities })=>{ + addUtilities({ + ".bg-repeat": { + "background-repeat": "repeat" + }, + ".bg-no-repeat": { + "background-repeat": "no-repeat" + }, + ".bg-repeat-x": { + "background-repeat": "repeat-x" + }, + ".bg-repeat-y": { + "background-repeat": "repeat-y" + }, + ".bg-repeat-round": { + "background-repeat": "round" + }, + ".bg-repeat-space": { + "background-repeat": "space" + } + }); + }, + backgroundOrigin: ({ addUtilities })=>{ + addUtilities({ + ".bg-origin-border": { + "background-origin": "border-box" + }, + ".bg-origin-padding": { + "background-origin": "padding-box" + }, + ".bg-origin-content": { + "background-origin": "content-box" + } + }); + }, + fill: ({ matchUtilities , theme })=>{ + matchUtilities({ + fill: (value)=>{ + return { + fill: (0, _toColorValue.default)(value) + }; + } + }, { + values: (0, _flattenColorPalette.default)(theme("fill")), + type: [ + "color", + "any" + ] + }); + }, + stroke: ({ matchUtilities , theme })=>{ + matchUtilities({ + stroke: (value)=>{ + return { + stroke: (0, _toColorValue.default)(value) + }; + } + }, { + values: (0, _flattenColorPalette.default)(theme("stroke")), + type: [ + "color", + "url", + "any" + ] + }); + }, + strokeWidth: (0, _createUtilityPlugin.default)("strokeWidth", [ + [ + "stroke", + [ + "stroke-width" + ] + ] + ], { + type: [ + "length", + "number", + "percentage" + ] + }), + objectFit: ({ addUtilities })=>{ + addUtilities({ + ".object-contain": { + "object-fit": "contain" + }, + ".object-cover": { + "object-fit": "cover" + }, + ".object-fill": { + "object-fit": "fill" + }, + ".object-none": { + "object-fit": "none" + }, + ".object-scale-down": { + "object-fit": "scale-down" + } + }); + }, + objectPosition: (0, _createUtilityPlugin.default)("objectPosition", [ + [ + "object", + [ + "object-position" + ] + ] + ]), + padding: (0, _createUtilityPlugin.default)("padding", [ + [ + "p", + [ + "padding" + ] + ], + [ + [ + "px", + [ + "padding-left", + "padding-right" + ] + ], + [ + "py", + [ + "padding-top", + "padding-bottom" + ] + ] + ], + [ + [ + "ps", + [ + "padding-inline-start" + ] + ], + [ + "pe", + [ + "padding-inline-end" + ] + ], + [ + "pt", + [ + "padding-top" + ] + ], + [ + "pr", + [ + "padding-right" + ] + ], + [ + "pb", + [ + "padding-bottom" + ] + ], + [ + "pl", + [ + "padding-left" + ] + ] + ] + ]), + textAlign: ({ addUtilities })=>{ + addUtilities({ + ".text-left": { + "text-align": "left" + }, + ".text-center": { + "text-align": "center" + }, + ".text-right": { + "text-align": "right" + }, + ".text-justify": { + "text-align": "justify" + }, + ".text-start": { + "text-align": "start" + }, + ".text-end": { + "text-align": "end" + } + }); + }, + textIndent: (0, _createUtilityPlugin.default)("textIndent", [ + [ + "indent", + [ + "text-indent" + ] + ] + ], { + supportsNegativeValues: true + }), + verticalAlign: ({ addUtilities , matchUtilities })=>{ + addUtilities({ + ".align-baseline": { + "vertical-align": "baseline" + }, + ".align-top": { + "vertical-align": "top" + }, + ".align-middle": { + "vertical-align": "middle" + }, + ".align-bottom": { + "vertical-align": "bottom" + }, + ".align-text-top": { + "vertical-align": "text-top" + }, + ".align-text-bottom": { + "vertical-align": "text-bottom" + }, + ".align-sub": { + "vertical-align": "sub" + }, + ".align-super": { + "vertical-align": "super" + } + }); + matchUtilities({ + align: (value)=>({ + "vertical-align": value + }) + }); + }, + fontFamily: ({ matchUtilities , theme })=>{ + matchUtilities({ + font: (value)=>{ + let [families, options = {}] = Array.isArray(value) && (0, _isPlainObject.default)(value[1]) ? value : [ + value + ]; + let { fontFeatureSettings , fontVariationSettings } = options; + return { + "font-family": Array.isArray(families) ? families.join(", ") : families, + ...fontFeatureSettings === undefined ? {} : { + "font-feature-settings": fontFeatureSettings + }, + ...fontVariationSettings === undefined ? {} : { + "font-variation-settings": fontVariationSettings + } + }; + } + }, { + values: theme("fontFamily"), + type: [ + "lookup", + "generic-name", + "family-name" + ] + }); + }, + fontSize: ({ matchUtilities , theme })=>{ + matchUtilities({ + text: (value, { modifier })=>{ + let [fontSize, options] = Array.isArray(value) ? value : [ + value + ]; + if (modifier) { + return { + "font-size": fontSize, + "line-height": modifier + }; + } + let { lineHeight , letterSpacing , fontWeight } = (0, _isPlainObject.default)(options) ? options : { + lineHeight: options + }; + return { + "font-size": fontSize, + ...lineHeight === undefined ? {} : { + "line-height": lineHeight + }, + ...letterSpacing === undefined ? {} : { + "letter-spacing": letterSpacing + }, + ...fontWeight === undefined ? {} : { + "font-weight": fontWeight + } + }; + } + }, { + values: theme("fontSize"), + modifiers: theme("lineHeight"), + type: [ + "absolute-size", + "relative-size", + "length", + "percentage" + ] + }); + }, + fontWeight: (0, _createUtilityPlugin.default)("fontWeight", [ + [ + "font", + [ + "fontWeight" + ] + ] + ], { + type: [ + "lookup", + "number", + "any" + ] + }), + textTransform: ({ addUtilities })=>{ + addUtilities({ + ".uppercase": { + "text-transform": "uppercase" + }, + ".lowercase": { + "text-transform": "lowercase" + }, + ".capitalize": { + "text-transform": "capitalize" + }, + ".normal-case": { + "text-transform": "none" + } + }); + }, + fontStyle: ({ addUtilities })=>{ + addUtilities({ + ".italic": { + "font-style": "italic" + }, + ".not-italic": { + "font-style": "normal" + } + }); + }, + fontVariantNumeric: ({ addDefaults , addUtilities })=>{ + let cssFontVariantNumericValue = "var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)"; + addDefaults("font-variant-numeric", { + "--tw-ordinal": " ", + "--tw-slashed-zero": " ", + "--tw-numeric-figure": " ", + "--tw-numeric-spacing": " ", + "--tw-numeric-fraction": " " + }); + addUtilities({ + ".normal-nums": { + "font-variant-numeric": "normal" + }, + ".ordinal": { + "@defaults font-variant-numeric": {}, + "--tw-ordinal": "ordinal", + "font-variant-numeric": cssFontVariantNumericValue + }, + ".slashed-zero": { + "@defaults font-variant-numeric": {}, + "--tw-slashed-zero": "slashed-zero", + "font-variant-numeric": cssFontVariantNumericValue + }, + ".lining-nums": { + "@defaults font-variant-numeric": {}, + "--tw-numeric-figure": "lining-nums", + "font-variant-numeric": cssFontVariantNumericValue + }, + ".oldstyle-nums": { + "@defaults font-variant-numeric": {}, + "--tw-numeric-figure": "oldstyle-nums", + "font-variant-numeric": cssFontVariantNumericValue + }, + ".proportional-nums": { + "@defaults font-variant-numeric": {}, + "--tw-numeric-spacing": "proportional-nums", + "font-variant-numeric": cssFontVariantNumericValue + }, + ".tabular-nums": { + "@defaults font-variant-numeric": {}, + "--tw-numeric-spacing": "tabular-nums", + "font-variant-numeric": cssFontVariantNumericValue + }, + ".diagonal-fractions": { + "@defaults font-variant-numeric": {}, + "--tw-numeric-fraction": "diagonal-fractions", + "font-variant-numeric": cssFontVariantNumericValue + }, + ".stacked-fractions": { + "@defaults font-variant-numeric": {}, + "--tw-numeric-fraction": "stacked-fractions", + "font-variant-numeric": cssFontVariantNumericValue + } + }); + }, + lineHeight: (0, _createUtilityPlugin.default)("lineHeight", [ + [ + "leading", + [ + "lineHeight" + ] + ] + ]), + letterSpacing: (0, _createUtilityPlugin.default)("letterSpacing", [ + [ + "tracking", + [ + "letterSpacing" + ] + ] + ], { + supportsNegativeValues: true + }), + textColor: ({ matchUtilities , theme , corePlugins })=>{ + matchUtilities({ + text: (value)=>{ + if (!corePlugins("textOpacity")) { + return { + color: (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "color", + variable: "--tw-text-opacity" + }); + } + }, { + values: (0, _flattenColorPalette.default)(theme("textColor")), + type: [ + "color", + "any" + ] + }); + }, + textOpacity: (0, _createUtilityPlugin.default)("textOpacity", [ + [ + "text-opacity", + [ + "--tw-text-opacity" + ] + ] + ]), + textDecoration: ({ addUtilities })=>{ + addUtilities({ + ".underline": { + "text-decoration-line": "underline" + }, + ".overline": { + "text-decoration-line": "overline" + }, + ".line-through": { + "text-decoration-line": "line-through" + }, + ".no-underline": { + "text-decoration-line": "none" + } + }); + }, + textDecorationColor: ({ matchUtilities , theme })=>{ + matchUtilities({ + decoration: (value)=>{ + return { + "text-decoration-color": (0, _toColorValue.default)(value) + }; + } + }, { + values: (0, _flattenColorPalette.default)(theme("textDecorationColor")), + type: [ + "color", + "any" + ] + }); + }, + textDecorationStyle: ({ addUtilities })=>{ + addUtilities({ + ".decoration-solid": { + "text-decoration-style": "solid" + }, + ".decoration-double": { + "text-decoration-style": "double" + }, + ".decoration-dotted": { + "text-decoration-style": "dotted" + }, + ".decoration-dashed": { + "text-decoration-style": "dashed" + }, + ".decoration-wavy": { + "text-decoration-style": "wavy" + } + }); + }, + textDecorationThickness: (0, _createUtilityPlugin.default)("textDecorationThickness", [ + [ + "decoration", + [ + "text-decoration-thickness" + ] + ] + ], { + type: [ + "length", + "percentage" + ] + }), + textUnderlineOffset: (0, _createUtilityPlugin.default)("textUnderlineOffset", [ + [ + "underline-offset", + [ + "text-underline-offset" + ] + ] + ], { + type: [ + "length", + "percentage", + "any" + ] + }), + fontSmoothing: ({ addUtilities })=>{ + addUtilities({ + ".antialiased": { + "-webkit-font-smoothing": "antialiased", + "-moz-osx-font-smoothing": "grayscale" + }, + ".subpixel-antialiased": { + "-webkit-font-smoothing": "auto", + "-moz-osx-font-smoothing": "auto" + } + }); + }, + placeholderColor: ({ matchUtilities , theme , corePlugins })=>{ + matchUtilities({ + placeholder: (value)=>{ + if (!corePlugins("placeholderOpacity")) { + return { + "&::placeholder": { + color: (0, _toColorValue.default)(value) + } + }; + } + return { + "&::placeholder": (0, _withAlphaVariable.default)({ + color: value, + property: "color", + variable: "--tw-placeholder-opacity" + }) + }; + } + }, { + values: (0, _flattenColorPalette.default)(theme("placeholderColor")), + type: [ + "color", + "any" + ] + }); + }, + placeholderOpacity: ({ matchUtilities , theme })=>{ + matchUtilities({ + "placeholder-opacity": (value)=>{ + return { + ["&::placeholder"]: { + "--tw-placeholder-opacity": value + } + }; + } + }, { + values: theme("placeholderOpacity") + }); + }, + caretColor: ({ matchUtilities , theme })=>{ + matchUtilities({ + caret: (value)=>{ + return { + "caret-color": (0, _toColorValue.default)(value) + }; + } + }, { + values: (0, _flattenColorPalette.default)(theme("caretColor")), + type: [ + "color", + "any" + ] + }); + }, + accentColor: ({ matchUtilities , theme })=>{ + matchUtilities({ + accent: (value)=>{ + return { + "accent-color": (0, _toColorValue.default)(value) + }; + } + }, { + values: (0, _flattenColorPalette.default)(theme("accentColor")), + type: [ + "color", + "any" + ] + }); + }, + opacity: (0, _createUtilityPlugin.default)("opacity", [ + [ + "opacity", + [ + "opacity" + ] + ] + ]), + backgroundBlendMode: ({ addUtilities })=>{ + addUtilities({ + ".bg-blend-normal": { + "background-blend-mode": "normal" + }, + ".bg-blend-multiply": { + "background-blend-mode": "multiply" + }, + ".bg-blend-screen": { + "background-blend-mode": "screen" + }, + ".bg-blend-overlay": { + "background-blend-mode": "overlay" + }, + ".bg-blend-darken": { + "background-blend-mode": "darken" + }, + ".bg-blend-lighten": { + "background-blend-mode": "lighten" + }, + ".bg-blend-color-dodge": { + "background-blend-mode": "color-dodge" + }, + ".bg-blend-color-burn": { + "background-blend-mode": "color-burn" + }, + ".bg-blend-hard-light": { + "background-blend-mode": "hard-light" + }, + ".bg-blend-soft-light": { + "background-blend-mode": "soft-light" + }, + ".bg-blend-difference": { + "background-blend-mode": "difference" + }, + ".bg-blend-exclusion": { + "background-blend-mode": "exclusion" + }, + ".bg-blend-hue": { + "background-blend-mode": "hue" + }, + ".bg-blend-saturation": { + "background-blend-mode": "saturation" + }, + ".bg-blend-color": { + "background-blend-mode": "color" + }, + ".bg-blend-luminosity": { + "background-blend-mode": "luminosity" + } + }); + }, + mixBlendMode: ({ addUtilities })=>{ + addUtilities({ + ".mix-blend-normal": { + "mix-blend-mode": "normal" + }, + ".mix-blend-multiply": { + "mix-blend-mode": "multiply" + }, + ".mix-blend-screen": { + "mix-blend-mode": "screen" + }, + ".mix-blend-overlay": { + "mix-blend-mode": "overlay" + }, + ".mix-blend-darken": { + "mix-blend-mode": "darken" + }, + ".mix-blend-lighten": { + "mix-blend-mode": "lighten" + }, + ".mix-blend-color-dodge": { + "mix-blend-mode": "color-dodge" + }, + ".mix-blend-color-burn": { + "mix-blend-mode": "color-burn" + }, + ".mix-blend-hard-light": { + "mix-blend-mode": "hard-light" + }, + ".mix-blend-soft-light": { + "mix-blend-mode": "soft-light" + }, + ".mix-blend-difference": { + "mix-blend-mode": "difference" + }, + ".mix-blend-exclusion": { + "mix-blend-mode": "exclusion" + }, + ".mix-blend-hue": { + "mix-blend-mode": "hue" + }, + ".mix-blend-saturation": { + "mix-blend-mode": "saturation" + }, + ".mix-blend-color": { + "mix-blend-mode": "color" + }, + ".mix-blend-luminosity": { + "mix-blend-mode": "luminosity" + }, + ".mix-blend-plus-darker": { + "mix-blend-mode": "plus-darker" + }, + ".mix-blend-plus-lighter": { + "mix-blend-mode": "plus-lighter" + } + }); + }, + boxShadow: (()=>{ + let transformValue = (0, _transformThemeValue.default)("boxShadow"); + let defaultBoxShadow = [ + `var(--tw-ring-offset-shadow, 0 0 #0000)`, + `var(--tw-ring-shadow, 0 0 #0000)`, + `var(--tw-shadow)` + ].join(", "); + return function({ matchUtilities , addDefaults , theme }) { + addDefaults("box-shadow", { + "--tw-ring-offset-shadow": "0 0 #0000", + "--tw-ring-shadow": "0 0 #0000", + "--tw-shadow": "0 0 #0000", + "--tw-shadow-colored": "0 0 #0000" + }); + matchUtilities({ + shadow: (value)=>{ + value = transformValue(value); + let ast = (0, _parseBoxShadowValue.parseBoxShadowValue)(value); + for (let shadow of ast){ + // Don't override color if the whole shadow is a variable + if (!shadow.valid) { + continue; + } + shadow.color = "var(--tw-shadow-color)"; + } + return { + "@defaults box-shadow": {}, + "--tw-shadow": value === "none" ? "0 0 #0000" : value, + "--tw-shadow-colored": value === "none" ? "0 0 #0000" : (0, _parseBoxShadowValue.formatBoxShadowValue)(ast), + "box-shadow": defaultBoxShadow + }; + } + }, { + values: theme("boxShadow"), + type: [ + "shadow" + ] + }); + }; + })(), + boxShadowColor: ({ matchUtilities , theme })=>{ + matchUtilities({ + shadow: (value)=>{ + return { + "--tw-shadow-color": (0, _toColorValue.default)(value), + "--tw-shadow": "var(--tw-shadow-colored)" + }; + } + }, { + values: (0, _flattenColorPalette.default)(theme("boxShadowColor")), + type: [ + "color", + "any" + ] + }); + }, + outlineStyle: ({ addUtilities })=>{ + addUtilities({ + ".outline-none": { + outline: "2px solid transparent", + "outline-offset": "2px" + }, + ".outline": { + "outline-style": "solid" + }, + ".outline-dashed": { + "outline-style": "dashed" + }, + ".outline-dotted": { + "outline-style": "dotted" + }, + ".outline-double": { + "outline-style": "double" + } + }); + }, + outlineWidth: (0, _createUtilityPlugin.default)("outlineWidth", [ + [ + "outline", + [ + "outline-width" + ] + ] + ], { + type: [ + "length", + "number", + "percentage" + ] + }), + outlineOffset: (0, _createUtilityPlugin.default)("outlineOffset", [ + [ + "outline-offset", + [ + "outline-offset" + ] + ] + ], { + type: [ + "length", + "number", + "percentage", + "any" + ], + supportsNegativeValues: true + }), + outlineColor: ({ matchUtilities , theme })=>{ + matchUtilities({ + outline: (value)=>{ + return { + "outline-color": (0, _toColorValue.default)(value) + }; + } + }, { + values: (0, _flattenColorPalette.default)(theme("outlineColor")), + type: [ + "color", + "any" + ] + }); + }, + ringWidth: ({ matchUtilities , addDefaults , addUtilities , theme , config })=>{ + let ringColorDefault = (()=>{ + var _theme, _theme1; + if ((0, _featureFlags.flagEnabled)(config(), "respectDefaultRingColorOpacity")) { + return theme("ringColor.DEFAULT"); + } + let ringOpacityDefault = theme("ringOpacity.DEFAULT", "0.5"); + if (!((_theme = theme("ringColor")) === null || _theme === void 0 ? void 0 : _theme.DEFAULT)) { + return `rgb(147 197 253 / ${ringOpacityDefault})`; + } + return (0, _withAlphaVariable.withAlphaValue)((_theme1 = theme("ringColor")) === null || _theme1 === void 0 ? void 0 : _theme1.DEFAULT, ringOpacityDefault, `rgb(147 197 253 / ${ringOpacityDefault})`); + })(); + addDefaults("ring-width", { + "--tw-ring-inset": " ", + "--tw-ring-offset-width": theme("ringOffsetWidth.DEFAULT", "0px"), + "--tw-ring-offset-color": theme("ringOffsetColor.DEFAULT", "#fff"), + "--tw-ring-color": ringColorDefault, + "--tw-ring-offset-shadow": "0 0 #0000", + "--tw-ring-shadow": "0 0 #0000", + "--tw-shadow": "0 0 #0000", + "--tw-shadow-colored": "0 0 #0000" + }); + matchUtilities({ + ring: (value)=>{ + return { + "@defaults ring-width": {}, + "--tw-ring-offset-shadow": `var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)`, + "--tw-ring-shadow": `var(--tw-ring-inset) 0 0 0 calc(${value} + var(--tw-ring-offset-width)) var(--tw-ring-color)`, + "box-shadow": [ + `var(--tw-ring-offset-shadow)`, + `var(--tw-ring-shadow)`, + `var(--tw-shadow, 0 0 #0000)` + ].join(", ") + }; + } + }, { + values: theme("ringWidth"), + type: "length" + }); + addUtilities({ + ".ring-inset": { + "@defaults ring-width": {}, + "--tw-ring-inset": "inset" + } + }); + }, + ringColor: ({ matchUtilities , theme , corePlugins })=>{ + matchUtilities({ + ring: (value)=>{ + if (!corePlugins("ringOpacity")) { + return { + "--tw-ring-color": (0, _toColorValue.default)(value) + }; + } + return (0, _withAlphaVariable.default)({ + color: value, + property: "--tw-ring-color", + variable: "--tw-ring-opacity" + }); + } + }, { + values: Object.fromEntries(Object.entries((0, _flattenColorPalette.default)(theme("ringColor"))).filter(([modifier])=>modifier !== "DEFAULT")), + type: [ + "color", + "any" + ] + }); + }, + ringOpacity: (helpers)=>{ + let { config } = helpers; + return (0, _createUtilityPlugin.default)("ringOpacity", [ + [ + "ring-opacity", + [ + "--tw-ring-opacity" + ] + ] + ], { + filterDefault: !(0, _featureFlags.flagEnabled)(config(), "respectDefaultRingColorOpacity") + })(helpers); + }, + ringOffsetWidth: (0, _createUtilityPlugin.default)("ringOffsetWidth", [ + [ + "ring-offset", + [ + "--tw-ring-offset-width" + ] + ] + ], { + type: "length" + }), + ringOffsetColor: ({ matchUtilities , theme })=>{ + matchUtilities({ + "ring-offset": (value)=>{ + return { + "--tw-ring-offset-color": (0, _toColorValue.default)(value) + }; + } + }, { + values: (0, _flattenColorPalette.default)(theme("ringOffsetColor")), + type: [ + "color", + "any" + ] + }); + }, + blur: ({ matchUtilities , theme })=>{ + matchUtilities({ + blur: (value)=>{ + return { + "--tw-blur": value.trim() === "" ? " " : `blur(${value})`, + "@defaults filter": {}, + filter: cssFilterValue + }; + } + }, { + values: theme("blur") + }); + }, + brightness: ({ matchUtilities , theme })=>{ + matchUtilities({ + brightness: (value)=>{ + return { + "--tw-brightness": `brightness(${value})`, + "@defaults filter": {}, + filter: cssFilterValue + }; + } + }, { + values: theme("brightness") + }); + }, + contrast: ({ matchUtilities , theme })=>{ + matchUtilities({ + contrast: (value)=>{ + return { + "--tw-contrast": `contrast(${value})`, + "@defaults filter": {}, + filter: cssFilterValue + }; + } + }, { + values: theme("contrast") + }); + }, + dropShadow: ({ matchUtilities , theme })=>{ + matchUtilities({ + "drop-shadow": (value)=>{ + return { + "--tw-drop-shadow": Array.isArray(value) ? value.map((v)=>`drop-shadow(${v})`).join(" ") : `drop-shadow(${value})`, + "@defaults filter": {}, + filter: cssFilterValue + }; + } + }, { + values: theme("dropShadow") + }); + }, + grayscale: ({ matchUtilities , theme })=>{ + matchUtilities({ + grayscale: (value)=>{ + return { + "--tw-grayscale": `grayscale(${value})`, + "@defaults filter": {}, + filter: cssFilterValue + }; + } + }, { + values: theme("grayscale") + }); + }, + hueRotate: ({ matchUtilities , theme })=>{ + matchUtilities({ + "hue-rotate": (value)=>{ + return { + "--tw-hue-rotate": `hue-rotate(${value})`, + "@defaults filter": {}, + filter: cssFilterValue + }; + } + }, { + values: theme("hueRotate"), + supportsNegativeValues: true + }); + }, + invert: ({ matchUtilities , theme })=>{ + matchUtilities({ + invert: (value)=>{ + return { + "--tw-invert": `invert(${value})`, + "@defaults filter": {}, + filter: cssFilterValue + }; + } + }, { + values: theme("invert") + }); + }, + saturate: ({ matchUtilities , theme })=>{ + matchUtilities({ + saturate: (value)=>{ + return { + "--tw-saturate": `saturate(${value})`, + "@defaults filter": {}, + filter: cssFilterValue + }; + } + }, { + values: theme("saturate") + }); + }, + sepia: ({ matchUtilities , theme })=>{ + matchUtilities({ + sepia: (value)=>{ + return { + "--tw-sepia": `sepia(${value})`, + "@defaults filter": {}, + filter: cssFilterValue + }; + } + }, { + values: theme("sepia") + }); + }, + filter: ({ addDefaults , addUtilities })=>{ + addDefaults("filter", { + "--tw-blur": " ", + "--tw-brightness": " ", + "--tw-contrast": " ", + "--tw-grayscale": " ", + "--tw-hue-rotate": " ", + "--tw-invert": " ", + "--tw-saturate": " ", + "--tw-sepia": " ", + "--tw-drop-shadow": " " + }); + addUtilities({ + ".filter": { + "@defaults filter": {}, + filter: cssFilterValue + }, + ".filter-none": { + filter: "none" + } + }); + }, + backdropBlur: ({ matchUtilities , theme })=>{ + matchUtilities({ + "backdrop-blur": (value)=>{ + return { + "--tw-backdrop-blur": value.trim() === "" ? " " : `blur(${value})`, + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }; + } + }, { + values: theme("backdropBlur") + }); + }, + backdropBrightness: ({ matchUtilities , theme })=>{ + matchUtilities({ + "backdrop-brightness": (value)=>{ + return { + "--tw-backdrop-brightness": `brightness(${value})`, + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }; + } + }, { + values: theme("backdropBrightness") + }); + }, + backdropContrast: ({ matchUtilities , theme })=>{ + matchUtilities({ + "backdrop-contrast": (value)=>{ + return { + "--tw-backdrop-contrast": `contrast(${value})`, + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }; + } + }, { + values: theme("backdropContrast") + }); + }, + backdropGrayscale: ({ matchUtilities , theme })=>{ + matchUtilities({ + "backdrop-grayscale": (value)=>{ + return { + "--tw-backdrop-grayscale": `grayscale(${value})`, + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }; + } + }, { + values: theme("backdropGrayscale") + }); + }, + backdropHueRotate: ({ matchUtilities , theme })=>{ + matchUtilities({ + "backdrop-hue-rotate": (value)=>{ + return { + "--tw-backdrop-hue-rotate": `hue-rotate(${value})`, + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }; + } + }, { + values: theme("backdropHueRotate"), + supportsNegativeValues: true + }); + }, + backdropInvert: ({ matchUtilities , theme })=>{ + matchUtilities({ + "backdrop-invert": (value)=>{ + return { + "--tw-backdrop-invert": `invert(${value})`, + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }; + } + }, { + values: theme("backdropInvert") + }); + }, + backdropOpacity: ({ matchUtilities , theme })=>{ + matchUtilities({ + "backdrop-opacity": (value)=>{ + return { + "--tw-backdrop-opacity": `opacity(${value})`, + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }; + } + }, { + values: theme("backdropOpacity") + }); + }, + backdropSaturate: ({ matchUtilities , theme })=>{ + matchUtilities({ + "backdrop-saturate": (value)=>{ + return { + "--tw-backdrop-saturate": `saturate(${value})`, + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }; + } + }, { + values: theme("backdropSaturate") + }); + }, + backdropSepia: ({ matchUtilities , theme })=>{ + matchUtilities({ + "backdrop-sepia": (value)=>{ + return { + "--tw-backdrop-sepia": `sepia(${value})`, + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }; + } + }, { + values: theme("backdropSepia") + }); + }, + backdropFilter: ({ addDefaults , addUtilities })=>{ + addDefaults("backdrop-filter", { + "--tw-backdrop-blur": " ", + "--tw-backdrop-brightness": " ", + "--tw-backdrop-contrast": " ", + "--tw-backdrop-grayscale": " ", + "--tw-backdrop-hue-rotate": " ", + "--tw-backdrop-invert": " ", + "--tw-backdrop-opacity": " ", + "--tw-backdrop-saturate": " ", + "--tw-backdrop-sepia": " " + }); + addUtilities({ + ".backdrop-filter": { + "@defaults backdrop-filter": {}, + "-webkit-backdrop-filter": cssBackdropFilterValue, + "backdrop-filter": cssBackdropFilterValue + }, + ".backdrop-filter-none": { + "-webkit-backdrop-filter": "none", + "backdrop-filter": "none" + } + }); + }, + transitionProperty: ({ matchUtilities , theme })=>{ + let defaultTimingFunction = theme("transitionTimingFunction.DEFAULT"); + let defaultDuration = theme("transitionDuration.DEFAULT"); + matchUtilities({ + transition: (value)=>{ + return { + "transition-property": value, + ...value === "none" ? {} : { + "transition-timing-function": defaultTimingFunction, + "transition-duration": defaultDuration + } + }; + } + }, { + values: theme("transitionProperty") + }); + }, + transitionDelay: (0, _createUtilityPlugin.default)("transitionDelay", [ + [ + "delay", + [ + "transitionDelay" + ] + ] + ]), + transitionDuration: (0, _createUtilityPlugin.default)("transitionDuration", [ + [ + "duration", + [ + "transitionDuration" + ] + ] + ], { + filterDefault: true + }), + transitionTimingFunction: (0, _createUtilityPlugin.default)("transitionTimingFunction", [ + [ + "ease", + [ + "transitionTimingFunction" + ] + ] + ], { + filterDefault: true + }), + willChange: (0, _createUtilityPlugin.default)("willChange", [ + [ + "will-change", + [ + "will-change" + ] + ] + ]), + contain: ({ addDefaults , addUtilities })=>{ + let cssContainValue = "var(--tw-contain-size) var(--tw-contain-layout) var(--tw-contain-paint) var(--tw-contain-style)"; + addDefaults("contain", { + "--tw-contain-size": " ", + "--tw-contain-layout": " ", + "--tw-contain-paint": " ", + "--tw-contain-style": " " + }); + addUtilities({ + ".contain-none": { + contain: "none" + }, + ".contain-content": { + contain: "content" + }, + ".contain-strict": { + contain: "strict" + }, + ".contain-size": { + "@defaults contain": {}, + "--tw-contain-size": "size", + contain: cssContainValue + }, + ".contain-inline-size": { + "@defaults contain": {}, + "--tw-contain-size": "inline-size", + contain: cssContainValue + }, + ".contain-layout": { + "@defaults contain": {}, + "--tw-contain-layout": "layout", + contain: cssContainValue + }, + ".contain-paint": { + "@defaults contain": {}, + "--tw-contain-paint": "paint", + contain: cssContainValue + }, + ".contain-style": { + "@defaults contain": {}, + "--tw-contain-style": "style", + contain: cssContainValue + } + }); + }, + content: (0, _createUtilityPlugin.default)("content", [ + [ + "content", + [ + "--tw-content", + [ + "content", + "var(--tw-content)" + ] + ] + ] + ]), + forcedColorAdjust: ({ addUtilities })=>{ + addUtilities({ + ".forced-color-adjust-auto": { + "forced-color-adjust": "auto" + }, + ".forced-color-adjust-none": { + "forced-color-adjust": "none" + } + }); + } +}; diff --git a/node_modules/tailwindcss/lib/css/LICENSE b/node_modules/tailwindcss/lib/css/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a1fb0394c924dc25311888ab85a5a5a1b4b9f20c --- /dev/null +++ b/node_modules/tailwindcss/lib/css/LICENSE @@ -0,0 +1,25 @@ +MIT License + +Copyright (c) Nicolas Gallagher +Copyright (c) Jonathan Neal +Copyright (c) Sindre Sorhus (sindresorhus.com) +Copyright (c) Adam Wathan +Copyright (c) Jonathan Reinink + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/tailwindcss/lib/css/preflight.css b/node_modules/tailwindcss/lib/css/preflight.css new file mode 100644 index 0000000000000000000000000000000000000000..04b9d1424a32ea876d61d6a6d0fd355f18c0b4e4 --- /dev/null +++ b/node_modules/tailwindcss/lib/css/preflight.css @@ -0,0 +1,386 @@ +/* +1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) +2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) +*/ + +*, +::before, +::after { + box-sizing: border-box; /* 1 */ + border-width: 0; /* 2 */ + border-style: solid; /* 2 */ + border-color: theme('borderColor.DEFAULT', currentColor); /* 2 */ +} + +::before, +::after { + --tw-content: ''; +} + +/* +1. Use a consistent sensible line-height in all browsers. +2. Prevent adjustments of font size after orientation changes in iOS. +3. Use a more readable tab size. +4. Use the user's configured `sans` font-family by default. +5. Use the user's configured `sans` font-feature-settings by default. +6. Use the user's configured `sans` font-variation-settings by default. +7. Disable tap highlights on iOS +*/ + +html, +:host { + line-height: 1.5; /* 1 */ + -webkit-text-size-adjust: 100%; /* 2 */ + -moz-tab-size: 4; /* 3 */ + tab-size: 4; /* 3 */ + font-family: theme('fontFamily.sans', ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"); /* 4 */ + font-feature-settings: theme('fontFamily.sans[1].fontFeatureSettings', normal); /* 5 */ + font-variation-settings: theme('fontFamily.sans[1].fontVariationSettings', normal); /* 6 */ + -webkit-tap-highlight-color: transparent; /* 7 */ +} + +/* +1. Remove the margin in all browsers. +2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. +*/ + +body { + margin: 0; /* 1 */ + line-height: inherit; /* 2 */ +} + +/* +1. Add the correct height in Firefox. +2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) +3. Ensure horizontal rules are visible by default. +*/ + +hr { + height: 0; /* 1 */ + color: inherit; /* 2 */ + border-top-width: 1px; /* 3 */ +} + +/* +Add the correct text decoration in Chrome, Edge, and Safari. +*/ + +abbr:where([title]) { + text-decoration: underline dotted; +} + +/* +Remove the default font size and weight for headings. +*/ + +h1, +h2, +h3, +h4, +h5, +h6 { + font-size: inherit; + font-weight: inherit; +} + +/* +Reset links to optimize for opt-in styling instead of opt-out. +*/ + +a { + color: inherit; + text-decoration: inherit; +} + +/* +Add the correct font weight in Edge and Safari. +*/ + +b, +strong { + font-weight: bolder; +} + +/* +1. Use the user's configured `mono` font-family by default. +2. Use the user's configured `mono` font-feature-settings by default. +3. Use the user's configured `mono` font-variation-settings by default. +4. Correct the odd `em` font sizing in all browsers. +*/ + +code, +kbd, +samp, +pre { + font-family: theme('fontFamily.mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace); /* 1 */ + font-feature-settings: theme('fontFamily.mono[1].fontFeatureSettings', normal); /* 2 */ + font-variation-settings: theme('fontFamily.mono[1].fontVariationSettings', normal); /* 3 */ + font-size: 1em; /* 4 */ +} + +/* +Add the correct font size in all browsers. +*/ + +small { + font-size: 80%; +} + +/* +Prevent `sub` and `sup` elements from affecting the line height in all browsers. +*/ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sub { + bottom: -0.25em; +} + +sup { + top: -0.5em; +} + +/* +1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) +2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) +3. Remove gaps between table borders by default. +*/ + +table { + text-indent: 0; /* 1 */ + border-color: inherit; /* 2 */ + border-collapse: collapse; /* 3 */ +} + +/* +1. Change the font styles in all browsers. +2. Remove the margin in Firefox and Safari. +3. Remove default padding in all browsers. +*/ + +button, +input, +optgroup, +select, +textarea { + font-family: inherit; /* 1 */ + font-feature-settings: inherit; /* 1 */ + font-variation-settings: inherit; /* 1 */ + font-size: 100%; /* 1 */ + font-weight: inherit; /* 1 */ + line-height: inherit; /* 1 */ + letter-spacing: inherit; /* 1 */ + color: inherit; /* 1 */ + margin: 0; /* 2 */ + padding: 0; /* 3 */ +} + +/* +Remove the inheritance of text transform in Edge and Firefox. +*/ + +button, +select { + text-transform: none; +} + +/* +1. Correct the inability to style clickable types in iOS and Safari. +2. Remove default button styles. +*/ + +button, +input:where([type='button']), +input:where([type='reset']), +input:where([type='submit']) { + -webkit-appearance: button; /* 1 */ + background-color: transparent; /* 2 */ + background-image: none; /* 2 */ +} + +/* +Use the modern Firefox focus style for all focusable elements. +*/ + +:-moz-focusring { + outline: auto; +} + +/* +Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) +*/ + +:-moz-ui-invalid { + box-shadow: none; +} + +/* +Add the correct vertical alignment in Chrome and Firefox. +*/ + +progress { + vertical-align: baseline; +} + +/* +Correct the cursor style of increment and decrement buttons in Safari. +*/ + +::-webkit-inner-spin-button, +::-webkit-outer-spin-button { + height: auto; +} + +/* +1. Correct the odd appearance in Chrome and Safari. +2. Correct the outline style in Safari. +*/ + +[type='search'] { + -webkit-appearance: textfield; /* 1 */ + outline-offset: -2px; /* 2 */ +} + +/* +Remove the inner padding in Chrome and Safari on macOS. +*/ + +::-webkit-search-decoration { + -webkit-appearance: none; +} + +/* +1. Correct the inability to style clickable types in iOS and Safari. +2. Change font properties to `inherit` in Safari. +*/ + +::-webkit-file-upload-button { + -webkit-appearance: button; /* 1 */ + font: inherit; /* 2 */ +} + +/* +Add the correct display in Chrome and Safari. +*/ + +summary { + display: list-item; +} + +/* +Removes the default spacing and border for appropriate elements. +*/ + +blockquote, +dl, +dd, +h1, +h2, +h3, +h4, +h5, +h6, +hr, +figure, +p, +pre { + margin: 0; +} + +fieldset { + margin: 0; + padding: 0; +} + +legend { + padding: 0; +} + +ol, +ul, +menu { + list-style: none; + margin: 0; + padding: 0; +} + +/* +Reset default styling for dialogs. +*/ +dialog { + padding: 0; +} + +/* +Prevent resizing textareas horizontally by default. +*/ + +textarea { + resize: vertical; +} + +/* +1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) +2. Set the default placeholder color to the user's configured gray 400 color. +*/ + +input::placeholder, +textarea::placeholder { + opacity: 1; /* 1 */ + color: theme('colors.gray.400', #9ca3af); /* 2 */ +} + +/* +Set the default cursor for buttons. +*/ + +button, +[role="button"] { + cursor: pointer; +} + +/* +Make sure disabled buttons don't get the pointer cursor. +*/ +:disabled { + cursor: default; +} + +/* +1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) +2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) + This can trigger a poorly considered lint error in some tools but is included by design. +*/ + +img, +svg, +video, +canvas, +audio, +iframe, +embed, +object { + display: block; /* 1 */ + vertical-align: middle; /* 2 */ +} + +/* +Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) +*/ + +img, +video { + max-width: 100%; + height: auto; +} + +/* Make elements with the HTML hidden attribute stay hidden by default */ +[hidden]:where(:not([hidden="until-found"])) { + display: none; +} diff --git a/node_modules/tailwindcss/lib/featureFlags.js b/node_modules/tailwindcss/lib/featureFlags.js new file mode 100644 index 0000000000000000000000000000000000000000..78826fd661c88b54aa0cdcb38117555ff423703f --- /dev/null +++ b/node_modules/tailwindcss/lib/featureFlags.js @@ -0,0 +1,79 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + flagEnabled: function() { + return flagEnabled; + }, + issueFlagNotices: function() { + return issueFlagNotices; + }, + default: function() { + return _default; + } +}); +const _picocolors = /*#__PURE__*/ _interop_require_default(require("picocolors")); +const _log = /*#__PURE__*/ _interop_require_default(require("./util/log")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +let defaults = { + optimizeUniversalDefaults: false, + generalizedModifiers: true, + disableColorOpacityUtilitiesByDefault: false, + relativeContentPathsByDefault: false +}; +let featureFlags = { + future: [ + "hoverOnlyWhenSupported", + "respectDefaultRingColorOpacity", + "disableColorOpacityUtilitiesByDefault", + "relativeContentPathsByDefault" + ], + experimental: [ + "optimizeUniversalDefaults", + "generalizedModifiers" + ] +}; +function flagEnabled(config, flag) { + if (featureFlags.future.includes(flag)) { + var _config_future; + var _config_future_flag, _ref; + return config.future === "all" || ((_ref = (_config_future_flag = config === null || config === void 0 ? void 0 : (_config_future = config.future) === null || _config_future === void 0 ? void 0 : _config_future[flag]) !== null && _config_future_flag !== void 0 ? _config_future_flag : defaults[flag]) !== null && _ref !== void 0 ? _ref : false); + } + if (featureFlags.experimental.includes(flag)) { + var _config_experimental; + var _config_experimental_flag, _ref1; + return config.experimental === "all" || ((_ref1 = (_config_experimental_flag = config === null || config === void 0 ? void 0 : (_config_experimental = config.experimental) === null || _config_experimental === void 0 ? void 0 : _config_experimental[flag]) !== null && _config_experimental_flag !== void 0 ? _config_experimental_flag : defaults[flag]) !== null && _ref1 !== void 0 ? _ref1 : false); + } + return false; +} +function experimentalFlagsEnabled(config) { + if (config.experimental === "all") { + return featureFlags.experimental; + } + var _config_experimental; + return Object.keys((_config_experimental = config === null || config === void 0 ? void 0 : config.experimental) !== null && _config_experimental !== void 0 ? _config_experimental : {}).filter((flag)=>featureFlags.experimental.includes(flag) && config.experimental[flag]); +} +function issueFlagNotices(config) { + if (process.env.JEST_WORKER_ID !== undefined) { + return; + } + if (experimentalFlagsEnabled(config).length > 0) { + let changes = experimentalFlagsEnabled(config).map((s)=>_picocolors.default.yellow(s)).join(", "); + _log.default.warn("experimental-flags-enabled", [ + `You have enabled experimental features: ${changes}`, + "Experimental features in Tailwind CSS are not covered by semver, may introduce breaking changes, and can change at any time." + ]); + } +} +const _default = featureFlags; diff --git a/node_modules/tailwindcss/lib/index.js b/node_modules/tailwindcss/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c947d974344ed3731bddc3f210cf94b270d1c983 --- /dev/null +++ b/node_modules/tailwindcss/lib/index.js @@ -0,0 +1,2 @@ +"use strict"; +module.exports = require("./plugin"); diff --git a/node_modules/tailwindcss/lib/lib/cacheInvalidation.js b/node_modules/tailwindcss/lib/lib/cacheInvalidation.js new file mode 100644 index 0000000000000000000000000000000000000000..c24717970ed01726821b4028479dc9d5ad522e06 --- /dev/null +++ b/node_modules/tailwindcss/lib/lib/cacheInvalidation.js @@ -0,0 +1,92 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "hasContentChanged", { + enumerable: true, + get: function() { + return hasContentChanged; + } +}); +const _crypto = /*#__PURE__*/ _interop_require_default(require("crypto")); +const _sharedState = /*#__PURE__*/ _interop_require_wildcard(require("./sharedState")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Calculate the hash of a string. + * + * This doesn't need to be cryptographically secure or + * anything like that since it's used only to detect + * when the CSS changes to invalidate the context. + * + * This is wrapped in a try/catch because it's really dependent + * on how Node itself is build and the environment and OpenSSL + * version / build that is installed on the user's machine. + * + * Based on the environment this can just outright fail. + * + * See https://github.com/nodejs/node/issues/40455 + * + * @param {string} str + */ function getHash(str) { + try { + return _crypto.default.createHash("md5").update(str, "utf-8").digest("binary"); + } catch (err) { + return ""; + } +} +function hasContentChanged(sourcePath, root) { + let css = root.toString(); + // We only care about files with @tailwind directives + // Other files use an existing context + if (!css.includes("@tailwind")) { + return false; + } + let existingHash = _sharedState.sourceHashMap.get(sourcePath); + let rootHash = getHash(css); + let didChange = existingHash !== rootHash; + _sharedState.sourceHashMap.set(sourcePath, rootHash); + return didChange; +} diff --git a/node_modules/tailwindcss/lib/lib/collapseAdjacentRules.js b/node_modules/tailwindcss/lib/lib/collapseAdjacentRules.js new file mode 100644 index 0000000000000000000000000000000000000000..e900872b05bc0917008e8cf526869143ab4d4698 --- /dev/null +++ b/node_modules/tailwindcss/lib/lib/collapseAdjacentRules.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return collapseAdjacentRules; + } +}); +let comparisonMap = { + atrule: [ + "name", + "params" + ], + rule: [ + "selector" + ] +}; +let types = new Set(Object.keys(comparisonMap)); +function collapseAdjacentRules() { + function collapseRulesIn(root) { + let currentRule = null; + root.each((node)=>{ + if (!types.has(node.type)) { + currentRule = null; + return; + } + if (currentRule === null) { + currentRule = node; + return; + } + let properties = comparisonMap[node.type]; + var _node_property, _currentRule_property; + if (node.type === "atrule" && node.name === "font-face") { + currentRule = node; + } else if (properties.every((property)=>((_node_property = node[property]) !== null && _node_property !== void 0 ? _node_property : "").replace(/\s+/g, " ") === ((_currentRule_property = currentRule[property]) !== null && _currentRule_property !== void 0 ? _currentRule_property : "").replace(/\s+/g, " "))) { + // An AtRule may not have children (for example if we encounter duplicate @import url(…) rules) + if (node.nodes) { + currentRule.append(node.nodes); + } + node.remove(); + } else { + currentRule = node; + } + }); + // After we've collapsed adjacent rules & at-rules, we need to collapse + // adjacent rules & at-rules that are children of at-rules. + // We do not care about nesting rules because Tailwind CSS + // explicitly does not handle rule nesting on its own as + // the user is expected to use a nesting plugin + root.each((node)=>{ + if (node.type === "atrule") { + collapseRulesIn(node); + } + }); + } + return (root)=>{ + collapseRulesIn(root); + }; +} diff --git a/node_modules/tailwindcss/lib/lib/collapseDuplicateDeclarations.js b/node_modules/tailwindcss/lib/lib/collapseDuplicateDeclarations.js new file mode 100644 index 0000000000000000000000000000000000000000..70a1ad1a388b7a2c9e9c60c12dde8e3d41a43e53 --- /dev/null +++ b/node_modules/tailwindcss/lib/lib/collapseDuplicateDeclarations.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return collapseDuplicateDeclarations; + } +}); +function collapseDuplicateDeclarations() { + return (root)=>{ + root.walkRules((node)=>{ + let seen = new Map(); + let droppable = new Set([]); + let byProperty = new Map(); + node.walkDecls((decl)=>{ + // This could happen if we have nested selectors. In that case the + // parent will loop over all its declarations but also the declarations + // of nested rules. With this we ensure that we are shallowly checking + // declarations. + if (decl.parent !== node) { + return; + } + if (seen.has(decl.prop)) { + // Exact same value as what we have seen so far + if (seen.get(decl.prop).value === decl.value) { + // Keep the last one, drop the one we've seen so far + droppable.add(seen.get(decl.prop)); + // Override the existing one with the new value. This is necessary + // so that if we happen to have more than one declaration with the + // same value, that we keep removing the previous one. Otherwise we + // will only remove the *first* one. + seen.set(decl.prop, decl); + return; + } + // Not the same value, so we need to check if we can merge it so + // let's collect it first. + if (!byProperty.has(decl.prop)) { + byProperty.set(decl.prop, new Set()); + } + byProperty.get(decl.prop).add(seen.get(decl.prop)); + byProperty.get(decl.prop).add(decl); + } + seen.set(decl.prop, decl); + }); + // Drop all the duplicate declarations with the exact same value we've + // already seen so far. + for (let decl of droppable){ + decl.remove(); + } + // Analyze the declarations based on its unit, drop all the declarations + // with the same unit but the last one in the list. + for (let declarations of byProperty.values()){ + let byUnit = new Map(); + for (let decl of declarations){ + let unit = resolveUnit(decl.value); + if (unit === null) { + continue; + } + if (!byUnit.has(unit)) { + byUnit.set(unit, new Set()); + } + byUnit.get(unit).add(decl); + } + for (let declarations of byUnit.values()){ + // Get all but the last one + let removableDeclarations = Array.from(declarations).slice(0, -1); + for (let decl of removableDeclarations){ + decl.remove(); + } + } + } + }); + }; +} +let UNITLESS_NUMBER = Symbol("unitless-number"); +function resolveUnit(input) { + let result = /^-?\d*.?\d+([\w%]+)?$/g.exec(input); + if (result) { + var _result_; + return (_result_ = result[1]) !== null && _result_ !== void 0 ? _result_ : UNITLESS_NUMBER; + } + return null; +} diff --git a/node_modules/tailwindcss/lib/lib/content.js b/node_modules/tailwindcss/lib/lib/content.js new file mode 100644 index 0000000000000000000000000000000000000000..a2d5941abe9b6b3f83f80f52e2323b8e392caf10 --- /dev/null +++ b/node_modules/tailwindcss/lib/lib/content.js @@ -0,0 +1,247 @@ +// @ts-check +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +function _export(target, all) { + for(var name in all)Object.defineProperty(target, name, { + enumerable: true, + get: all[name] + }); +} +_export(exports, { + parseCandidateFiles: function() { + return parseCandidateFiles; + }, + resolvedChangedContent: function() { + return resolvedChangedContent; + }, + createBroadPatternCheck: function() { + return createBroadPatternCheck; + } +}); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _path = /*#__PURE__*/ _interop_require_default(require("path")); +const _isglob = /*#__PURE__*/ _interop_require_default(require("is-glob")); +const _fastglob = /*#__PURE__*/ _interop_require_default(require("fast-glob")); +const _normalizepath = /*#__PURE__*/ _interop_require_default(require("normalize-path")); +const _parseGlob = require("../util/parseGlob"); +const _sharedState = require("./sharedState"); +const _log = /*#__PURE__*/ _interop_require_default(require("../util/log")); +const _micromatch = /*#__PURE__*/ _interop_require_default(require("micromatch")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function parseCandidateFiles(context, tailwindConfig) { + let files = tailwindConfig.content.files; + // Normalize the file globs + files = files.filter((filePath)=>typeof filePath === "string"); + files = files.map(_normalizepath.default); + // Split into included and excluded globs + let tasks = _fastglob.default.generateTasks(files); + /** @type {ContentPath[]} */ let included = []; + /** @type {ContentPath[]} */ let excluded = []; + for (const task of tasks){ + included.push(...task.positive.map((filePath)=>parseFilePath(filePath, false))); + excluded.push(...task.negative.map((filePath)=>parseFilePath(filePath, true))); + } + let paths = [ + ...included, + ...excluded + ]; + // Resolve paths relative to the config file or cwd + paths = resolveRelativePaths(context, paths); + // Resolve symlinks if possible + paths = paths.flatMap(resolvePathSymlinks); + // Update cached patterns + paths = paths.map(resolveGlobPattern); + return paths; +} +/** + * + * @param {string} filePath + * @param {boolean} ignore + * @returns {ContentPath} + */ function parseFilePath(filePath, ignore) { + let contentPath = { + original: filePath, + base: filePath, + ignore, + pattern: filePath, + glob: null + }; + if ((0, _isglob.default)(filePath)) { + Object.assign(contentPath, (0, _parseGlob.parseGlob)(filePath)); + } + return contentPath; +} +/** + * + * @param {ContentPath} contentPath + * @returns {ContentPath} + */ function resolveGlobPattern(contentPath) { + // This is required for Windows support to properly pick up Glob paths. + // Afaik, this technically shouldn't be needed but there's probably + // some internal, direct path matching with a normalized path in + // a package which can't handle mixed directory separators + let base = (0, _normalizepath.default)(contentPath.base); + // If the user's file path contains any special characters (like parens) for instance fast-glob + // is like "OOOH SHINY" and treats them as such. So we have to escape the base path to fix this + base = _fastglob.default.escapePath(base); + contentPath.pattern = contentPath.glob ? `${base}/${contentPath.glob}` : base; + contentPath.pattern = contentPath.ignore ? `!${contentPath.pattern}` : contentPath.pattern; + return contentPath; +} +/** + * Resolve each path relative to the config file (when possible) if the experimental flag is enabled + * Otherwise, resolve relative to the current working directory + * + * @param {any} context + * @param {ContentPath[]} contentPaths + * @returns {ContentPath[]} + */ function resolveRelativePaths(context, contentPaths) { + let resolveFrom = []; + // Resolve base paths relative to the config file (when possible) if the experimental flag is enabled + if (context.userConfigPath && context.tailwindConfig.content.relative) { + resolveFrom = [ + _path.default.dirname(context.userConfigPath) + ]; + } + return contentPaths.map((contentPath)=>{ + contentPath.base = _path.default.resolve(...resolveFrom, contentPath.base); + return contentPath; + }); +} +/** + * Resolve the symlink for the base directory / file in each path + * These are added as additional dependencies to watch for changes because + * some tools (like webpack) will only watch the actual file or directory + * but not the symlink itself even in projects that use monorepos. + * + * @param {ContentPath} contentPath + * @returns {ContentPath[]} + */ function resolvePathSymlinks(contentPath) { + let paths = [ + contentPath + ]; + try { + let resolvedPath = _fs.default.realpathSync(contentPath.base); + if (resolvedPath !== contentPath.base) { + paths.push({ + ...contentPath, + base: resolvedPath + }); + } + } catch { + // TODO: log this? + } + return paths; +} +function resolvedChangedContent(context, candidateFiles, fileModifiedMap) { + let changedContent = context.tailwindConfig.content.files.filter((item)=>typeof item.raw === "string").map(({ raw , extension ="html" })=>({ + content: raw, + extension + })); + let [changedFiles, mTimesToCommit] = resolveChangedFiles(candidateFiles, fileModifiedMap); + for (let changedFile of changedFiles){ + let extension = _path.default.extname(changedFile).slice(1); + changedContent.push({ + file: changedFile, + extension + }); + } + return [ + changedContent, + mTimesToCommit + ]; +} +const LARGE_DIRECTORIES = [ + "node_modules" +]; +// Ensures that `node_modules` has to match as-is, otherwise `mynode_modules` +// would match as well, but that is not a known large directory. +const LARGE_DIRECTORIES_REGEX = new RegExp(`(${LARGE_DIRECTORIES.map((dir)=>String.raw`\b${dir}\b`).join("|")})`); +function createBroadPatternCheck(paths) { + // Detect whether a glob pattern might be too broad. This means that it: + // - Includes `**` + // - Does not include any of the known large directories (e.g.: node_modules) + let maybeBroadPattern = paths.some((path)=>path.includes("**") && !LARGE_DIRECTORIES_REGEX.test(path)); + // Didn't detect any potentially broad patterns, so we can skip further + // checks. + if (!maybeBroadPattern) { + return ()=>{}; + } + // All glob matchers + let matchers = []; + // All glob matchers that explicitly contain any of the known large + // directories (e.g.: node_modules). + let explicitMatchers = []; + // Create matchers for all paths + for (let path of paths){ + let matcher = _micromatch.default.matcher(path); + if (LARGE_DIRECTORIES_REGEX.test(path)) { + explicitMatchers.push(matcher); + } + matchers.push(matcher); + } + // Keep track of whether we already warned about the broad pattern issue or + // not. The `log.warn` function already does something similar where we only + // output the log once. However, with this we can also skip the other checks + // when we already warned about the broad pattern. + let warned = false; + /** + * @param {string} file + */ return (file)=>{ + if (warned) return; // Already warned about the broad pattern + if (explicitMatchers.some((matcher)=>matcher(file))) return; // Explicitly included, so we can skip further checks + // When a broad pattern is used, we have to double check that the file was + // not explicitly included in the globs. + let matchingGlobIndex = matchers.findIndex((matcher)=>matcher(file)); + if (matchingGlobIndex === -1) return; // This should never happen + let matchingGlob = paths[matchingGlobIndex]; + // Create relative paths to make the output a bit more readable. + let relativeMatchingGlob = _path.default.relative(process.cwd(), matchingGlob); + if (relativeMatchingGlob[0] !== ".") relativeMatchingGlob = `./${relativeMatchingGlob}`; + let largeDirectory = LARGE_DIRECTORIES.find((directory)=>file.includes(directory)); + if (largeDirectory) { + warned = true; + _log.default.warn("broad-content-glob-pattern", [ + `Your \`content\` configuration includes a pattern which looks like it's accidentally matching all of \`${largeDirectory}\` and can cause serious performance issues.`, + `Pattern: \`${relativeMatchingGlob}\``, + `See our documentation for recommendations:`, + "https://tailwindcss.com/docs/content-configuration#pattern-recommendations" + ]); + } + }; +} +/** + * + * @param {ContentPath[]} candidateFiles + * @param {Map} fileModifiedMap + * @returns {[Set, Map]} + */ function resolveChangedFiles(candidateFiles, fileModifiedMap) { + let paths = candidateFiles.map((contentPath)=>contentPath.pattern); + let mTimesToCommit = new Map(); + let checkBroadPattern = createBroadPatternCheck(paths); + let changedFiles = new Set(); + _sharedState.env.DEBUG && console.time("Finding changed files"); + let files = _fastglob.default.sync(paths, { + absolute: true + }); + for (let file of files){ + checkBroadPattern(file); + let prevModified = fileModifiedMap.get(file) || -Infinity; + let modified = _fs.default.statSync(file).mtimeMs; + if (modified > prevModified) { + changedFiles.add(file); + mTimesToCommit.set(file, modified); + } + } + _sharedState.env.DEBUG && console.timeEnd("Finding changed files"); + return [ + changedFiles, + mTimesToCommit + ]; +} diff --git a/node_modules/tailwindcss/lib/lib/defaultExtractor.js b/node_modules/tailwindcss/lib/lib/defaultExtractor.js new file mode 100644 index 0000000000000000000000000000000000000000..684808b5a5603e5ebce28a51f5aca7baf0a190c6 --- /dev/null +++ b/node_modules/tailwindcss/lib/lib/defaultExtractor.js @@ -0,0 +1,273 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "defaultExtractor", { + enumerable: true, + get: function() { + return defaultExtractor; + } +}); +const _regex = /*#__PURE__*/ _interop_require_wildcard(require("./regex")); +const _splitAtTopLevelOnly = require("../util/splitAtTopLevelOnly"); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function defaultExtractor(context) { + let patterns = Array.from(buildRegExps(context)); + /** + * @param {string} content + */ return (content)=>{ + /** @type {(string|string)[]} */ let results = []; + for (let pattern of patterns){ + var _content_match; + for (let result of (_content_match = content.match(pattern)) !== null && _content_match !== void 0 ? _content_match : []){ + results.push(clipAtBalancedParens(result)); + } + } + // Extract any subclasses from languages like Slim and Pug, eg: + // div.flex.px-5.underline + for (let result of results.slice()){ + let segments = (0, _splitAtTopLevelOnly.splitAtTopLevelOnly)(result, "."); + for(let idx = 0; idx < segments.length; idx++){ + let segment = segments[idx]; + if (idx >= segments.length - 1) { + results.push(segment); + continue; + } + // If the next segment is a number, discard both, for example seeing + // `px-1` and `5` means the real candidate was `px-1.5` which is already + // captured. + let next = Number(segments[idx + 1]); + if (isNaN(next)) { + results.push(segment); + } else { + idx++; + } + } + } + return results; + }; +} +function* buildRegExps(context) { + let separator = context.tailwindConfig.separator; + let prefix = context.tailwindConfig.prefix !== "" ? _regex.optional(_regex.pattern([ + /-?/, + _regex.escape(context.tailwindConfig.prefix) + ])) : ""; + let utility = _regex.any([ + // Arbitrary properties (without square brackets) + /\[[^\s:'"`]+:[^\s\[\]]+\]/, + // Arbitrary properties with balanced square brackets + // This is a targeted fix to continue to allow theme() + // with square brackets to work in arbitrary properties + // while fixing a problem with the regex matching too much + /\[[^\s:'"`\]]+:[^\s]+?\[[^\s]+\][^\s]+?\]/, + // Utilities + _regex.pattern([ + // Utility Name / Group Name + _regex.any([ + /-?(?:\w+)/, + // This is here to make sure @container supports everything that other utilities do + /@(?:\w+)/ + ]), + // Normal/Arbitrary values + _regex.optional(_regex.any([ + _regex.pattern([ + // Arbitrary values + _regex.any([ + /-(?:\w+-)*\['[^\s]+'\]/, + /-(?:\w+-)*\["[^\s]+"\]/, + /-(?:\w+-)*\[`[^\s]+`\]/, + /-(?:\w+-)*\[(?:[^\s\[\]]+\[[^\s\[\]]+\])*[^\s:\[\]]+\]/ + ]), + // Not immediately followed by an `{[(` + /(?![{([]])/, + // optionally followed by an opacity modifier + /(?:\/[^\s'"`\\><$]*)?/ + ]), + _regex.pattern([ + // Arbitrary values + _regex.any([ + /-(?:\w+-)*\['[^\s]+'\]/, + /-(?:\w+-)*\["[^\s]+"\]/, + /-(?:\w+-)*\[`[^\s]+`\]/, + /-(?:\w+-)*\[(?:[^\s\[\]]+\[[^\s\[\]]+\])*[^\s\[\]]+\]/ + ]), + // Not immediately followed by an `{[(` + /(?![{([]])/, + // optionally followed by an opacity modifier + /(?:\/[^\s'"`\\$]*)?/ + ]), + // Normal values w/o quotes — may include an opacity modifier + /[-\/][^\s'"`\\$={><]*/ + ])) + ]) + ]); + let variantPatterns = [ + // Without quotes + _regex.any([ + // This is here to provide special support for the `@` variant + _regex.pattern([ + /@\[[^\s"'`]+\](\/[^\s"'`]+)?/, + separator + ]), + // With variant modifier (e.g.: group-[..]/modifier) + _regex.pattern([ + /([^\s"'`\[\\]+-)?\[[^\s"'`]+\]\/[\w_-]+/, + separator + ]), + _regex.pattern([ + /([^\s"'`\[\\]+-)?\[[^\s"'`]+\]/, + separator + ]), + _regex.pattern([ + /[^\s"'`\[\\]+/, + separator + ]) + ]), + // With quotes allowed + _regex.any([ + // With variant modifier (e.g.: group-[..]/modifier) + _regex.pattern([ + /([^\s"'`\[\\]+-)?\[[^\s`]+\]\/[\w_-]+/, + separator + ]), + _regex.pattern([ + /([^\s"'`\[\\]+-)?\[[^\s`]+\]/, + separator + ]), + _regex.pattern([ + /[^\s`\[\\]+/, + separator + ]) + ]) + ]; + for (const variantPattern of variantPatterns){ + yield _regex.pattern([ + // Variants + "((?=((", + variantPattern, + ")+))\\2)?", + // Important (optional) + /!?/, + prefix, + utility + ]); + } + // 5. Inner matches + yield /[^<>"'`\s.(){}[\]#=%$][^<>"'`\s(){}[\]#=%$]*[^<>"'`\s.(){}[\]#=%:$]/g; +} +// We want to capture any "special" characters +// AND the characters immediately following them (if there is one) +let SPECIALS = /([\[\]'"`])([^\[\]'"`])?/g; +let ALLOWED_CLASS_CHARACTERS = /[^"'`\s<>\]]+/; +/** + * Clips a string ensuring that parentheses, quotes, etc… are balanced + * Used for arbitrary values only + * + * We will go past the end of the balanced parens until we find a non-class character + * + * Depth matching behavior: + * w-[calc(100%-theme('spacing[some_key][1.5]'))]'] + * ┬ ┬ ┬┬ ┬ ┬┬ ┬┬┬┬┬┬┬ + * 1 2 3 4 34 3 210 END + * ╰────┴──────────┴────────┴────────┴┴───┴─┴┴┴ + * + * @param {string} input + */ function clipAtBalancedParens(input) { + // We are care about this for arbitrary values + if (!input.includes("-[")) { + return input; + } + let depth = 0; + let openStringTypes = []; + // Find all parens, brackets, quotes, etc + // Stop when we end at a balanced pair + // This is naive and will treat mismatched parens as balanced + // This shouldn't be a problem in practice though + let matches = input.matchAll(SPECIALS); + // We can't use lookbehind assertions because we have to support Safari + // So, instead, we've emulated it using capture groups and we'll re-work the matches to accommodate + matches = Array.from(matches).flatMap((match)=>{ + const [, ...groups] = match; + return groups.map((group, idx)=>Object.assign([], match, { + index: match.index + idx, + 0: group + })); + }); + for (let match of matches){ + let char = match[0]; + let inStringType = openStringTypes[openStringTypes.length - 1]; + if (char === inStringType) { + openStringTypes.pop(); + } else if (char === "'" || char === '"' || char === "`") { + openStringTypes.push(char); + } + if (inStringType) { + continue; + } else if (char === "[") { + depth++; + continue; + } else if (char === "]") { + depth--; + continue; + } + // We've gone one character past the point where we should stop + // This means that there was an extra closing `]` + // We'll clip to just before it + if (depth < 0) { + return input.substring(0, match.index - 1); + } + // We've finished balancing the brackets but there still may be characters that can be included + // For example in the class `text-[#336699]/[.35]` + // The depth goes to `0` at the closing `]` but goes up again at the `[` + // If we're at zero and encounter a non-class character then we clip the class there + if (depth === 0 && !ALLOWED_CLASS_CHARACTERS.test(char)) { + return input.substring(0, match.index); + } + } + return input; +} // Regular utilities + // {{modifier}:}*{namespace}{-{suffix}}*{/{opacityModifier}}? + // Arbitrary values + // {{modifier}:}*{namespace}-[{arbitraryValue}]{/{opacityModifier}}? + // arbitraryValue: no whitespace, balanced quotes unless within quotes, balanced brackets unless within quotes + // Arbitrary properties + // {{modifier}:}*[{validCssPropertyName}:{arbitraryValue}] diff --git a/node_modules/tailwindcss/lib/lib/evaluateTailwindFunctions.js b/node_modules/tailwindcss/lib/lib/evaluateTailwindFunctions.js new file mode 100644 index 0000000000000000000000000000000000000000..e2e3c265eed131f192bd37f4b2cc0855a6109bbe --- /dev/null +++ b/node_modules/tailwindcss/lib/lib/evaluateTailwindFunctions.js @@ -0,0 +1,238 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return _default; + } +}); +const _dlv = /*#__PURE__*/ _interop_require_default(require("dlv")); +const _didyoumean = /*#__PURE__*/ _interop_require_default(require("didyoumean")); +const _transformThemeValue = /*#__PURE__*/ _interop_require_default(require("../util/transformThemeValue")); +const _index = /*#__PURE__*/ _interop_require_default(require("../value-parser/index")); +const _normalizeScreens = require("../util/normalizeScreens"); +const _buildMediaQuery = /*#__PURE__*/ _interop_require_default(require("../util/buildMediaQuery")); +const _toPath = require("../util/toPath"); +const _withAlphaVariable = require("../util/withAlphaVariable"); +const _pluginUtils = require("../util/pluginUtils"); +const _log = /*#__PURE__*/ _interop_require_default(require("../util/log")); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function isObject(input) { + return typeof input === "object" && input !== null; +} +function findClosestExistingPath(theme, path) { + let parts = (0, _toPath.toPath)(path); + do { + parts.pop(); + if ((0, _dlv.default)(theme, parts) !== undefined) break; + }while (parts.length); + return parts.length ? parts : undefined; +} +function pathToString(path) { + if (typeof path === "string") return path; + return path.reduce((acc, cur, i)=>{ + if (cur.includes(".")) return `${acc}[${cur}]`; + return i === 0 ? cur : `${acc}.${cur}`; + }, ""); +} +function list(items) { + return items.map((key)=>`'${key}'`).join(", "); +} +function listKeys(obj) { + return list(Object.keys(obj)); +} +function validatePath(config, path, defaultValue, themeOpts = {}) { + const pathString = Array.isArray(path) ? pathToString(path) : path.replace(/^['"]+|['"]+$/g, ""); + const pathSegments = Array.isArray(path) ? path : (0, _toPath.toPath)(pathString); + const value = (0, _dlv.default)(config.theme, pathSegments, defaultValue); + if (value === undefined) { + let error = `'${pathString}' does not exist in your theme config.`; + const parentSegments = pathSegments.slice(0, -1); + const parentValue = (0, _dlv.default)(config.theme, parentSegments); + if (isObject(parentValue)) { + const validKeys = Object.keys(parentValue).filter((key)=>validatePath(config, [ + ...parentSegments, + key + ]).isValid); + const suggestion = (0, _didyoumean.default)(pathSegments[pathSegments.length - 1], validKeys); + if (suggestion) { + error += ` Did you mean '${pathToString([ + ...parentSegments, + suggestion + ])}'?`; + } else if (validKeys.length > 0) { + error += ` '${pathToString(parentSegments)}' has the following valid keys: ${list(validKeys)}`; + } + } else { + const closestPath = findClosestExistingPath(config.theme, pathString); + if (closestPath) { + const closestValue = (0, _dlv.default)(config.theme, closestPath); + if (isObject(closestValue)) { + error += ` '${pathToString(closestPath)}' has the following keys: ${listKeys(closestValue)}`; + } else { + error += ` '${pathToString(closestPath)}' is not an object.`; + } + } else { + error += ` Your theme has the following top-level keys: ${listKeys(config.theme)}`; + } + } + return { + isValid: false, + error + }; + } + if (!(typeof value === "string" || typeof value === "number" || typeof value === "function" || value instanceof String || value instanceof Number || Array.isArray(value))) { + let error = `'${pathString}' was found but does not resolve to a string.`; + if (isObject(value)) { + let validKeys = Object.keys(value).filter((key)=>validatePath(config, [ + ...pathSegments, + key + ]).isValid); + if (validKeys.length) { + error += ` Did you mean something like '${pathToString([ + ...pathSegments, + validKeys[0] + ])}'?`; + } + } + return { + isValid: false, + error + }; + } + const [themeSection] = pathSegments; + return { + isValid: true, + value: (0, _transformThemeValue.default)(themeSection)(value, themeOpts) + }; +} +function extractArgs(node, vNodes, functions) { + vNodes = vNodes.map((vNode)=>resolveVNode(node, vNode, functions)); + let args = [ + "" + ]; + for (let vNode of vNodes){ + if (vNode.type === "div" && vNode.value === ",") { + args.push(""); + } else { + args[args.length - 1] += _index.default.stringify(vNode); + } + } + return args; +} +function resolveVNode(node, vNode, functions) { + if (vNode.type === "function" && functions[vNode.value] !== undefined) { + let args = extractArgs(node, vNode.nodes, functions); + vNode.type = "word"; + vNode.value = functions[vNode.value](node, ...args); + } + return vNode; +} +function resolveFunctions(node, input, functions) { + let hasAnyFn = Object.keys(functions).some((fn)=>input.includes(`${fn}(`)); + if (!hasAnyFn) return input; + return (0, _index.default)(input).walk((vNode)=>{ + resolveVNode(node, vNode, functions); + }).toString(); +} +let nodeTypePropertyMap = { + atrule: "params", + decl: "value" +}; +/** + * @param {string} path + * @returns {Iterable<[path: string, alpha: string|undefined]>} + */ function* toPaths(path) { + // Strip quotes from beginning and end of string + // This allows the alpha value to be present inside of quotes + path = path.replace(/^['"]+|['"]+$/g, ""); + let matches = path.match(/^([^\s]+)(?![^\[]*\])(?:\s*\/\s*([^\/\s]+))$/); + let alpha = undefined; + yield [ + path, + undefined + ]; + if (matches) { + path = matches[1]; + alpha = matches[2]; + yield [ + path, + alpha + ]; + } +} +/** + * + * @param {any} config + * @param {string} path + * @param {any} defaultValue + */ function resolvePath(config, path, defaultValue) { + const results = Array.from(toPaths(path)).map(([path, alpha])=>{ + return Object.assign(validatePath(config, path, defaultValue, { + opacityValue: alpha + }), { + resolvedPath: path, + alpha + }); + }); + var _results_find; + return (_results_find = results.find((result)=>result.isValid)) !== null && _results_find !== void 0 ? _results_find : results[0]; +} +function _default(context) { + let config = context.tailwindConfig; + let functions = { + theme: (node, path, ...defaultValue)=>{ + let { isValid , value , error , alpha } = resolvePath(config, path, defaultValue.length ? defaultValue : undefined); + if (!isValid) { + var _parentNode_raws_tailwind; + let parentNode = node.parent; + let candidate = (_parentNode_raws_tailwind = parentNode === null || parentNode === void 0 ? void 0 : parentNode.raws.tailwind) === null || _parentNode_raws_tailwind === void 0 ? void 0 : _parentNode_raws_tailwind.candidate; + if (parentNode && candidate !== undefined) { + // Remove this utility from any caches + context.markInvalidUtilityNode(parentNode); + // Remove the CSS node from the markup + parentNode.remove(); + // Show a warning + _log.default.warn("invalid-theme-key-in-class", [ + `The utility \`${candidate}\` contains an invalid theme value and was not generated.` + ]); + return; + } + throw node.error(error); + } + let maybeColor = (0, _pluginUtils.parseColorFormat)(value); + let isColorFunction = maybeColor !== undefined && typeof maybeColor === "function"; + if (alpha !== undefined || isColorFunction) { + if (alpha === undefined) { + alpha = 1.0; + } + value = (0, _withAlphaVariable.withAlphaValue)(maybeColor, alpha, maybeColor); + } + return value; + }, + screen: (node, screen)=>{ + screen = screen.replace(/^['"]+/g, "").replace(/['"]+$/g, ""); + let screens = (0, _normalizeScreens.normalizeScreens)(config.theme.screens); + let screenDefinition = screens.find(({ name })=>name === screen); + if (!screenDefinition) { + throw node.error(`The '${screen}' screen does not exist in your theme.`); + } + return (0, _buildMediaQuery.default)(screenDefinition); + } + }; + return (root)=>{ + root.walk((node)=>{ + let property = nodeTypePropertyMap[node.type]; + if (property === undefined) { + return; + } + node[property] = resolveFunctions(node, node[property], functions); + }); + }; +} diff --git a/node_modules/tailwindcss/lib/lib/expandApplyAtRules.js b/node_modules/tailwindcss/lib/lib/expandApplyAtRules.js new file mode 100644 index 0000000000000000000000000000000000000000..c47ea1a74270dbf0889c5628a9c2fd70b196e685 --- /dev/null +++ b/node_modules/tailwindcss/lib/lib/expandApplyAtRules.js @@ -0,0 +1,553 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return expandApplyAtRules; + } +}); +const _postcss = /*#__PURE__*/ _interop_require_default(require("postcss")); +const _postcssselectorparser = /*#__PURE__*/ _interop_require_default(require("postcss-selector-parser")); +const _generateRules = require("./generateRules"); +const _escapeClassName = /*#__PURE__*/ _interop_require_default(require("../util/escapeClassName")); +const _applyImportantSelector = require("../util/applyImportantSelector"); +const _pseudoElements = require("../util/pseudoElements"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +/** @typedef {Map} ApplyCache */ function extractClasses(node) { + /** @type {Map>} */ let groups = new Map(); + let container = _postcss.default.root({ + nodes: [ + node.clone() + ] + }); + container.walkRules((rule)=>{ + (0, _postcssselectorparser.default)((selectors)=>{ + selectors.walkClasses((classSelector)=>{ + let parentSelector = classSelector.parent.toString(); + let classes = groups.get(parentSelector); + if (!classes) { + groups.set(parentSelector, classes = new Set()); + } + classes.add(classSelector.value); + }); + }).processSync(rule.selector); + }); + let normalizedGroups = Array.from(groups.values(), (classes)=>Array.from(classes)); + let classes = normalizedGroups.flat(); + return Object.assign(classes, { + groups: normalizedGroups + }); +} +let selectorExtractor = (0, _postcssselectorparser.default)(); +/** + * @param {string} ruleSelectors + */ function extractSelectors(ruleSelectors) { + return selectorExtractor.astSync(ruleSelectors); +} +function extractBaseCandidates(candidates, separator) { + let baseClasses = new Set(); + for (let candidate of candidates){ + baseClasses.add(candidate.split(separator).pop()); + } + return Array.from(baseClasses); +} +function prefix(context, selector) { + let prefix = context.tailwindConfig.prefix; + return typeof prefix === "function" ? prefix(selector) : prefix + selector; +} +function* pathToRoot(node) { + yield node; + while(node.parent){ + yield node.parent; + node = node.parent; + } +} +/** + * Only clone the node itself and not its children + * + * @param {*} node + * @param {*} overrides + * @returns + */ function shallowClone(node, overrides = {}) { + let children = node.nodes; + node.nodes = []; + let tmp = node.clone(overrides); + node.nodes = children; + return tmp; +} +/** + * Clone just the nodes all the way to the top that are required to represent + * this singular rule in the tree. + * + * For example, if we have CSS like this: + * ```css + * @media (min-width: 768px) { + * @supports (display: grid) { + * .foo { + * display: grid; + * grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + * } + * } + * + * @supports (backdrop-filter: blur(1px)) { + * .bar { + * backdrop-filter: blur(1px); + * } + * } + * + * .baz { + * color: orange; + * } + * } + * ``` + * + * And we're cloning `.bar` it'll return a cloned version of what's required for just that single node: + * + * ```css + * @media (min-width: 768px) { + * @supports (backdrop-filter: blur(1px)) { + * .bar { + * backdrop-filter: blur(1px); + * } + * } + * } + * ``` + * + * @param {import('postcss').Node} node + */ function nestedClone(node) { + for (let parent of pathToRoot(node)){ + if (node === parent) { + continue; + } + if (parent.type === "root") { + break; + } + node = shallowClone(parent, { + nodes: [ + node + ] + }); + } + return node; +} +/** + * @param {import('postcss').Root} root + */ function buildLocalApplyCache(root, context) { + /** @type {ApplyCache} */ let cache = new Map(); + root.walkRules((rule)=>{ + // Ignore rules generated by Tailwind + for (let node of pathToRoot(rule)){ + var _node_raws_tailwind; + if (((_node_raws_tailwind = node.raws.tailwind) === null || _node_raws_tailwind === void 0 ? void 0 : _node_raws_tailwind.layer) !== undefined) { + return; + } + } + // Clone what's required to represent this singular rule in the tree + let container = nestedClone(rule); + let sort = context.offsets.create("user"); + for (let className of extractClasses(rule)){ + let list = cache.get(className) || []; + cache.set(className, list); + list.push([ + { + layer: "user", + sort, + important: false + }, + container + ]); + } + }); + return cache; +} +/** + * @returns {ApplyCache} + */ function buildApplyCache(applyCandidates, context) { + for (let candidate of applyCandidates){ + if (context.notClassCache.has(candidate) || context.applyClassCache.has(candidate)) { + continue; + } + if (context.classCache.has(candidate)) { + context.applyClassCache.set(candidate, context.classCache.get(candidate).map(([meta, rule])=>[ + meta, + rule.clone() + ])); + continue; + } + let matches = Array.from((0, _generateRules.resolveMatches)(candidate, context)); + if (matches.length === 0) { + context.notClassCache.add(candidate); + continue; + } + context.applyClassCache.set(candidate, matches); + } + return context.applyClassCache; +} +/** + * Build a cache only when it's first used + * + * @param {() => ApplyCache} buildCacheFn + * @returns {ApplyCache} + */ function lazyCache(buildCacheFn) { + let cache = null; + return { + get: (name)=>{ + cache = cache || buildCacheFn(); + return cache.get(name); + }, + has: (name)=>{ + cache = cache || buildCacheFn(); + return cache.has(name); + } + }; +} +/** + * Take a series of multiple caches and merge + * them so they act like one large cache + * + * @param {ApplyCache[]} caches + * @returns {ApplyCache} + */ function combineCaches(caches) { + return { + get: (name)=>caches.flatMap((cache)=>cache.get(name) || []), + has: (name)=>caches.some((cache)=>cache.has(name)) + }; +} +function extractApplyCandidates(params) { + let candidates = params.split(/[\s\t\n]+/g); + if (candidates[candidates.length - 1] === "!important") { + return [ + candidates.slice(0, -1), + true + ]; + } + return [ + candidates, + false + ]; +} +function processApply(root, context, localCache) { + let applyCandidates = new Set(); + // Collect all @apply rules and candidates + let applies = []; + root.walkAtRules("apply", (rule)=>{ + let [candidates] = extractApplyCandidates(rule.params); + for (let util of candidates){ + applyCandidates.add(util); + } + applies.push(rule); + }); + // Start the @apply process if we have rules with @apply in them + if (applies.length === 0) { + return; + } + // Fill up some caches! + let applyClassCache = combineCaches([ + localCache, + buildApplyCache(applyCandidates, context) + ]); + /** + * When we have an apply like this: + * + * .abc { + * @apply hover:font-bold; + * } + * + * What we essentially will do is resolve to this: + * + * .abc { + * @apply .hover\:font-bold:hover { + * font-weight: 500; + * } + * } + * + * Notice that the to-be-applied class is `.hover\:font-bold:hover` and that the utility candidate was `hover:font-bold`. + * What happens in this function is that we prepend a `.` and escape the candidate. + * This will result in `.hover\:font-bold` + * Which means that we can replace `.hover\:font-bold` with `.abc` in `.hover\:font-bold:hover` resulting in `.abc:hover` + * + * @param {string} selector + * @param {string} utilitySelectors + * @param {string} candidate + */ function replaceSelector(selector, utilitySelectors, candidate) { + let selectorList = extractSelectors(selector); + let utilitySelectorsList = extractSelectors(utilitySelectors); + let candidateList = extractSelectors(`.${(0, _escapeClassName.default)(candidate)}`); + let candidateClass = candidateList.nodes[0].nodes[0]; + selectorList.each((sel)=>{ + /** @type {Set} */ let replaced = new Set(); + utilitySelectorsList.each((utilitySelector)=>{ + let hasReplaced = false; + utilitySelector = utilitySelector.clone(); + utilitySelector.walkClasses((node)=>{ + if (node.value !== candidateClass.value) { + return; + } + // Don't replace multiple instances of the same class + // This is theoretically correct but only partially + // We'd need to generate every possible permutation of the replacement + // For example with `.foo + .foo { … }` and `section { @apply foo; }` + // We'd need to generate all of these: + // - `.foo + .foo` + // - `.foo + section` + // - `section + .foo` + // - `section + section` + if (hasReplaced) { + return; + } + // Since you can only `@apply` class names this is sufficient + // We want to replace the matched class name with the selector the user is using + // Ex: Replace `.text-blue-500` with `.foo.bar:is(.something-cool)` + node.replaceWith(...sel.nodes.map((node)=>node.clone())); + // Record that we did something and we want to use this new selector + replaced.add(utilitySelector); + hasReplaced = true; + }); + }); + // Sort tag names before class names (but only sort each group (separated by a combinator) + // separately and not in total) + // This happens when replacing `.bar` in `.foo.bar` with a tag like `section` + for (let sel of replaced){ + let groups = [ + [] + ]; + for (let node of sel.nodes){ + if (node.type === "combinator") { + groups.push(node); + groups.push([]); + } else { + let last = groups[groups.length - 1]; + last.push(node); + } + } + sel.nodes = []; + for (let group of groups){ + if (Array.isArray(group)) { + group.sort((a, b)=>{ + if (a.type === "tag" && b.type === "class") { + return -1; + } else if (a.type === "class" && b.type === "tag") { + return 1; + } else if (a.type === "class" && b.type === "pseudo" && b.value.startsWith("::")) { + return -1; + } else if (a.type === "pseudo" && a.value.startsWith("::") && b.type === "class") { + return 1; + } + return 0; + }); + } + sel.nodes = sel.nodes.concat(group); + } + } + sel.replaceWith(...replaced); + }); + return selectorList.toString(); + } + let perParentApplies = new Map(); + // Collect all apply candidates and their rules + for (let apply of applies){ + let [candidates] = perParentApplies.get(apply.parent) || [ + [], + apply.source + ]; + perParentApplies.set(apply.parent, [ + candidates, + apply.source + ]); + let [applyCandidates, important] = extractApplyCandidates(apply.params); + if (apply.parent.type === "atrule") { + if (apply.parent.name === "screen") { + let screenType = apply.parent.params; + throw apply.error(`@apply is not supported within nested at-rules like @screen. We suggest you write this as @apply ${applyCandidates.map((c)=>`${screenType}:${c}`).join(" ")} instead.`); + } + throw apply.error(`@apply is not supported within nested at-rules like @${apply.parent.name}. You can fix this by un-nesting @${apply.parent.name}.`); + } + for (let applyCandidate of applyCandidates){ + if ([ + prefix(context, "group"), + prefix(context, "peer") + ].includes(applyCandidate)) { + // TODO: Link to specific documentation page with error code. + throw apply.error(`@apply should not be used with the '${applyCandidate}' utility`); + } + if (!applyClassCache.has(applyCandidate)) { + throw apply.error(`The \`${applyCandidate}\` class does not exist. If \`${applyCandidate}\` is a custom class, make sure it is defined within a \`@layer\` directive.`); + } + let rules = applyClassCache.get(applyCandidate); + // Verify that we can apply the class + for (let [, rule] of rules){ + if (rule.type === "atrule") { + continue; + } + rule.walkRules(()=>{ + throw apply.error([ + `The \`${applyCandidate}\` class cannot be used with \`@apply\` because \`@apply\` does not currently support nested CSS.`, + "Rewrite the selector without nesting or configure the `tailwindcss/nesting` plugin:", + "https://tailwindcss.com/docs/using-with-preprocessors#nesting" + ].join("\n")); + }); + } + candidates.push([ + applyCandidate, + important, + rules + ]); + } + } + for (let [parent, [candidates, atApplySource]] of perParentApplies){ + let siblings = []; + for (let [applyCandidate, important, rules] of candidates){ + let potentialApplyCandidates = [ + applyCandidate, + ...extractBaseCandidates([ + applyCandidate + ], context.tailwindConfig.separator) + ]; + for (let [meta, node] of rules){ + let parentClasses = extractClasses(parent); + let nodeClasses = extractClasses(node); + // When we encounter a rule like `.dark .a, .b { … }` we only want to be left with `[.dark, .a]` if the base applyCandidate is `.a` or with `[.b]` if the base applyCandidate is `.b` + // So we've split them into groups + nodeClasses = nodeClasses.groups.filter((classList)=>classList.some((className)=>potentialApplyCandidates.includes(className))).flat(); + // Add base utility classes from the @apply node to the list of + // classes to check whether it intersects and therefore results in a + // circular dependency or not. + // + // E.g.: + // .foo { + // @apply hover:a; // This applies "a" but with a modifier + // } + // + // We only have to do that with base classes of the `node`, not of the `parent` + // E.g.: + // .hover\:foo { + // @apply bar; + // } + // .bar { + // @apply foo; + // } + // + // This should not result in a circular dependency because we are + // just applying `.foo` and the rule above is `.hover\:foo` which is + // unrelated. However, if we were to apply `hover:foo` then we _did_ + // have to include this one. + nodeClasses = nodeClasses.concat(extractBaseCandidates(nodeClasses, context.tailwindConfig.separator)); + let intersects = parentClasses.some((selector)=>nodeClasses.includes(selector)); + if (intersects) { + throw node.error(`You cannot \`@apply\` the \`${applyCandidate}\` utility here because it creates a circular dependency.`); + } + let root = _postcss.default.root({ + nodes: [ + node.clone() + ] + }); + // Make sure every node in the entire tree points back at the @apply rule that generated it + root.walk((node)=>{ + node.source = atApplySource; + }); + let canRewriteSelector = node.type !== "atrule" || node.type === "atrule" && node.name !== "keyframes"; + if (canRewriteSelector) { + root.walkRules((rule)=>{ + // Let's imagine you have the following structure: + // + // .foo { + // @apply bar; + // } + // + // @supports (a: b) { + // .bar { + // color: blue + // } + // + // .something-unrelated {} + // } + // + // In this case we want to apply `.bar` but it happens to be in + // an atrule node. We clone that node instead of the nested one + // because we still want that @supports rule to be there once we + // applied everything. + // + // However it happens to be that the `.something-unrelated` is + // also in that same shared @supports atrule. This is not good, + // and this should not be there. The good part is that this is + // a clone already and it can be safely removed. The question is + // how do we know we can remove it. Basically what we can do is + // match it against the applyCandidate that you want to apply. If + // it doesn't match the we can safely delete it. + // + // If we didn't do this, then the `replaceSelector` function + // would have replaced this with something that didn't exist and + // therefore it removed the selector altogether. In this specific + // case it would result in `{}` instead of `.something-unrelated {}` + if (!extractClasses(rule).some((candidate)=>candidate === applyCandidate)) { + rule.remove(); + return; + } + // Strip the important selector from the parent selector if at the beginning + let importantSelector = typeof context.tailwindConfig.important === "string" ? context.tailwindConfig.important : null; + // We only want to move the "important" selector if this is a Tailwind-generated utility + // We do *not* want to do this for user CSS that happens to be structured the same + let isGenerated = parent.raws.tailwind !== undefined; + let parentSelector = isGenerated && importantSelector && parent.selector.indexOf(importantSelector) === 0 ? parent.selector.slice(importantSelector.length) : parent.selector; + // If the selector becomes empty after replacing the important selector + // This means that it's the same as the parent selector and we don't want to replace it + // Otherwise we'll crash + if (parentSelector === "") { + parentSelector = parent.selector; + } + rule.selector = replaceSelector(parentSelector, rule.selector, applyCandidate); + // And then re-add it if it was removed + if (importantSelector && parentSelector !== parent.selector) { + rule.selector = (0, _applyImportantSelector.applyImportantSelector)(rule.selector, importantSelector); + } + rule.walkDecls((d)=>{ + d.important = meta.important || important; + }); + // Move pseudo elements to the end of the selector (if necessary) + let selector = (0, _postcssselectorparser.default)().astSync(rule.selector); + selector.each((sel)=>(0, _pseudoElements.movePseudos)(sel)); + rule.selector = selector.toString(); + }); + } + // It could be that the node we were inserted was removed because the class didn't match + // If that was the *only* rule in the parent, then we have nothing add so we skip it + if (!root.nodes[0]) { + continue; + } + // Insert it + siblings.push([ + meta.sort, + root.nodes[0] + ]); + } + } + // Inject the rules, sorted, correctly + let nodes = context.offsets.sort(siblings).map((s)=>s[1]); + // `parent` refers to the node at `.abc` in: .abc { @apply mt-2 } + parent.after(nodes); + } + for (let apply of applies){ + // If there are left-over declarations, just remove the @apply + if (apply.parent.nodes.length > 1) { + apply.remove(); + } else { + // The node is empty, drop the full node + apply.parent.remove(); + } + } + // Do it again, in case we have other `@apply` rules + processApply(root, context, localCache); +} +function expandApplyAtRules(context) { + return (root)=>{ + // Build a cache of the user's CSS so we can use it to resolve classes used by @apply + let localCache = lazyCache(()=>buildLocalApplyCache(root, context)); + processApply(root, context, localCache); + }; +} diff --git a/node_modules/tailwindcss/lib/lib/expandTailwindAtRules.js b/node_modules/tailwindcss/lib/lib/expandTailwindAtRules.js new file mode 100644 index 0000000000000000000000000000000000000000..0836d3f90fd59ee35b502edc34627c7ec0da6a8d --- /dev/null +++ b/node_modules/tailwindcss/lib/lib/expandTailwindAtRules.js @@ -0,0 +1,279 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "default", { + enumerable: true, + get: function() { + return expandTailwindAtRules; + } +}); +const _fs = /*#__PURE__*/ _interop_require_default(require("fs")); +const _quicklru = /*#__PURE__*/ _interop_require_default(require("@alloc/quick-lru")); +const _sharedState = /*#__PURE__*/ _interop_require_wildcard(require("./sharedState")); +const _generateRules = require("./generateRules"); +const _log = /*#__PURE__*/ _interop_require_default(require("../util/log")); +const _cloneNodes = /*#__PURE__*/ _interop_require_default(require("../util/cloneNodes")); +const _defaultExtractor = require("./defaultExtractor"); +function _interop_require_default(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interop_require_wildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +let env = _sharedState.env; +const builtInExtractors = { + DEFAULT: _defaultExtractor.defaultExtractor +}; +const builtInTransformers = { + DEFAULT: (content)=>content, + svelte: (content)=>content.replace(/(?:^|\s)class:/g, " ") +}; +function getExtractor(context, fileExtension) { + let extractors = context.tailwindConfig.content.extract; + return extractors[fileExtension] || extractors.DEFAULT || builtInExtractors[fileExtension] || builtInExtractors.DEFAULT(context); +} +function getTransformer(tailwindConfig, fileExtension) { + let transformers = tailwindConfig.content.transform; + return transformers[fileExtension] || transformers.DEFAULT || builtInTransformers[fileExtension] || builtInTransformers.DEFAULT; +} +let extractorCache = new WeakMap(); +// Scans template contents for possible classes. This is a hot path on initial build but +// not too important for subsequent builds. The faster the better though — if we can speed +// up these regexes by 50% that could cut initial build time by like 20%. +function getClassCandidates(content, extractor, candidates, seen) { + if (!extractorCache.has(extractor)) { + extractorCache.set(extractor, new _quicklru.default({ + maxSize: 25000 + })); + } + for (let line of content.split("\n")){ + line = line.trim(); + if (seen.has(line)) { + continue; + } + seen.add(line); + if (extractorCache.get(extractor).has(line)) { + for (let match of extractorCache.get(extractor).get(line)){ + candidates.add(match); + } + } else { + let extractorMatches = extractor(line).filter((s)=>s !== "!*"); + let lineMatchesSet = new Set(extractorMatches); + for (let match of lineMatchesSet){ + candidates.add(match); + } + extractorCache.get(extractor).set(line, lineMatchesSet); + } + } +} +/** + * + * @param {[import('./offsets.js').RuleOffset, import('postcss').Node][]} rules + * @param {*} context + */ function buildStylesheet(rules, context) { + let sortedRules = context.offsets.sort(rules); + let returnValue = { + base: new Set(), + defaults: new Set(), + components: new Set(), + utilities: new Set(), + variants: new Set() + }; + for (let [sort, rule] of sortedRules){ + returnValue[sort.layer].add(rule); + } + return returnValue; +} +function expandTailwindAtRules(context) { + return async (root)=>{ + let layerNodes = { + base: null, + components: null, + utilities: null, + variants: null + }; + root.walkAtRules((rule)=>{ + // Make sure this file contains Tailwind directives. If not, we can save + // a lot of work and bail early. Also we don't have to register our touch + // file as a dependency since the output of this CSS does not depend on + // the source of any templates. Think Vue