progress on migrating to heex templates and font-icons

This commit is contained in:
Adam Piontek 2022-08-13 07:32:36 -04:00
parent d43daafdb7
commit 3eff955672
21793 changed files with 2161968 additions and 16895 deletions

20
assets_old/node_modules/postcss/LICENSE generated vendored Normal file
View file

@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2013 Andrey Sitnik <andrey@sitnik.ru>
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.

533
assets_old/node_modules/postcss/README.md generated vendored Normal file
View file

@ -0,0 +1,533 @@
# PostCSS [![Gitter][chat-img]][chat]
<img align="right" width="95" height="95"
alt="Philosophers stone, logo of PostCSS"
src="https://postcss.org/logo.svg">
[chat-img]: https://img.shields.io/badge/Gitter-Join_the_PostCSS_chat-brightgreen.svg
[chat]: https://gitter.im/postcss/postcss
PostCSS is a tool for transforming styles with JS plugins.
These plugins can lint your CSS, support variables and mixins,
transpile future CSS syntax, inline images, and more.
PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba,
and JetBrains. The [Autoprefixer] PostCSS plugin is one of the most popular
CSS processors.
PostCSS takes a CSS file and provides an API to analyze and modify its rules
(by transforming them into an [Abstract Syntax Tree]).
This API can then be used by [plugins] to do a lot of useful things,
e.g., to find errors automatically, or to insert vendor prefixes.
**Support / Discussion:** [Gitter](https://gitter.im/postcss/postcss)<br>
**Twitter account:** [@postcss](https://twitter.com/postcss)<br>
**VK.com page:** [postcss](https://vk.com/postcss)<br>
**中文翻译**: [`docs/README-cn.md`](./docs/README-cn.md)
For PostCSS commercial support (consulting, improving the front-end culture
of your company, PostCSS plugins), contact [Evil Martians]
at <postcss@evilmartians.com>.
[Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree
[Evil Martians]: https://evilmartians.com/?utm_source=postcss
[Autoprefixer]: https://github.com/postcss/autoprefixer
[plugins]: https://github.com/postcss/postcss#plugins
<a href="https://evilmartians.com/?utm_source=postcss">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
alt="Sponsored by Evil Martians" width="236" height="54">
</a>
## Sponsorship
PostCSS needs your support. We are accepting donations
[at Open Collective](https://opencollective.com/postcss/).
<a href="https://tailwindcss.com/">
<img src="https://refactoringui.nyc3.cdn.digitaloceanspaces.com/tailwind-logo.svg"
alt="Sponsored by Tailwind CSS" width="213" height="50">
</a>      <a href="https://themeisle.com/">
<img src="https://mllj2j8xvfl0.i.optimole.com/d0cOXWA.3970~373ad/w:auto/h:auto/q:90/https://s30246.pcdn.co/wp-content/uploads/2019/03/logo.png"
alt="Sponsored by ThemeIsle" width="171" height="56">
</a>
## Plugins
Currently, PostCSS has more than 200 plugins. You can find all of the plugins
in the [plugins list] or in the [searchable catalog]. Below is a list
of our favorite plugins — the best demonstrations of what can be built
on top of PostCSS.
If you have any new ideas, [PostCSS plugin development] is really easy.
[searchable catalog]: https://www.postcss.parts/
[plugins list]: https://github.com/postcss/postcss/blob/main/docs/plugins.md
### Solve Global CSS Problem
* [`postcss-use`] allows you to explicitly set PostCSS plugins within CSS
and execute them only for the current file.
* [`postcss-modules`] and [`react-css-modules`] automatically isolate
selectors within components.
* [`postcss-autoreset`] is an alternative to using a global reset
that is better for isolatable components.
* [`postcss-initial`] adds `all: initial` support, which resets
all inherited styles.
* [`cq-prolyfill`] adds container query support, allowing styles that respond
to the width of the parent.
### Use Future CSS, Today
* [`autoprefixer`] adds vendor prefixes, using data from Can I Use.
* [`postcss-preset-env`] allows you to use future CSS features today.
### Better CSS Readability
* [`precss`] contains plugins for Sass-like features, like variables, nesting,
and mixins.
* [`postcss-sorting`] sorts the content of rules and at-rules.
* [`postcss-utilities`] includes the most commonly used shortcuts and helpers.
* [`short`] adds and extends numerous shorthand properties.
### Images and Fonts
* [`postcss-assets`] inserts image dimensions and inlines files.
* [`postcss-sprites`] generates image sprites.
* [`font-magician`] generates all the `@font-face` rules needed in CSS.
* [`postcss-inline-svg`] allows you to inline SVG and customize its styles.
* [`postcss-write-svg`] allows you to write simple SVG directly in your CSS.
* [`webp-in-css`] to use WebP image format in CSS background.
* [`avif-in-css`] to use AVIF image format in CSS background.
### Linters
* [`stylelint`] is a modular stylesheet linter.
* [`stylefmt`] is a tool that automatically formats CSS
according `stylelint` rules.
* [`doiuse`] lints CSS for browser support, using data from Can I Use.
* [`colorguard`] helps you maintain a consistent color palette.
### Other
* [`postcss-rtl`] combines both-directional (left-to-right and right-to-left) styles in one CSS file.
* [`cssnano`] is a modular CSS minifier.
* [`lost`] is a feature-rich `calc()` grid system.
* [`rtlcss`] mirrors styles for right-to-left locales.
[PostCSS plugin development]: https://github.com/postcss/postcss/blob/main/docs/writing-a-plugin.md
[`postcss-inline-svg`]: https://github.com/TrySound/postcss-inline-svg
[`postcss-preset-env`]: https://github.com/jonathantneal/postcss-preset-env
[`react-css-modules`]: https://github.com/gajus/react-css-modules
[`postcss-autoreset`]: https://github.com/maximkoretskiy/postcss-autoreset
[`postcss-write-svg`]: https://github.com/jonathantneal/postcss-write-svg
[`postcss-utilities`]: https://github.com/ismamz/postcss-utilities
[`postcss-initial`]: https://github.com/maximkoretskiy/postcss-initial
[`postcss-sprites`]: https://github.com/2createStudio/postcss-sprites
[`postcss-modules`]: https://github.com/outpunk/postcss-modules
[`postcss-sorting`]: https://github.com/hudochenkov/postcss-sorting
[`postcss-assets`]: https://github.com/assetsjs/postcss-assets
[`font-magician`]: https://github.com/jonathantneal/postcss-font-magician
[`autoprefixer`]: https://github.com/postcss/autoprefixer
[`cq-prolyfill`]: https://github.com/ausi/cq-prolyfill
[`postcss-rtl`]: https://github.com/vkalinichev/postcss-rtl
[`postcss-use`]: https://github.com/postcss/postcss-use
[`css-modules`]: https://github.com/css-modules/css-modules
[`webp-in-css`]: https://github.com/ai/webp-in-css
[`avif-in-css`]: https://github.com/nucliweb/avif-in-css
[`colorguard`]: https://github.com/SlexAxton/css-colorguard
[`stylelint`]: https://github.com/stylelint/stylelint
[`stylefmt`]: https://github.com/morishitter/stylefmt
[`cssnano`]: https://cssnano.co/
[`precss`]: https://github.com/jonathantneal/precss
[`doiuse`]: https://github.com/anandthakker/doiuse
[`rtlcss`]: https://github.com/MohammadYounes/rtlcss
[`short`]: https://github.com/jonathantneal/postcss-short
[`lost`]: https://github.com/peterramsing/lost
## Syntaxes
PostCSS can transform styles in any syntax, not just CSS.
If there is not yet support for your favorite syntax,
you can write a parser and/or stringifier to extend PostCSS.
* [`sugarss`] is a indent-based syntax like Sass or Stylus.
* [`postcss-syntax`] switch syntax automatically by file extensions.
* [`postcss-html`] parsing styles in `<style>` tags of HTML-like files.
* [`postcss-markdown`] parsing styles in code blocks of Markdown files.
* [`postcss-jsx`] parsing CSS in template / object literals of source files.
* [`postcss-styled`] parsing CSS in template literals of source files.
* [`postcss-scss`] allows you to work with SCSS
*(but does not compile SCSS to CSS)*.
* [`postcss-sass`] allows you to work with Sass
*(but does not compile Sass to CSS)*.
* [`postcss-less`] allows you to work with Less
*(but does not compile LESS to CSS)*.
* [`postcss-less-engine`] allows you to work with Less
*(and DOES compile LESS to CSS using true Less.js evaluation)*.
* [`postcss-js`] allows you to write styles in JS or transform
React Inline Styles, Radium or JSS.
* [`postcss-safe-parser`] finds and fixes CSS syntax errors.
* [`midas`] converts a CSS string to highlighted HTML.
[`postcss-less-engine`]: https://github.com/Crunch/postcss-less
[`postcss-safe-parser`]: https://github.com/postcss/postcss-safe-parser
[`postcss-syntax`]: https://github.com/gucong3000/postcss-syntax
[`postcss-html`]: https://github.com/gucong3000/postcss-html
[`postcss-markdown`]: https://github.com/gucong3000/postcss-markdown
[`postcss-jsx`]: https://github.com/gucong3000/postcss-jsx
[`postcss-styled`]: https://github.com/gucong3000/postcss-styled
[`postcss-scss`]: https://github.com/postcss/postcss-scss
[`postcss-sass`]: https://github.com/AleshaOleg/postcss-sass
[`postcss-less`]: https://github.com/webschik/postcss-less
[`postcss-js`]: https://github.com/postcss/postcss-js
[`sugarss`]: https://github.com/postcss/sugarss
[`midas`]: https://github.com/ben-eb/midas
## Articles
* [Some things you may think about PostCSS… and you might be wrong](http://julian.io/some-things-you-may-think-about-postcss-and-you-might-be-wrong)
* [What PostCSS Really Is; What It Really Does](https://davidtheclark.com/its-time-for-everyone-to-learn-about-postcss/)
* [PostCSS Guides](https://webdesign.tutsplus.com/series/postcss-deep-dive--cms-889)
More articles and videos you can find on [awesome-postcss](https://github.com/jjaderg/awesome-postcss) list.
## Books
* [Mastering PostCSS for Web Design](https://www.packtpub.com/web-development/mastering-postcss-web-design) by Alex Libby, Packt. (June 2016)
## Usage
You can start using PostCSS in just two steps:
1. Find and add PostCSS extensions for your build tool.
2. [Select plugins] and add them to your PostCSS process.
[Select plugins]: https://www.postcss.parts/
### CSS-in-JS
The best way to use PostCSS with CSS-in-JS is [`astroturf`].
Add its loader to your `webpack.config.js`:
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'postcss-loader'],
},
{
test: /\.jsx?$/,
use: ['babel-loader', 'astroturf/loader'],
}
]
}
}
```
Then create `postcss.config.js`:
```js
module.exports = {
plugins: [
require('autoprefixer'),
require('postcss-nested')
]
}
```
[`astroturf`]: https://github.com/4Catalyzer/astroturf
### Parcel
[Parcel] has built-in PostCSS support. It already uses Autoprefixer
and cssnano. If you want to change plugins, create `postcss.config.js`
in projects root:
```js
module.exports = {
plugins: [
require('autoprefixer'),
require('postcss-nested')
]
}
```
Parcel will even automatically install these plugins for you.
> Please, be aware of [the several issues in Version 1](https://github.com/parcel-bundler/parcel/labels/CSS%20Preprocessing). Notice, [Version 2](https://github.com/parcel-bundler/parcel/projects/5) may resolve the issues via [issue #2157](https://github.com/parcel-bundler/parcel/issues/2157).
[Parcel]: https://parceljs.org
### Webpack
Use [`postcss-loader`] in `webpack.config.js`:
```js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
importLoaders: 1,
}
},
{
loader: 'postcss-loader'
}
]
}
]
}
}
```
Then create `postcss.config.js`:
```js
module.exports = {
plugins: [
require('precss'),
require('autoprefixer')
]
}
```
[`postcss-loader`]: https://github.com/postcss/postcss-loader
### Gulp
Use [`gulp-postcss`] and [`gulp-sourcemaps`].
```js
gulp.task('css', () => {
const postcss = require('gulp-postcss')
const sourcemaps = require('gulp-sourcemaps')
return gulp.src('src/**/*.css')
.pipe( sourcemaps.init() )
.pipe( postcss([ require('precss'), require('autoprefixer') ]) )
.pipe( sourcemaps.write('.') )
.pipe( gulp.dest('build/') )
})
```
[`gulp-sourcemaps`]: https://github.com/floridoo/gulp-sourcemaps
[`gulp-postcss`]: https://github.com/postcss/gulp-postcss
### npm Scripts
To use PostCSS from your command-line interface or with npm scripts
there is [`postcss-cli`].
```sh
postcss --use autoprefixer -o main.css css/*.css
```
[`postcss-cli`]: https://github.com/postcss/postcss-cli
### Browser
If you want to compile CSS string in browser (for instance, in live edit
tools like CodePen), just use [Browserify] or [webpack]. They will pack
PostCSS and plugins files into a single file.
To apply PostCSS plugins to React Inline Styles, JSS, Radium
and other [CSS-in-JS], you can use [`postcss-js`] and transforms style objects.
```js
const postcss = require('postcss-js')
const prefixer = postcss.sync([ require('autoprefixer') ])
prefixer({ display: 'flex' }) //=> { display: ['-webkit-box', '-webkit-flex', '-ms-flexbox', 'flex'] }
```
[`postcss-js`]: https://github.com/postcss/postcss-js
[Browserify]: http://browserify.org/
[CSS-in-JS]: https://github.com/MicheleBertoli/css-in-js
[webpack]: https://webpack.github.io/
### Deno
PostCSS also supports [Deno]:
```js
import postcss from 'https://deno.land/x/postcss/mod.js'
import autoprefixer from 'https://dev.jspm.io/autoprefixer'
const result = await postcss([autoprefixer]).process(css)
```
[Deno]: https://deno.land/
### Runners
* **Grunt**: [`@lodder/grunt-postcss`](https://github.com/C-Lodder/grunt-postcss)
* **HTML**: [`posthtml-postcss`](https://github.com/posthtml/posthtml-postcss)
* **Stylus**: [`poststylus`](https://github.com/seaneking/poststylus)
* **Rollup**: [`rollup-plugin-postcss`](https://github.com/egoist/rollup-plugin-postcss)
* **Brunch**: [`postcss-brunch`](https://github.com/brunch/postcss-brunch)
* **Broccoli**: [`broccoli-postcss`](https://github.com/jeffjewiss/broccoli-postcss)
* **Meteor**: [`postcss`](https://atmospherejs.com/juliancwirko/postcss)
* **ENB**: [`enb-postcss`](https://github.com/awinogradov/enb-postcss)
* **Taskr**: [`taskr-postcss`](https://github.com/lukeed/taskr/tree/master/packages/postcss)
* **Start**: [`start-postcss`](https://github.com/start-runner/postcss)
* **Connect/Express**: [`postcss-middleware`](https://github.com/jedmao/postcss-middleware)
### JS API
For other environments, you can use the JS API:
```js
const autoprefixer = require('autoprefixer')
const postcss = require('postcss')
const precss = require('precss')
const fs = require('fs')
fs.readFile('src/app.css', (err, css) => {
postcss([precss, autoprefixer])
.process(css, { from: 'src/app.css', to: 'dest/app.css' })
.then(result => {
fs.writeFile('dest/app.css', result.css, () => true)
if ( result.map ) {
fs.writeFile('dest/app.css.map', result.map.toString(), () => true)
}
})
})
```
Read the [PostCSS API documentation] for more details about the JS API.
All PostCSS runners should pass [PostCSS Runner Guidelines].
[PostCSS Runner Guidelines]: https://github.com/postcss/postcss/blob/main/docs/guidelines/runner.md
[PostCSS API documentation]: https://postcss.org/api/
### Options
Most PostCSS runners accept two parameters:
* An array of plugins.
* An object of options.
Common options:
* `syntax`: an object providing a syntax parser and a stringifier.
* `parser`: a special syntax parser (for example, [SCSS]).
* `stringifier`: a special syntax output generator (for example, [Midas]).
* `map`: [source map options].
* `from`: the input file name (most runners set it automatically).
* `to`: the output file name (most runners set it automatically).
[source map options]: https://postcss.org/api/#sourcemapoptions
[Midas]: https://github.com/ben-eb/midas
[SCSS]: https://github.com/postcss/postcss-scss
### Treat Warnings as Errors
In some situations it might be helpful to fail the build on any warning
from PostCSS or one of its plugins. This guarantees that no warnings
go unnoticed, and helps to avoid bugs. While there is no option to enable
treating warnings as errors, it can easily be done
by adding `postcss-fail-on-warn` plugin in the end of PostCSS plugins:
```js
module.exports = {
plugins: [
require('autoprefixer'),
require('postcss-fail-on-warn')
]
}
```
## Editors & IDE Integration
### VS Code
* [`csstools.postcss`] adds support for PostCSS, `postcss-preset-env`
and CSS Modules.
[`csstools.postcss`]: https://marketplace.visualstudio.com/items?itemName=csstools.postcss
### Atom
* [`language-postcss`] adds PostCSS and [SugarSS] highlight.
* [`source-preview-postcss`] previews your output CSS in a separate, live pane.
[SugarSS]: https://github.com/postcss/sugarss
### Sublime Text
* [`Syntax-highlighting-for-PostCSS`] adds PostCSS highlight.
[`Syntax-highlighting-for-PostCSS`]: https://github.com/hudochenkov/Syntax-highlighting-for-PostCSS
[`source-preview-postcss`]: https://atom.io/packages/source-preview-postcss
[`language-postcss`]: https://atom.io/packages/language-postcss
### Vim
* [`postcss.vim`] adds PostCSS highlight.
[`postcss.vim`]: https://github.com/stephenway/postcss.vim
### WebStorm
WebStorm 2016.3 [has] built-in PostCSS support.
[has]: https://blog.jetbrains.com/webstorm/2016/08/webstorm-2016-3-early-access-preview/
## Security Contact
To report a security vulnerability, please use the [Tidelift security contact].
Tidelift will coordinate the fix and disclosure.
[Tidelift security contact]: https://tidelift.com/security
## For Enterprise
Available as part of the Tidelift Subscription.
The maintainers of `postcss` and thousands of other packages are working
with Tidelift to deliver commercial support and maintenance for the open source
dependencies you use to build your applications. Save time, reduce risk,
and improve code health, while paying the maintainers of the exact dependencies
you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-postcss?utm_source=npm-postcss&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

101
assets_old/node_modules/postcss/lib/at-rule.d.ts generated vendored Normal file
View file

@ -0,0 +1,101 @@
import Container, { ContainerProps } from './container.js'
interface AtRuleRaws {
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
/**
* The space symbols after the last child of the node to the end of the node.
*/
after?: string
/**
* The space between the at-rule name and its parameters.
*/
afterName?: string
/**
* The symbols between the last parameter and `{` for rules.
*/
between?: string
/**
* Contains `true` if the last child has an (optional) semicolon.
*/
semicolon?: boolean
/**
* The rules selector with comments.
*/
params?: {
value: string
raw: string
}
}
export interface AtRuleProps extends ContainerProps {
name: string
params?: string | number
raws?: AtRuleRaws
}
/**
* Represents an at-rule.
*
* ```js
* Once (root, { AtRule }) {
* let media = new AtRule({ name: 'media', params: 'print' })
* media.append()
* root.append(media)
* }
* ```
*
* If its followed in the CSS by a {} block, this node will have
* a nodes property representing its children.
*
* ```js
* const root = postcss.parse('@charset "UTF-8"; @media print {}')
*
* const charset = root.first
* charset.type //=> 'atrule'
* charset.nodes //=> undefined
*
* const media = root.last
* media.nodes //=> []
* ```
*/
export default class AtRule extends Container {
type: 'atrule'
raws: AtRuleRaws
/**
* The at-rules name immediately follows the `@`.
*
* ```js
* const root = postcss.parse('@media print {}')
* media.name //=> 'media'
* const media = root.first
* ```
*/
name: string
/**
* The at-rules parameters, the values that follow the at-rules name
* but precede any {} block.
*
* ```js
* const root = postcss.parse('@media print, screen {}')
* const media = root.first
* media.params //=> 'print, screen'
* ```
*/
params: string
constructor(defaults?: AtRuleProps)
clone(overrides?: Partial<AtRuleProps>): this
cloneBefore(overrides?: Partial<AtRuleProps>): this
cloneAfter(overrides?: Partial<AtRuleProps>): this
}

25
assets_old/node_modules/postcss/lib/at-rule.js generated vendored Normal file
View file

@ -0,0 +1,25 @@
'use strict'
let Container = require('./container')
class AtRule extends Container {
constructor(defaults) {
super(defaults)
this.type = 'atrule'
}
append(...children) {
if (!this.proxyOf.nodes) this.nodes = []
return super.append(...children)
}
prepend(...children) {
if (!this.proxyOf.nodes) this.nodes = []
return super.prepend(...children)
}
}
module.exports = AtRule
AtRule.default = AtRule
Container.registerAtRule(AtRule)

51
assets_old/node_modules/postcss/lib/comment.d.ts generated vendored Normal file
View file

@ -0,0 +1,51 @@
import Node, { NodeProps } from './node.js'
interface CommentRaws {
/**
* The space symbols before the node.
*/
before?: string
/**
* The space symbols between `/*` and the comments text.
*/
left?: string
/**
* The space symbols between the comments text.
*/
right?: string
}
export interface CommentProps extends NodeProps {
text: string
raws?: CommentRaws
}
/**
* Represents a comment between declarations or statements (rule and at-rules).
*
* ```js
* Once (root, { Comment }) {
* let note = new Comment({ text: 'Note: …' })
* root.append(note)
* }
* ```
*
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*/
export default class Comment extends Node {
type: 'comment'
raws: CommentRaws
/**
* The comment's text.
*/
text: string
constructor(defaults?: CommentProps)
clone(overrides?: Partial<CommentProps>): this
cloneBefore(overrides?: Partial<CommentProps>): this
cloneAfter(overrides?: Partial<CommentProps>): this
}

13
assets_old/node_modules/postcss/lib/comment.js generated vendored Normal file
View file

@ -0,0 +1,13 @@
'use strict'
let Node = require('./node')
class Comment extends Node {
constructor(defaults) {
super(defaults)
this.type = 'comment'
}
}
module.exports = Comment
Comment.default = Comment

452
assets_old/node_modules/postcss/lib/container.d.ts generated vendored Normal file
View file

@ -0,0 +1,452 @@
import Node, { ChildNode, NodeProps, ChildProps } from './node.js'
import Declaration from './declaration.js'
import Comment from './comment.js'
import AtRule from './at-rule.js'
import Rule from './rule.js'
interface ValueOptions {
/**
* An array of property names.
*/
props?: string[]
/**
* String thats used to narrow down values and speed up the regexp search.
*/
fast?: string
}
export interface ContainerProps extends NodeProps {
nodes?: (ChildNode | ChildProps)[]
}
/**
* The `Root`, `AtRule`, and `Rule` container nodes
* inherit some common methods to help work with their children.
*
* Note that all containers can store any content. If you write a rule inside
* a rule, PostCSS will parse it.
*/
export default abstract class Container extends Node {
/**
* An array containing the containers children.
*
* ```js
* const root = postcss.parse('a { color: black }')
* root.nodes.length //=> 1
* root.nodes[0].selector //=> 'a'
* root.nodes[0].nodes[0].prop //=> 'color'
* ```
*/
nodes: ChildNode[]
/**
* The containers first child.
*
* ```js
* rule.first === rules.nodes[0]
* ```
*/
get first(): ChildNode | undefined
/**
* The containers last child.
*
* ```js
* rule.last === rule.nodes[rule.nodes.length - 1]
* ```
*/
get last(): ChildNode | undefined
/**
* Iterates through the containers immediate children,
* calling `callback` for each child.
*
* Returning `false` in the callback will break iteration.
*
* This method only iterates through the containers immediate children.
* If you need to recursively iterate through all the containers descendant
* nodes, use `Container#walk`.
*
* Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
* if you are mutating the array of child nodes during iteration.
* PostCSS will adjust the current index to match the mutations.
*
* ```js
* const root = postcss.parse('a { color: black; z-index: 1 }')
* const rule = root.first
*
* for (const decl of rule.nodes) {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop })
* // Cycle will be infinite, because cloneBefore moves the current node
* // to the next index
* }
*
* rule.each(decl => {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop })
* // Will be executed only for color and z-index
* })
* ```
*
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
each(
callback: (node: ChildNode, index: number) => false | void
): false | undefined
/**
* Traverses the containers descendant nodes, calling callback
* for each node.
*
* Like container.each(), this method is safe to use
* if you are mutating arrays during iteration.
*
* If you only need to iterate through the containers immediate children,
* use `Container#each`.
*
* ```js
* root.walk(node => {
* // Traverses all descendant nodes.
* })
* ```
*
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
walk(
callback: (node: ChildNode, index: number) => false | void
): false | undefined
/**
* Traverses the containers descendant nodes, calling callback
* for each declaration node.
*
* If you pass a filter, iteration will only happen over declarations
* with matching properties.
*
* ```js
* root.walkDecls(decl => {
* checkPropertySupport(decl.prop)
* })
*
* root.walkDecls('border-radius', decl => {
* decl.remove()
* })
*
* root.walkDecls(/^background/, decl => {
* decl.value = takeFirstColorFromGradient(decl.value)
* })
* ```
*
* Like `Container#each`, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param prop String or regular expression to filter declarations
* by property name.
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
walkDecls(
propFilter: string | RegExp,
callback: (decl: Declaration, index: number) => false | void
): false | undefined
walkDecls(
callback: (decl: Declaration, index: number) => false | void
): false | undefined
/**
* Traverses the containers descendant nodes, calling callback
* for each rule node.
*
* If you pass a filter, iteration will only happen over rules
* with matching selectors.
*
* Like `Container#each`, this method is safe
* to use if you are mutating arrays during iteration.
*
* ```js
* const selectors = []
* root.walkRules(rule => {
* selectors.push(rule.selector)
* })
* console.log(`Your CSS uses ${ selectors.length } selectors`)
* ```
*
* @param selector String or regular expression to filter rules by selector.
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
walkRules(
selectorFilter: string | RegExp,
callback: (atRule: Rule, index: number) => false | void
): false | undefined
walkRules(
callback: (atRule: Rule, index: number) => false | void
): false | undefined
/**
* Traverses the containers descendant nodes, calling callback
* for each at-rule node.
*
* If you pass a filter, iteration will only happen over at-rules
* that have matching names.
*
* Like `Container#each`, this method is safe
* to use if you are mutating arrays during iteration.
*
* ```js
* root.walkAtRules(rule => {
* if (isOld(rule.name)) rule.remove()
* })
*
* let first = false
* root.walkAtRules('charset', rule => {
* if (!first) {
* first = true
* } else {
* rule.remove()
* }
* })
* ```
*
* @param name String or regular expression to filter at-rules by name.
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
walkAtRules(
nameFilter: string | RegExp,
callback: (atRule: AtRule, index: number) => false | void
): false | undefined
walkAtRules(
callback: (atRule: AtRule, index: number) => false | void
): false | undefined
/**
* Traverses the containers descendant nodes, calling callback
* for each comment node.
*
* Like `Container#each`, this method is safe
* to use if you are mutating arrays during iteration.
*
* ```js
* root.walkComments(comment => {
* comment.remove()
* })
* ```
*
* @param callback Iterator receives each node and index.
* @return Returns `false` if iteration was broke.
*/
walkComments(
callback: (comment: Comment, indexed: number) => false | void
): false | undefined
walkComments(
callback: (comment: Comment, indexed: number) => false | void
): false | undefined
/**
* Inserts new nodes to the end of the container.
*
* ```js
* const decl1 = new Declaration({ prop: 'color', value: 'black' })
* const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
* rule.append(decl1, decl2)
*
* root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
* root.append({ selector: 'a' }) // rule
* rule.append({ prop: 'color', value: 'black' }) // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}')
* root.first.append('color: black; z-index: 1')
* ```
*
* @param nodes New nodes.
* @return This node for methods chain.
*/
append(
...nodes: (Node | Node[] | ChildProps | ChildProps[] | string | string[])[]
): this
/**
* Inserts new nodes to the start of the container.
*
* ```js
* const decl1 = new Declaration({ prop: 'color', value: 'black' })
* const decl2 = new Declaration({ prop: 'background-color', value: 'white' })
* rule.prepend(decl1, decl2)
*
* root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule
* root.append({ selector: 'a' }) // rule
* rule.append({ prop: 'color', value: 'black' }) // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}')
* root.first.append('color: black; z-index: 1')
* ```
*
* @param nodes New nodes.
* @return This node for methods chain.
*/
prepend(
...nodes: (Node | Node[] | ChildProps | ChildProps[] | string | string[])[]
): this
/**
* Add child to the end of the node.
*
* ```js
* rule.push(new Declaration({ prop: 'color', value: 'black' }))
* ```
*
* @param child New node.
* @return This node for methods chain.
*/
push(child: ChildNode): this
/**
* Insert new node before old node within the container.
*
* ```js
* rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }))
* ```
*
* @param oldNode Child or childs index.
* @param newNode New node.
* @return This node for methods chain.
*/
insertBefore(
oldNode: ChildNode | number,
newNode:
| ChildNode
| ChildProps
| string
| ChildNode[]
| ChildProps[]
| string[]
): this
/**
* Insert new node after old node within the container.
*
* @param oldNode Child or childs index.
* @param newNode New node.
* @return This node for methods chain.
*/
insertAfter(
oldNode: ChildNode | number,
newNode:
| ChildNode
| ChildProps
| string
| ChildNode[]
| ChildProps[]
| string[]
): this
/**
* Removes node from the container and cleans the parent properties
* from the node and its children.
*
* ```js
* rule.nodes.length //=> 5
* rule.removeChild(decl)
* rule.nodes.length //=> 4
* decl.parent //=> undefined
* ```
*
* @param child Child or childs index.
* @return This node for methods chain.
*/
removeChild(child: ChildNode | number): this
/**
* Removes all children from the container
* and cleans their parent properties.
*
* ```js
* rule.removeAll()
* rule.nodes.length //=> 0
* ```
*
* @return This node for methods chain.
*/
removeAll(): this
/**
* Passes all declaration values within the container that match pattern
* through callback, replacing those values with the returned result
* of callback.
*
* This method is useful if you are using a custom unit or function
* and need to iterate through all values.
*
* ```js
* root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
* return 15 * parseInt(string) + 'px'
* })
* ```
*
* @param pattern Replace pattern.
* @param {object} opts Options to speed up the search.
* @param callback String to replace pattern or callback
* that returns a new value. The callback
* will receive the same arguments
* as those passed to a function parameter
* of `String#replace`.
* @return This node for methods chain.
*/
replaceValues(
pattern: string | RegExp,
options: ValueOptions,
replaced: string | { (substring: string, ...args: any[]): string }
): this
replaceValues(
pattern: string | RegExp,
replaced: string | { (substring: string, ...args: any[]): string }
): this
/**
* Returns `true` if callback returns `true`
* for all of the containers children.
*
* ```js
* const noPrefixes = rule.every(i => i.prop[0] !== '-')
* ```
*
* @param condition Iterator returns true or false.
* @return Is every child pass condition.
*/
every(
condition: (node: ChildNode, index: number, nodes: ChildNode[]) => boolean
): boolean
/**
* Returns `true` if callback returns `true` for (at least) one
* of the containers children.
*
* ```js
* const hasPrefix = rule.some(i => i.prop[0] === '-')
* ```
*
* @param condition Iterator returns true or false.
* @return Is some child pass condition.
*/
some(
condition: (node: ChildNode, index: number, nodes: ChildNode[]) => boolean
): boolean
/**
* Returns a `child`s index within the `Container#nodes` array.
*
* ```js
* rule.index( rule.nodes[2] ) //=> 2
* ```
*
* @param child Child of the current container.
* @return Child index.
*/
index(child: ChildNode | number): number
}

430
assets_old/node_modules/postcss/lib/container.js generated vendored Normal file
View file

@ -0,0 +1,430 @@
'use strict'
let Declaration = require('./declaration')
let { isClean } = require('./symbols')
let Comment = require('./comment')
let Node = require('./node')
let parse, Rule, AtRule
function cleanSource(nodes) {
return nodes.map(i => {
if (i.nodes) i.nodes = cleanSource(i.nodes)
delete i.source
return i
})
}
function markDirtyUp(node) {
node[isClean] = false
if (node.proxyOf.nodes) {
for (let i of node.proxyOf.nodes) {
markDirtyUp(i)
}
}
}
// istanbul ignore next
function rebuild(node) {
if (node.type === 'atrule') {
Object.setPrototypeOf(node, AtRule.prototype)
} else if (node.type === 'rule') {
Object.setPrototypeOf(node, Rule.prototype)
} else if (node.type === 'decl') {
Object.setPrototypeOf(node, Declaration.prototype)
} else if (node.type === 'comment') {
Object.setPrototypeOf(node, Comment.prototype)
}
if (node.nodes) {
node.nodes.forEach(child => {
rebuild(child)
})
}
}
class Container extends Node {
push(child) {
child.parent = this
this.proxyOf.nodes.push(child)
return this
}
each(callback) {
if (!this.proxyOf.nodes) return undefined
let iterator = this.getIterator()
let index, result
while (this.indexes[iterator] < this.proxyOf.nodes.length) {
index = this.indexes[iterator]
result = callback(this.proxyOf.nodes[index], index)
if (result === false) break
this.indexes[iterator] += 1
}
delete this.indexes[iterator]
return result
}
walk(callback) {
return this.each((child, i) => {
let result
try {
result = callback(child, i)
} catch (e) {
throw child.addToError(e)
}
if (result !== false && child.walk) {
result = child.walk(callback)
}
return result
})
}
walkDecls(prop, callback) {
if (!callback) {
callback = prop
return this.walk((child, i) => {
if (child.type === 'decl') {
return callback(child, i)
}
})
}
if (prop instanceof RegExp) {
return this.walk((child, i) => {
if (child.type === 'decl' && prop.test(child.prop)) {
return callback(child, i)
}
})
}
return this.walk((child, i) => {
if (child.type === 'decl' && child.prop === prop) {
return callback(child, i)
}
})
}
walkRules(selector, callback) {
if (!callback) {
callback = selector
return this.walk((child, i) => {
if (child.type === 'rule') {
return callback(child, i)
}
})
}
if (selector instanceof RegExp) {
return this.walk((child, i) => {
if (child.type === 'rule' && selector.test(child.selector)) {
return callback(child, i)
}
})
}
return this.walk((child, i) => {
if (child.type === 'rule' && child.selector === selector) {
return callback(child, i)
}
})
}
walkAtRules(name, callback) {
if (!callback) {
callback = name
return this.walk((child, i) => {
if (child.type === 'atrule') {
return callback(child, i)
}
})
}
if (name instanceof RegExp) {
return this.walk((child, i) => {
if (child.type === 'atrule' && name.test(child.name)) {
return callback(child, i)
}
})
}
return this.walk((child, i) => {
if (child.type === 'atrule' && child.name === name) {
return callback(child, i)
}
})
}
walkComments(callback) {
return this.walk((child, i) => {
if (child.type === 'comment') {
return callback(child, i)
}
})
}
append(...children) {
for (let child of children) {
let nodes = this.normalize(child, this.last)
for (let node of nodes) this.proxyOf.nodes.push(node)
}
this.markDirty()
return this
}
prepend(...children) {
children = children.reverse()
for (let child of children) {
let nodes = this.normalize(child, this.first, 'prepend').reverse()
for (let node of nodes) this.proxyOf.nodes.unshift(node)
for (let id in this.indexes) {
this.indexes[id] = this.indexes[id] + nodes.length
}
}
this.markDirty()
return this
}
cleanRaws(keepBetween) {
super.cleanRaws(keepBetween)
if (this.nodes) {
for (let node of this.nodes) node.cleanRaws(keepBetween)
}
}
insertBefore(exist, add) {
exist = this.index(exist)
let type = exist === 0 ? 'prepend' : false
let nodes = this.normalize(add, this.proxyOf.nodes[exist], type).reverse()
for (let node of nodes) this.proxyOf.nodes.splice(exist, 0, node)
let index
for (let id in this.indexes) {
index = this.indexes[id]
if (exist <= index) {
this.indexes[id] = index + nodes.length
}
}
this.markDirty()
return this
}
insertAfter(exist, add) {
exist = this.index(exist)
let nodes = this.normalize(add, this.proxyOf.nodes[exist]).reverse()
for (let node of nodes) this.proxyOf.nodes.splice(exist + 1, 0, node)
let index
for (let id in this.indexes) {
index = this.indexes[id]
if (exist < index) {
this.indexes[id] = index + nodes.length
}
}
this.markDirty()
return this
}
removeChild(child) {
child = this.index(child)
this.proxyOf.nodes[child].parent = undefined
this.proxyOf.nodes.splice(child, 1)
let index
for (let id in this.indexes) {
index = this.indexes[id]
if (index >= child) {
this.indexes[id] = index - 1
}
}
this.markDirty()
return this
}
removeAll() {
for (let node of this.proxyOf.nodes) node.parent = undefined
this.proxyOf.nodes = []
this.markDirty()
return this
}
replaceValues(pattern, opts, callback) {
if (!callback) {
callback = opts
opts = {}
}
this.walkDecls(decl => {
if (opts.props && !opts.props.includes(decl.prop)) return
if (opts.fast && !decl.value.includes(opts.fast)) return
decl.value = decl.value.replace(pattern, callback)
})
this.markDirty()
return this
}
every(condition) {
return this.nodes.every(condition)
}
some(condition) {
return this.nodes.some(condition)
}
index(child) {
if (typeof child === 'number') return child
if (child.proxyOf) child = child.proxyOf
return this.proxyOf.nodes.indexOf(child)
}
get first() {
if (!this.proxyOf.nodes) return undefined
return this.proxyOf.nodes[0]
}
get last() {
if (!this.proxyOf.nodes) return undefined
return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
}
normalize(nodes, sample) {
if (typeof nodes === 'string') {
nodes = cleanSource(parse(nodes).nodes)
} else if (Array.isArray(nodes)) {
nodes = nodes.slice(0)
for (let i of nodes) {
if (i.parent) i.parent.removeChild(i, 'ignore')
}
} else if (nodes.type === 'root') {
nodes = nodes.nodes.slice(0)
for (let i of nodes) {
if (i.parent) i.parent.removeChild(i, 'ignore')
}
} else if (nodes.type) {
nodes = [nodes]
} else if (nodes.prop) {
if (typeof nodes.value === 'undefined') {
throw new Error('Value field is missed in node creation')
} else if (typeof nodes.value !== 'string') {
nodes.value = String(nodes.value)
}
nodes = [new Declaration(nodes)]
} else if (nodes.selector) {
nodes = [new Rule(nodes)]
} else if (nodes.name) {
nodes = [new AtRule(nodes)]
} else if (nodes.text) {
nodes = [new Comment(nodes)]
} else {
throw new Error('Unknown node type in node creation')
}
let processed = nodes.map(i => {
// istanbul ignore next
if (typeof i.markDirty !== 'function') rebuild(i)
i = i.proxyOf
if (i.parent) i.parent.removeChild(i)
if (i[isClean]) markDirtyUp(i)
if (typeof i.raws.before === 'undefined') {
if (sample && typeof sample.raws.before !== 'undefined') {
i.raws.before = sample.raws.before.replace(/\S/g, '')
}
}
i.parent = this
return i
})
return processed
}
getProxyProcessor() {
return {
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value
if (prop === 'name' || prop === 'params' || prop === 'selector') {
node.markDirty()
}
return true
},
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (!node[prop]) {
return node[prop]
} else if (
prop === 'each' ||
(typeof prop === 'string' && prop.startsWith('walk'))
) {
return (...args) => {
return node[prop](
...args.map(i => {
if (typeof i === 'function') {
return (child, index) => i(child.toProxy(), index)
} else {
return i
}
})
)
}
} else if (prop === 'every' || prop === 'some') {
return cb => {
return node[prop]((child, ...other) =>
cb(child.toProxy(), ...other)
)
}
} else if (prop === 'root') {
return () => node.root().toProxy()
} else if (prop === 'nodes') {
return node.nodes.map(i => i.toProxy())
} else if (prop === 'first' || prop === 'last') {
return node[prop].toProxy()
} else {
return node[prop]
}
}
}
}
getIterator() {
if (!this.lastEach) this.lastEach = 0
if (!this.indexes) this.indexes = {}
this.lastEach += 1
let iterator = this.lastEach
this.indexes[iterator] = 0
return iterator
}
}
Container.registerParse = dependant => {
parse = dependant
}
Container.registerRule = dependant => {
Rule = dependant
}
Container.registerAtRule = dependant => {
AtRule = dependant
}
module.exports = Container
Container.default = Container

View file

@ -0,0 +1,192 @@
import { FilePosition } from './input.js'
/**
* The CSS parser throws this error for broken CSS.
*
* Custom parsers can throw this error for broken custom syntax using
* the `Node#error` method.
*
* PostCSS will use the input source map to detect the original error location.
* If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
* PostCSS will show the original position in the Sass file.
*
* If you need the position in the PostCSS input
* (e.g., to debug the previous compiler), use `error.input.file`.
*
* ```js
* // Raising error from plugin
* throw node.error('Unknown variable', { plugin: 'postcss-vars' })
* ```
*
* ```js
* // Catching and checking syntax error
* try {
* postcss.parse('a{')
* } catch (error) {
* if (error.name === 'CssSyntaxError') {
* error //=> CssSyntaxError
* }
* }
* ```
*/
export default class CssSyntaxError {
/**
* @param message Error message.
* @param line Source line of the error.
* @param column Source column of the error.
* @param source Source code of the broken file.
* @param file Absolute path to the broken file.
* @param plugin PostCSS plugin name, if error came from plugin.
*/
constructor(
message: string,
line?: number,
column?: number,
source?: string,
file?: string,
plugin?: string
)
stack: string
/**
* Always equal to `'CssSyntaxError'`. You should always check error type
* by `error.name === 'CssSyntaxError'`
* instead of `error instanceof CssSyntaxError`,
* because npm could have several PostCSS versions.
*
* ```js
* if (error.name === 'CssSyntaxError') {
* error //=> CssSyntaxError
* }
* ```
*/
name: 'CssSyntaxError'
/**
* Error message.
*
* ```js
* error.message //=> 'Unclosed block'
* ```
*/
reason: string
/**
* Full error text in the GNU error format
* with plugin, file, line and column.
*
* ```js
* error.message //=> 'a.css:1:1: Unclosed block'
* ```
*/
message: string
/**
* Absolute path to the broken file.
*
* ```js
* error.file //=> 'a.sass'
* error.input.file //=> 'a.css'
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.file`.
*/
file?: string
/**
* Source line of the error.
*
* ```js
* error.line //=> 2
* error.input.line //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.line`.
*/
line?: number
/**
* Source column of the error.
*
* ```js
* error.column //=> 1
* error.input.column //=> 4
* ```
*
* PostCSS will use the input source map to detect the original location.
* If you need the position in the PostCSS input, use `error.input.column`.
*/
column?: number
/**
* Source code of the broken file.
*
* ```js
* error.source //=> 'a { b {} }'
* error.input.column //=> 'a b { }'
* ```
*/
source?: string
/**
* Plugin name, if error came from plugin.
*
* ```js
* error.plugin //=> 'postcss-vars'
* ```
*/
plugin?: string
/**
* Input object with PostCSS internal information
* about input file. If input has source map
* from previous tool, PostCSS will use origin
* (for example, Sass) source. You can use this
* object to get PostCSS input source.
*
* ```js
* error.input.file //=> 'a.css'
* error.file //=> 'a.sass'
* ```
*/
input?: FilePosition
/**
* Returns error position, message and source code of the broken part.
*
* ```js
* error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
* // > 1 | a {
* // | ^"
* ```
*
* @return Error position, message and source code.
*/
toString(): string
/**
* Returns a few lines of CSS source that caused the error.
*
* If the CSS has an input source map without `sourceContent`,
* this method will return an empty string.
*
* ```js
* error.showSourceCode() //=> " 4 | }
* // 5 | a {
* // > 6 | bad
* // | ^
* // 7 | }
* // 8 | b {"
* ```
*
* @param color Whether arrow will be colored red by terminal
* color codes. By default, PostCSS will detect
* color support by `process.stdout.isTTY`
* and `process.env.NODE_DISABLE_COLORS`.
* @return Few lines of CSS source that caused the error.
*/
showSourceCode(color?: boolean): string
}

View file

@ -0,0 +1,92 @@
'use strict'
let { red, bold, gray, options: colorette } = require('colorette')
let terminalHighlight = require('./terminal-highlight')
class CssSyntaxError extends Error {
constructor(message, line, column, source, file, plugin) {
super(message)
this.name = 'CssSyntaxError'
this.reason = message
if (file) {
this.file = file
}
if (source) {
this.source = source
}
if (plugin) {
this.plugin = plugin
}
if (typeof line !== 'undefined' && typeof column !== 'undefined') {
this.line = line
this.column = column
}
this.setMessage()
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError)
}
}
setMessage() {
this.message = this.plugin ? this.plugin + ': ' : ''
this.message += this.file ? this.file : '<css input>'
if (typeof this.line !== 'undefined') {
this.message += ':' + this.line + ':' + this.column
}
this.message += ': ' + this.reason
}
showSourceCode(color) {
if (!this.source) return ''
let css = this.source
if (color == null) color = colorette.enabled
if (terminalHighlight) {
if (color) css = terminalHighlight(css)
}
let lines = css.split(/\r?\n/)
let start = Math.max(this.line - 3, 0)
let end = Math.min(this.line + 2, lines.length)
let maxWidth = String(end).length
let mark, aside
if (color) {
mark = text => bold(red(text))
aside = text => gray(text)
} else {
mark = aside = str => str
}
return lines
.slice(start, end)
.map((line, index) => {
let number = start + 1 + index
let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '
if (number === this.line) {
let spacing =
aside(gutter.replace(/\d/g, ' ')) +
line.slice(0, this.column - 1).replace(/[^\t]/g, ' ')
return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
}
return ' ' + aside(gutter) + line
})
.join('\n')
}
toString() {
let code = this.showSourceCode()
if (code) {
code = '\n\n' + code + '\n'
}
return this.name + ': ' + this.message + code
}
}
module.exports = CssSyntaxError
CssSyntaxError.default = CssSyntaxError

116
assets_old/node_modules/postcss/lib/declaration.d.ts generated vendored Normal file
View file

@ -0,0 +1,116 @@
import Node from './node.js'
interface DeclarationRaws {
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
/**
* The symbols between the property and value for declarations.
*/
between?: string
/**
* The content of the important statement, if it is not just `!important`.
*/
important?: string
/**
* Declaration value with comments.
*/
value: {
value: string
raw: string
}
}
export interface DeclarationProps {
prop: string
value: string
raws?: DeclarationRaws
}
/**
* Represents a CSS declaration.
*
* ```js
* Once (root, { Declaration }) {
* let color = new Declaration({ prop: 'color', value: 'black' })
* root.append(color)
* }
* ```
*
* ```js
* const root = postcss.parse('a { color: black }')
* const decl = root.first.first
* decl.type //=> 'decl'
* decl.toString() //=> ' color: black'
* ```
*/
export default class Declaration extends Node {
type: 'decl'
raws: DeclarationRaws
/**
* The declaration's property name.
*
* ```js
* const root = postcss.parse('a { color: black }')
* const decl = root.first.first
* decl.prop //=> 'color'
* ```
*/
prop: string
/**
* The declarations value.
*
* This value will be cleaned of comments. If the source value contained
* comments, those comments will be available in the `raws` property.
* If you have not changed the value, the result of `decl.toString()`
* will include the original raws value (comments and all).
*
* ```js
* const root = postcss.parse('a { color: black }')
* const decl = root.first.first
* decl.value //=> 'black'
* ```
*/
value: string
/**
* `true` if the declaration has an `!important` annotation.
*
* ```js
* const root = postcss.parse('a { color: black !important; color: red }')
* root.first.first.important //=> true
* root.first.last.important //=> undefined
* ```
*/
important: boolean
/**
* `true` if declaration is declaration of CSS Custom Property
* or Sass variable.
*
* ```js
* const root = postcss.parse(':root { --one: 1 }')
* let one = root.first.first
* one.variable //=> true
* ```
*
* ```js
* const root = postcss.parse('$one: 1')
* let one = root.first
* one.variable //=> true
* ```
*/
variable: boolean
constructor(defaults?: DeclarationProps)
clone(overrides?: Partial<DeclarationProps>): this
cloneBefore(overrides?: Partial<DeclarationProps>): this
cloneAfter(overrides?: Partial<DeclarationProps>): this
}

24
assets_old/node_modules/postcss/lib/declaration.js generated vendored Normal file
View file

@ -0,0 +1,24 @@
'use strict'
let Node = require('./node')
class Declaration extends Node {
constructor(defaults) {
if (
defaults &&
typeof defaults.value !== 'undefined' &&
typeof defaults.value !== 'string'
) {
defaults = { ...defaults, value: String(defaults.value) }
}
super(defaults)
this.type = 'decl'
}
get variable() {
return this.prop.startsWith('--') || this.prop[0] === '$'
}
}
module.exports = Declaration
Declaration.default = Declaration

5
assets_old/node_modules/postcss/lib/fromJSON.d.ts generated vendored Normal file
View file

@ -0,0 +1,5 @@
import { JSONHydrator } from './postcss.js'
declare const fromJSON: JSONHydrator
export default fromJSON

54
assets_old/node_modules/postcss/lib/fromJSON.js generated vendored Normal file
View file

@ -0,0 +1,54 @@
'use strict'
let Declaration = require('./declaration')
let PreviousMap = require('./previous-map')
let Comment = require('./comment')
let AtRule = require('./at-rule')
let Input = require('./input')
let Root = require('./root')
let Rule = require('./rule')
function fromJSON(json, inputs) {
if (Array.isArray(json)) return json.map(n => fromJSON(n))
let { inputs: ownInputs, ...defaults } = json
if (ownInputs) {
inputs = []
for (let input of ownInputs) {
let inputHydrated = { ...input, __proto__: Input.prototype }
if (inputHydrated.map) {
inputHydrated.map = {
...inputHydrated.map,
__proto__: PreviousMap.prototype
}
}
inputs.push(inputHydrated)
}
}
if (defaults.nodes) {
defaults.nodes = json.nodes.map(n => fromJSON(n, inputs))
}
if (defaults.source) {
let { inputId, ...source } = defaults.source
defaults.source = source
if (inputId != null) {
defaults.source.input = inputs[inputId]
}
}
if (defaults.type === 'root') {
return new Root(defaults)
} else if (defaults.type === 'decl') {
return new Declaration(defaults)
} else if (defaults.type === 'rule') {
return new Rule(defaults)
} else if (defaults.type === 'comment') {
return new Comment(defaults)
} else if (defaults.type === 'atrule') {
return new AtRule(defaults)
} else {
throw new Error('Unknown node type: ' + json.type)
}
}
module.exports = fromJSON
fromJSON.default = fromJSON

130
assets_old/node_modules/postcss/lib/input.d.ts generated vendored Normal file
View file

@ -0,0 +1,130 @@
import { ProcessOptions } from './postcss.js'
import PreviousMap from './previous-map.js'
export interface FilePosition {
/**
* URL for the source file.
*/
url: string
/**
* Absolute path to the source file.
*/
file?: string
/**
* Line in source file.
*/
line: number
/**
* Column in source file.
*/
column: number
/**
* Source code.
*/
source?: string
}
/**
* Represents the source CSS.
*
* ```js
* const root = postcss.parse(css, { from: file })
* const input = root.source.input
* ```
*/
export default class Input {
/**
* Input CSS source.
*
* ```js
* const input = postcss.parse('a{}', { from: file }).input
* input.css //=> "a{}"
* ```
*/
css: string
/**
* The input source map passed from a compilation step before PostCSS
* (for example, from Sass compiler).
*
* ```js
* root.source.input.map.consumer().sources //=> ['a.sass']
* ```
*/
map: PreviousMap
/**
* The absolute path to the CSS source file defined
* with the `from` option.
*
* ```js
* const root = postcss.parse(css, { from: 'a.css' })
* root.source.input.file //=> '/home/ai/a.css'
* ```
*/
file?: string
/**
* The unique ID of the CSS source. It will be created if `from` option
* is not provided (because PostCSS does not know the file path).
*
* ```js
* const root = postcss.parse(css)
* root.source.input.file //=> undefined
* root.source.input.id //=> "<input css 8LZeVF>"
* ```
*/
id?: string
/**
* The flag to indicate whether or not the source code has Unicode BOM.
*/
hasBOM: boolean
/**
* @param css Input CSS source.
* @param opts Process options.
*/
constructor(css: string, opts?: ProcessOptions)
/**
* The CSS source identifier. Contains `Input#file` if the user
* set the `from` option, or `Input#id` if they did not.
*
* ```js
* const root = postcss.parse(css, { from: 'a.css' })
* root.source.input.from //=> "/home/ai/a.css"
*
* const root = postcss.parse(css)
* root.source.input.from //=> "<input css 1>"
* ```
*/
get from(): string
/**
* Reads the input source map and returns a symbol position
* in the input source (e.g., in a Sass file that was compiled
* to CSS before being passed to PostCSS).
*
* ```js
* root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
* ```
*
* @param line Line in input CSS.
* @param column Column in input CSS.
*
* @return Position in input source.
*/
origin(line: number, column: number): FilePosition | false
/**
* Converts source offset to line and column.
*
* @param offset Source offset.
*/
fromOffset(offset: number): { line: number; col: number } | null
}

207
assets_old/node_modules/postcss/lib/input.js generated vendored Normal file
View file

@ -0,0 +1,207 @@
'use strict'
let { fileURLToPath, pathToFileURL } = require('url')
let { resolve, isAbsolute } = require('path')
let { nanoid } = require('nanoid/non-secure')
let terminalHighlight = require('./terminal-highlight')
let CssSyntaxError = require('./css-syntax-error')
let PreviousMap = require('./previous-map')
let fromOffsetCache = Symbol('fromOffset cache')
let pathAvailable = Boolean(resolve && isAbsolute)
class Input {
constructor(css, opts = {}) {
if (
css === null ||
typeof css === 'undefined' ||
(typeof css === 'object' && !css.toString)
) {
throw new Error(`PostCSS received ${css} instead of CSS string`)
}
this.css = css.toString()
if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
this.hasBOM = true
this.css = this.css.slice(1)
} else {
this.hasBOM = false
}
if (opts.from) {
if (
!pathAvailable ||
/^\w+:\/\//.test(opts.from) ||
isAbsolute(opts.from)
) {
this.file = opts.from
} else {
this.file = resolve(opts.from)
}
}
if (pathAvailable) {
let map = new PreviousMap(this.css, opts)
if (map.text) {
this.map = map
let file = map.consumer().file
if (!this.file && file) this.file = this.mapResolve(file)
}
}
if (!this.file) {
this.id = '<input css ' + nanoid(6) + '>'
}
if (this.map) this.map.file = this.from
}
fromOffset(offset) {
let lastLine, lineToIndex
if (!this[fromOffsetCache]) {
let lines = this.css.split('\n')
lineToIndex = new Array(lines.length)
let prevIndex = 0
for (let i = 0, l = lines.length; i < l; i++) {
lineToIndex[i] = prevIndex
prevIndex += lines[i].length + 1
}
this[fromOffsetCache] = lineToIndex
} else {
lineToIndex = this[fromOffsetCache]
}
lastLine = lineToIndex[lineToIndex.length - 1]
let min = 0
if (offset >= lastLine) {
min = lineToIndex.length - 1
} else {
let max = lineToIndex.length - 2
let mid
while (min < max) {
mid = min + ((max - min) >> 1)
if (offset < lineToIndex[mid]) {
max = mid - 1
} else if (offset >= lineToIndex[mid + 1]) {
min = mid + 1
} else {
min = mid
break
}
}
}
return {
line: min + 1,
col: offset - lineToIndex[min] + 1
}
}
error(message, line, column, opts = {}) {
let result
if (!column) {
let pos = this.fromOffset(line)
line = pos.line
column = pos.col
}
let origin = this.origin(line, column)
if (origin) {
result = new CssSyntaxError(
message,
origin.line,
origin.column,
origin.source,
origin.file,
opts.plugin
)
} else {
result = new CssSyntaxError(
message,
line,
column,
this.css,
this.file,
opts.plugin
)
}
result.input = { line, column, source: this.css }
if (this.file) {
result.input.url = pathToFileURL(this.file).toString()
result.input.file = this.file
}
return result
}
origin(line, column) {
if (!this.map) return false
let consumer = this.map.consumer()
let from = consumer.originalPositionFor({ line, column })
if (!from.source) return false
let fromUrl
if (isAbsolute(from.source)) {
fromUrl = pathToFileURL(from.source)
} else {
fromUrl = new URL(
from.source,
this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
)
}
let result = {
url: fromUrl.toString(),
line: from.line,
column: from.column
}
if (fromUrl.protocol === 'file:') {
result.file = fileURLToPath(fromUrl)
}
let source = consumer.sourceContentFor(from.source)
if (source) result.source = source
return result
}
mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file
}
return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
}
get from() {
return this.file || this.id
}
toJSON() {
let json = {}
for (let name of ['hasBOM', 'css', 'file', 'id']) {
if (this[name] != null) {
json[name] = this[name]
}
}
if (this.map) {
json.map = { ...this.map }
if (json.map.consumerCache) {
json.map.consumerCache = undefined
}
}
return json
}
}
module.exports = Input
Input.default = Input
if (terminalHighlight && terminalHighlight.registerInput) {
terminalHighlight.registerInput(Input)
}

175
assets_old/node_modules/postcss/lib/lazy-result.d.ts generated vendored Normal file
View file

@ -0,0 +1,175 @@
import Result, { Message, ResultOptions } from './result.js'
import { SourceMap } from './postcss.js'
import Processor from './processor.js'
import Warning from './warning.js'
import Root from './root.js'
/**
* A Promise proxy for the result of PostCSS transformations.
*
* A `LazyResult` instance is returned by `Processor#process`.
*
* ```js
* const lazy = postcss([autoprefixer]).process(css)
* ```
*/
export default class LazyResult implements PromiseLike<Result> {
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls `onFulfilled` with a Result instance. If a plugin throws
* an error, the `onRejected` callback will be executed.
*
* It implements standard Promise API.
*
* ```js
* postcss([autoprefixer]).process(css, { from: cssPath }).then(result => {
* console.log(result.css)
* })
* ```
*/
then: Promise<Result>['then']
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls onRejected for each error thrown in any plugin.
*
* It implements standard Promise API.
*
* ```js
* postcss([autoprefixer]).process(css).then(result => {
* console.log(result.css)
* }).catch(error => {
* console.error(error)
* })
* ```
*/
catch: Promise<Result>['catch']
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls onFinally on any error or when all plugins will finish work.
*
* It implements standard Promise API.
*
* ```js
* postcss([autoprefixer]).process(css).finally(() => {
* console.log('processing ended')
* })
* ```
*/
finally: Promise<Result>['finally']
/**
* @param processor Processor used for this transformation.
* @param css CSS to parse and transform.
* @param opts Options from the `Processor#process` or `Root#toResult`.
*/
constructor(processor: Processor, css: string, opts: ResultOptions)
/**
* Returns the default string description of an object.
* Required to implement the Promise interface.
*/
get [Symbol.toStringTag](): string
/**
* Returns a `Processor` instance, which will be used
* for CSS transformations.
*/
get processor(): Processor
/**
* Options from the `Processor#process` call.
*/
get opts(): ResultOptions
/**
* Processes input CSS through synchronous plugins, converts `Root`
* to a CSS string and returns `Result#css`.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use `LazyResult#then`.
*/
get css(): string
/**
* An alias for the `css` property. Use it with syntaxes
* that generate non-CSS output.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use `LazyResult#then`.
*/
get content(): string
/**
* Processes input CSS through synchronous plugins
* and returns `Result#map`.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use `LazyResult#then`.
*/
get map(): SourceMap
/**
* Processes input CSS through synchronous plugins
* and returns `Result#root`.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use `LazyResult#then`.
*/
get root(): Root
/**
* Processes input CSS through synchronous plugins
* and returns `Result#messages`.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use `LazyResult#then`.
*/
get messages(): Message[]
/**
* Processes input CSS through synchronous plugins
* and calls `Result#warnings`.
*
* @return Warnings from plugins.
*/
warnings(): Warning[]
/**
* Alias for the `LazyResult#css` property.
*
* ```js
* lazy + '' === lazy.css
* ```
*
* @return Output CSS.
*/
toString(): string
/**
* Run plugin in sync way and return `Result`.
*
* @return Result with output content.
*/
sync(): Result
/**
* Run plugin in async way and return `Result`.
*
* @return Result with output content.
*/
async(): Promise<Result>
}

503
assets_old/node_modules/postcss/lib/lazy-result.js generated vendored Normal file
View file

@ -0,0 +1,503 @@
'use strict'
let MapGenerator = require('./map-generator')
let { isClean } = require('./symbols')
let stringify = require('./stringify')
let warnOnce = require('./warn-once')
let Result = require('./result')
let parse = require('./parse')
let Root = require('./root')
const TYPE_TO_CLASS_NAME = {
root: 'Root',
atrule: 'AtRule',
rule: 'Rule',
decl: 'Declaration',
comment: 'Comment'
}
const PLUGIN_PROPS = {
postcssPlugin: true,
prepare: true,
Once: true,
Root: true,
Declaration: true,
Rule: true,
AtRule: true,
Comment: true,
DeclarationExit: true,
RuleExit: true,
AtRuleExit: true,
CommentExit: true,
RootExit: true,
OnceExit: true
}
const NOT_VISITORS = {
postcssPlugin: true,
prepare: true,
Once: true
}
const CHILDREN = 0
function isPromise(obj) {
return typeof obj === 'object' && typeof obj.then === 'function'
}
function getEvents(node) {
let key = false
let type = TYPE_TO_CLASS_NAME[node.type]
if (node.type === 'decl') {
key = node.prop.toLowerCase()
} else if (node.type === 'atrule') {
key = node.name.toLowerCase()
}
if (key && node.append) {
return [
type,
type + '-' + key,
CHILDREN,
type + 'Exit',
type + 'Exit-' + key
]
} else if (key) {
return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
} else if (node.append) {
return [type, CHILDREN, type + 'Exit']
} else {
return [type, type + 'Exit']
}
}
function toStack(node) {
let events
if (node.type === 'root') {
events = ['Root', CHILDREN, 'RootExit']
} else {
events = getEvents(node)
}
return {
node,
events,
eventIndex: 0,
visitors: [],
visitorIndex: 0,
iterator: 0
}
}
function cleanMarks(node) {
node[isClean] = false
if (node.nodes) node.nodes.forEach(i => cleanMarks(i))
return node
}
let postcss = {}
class LazyResult {
constructor(processor, css, opts) {
this.stringified = false
this.processed = false
let root
if (typeof css === 'object' && css !== null && css.type === 'root') {
root = cleanMarks(css)
} else if (css instanceof LazyResult || css instanceof Result) {
root = cleanMarks(css.root)
if (css.map) {
if (typeof opts.map === 'undefined') opts.map = {}
if (!opts.map.inline) opts.map.inline = false
opts.map.prev = css.map
}
} else {
let parser = parse
if (opts.syntax) parser = opts.syntax.parse
if (opts.parser) parser = opts.parser
if (parser.parse) parser = parser.parse
try {
root = parser(css, opts)
} catch (error) {
this.processed = true
this.error = error
}
}
this.result = new Result(processor, root, opts)
this.helpers = { ...postcss, result: this.result, postcss }
this.plugins = this.processor.plugins.map(plugin => {
if (typeof plugin === 'object' && plugin.prepare) {
return { ...plugin, ...plugin.prepare(this.result) }
} else {
return plugin
}
})
}
get [Symbol.toStringTag]() {
return 'LazyResult'
}
get processor() {
return this.result.processor
}
get opts() {
return this.result.opts
}
get css() {
return this.stringify().css
}
get content() {
return this.stringify().content
}
get map() {
return this.stringify().map
}
get root() {
return this.sync().root
}
get messages() {
return this.sync().messages
}
warnings() {
return this.sync().warnings()
}
toString() {
return this.css
}
then(onFulfilled, onRejected) {
if (process.env.NODE_ENV !== 'production') {
if (!('from' in this.opts)) {
warnOnce(
'Without `from` option PostCSS could generate wrong source map ' +
'and will not find Browserslist config. Set it to CSS file path ' +
'or to `undefined` to prevent this warning.'
)
}
}
return this.async().then(onFulfilled, onRejected)
}
catch(onRejected) {
return this.async().catch(onRejected)
}
finally(onFinally) {
return this.async().then(onFinally, onFinally)
}
async() {
if (this.error) return Promise.reject(this.error)
if (this.processed) return Promise.resolve(this.result)
if (!this.processing) {
this.processing = this.runAsync()
}
return this.processing
}
sync() {
if (this.error) throw this.error
if (this.processed) return this.result
this.processed = true
if (this.processing) {
throw this.getAsyncError()
}
for (let plugin of this.plugins) {
let promise = this.runOnRoot(plugin)
if (isPromise(promise)) {
throw this.getAsyncError()
}
}
this.prepareVisitors()
if (this.hasListener) {
let root = this.result.root
while (!root[isClean]) {
root[isClean] = true
this.walkSync(root)
}
if (this.listeners.OnceExit) {
this.visitSync(this.listeners.OnceExit, root)
}
}
return this.result
}
stringify() {
if (this.error) throw this.error
if (this.stringified) return this.result
this.stringified = true
this.sync()
let opts = this.result.opts
let str = stringify
if (opts.syntax) str = opts.syntax.stringify
if (opts.stringifier) str = opts.stringifier
if (str.stringify) str = str.stringify
let map = new MapGenerator(str, this.result.root, this.result.opts)
let data = map.generate()
this.result.css = data[0]
this.result.map = data[1]
return this.result
}
walkSync(node) {
node[isClean] = true
let events = getEvents(node)
for (let event of events) {
if (event === CHILDREN) {
if (node.nodes) {
node.each(child => {
if (!child[isClean]) this.walkSync(child)
})
}
} else {
let visitors = this.listeners[event]
if (visitors) {
if (this.visitSync(visitors, node.toProxy())) return
}
}
}
}
visitSync(visitors, node) {
for (let [plugin, visitor] of visitors) {
this.result.lastPlugin = plugin
let promise
try {
promise = visitor(node, this.helpers)
} catch (e) {
throw this.handleError(e, node.proxyOf)
}
if (node.type !== 'root' && !node.parent) return true
if (isPromise(promise)) {
throw this.getAsyncError()
}
}
}
runOnRoot(plugin) {
this.result.lastPlugin = plugin
try {
if (typeof plugin === 'object' && plugin.Once) {
return plugin.Once(this.result.root, this.helpers)
} else if (typeof plugin === 'function') {
return plugin(this.result.root, this.result)
}
} catch (error) {
throw this.handleError(error)
}
}
getAsyncError() {
throw new Error('Use process(css).then(cb) to work with async plugins')
}
handleError(error, node) {
let plugin = this.result.lastPlugin
try {
if (node) node.addToError(error)
this.error = error
if (error.name === 'CssSyntaxError' && !error.plugin) {
error.plugin = plugin.postcssPlugin
error.setMessage()
} else if (plugin.postcssVersion) {
if (process.env.NODE_ENV !== 'production') {
let pluginName = plugin.postcssPlugin
let pluginVer = plugin.postcssVersion
let runtimeVer = this.result.processor.version
let a = pluginVer.split('.')
let b = runtimeVer.split('.')
if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
console.error(
'Unknown error from PostCSS plugin. Your current PostCSS ' +
'version is ' +
runtimeVer +
', but ' +
pluginName +
' uses ' +
pluginVer +
'. Perhaps this is the source of the error below.'
)
}
}
}
} catch (err) {
// istanbul ignore next
if (console && console.error) console.error(err)
}
return error
}
async runAsync() {
this.plugin = 0
for (let i = 0; i < this.plugins.length; i++) {
let plugin = this.plugins[i]
let promise = this.runOnRoot(plugin)
if (isPromise(promise)) {
try {
await promise
} catch (error) {
throw this.handleError(error)
}
}
}
this.prepareVisitors()
if (this.hasListener) {
let root = this.result.root
while (!root[isClean]) {
root[isClean] = true
let stack = [toStack(root)]
while (stack.length > 0) {
let promise = this.visitTick(stack)
if (isPromise(promise)) {
try {
await promise
} catch (e) {
let node = stack[stack.length - 1].node
throw this.handleError(e, node)
}
}
}
}
if (this.listeners.OnceExit) {
for (let [plugin, visitor] of this.listeners.OnceExit) {
this.result.lastPlugin = plugin
try {
await visitor(root, this.helpers)
} catch (e) {
throw this.handleError(e)
}
}
}
}
this.processed = true
return this.stringify()
}
prepareVisitors() {
this.listeners = {}
let add = (plugin, type, cb) => {
if (!this.listeners[type]) this.listeners[type] = []
this.listeners[type].push([plugin, cb])
}
for (let plugin of this.plugins) {
if (typeof plugin === 'object') {
for (let event in plugin) {
if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
throw new Error(
`Unknown event ${event} in ${plugin.postcssPlugin}. ` +
`Try to update PostCSS (${this.processor.version} now).`
)
}
if (!NOT_VISITORS[event]) {
if (typeof plugin[event] === 'object') {
for (let filter in plugin[event]) {
if (filter === '*') {
add(plugin, event, plugin[event][filter])
} else {
add(
plugin,
event + '-' + filter.toLowerCase(),
plugin[event][filter]
)
}
}
} else if (typeof plugin[event] === 'function') {
add(plugin, event, plugin[event])
}
}
}
}
}
this.hasListener = Object.keys(this.listeners).length > 0
}
visitTick(stack) {
let visit = stack[stack.length - 1]
let { node, visitors } = visit
if (node.type !== 'root' && !node.parent) {
stack.pop()
return
}
if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
let [plugin, visitor] = visitors[visit.visitorIndex]
visit.visitorIndex += 1
if (visit.visitorIndex === visitors.length) {
visit.visitors = []
visit.visitorIndex = 0
}
this.result.lastPlugin = plugin
try {
return visitor(node.toProxy(), this.helpers)
} catch (e) {
throw this.handleError(e, node)
}
}
if (visit.iterator !== 0) {
let iterator = visit.iterator
let child
while ((child = node.nodes[node.indexes[iterator]])) {
node.indexes[iterator] += 1
if (!child[isClean]) {
child[isClean] = true
stack.push(toStack(child))
return
}
}
visit.iterator = 0
delete node.indexes[iterator]
}
let events = visit.events
while (visit.eventIndex < events.length) {
let event = events[visit.eventIndex]
visit.eventIndex += 1
if (event === CHILDREN) {
if (node.nodes && node.nodes.length) {
node[isClean] = true
visit.iterator = node.getIterator()
}
return
} else if (this.listeners[event]) {
visit.visitors = this.listeners[event]
return
}
}
stack.pop()
}
}
LazyResult.registerPostcss = dependant => {
postcss = dependant
}
module.exports = LazyResult
LazyResult.default = LazyResult
Root.registerLazyResult(LazyResult)

36
assets_old/node_modules/postcss/lib/list.d.ts generated vendored Normal file
View file

@ -0,0 +1,36 @@
export type List = {
/**
* Safely splits space-separated values (such as those for `background`,
* `border-radius`, and other shorthand properties).
*
* ```js
* Once (root, { list }) {
* list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
* }
* ```
*
* @param str Space-separated values.
* @return Split values.
*/
space(str: string): string[]
/**
* Safely splits comma-separated values (such as those for `transition-*`
* and `background` properties).
*
* ```js
* Once (root, { list }) {
* list.comma('black, linear-gradient(white, black)')
* //=> ['black', 'linear-gradient(white, black)']
* }
* ```
*
* @param str Comma-separated values.
* @return Split values.
*/
comma(str: string): string[]
}
declare const list: List
export default list

56
assets_old/node_modules/postcss/lib/list.js generated vendored Normal file
View file

@ -0,0 +1,56 @@
'use strict'
let list = {
split(string, separators, last) {
let array = []
let current = ''
let split = false
let func = 0
let quote = false
let escape = false
for (let letter of string) {
if (escape) {
escape = false
} else if (letter === '\\') {
escape = true
} else if (quote) {
if (letter === quote) {
quote = false
}
} else if (letter === '"' || letter === "'") {
quote = letter
} else if (letter === '(') {
func += 1
} else if (letter === ')') {
if (func > 0) func -= 1
} else if (func === 0) {
if (separators.includes(letter)) split = true
}
if (split) {
if (current !== '') array.push(current.trim())
current = ''
split = false
} else {
current += letter
}
}
if (last || current !== '') array.push(current.trim())
return array
},
space(string) {
let spaces = [' ', '\n', '\t']
return list.split(string, spaces)
},
comma(string) {
return list.split(string, [','], true)
}
}
module.exports = list
list.default = list

292
assets_old/node_modules/postcss/lib/map-generator.js generated vendored Normal file
View file

@ -0,0 +1,292 @@
'use strict'
let { dirname, resolve, relative, sep } = require('path')
let { pathToFileURL } = require('url')
let mozilla = require('source-map')
let pathAvailable = Boolean(dirname, resolve, relative, sep)
class MapGenerator {
constructor(stringify, root, opts) {
this.stringify = stringify
this.mapOpts = opts.map || {}
this.root = root
this.opts = opts
}
isMap() {
if (typeof this.opts.map !== 'undefined') {
return !!this.opts.map
}
return this.previous().length > 0
}
previous() {
if (!this.previousMaps) {
this.previousMaps = []
this.root.walk(node => {
if (node.source && node.source.input.map) {
let map = node.source.input.map
if (!this.previousMaps.includes(map)) {
this.previousMaps.push(map)
}
}
})
}
return this.previousMaps
}
isInline() {
if (typeof this.mapOpts.inline !== 'undefined') {
return this.mapOpts.inline
}
let annotation = this.mapOpts.annotation
if (typeof annotation !== 'undefined' && annotation !== true) {
return false
}
if (this.previous().length) {
return this.previous().some(i => i.inline)
}
return true
}
isSourcesContent() {
if (typeof this.mapOpts.sourcesContent !== 'undefined') {
return this.mapOpts.sourcesContent
}
if (this.previous().length) {
return this.previous().some(i => i.withContent())
}
return true
}
clearAnnotation() {
if (this.mapOpts.annotation === false) return
let node
for (let i = this.root.nodes.length - 1; i >= 0; i--) {
node = this.root.nodes[i]
if (node.type !== 'comment') continue
if (node.text.indexOf('# sourceMappingURL=') === 0) {
this.root.removeChild(i)
}
}
}
setSourcesContent() {
let already = {}
this.root.walk(node => {
if (node.source) {
let from = node.source.input.from
if (from && !already[from]) {
already[from] = true
this.map.setSourceContent(
this.toUrl(this.path(from)),
node.source.input.css
)
}
}
})
}
applyPrevMaps() {
for (let prev of this.previous()) {
let from = this.toUrl(this.path(prev.file))
let root = prev.root || dirname(prev.file)
let map
if (this.mapOpts.sourcesContent === false) {
map = new mozilla.SourceMapConsumer(prev.text)
if (map.sourcesContent) {
map.sourcesContent = map.sourcesContent.map(() => null)
}
} else {
map = prev.consumer()
}
this.map.applySourceMap(map, from, this.toUrl(this.path(root)))
}
}
isAnnotation() {
if (this.isInline()) {
return true
}
if (typeof this.mapOpts.annotation !== 'undefined') {
return this.mapOpts.annotation
}
if (this.previous().length) {
return this.previous().some(i => i.annotation)
}
return true
}
toBase64(str) {
if (Buffer) {
return Buffer.from(str).toString('base64')
} else {
// istanbul ignore next
return window.btoa(unescape(encodeURIComponent(str)))
}
}
addAnnotation() {
let content
if (this.isInline()) {
content =
'data:application/json;base64,' + this.toBase64(this.map.toString())
} else if (typeof this.mapOpts.annotation === 'string') {
content = this.mapOpts.annotation
} else if (typeof this.mapOpts.annotation === 'function') {
content = this.mapOpts.annotation(this.opts.to, this.root)
} else {
content = this.outputFile() + '.map'
}
let eol = '\n'
if (this.css.includes('\r\n')) eol = '\r\n'
this.css += eol + '/*# sourceMappingURL=' + content + ' */'
}
outputFile() {
if (this.opts.to) {
return this.path(this.opts.to)
}
if (this.opts.from) {
return this.path(this.opts.from)
}
return 'to.css'
}
generateMap() {
this.generateString()
if (this.isSourcesContent()) this.setSourcesContent()
if (this.previous().length > 0) this.applyPrevMaps()
if (this.isAnnotation()) this.addAnnotation()
if (this.isInline()) {
return [this.css]
}
return [this.css, this.map]
}
path(file) {
if (file.indexOf('<') === 0) return file
if (/^\w+:\/\//.test(file)) return file
if (this.mapOpts.absolute) return file
let from = this.opts.to ? dirname(this.opts.to) : '.'
if (typeof this.mapOpts.annotation === 'string') {
from = dirname(resolve(from, this.mapOpts.annotation))
}
file = relative(from, file)
return file
}
toUrl(path) {
if (sep === '\\') {
// istanbul ignore next
path = path.replace(/\\/g, '/')
}
return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
}
sourcePath(node) {
if (this.mapOpts.from) {
return this.toUrl(this.mapOpts.from)
} else if (this.mapOpts.absolute) {
return pathToFileURL(node.source.input.from).toString()
} else {
return this.toUrl(this.path(node.source.input.from))
}
}
generateString() {
this.css = ''
this.map = new mozilla.SourceMapGenerator({ file: this.outputFile() })
let line = 1
let column = 1
let noSource = '<no source>'
let mapping = {
source: '',
generated: { line: 0, column: 0 },
original: { line: 0, column: 0 }
}
let lines, last
this.stringify(this.root, (str, node, type) => {
this.css += str
if (node && type !== 'end') {
mapping.generated.line = line
mapping.generated.column = column - 1
if (node.source && node.source.start) {
mapping.source = this.sourcePath(node)
mapping.original.line = node.source.start.line
mapping.original.column = node.source.start.column - 1
this.map.addMapping(mapping)
} else {
mapping.source = noSource
mapping.original.line = 1
mapping.original.column = 0
this.map.addMapping(mapping)
}
}
lines = str.match(/\n/g)
if (lines) {
line += lines.length
last = str.lastIndexOf('\n')
column = str.length - last
} else {
column += str.length
}
if (node && type !== 'start') {
let p = node.parent || { raws: {} }
if (node.type !== 'decl' || node !== p.last || p.raws.semicolon) {
if (node.source && node.source.end) {
mapping.source = this.sourcePath(node)
mapping.original.line = node.source.end.line
mapping.original.column = node.source.end.column - 1
mapping.generated.line = line
mapping.generated.column = column - 2
this.map.addMapping(mapping)
} else {
mapping.source = noSource
mapping.original.line = 1
mapping.original.column = 0
mapping.generated.line = line
mapping.generated.column = column - 1
this.map.addMapping(mapping)
}
}
}
})
}
generate() {
this.clearAnnotation()
if (pathAvailable && this.isMap()) {
return this.generateMap()
}
let result = ''
this.stringify(this.root, i => {
result += i
})
return [result]
}
}
module.exports = MapGenerator

431
assets_old/node_modules/postcss/lib/node.d.ts generated vendored Normal file
View file

@ -0,0 +1,431 @@
import Declaration, { DeclarationProps } from './declaration.js'
import Comment, { CommentProps } from './comment.js'
import { Stringifier, Syntax } from './postcss.js'
import AtRule, { AtRuleProps } from './at-rule.js'
import Rule, { RuleProps } from './rule.js'
import { WarningOptions } from './warning.js'
import CssSyntaxError from './css-syntax-error.js'
import Container from './container.js'
import Result from './result.js'
import Input from './input.js'
import Root from './root.js'
export type ChildNode = AtRule | Rule | Declaration | Comment
export type AnyNode = AtRule | Rule | Declaration | Comment | Root
export type ChildProps =
| AtRuleProps
| RuleProps
| DeclarationProps
| CommentProps
export interface Position {
/**
* Source offset in file. It starts from 0.
*/
offset: number
/**
* Source line in file. In contrast to `offset` it starts from 1.
*/
column: number
/**
* Source column in file.
*/
line: number
}
export interface Source {
/**
* The file source of the node.
*/
input: Input
/**
* The starting position of the nodes source.
*/
start?: Position
/**
* The ending position of the node's source.
*/
end?: Position
}
export interface NodeProps {
source?: Source
}
interface NodeErrorOptions {
/**
* Plugin name that created this error. PostCSS will set it automatically.
*/
plugin?: string
/**
* A word inside a node's string, that should be highlighted as source
* of error.
*/
word?: string
/**
* An index inside a node's string that should be highlighted as source
* of error.
*/
index?: number
}
/**
* All node classes inherit the following common methods.
*
* You should not extend this classes to create AST for selector or value
* parser.
*/
export default abstract class Node {
/**
* tring representing the nodes type. Possible values are `root`, `atrule`,
* `rule`, `decl`, or `comment`.
*
* ```js
* new Declaration({ prop: 'color', value: 'black' }).type //=> 'decl'
* ```
*/
type: string
/**
* The nodes parent node.
*
* ```js
* root.nodes[0].parent === root
* ```
*/
parent: Container | undefined
/**
* The input source of the node.
*
* The property is used in source map generation.
*
* If you create a node manually (e.g., with `postcss.decl()`),
* that node will not have a `source` property and will be absent
* from the source map. For this reason, the plugin developer should
* consider cloning nodes to create new ones (in which case the new nodes
* source will reference the original, cloned node) or setting
* the `source` property manually.
*
* ```js
* decl.source.input.from //=> '/home/ai/a.sass'
* decl.source.start //=> { line: 10, column: 2 }
* decl.source.end //=> { line: 10, column: 12 }
* ```
*
* ```js
* // Bad
* const prefixed = postcss.decl({
* prop: '-moz-' + decl.prop,
* value: decl.value
* })
*
* // Good
* const prefixed = decl.clone({ prop: '-moz-' + decl.prop })
* ```
*
* ```js
* if (atrule.name === 'add-link') {
* const rule = postcss.rule({ selector: 'a', source: atrule.source })
* atrule.parent.insertBefore(atrule, rule)
* }
* ```
*/
source?: Source
/**
* Information to generate byte-to-byte equal node string as it was
* in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
* * `left`: the space symbols between `/*` and the comments text.
* * `right`: the space symbols between the comments text
* and <code>*&#47;</code>.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans selectors, declaration values and at-rule parameters
* from comments and extra spaces, but it stores origin content in raws
* properties. As such, if you dont change a declarations value,
* PostCSS will use the raw value with comments.
*
* ```js
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
* ```
*/
raws: any
/**
* @param defaults Value for node properties.
*/
constructor(defaults?: object)
/**
* Returns a `CssSyntaxError` instance containing the original position
* of the node in the source, showing line and column numbers and also
* a small excerpt to facilitate debugging.
*
* If present, an input source map will be used to get the original position
* of the source, even from a previous compilation step
* (e.g., from Sass compilation).
*
* This method produces very useful error messages.
*
* ```js
* if (!variables[name]) {
* throw decl.error(`Unknown variable ${name}`, { word: name })
* // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
* // color: $black
* // a
* // ^
* // background: white
* }
* ```
*
* @param message Error description.
* @param opts Options.
*
* @return Error object to throw it.
*/
error(message: string, options?: NodeErrorOptions): CssSyntaxError
/**
* This method is provided as a convenience wrapper for `Result#warn`.
*
* ```js
* Declaration: {
* bad: (decl, { result }) => {
* decl.warn(result, 'Deprecated property bad')
* }
* }
* ```
*
* @param result The `Result` instance that will receive the warning.
* @param text Warning message.
* @param opts Warning Options.
*
* @return Created warning object.
*/
warn(result: Result, text: string, opts?: WarningOptions): void
/**
* Removes the node from its parent and cleans the parent properties
* from the node and its children.
*
* ```js
* if (decl.prop.match(/^-webkit-/)) {
* decl.remove()
* }
* ```
*
* @return Node to make calls chain.
*/
remove(): this
/**
* Returns a CSS string representing the node.
*
* ```js
* new Rule({ selector: 'a' }).toString() //=> "a {}"
* ```
*
* @param stringifier A syntax to use in string generation.
* @return CSS string of this node.
*/
toString(stringifier?: Stringifier | Syntax): string
/**
* Returns an exact clone of the node.
*
* The resulting cloned node and its (cloned) children will retain
* code style properties.
*
* ```js
* decl.raws.before //=> "\n "
* const cloned = decl.clone({ prop: '-moz-' + decl.prop })
* cloned.raws.before //=> "\n "
* cloned.toString() //=> -moz-transform: scale(0)
* ```
*
* @param overrides New properties to override in the clone.
* @return Clone of the node.
*/
clone(overrides?: object): this
/**
* Shortcut to clone the node and insert the resulting cloned node
* before the current node.
*
* ```js
* decl.cloneBefore({ prop: '-moz-' + decl.prop })
* ```
*
* @param overrides Mew properties to override in the clone.
*
* @return New node
*/
cloneBefore(overrides?: object): this
/**
* Shortcut to clone the node and insert the resulting cloned node
* after the current node.
*
* @param overrides New properties to override in the clone.
* @return New node.
*/
cloneAfter(overrides?: object): this
/**
* Inserts node(s) before the current node and removes the current node.
*
* ```js
* AtRule: {
* mixin: atrule => {
* atrule.replaceWith(mixinRules[atrule.params])
* }
* }
* ```
*
* @param nodes Mode(s) to replace current one.
* @return Current node to methods chain.
*/
replaceWith(
...nodes: (ChildNode | ChildProps | ChildNode[] | ChildProps[])[]
): this
/**
* Returns the next child of the nodes parent.
* Returns `undefined` if the current node is the last child.
*
* ```js
* if (comment.text === 'delete next') {
* const next = comment.next()
* if (next) {
* next.remove()
* }
* }
* ```
*
* @return Next node.
*/
next(): ChildNode | undefined
/**
* Returns the previous child of the nodes parent.
* Returns `undefined` if the current node is the first child.
*
* ```js
* const annotation = decl.prev()
* if (annotation.type === 'comment') {
* readAnnotation(annotation.text)
* }
* ```
*
* @return Previous node.
*/
prev(): ChildNode | undefined
/**
* Insert new node before current node to current nodes parent.
*
* Just alias for `node.parent.insertBefore(node, add)`.
*
* ```js
* decl.before('content: ""')
* ```
*
* @param newNode New node.
* @return This node for methods chain.
*/
before(newNode: Node | ChildProps | string | Node[]): this
/**
* Insert new node after current node to current nodes parent.
*
* Just alias for `node.parent.insertAfter(node, add)`.
*
* ```js
* decl.after('color: black')
* ```
*
* @param newNode New node.
* @return This node for methods chain.
*/
after(newNode: Node | ChildProps | string | Node[]): this
/**
* Finds the Root instance of the nodes tree.
*
* ```js
* root.nodes[0].nodes[0].root() === root
* ```
*
* @return Root parent.
*/
root(): Root
/**
* Returns a `Node#raws` value. If the node is missing
* the code style property (because the node was manually built or cloned),
* PostCSS will try to autodetect the code style property by looking
* at other nodes in the tree.
*
* ```js
* const root = postcss.parse('a { background: white }')
* root.nodes[0].append({ prop: 'color', value: 'black' })
* root.nodes[0].nodes[1].raws.before //=> undefined
* root.nodes[0].nodes[1].raw('before') //=> ' '
* ```
*
* @param prop Name of code style property.
* @param defaultType Name of default value, it can be missed
* if the value is the same as prop.
* @return {string} Code style value.
*/
raw(prop: string, defaultType?: string): string
/**
* Clear the code style properties for the node and its children.
*
* ```js
* node.raws.before //=> ' '
* node.cleanRaws()
* node.raws.before //=> undefined
* ```
*
* @param keepBetween Keep the `raws.between` symbols.
*/
cleanRaws(keepBetween?: boolean): void
/**
* Fix circular links on `JSON.stringify()`.
*
* @return Cleaned object.
*/
toJSON(): object
/**
* Convert string index to line/column.
*
* @param index The symbol number in the nodes string.
* @return Symbol position in file.
*/
positionInside(index: number): Position
}

310
assets_old/node_modules/postcss/lib/node.js generated vendored Normal file
View file

@ -0,0 +1,310 @@
'use strict'
let CssSyntaxError = require('./css-syntax-error')
let Stringifier = require('./stringifier')
let { isClean } = require('./symbols')
let stringify = require('./stringify')
function cloneNode(obj, parent) {
let cloned = new obj.constructor()
for (let i in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, i)) {
// istanbul ignore next
continue
}
if (i === 'proxyCache') continue
let value = obj[i]
let type = typeof value
if (i === 'parent' && type === 'object') {
if (parent) cloned[i] = parent
} else if (i === 'source') {
cloned[i] = value
} else if (Array.isArray(value)) {
cloned[i] = value.map(j => cloneNode(j, cloned))
} else {
if (type === 'object' && value !== null) value = cloneNode(value)
cloned[i] = value
}
}
return cloned
}
class Node {
constructor(defaults = {}) {
this.raws = {}
this[isClean] = false
for (let name in defaults) {
if (name === 'nodes') {
this.nodes = []
for (let node of defaults[name]) {
if (typeof node.clone === 'function') {
this.append(node.clone())
} else {
this.append(node)
}
}
} else {
this[name] = defaults[name]
}
}
}
error(message, opts = {}) {
if (this.source) {
let pos = this.positionBy(opts)
return this.source.input.error(message, pos.line, pos.column, opts)
}
return new CssSyntaxError(message)
}
warn(result, text, opts) {
let data = { node: this }
for (let i in opts) data[i] = opts[i]
return result.warn(text, data)
}
remove() {
if (this.parent) {
this.parent.removeChild(this)
}
this.parent = undefined
return this
}
toString(stringifier = stringify) {
if (stringifier.stringify) stringifier = stringifier.stringify
let result = ''
stringifier(this, i => {
result += i
})
return result
}
clone(overrides = {}) {
let cloned = cloneNode(this)
for (let name in overrides) {
cloned[name] = overrides[name]
}
return cloned
}
cloneBefore(overrides = {}) {
let cloned = this.clone(overrides)
this.parent.insertBefore(this, cloned)
return cloned
}
cloneAfter(overrides = {}) {
let cloned = this.clone(overrides)
this.parent.insertAfter(this, cloned)
return cloned
}
replaceWith(...nodes) {
if (this.parent) {
let bookmark = this
let foundSelf = false
for (let node of nodes) {
if (node === this) {
foundSelf = true
} else if (foundSelf) {
this.parent.insertAfter(bookmark, node)
bookmark = node
} else {
this.parent.insertBefore(bookmark, node)
}
}
if (!foundSelf) {
this.remove()
}
}
return this
}
next() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index + 1]
}
prev() {
if (!this.parent) return undefined
let index = this.parent.index(this)
return this.parent.nodes[index - 1]
}
before(add) {
this.parent.insertBefore(this, add)
return this
}
after(add) {
this.parent.insertAfter(this, add)
return this
}
root() {
let result = this
while (result.parent) result = result.parent
return result
}
raw(prop, defaultType) {
let str = new Stringifier()
return str.raw(this, prop, defaultType)
}
cleanRaws(keepBetween) {
delete this.raws.before
delete this.raws.after
if (!keepBetween) delete this.raws.between
}
toJSON(_, inputs) {
let fixed = {}
let emitInputs = inputs == null
inputs = inputs || new Map()
let inputsNextIndex = 0
for (let name in this) {
if (!Object.prototype.hasOwnProperty.call(this, name)) {
// istanbul ignore next
continue
}
if (name === 'parent' || name === 'proxyCache') continue
let value = this[name]
if (Array.isArray(value)) {
fixed[name] = value.map(i => {
if (typeof i === 'object' && i.toJSON) {
return i.toJSON(null, inputs)
} else {
return i
}
})
} else if (typeof value === 'object' && value.toJSON) {
fixed[name] = value.toJSON(null, inputs)
} else if (name === 'source') {
let inputId = inputs.get(value.input)
if (inputId == null) {
inputId = inputsNextIndex
inputs.set(value.input, inputsNextIndex)
inputsNextIndex++
}
fixed[name] = {
inputId,
start: value.start,
end: value.end
}
} else {
fixed[name] = value
}
}
if (emitInputs) {
fixed.inputs = [...inputs.keys()].map(input => input.toJSON())
}
return fixed
}
positionInside(index) {
let string = this.toString()
let column = this.source.start.column
let line = this.source.start.line
for (let i = 0; i < index; i++) {
if (string[i] === '\n') {
column = 1
line += 1
} else {
column += 1
}
}
return { line, column }
}
positionBy(opts) {
let pos = this.source.start
if (opts.index) {
pos = this.positionInside(opts.index)
} else if (opts.word) {
let index = this.toString().indexOf(opts.word)
if (index !== -1) pos = this.positionInside(index)
}
return pos
}
getProxyProcessor() {
return {
set(node, prop, value) {
if (node[prop] === value) return true
node[prop] = value
if (
prop === 'prop' ||
prop === 'value' ||
prop === 'name' ||
prop === 'params' ||
prop === 'important' ||
prop === 'text'
) {
node.markDirty()
}
return true
},
get(node, prop) {
if (prop === 'proxyOf') {
return node
} else if (prop === 'root') {
return () => node.root().toProxy()
} else {
return node[prop]
}
}
}
}
toProxy() {
if (!this.proxyCache) {
this.proxyCache = new Proxy(this, this.getProxyProcessor())
}
return this.proxyCache
}
addToError(error) {
error.postcssNode = this
if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
let s = this.source
error.stack = error.stack.replace(
/\n\s{4}at /,
`$&${s.input.from}:${s.start.line}:${s.start.column}$&`
)
}
return error
}
markDirty() {
if (this[isClean]) {
this[isClean] = false
let next = this
while ((next = next.parent)) {
next[isClean] = false
}
}
}
get proxyOf() {
return this
}
}
module.exports = Node
Node.default = Node

5
assets_old/node_modules/postcss/lib/parse.d.ts generated vendored Normal file
View file

@ -0,0 +1,5 @@
import { Parser } from './postcss.js'
declare const parse: Parser
export default parse

42
assets_old/node_modules/postcss/lib/parse.js generated vendored Normal file
View file

@ -0,0 +1,42 @@
'use strict'
let Container = require('./container')
let Parser = require('./parser')
let Input = require('./input')
function parse(css, opts) {
let input = new Input(css, opts)
let parser = new Parser(input)
try {
parser.parse()
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
if (e.name === 'CssSyntaxError' && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e.message +=
'\nYou tried to parse SCSS with ' +
'the standard CSS parser; ' +
'try again with the postcss-scss parser'
} else if (/\.sass/i.test(opts.from)) {
e.message +=
'\nYou tried to parse Sass with ' +
'the standard CSS parser; ' +
'try again with the postcss-sass parser'
} else if (/\.less$/i.test(opts.from)) {
e.message +=
'\nYou tried to parse Less with ' +
'the standard CSS parser; ' +
'try again with the postcss-less parser'
}
}
}
throw e
}
return parser.root
}
module.exports = parse
parse.default = parse
Container.registerParse(parse)

559
assets_old/node_modules/postcss/lib/parser.js generated vendored Normal file
View file

@ -0,0 +1,559 @@
'use strict'
let Declaration = require('./declaration')
let tokenizer = require('./tokenize')
let Comment = require('./comment')
let AtRule = require('./at-rule')
let Root = require('./root')
let Rule = require('./rule')
class Parser {
constructor(input) {
this.input = input
this.root = new Root()
this.current = this.root
this.spaces = ''
this.semicolon = false
this.customProperty = false
this.createTokenizer()
this.root.source = { input, start: { offset: 0, line: 1, column: 1 } }
}
createTokenizer() {
this.tokenizer = tokenizer(this.input)
}
parse() {
let token
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken()
switch (token[0]) {
case 'space':
this.spaces += token[1]
break
case ';':
this.freeSemicolon(token)
break
case '}':
this.end(token)
break
case 'comment':
this.comment(token)
break
case 'at-word':
this.atrule(token)
break
case '{':
this.emptyRule(token)
break
default:
this.other(token)
break
}
}
this.endFile()
}
comment(token) {
let node = new Comment()
this.init(node, token[2])
node.source.end = this.getPosition(token[3] || token[2])
let text = token[1].slice(2, -2)
if (/^\s*$/.test(text)) {
node.text = ''
node.raws.left = text
node.raws.right = ''
} else {
let match = text.match(/^(\s*)([^]*\S)(\s*)$/)
node.text = match[2]
node.raws.left = match[1]
node.raws.right = match[3]
}
}
emptyRule(token) {
let node = new Rule()
this.init(node, token[2])
node.selector = ''
node.raws.between = ''
this.current = node
}
other(start) {
let end = false
let type = null
let colon = false
let bracket = null
let brackets = []
let customProperty = start[1].startsWith('--')
let tokens = []
let token = start
while (token) {
type = token[0]
tokens.push(token)
if (type === '(' || type === '[') {
if (!bracket) bracket = token
brackets.push(type === '(' ? ')' : ']')
} else if (customProperty && colon && type === '{') {
if (!bracket) bracket = token
brackets.push('}')
} else if (brackets.length === 0) {
if (type === ';') {
if (colon) {
this.decl(tokens, customProperty)
return
} else {
break
}
} else if (type === '{') {
this.rule(tokens)
return
} else if (type === '}') {
this.tokenizer.back(tokens.pop())
end = true
break
} else if (type === ':') {
colon = true
}
} else if (type === brackets[brackets.length - 1]) {
brackets.pop()
if (brackets.length === 0) bracket = null
}
token = this.tokenizer.nextToken()
}
if (this.tokenizer.endOfFile()) end = true
if (brackets.length > 0) this.unclosedBracket(bracket)
if (end && colon) {
while (tokens.length) {
token = tokens[tokens.length - 1][0]
if (token !== 'space' && token !== 'comment') break
this.tokenizer.back(tokens.pop())
}
this.decl(tokens, customProperty)
} else {
this.unknownWord(tokens)
}
}
rule(tokens) {
tokens.pop()
let node = new Rule()
this.init(node, tokens[0][2])
node.raws.between = this.spacesAndCommentsFromEnd(tokens)
this.raw(node, 'selector', tokens)
this.current = node
}
decl(tokens, customProperty) {
let node = new Declaration()
this.init(node, tokens[0][2])
let last = tokens[tokens.length - 1]
if (last[0] === ';') {
this.semicolon = true
tokens.pop()
}
node.source.end = this.getPosition(last[3] || last[2])
while (tokens[0][0] !== 'word') {
if (tokens.length === 1) this.unknownWord(tokens)
node.raws.before += tokens.shift()[1]
}
node.source.start = this.getPosition(tokens[0][2])
node.prop = ''
while (tokens.length) {
let type = tokens[0][0]
if (type === ':' || type === 'space' || type === 'comment') {
break
}
node.prop += tokens.shift()[1]
}
node.raws.between = ''
let token
while (tokens.length) {
token = tokens.shift()
if (token[0] === ':') {
node.raws.between += token[1]
break
} else {
if (token[0] === 'word' && /\w/.test(token[1])) {
this.unknownWord([token])
}
node.raws.between += token[1]
}
}
if (node.prop[0] === '_' || node.prop[0] === '*') {
node.raws.before += node.prop[0]
node.prop = node.prop.slice(1)
}
let firstSpaces = this.spacesAndCommentsFromStart(tokens)
this.precheckMissedSemicolon(tokens)
for (let i = tokens.length - 1; i >= 0; i--) {
token = tokens[i]
if (token[1].toLowerCase() === '!important') {
node.important = true
let string = this.stringFrom(tokens, i)
string = this.spacesFromEnd(tokens) + string
if (string !== ' !important') node.raws.important = string
break
} else if (token[1].toLowerCase() === 'important') {
let cache = tokens.slice(0)
let str = ''
for (let j = i; j > 0; j--) {
let type = cache[j][0]
if (str.trim().indexOf('!') === 0 && type !== 'space') {
break
}
str = cache.pop()[1] + str
}
if (str.trim().indexOf('!') === 0) {
node.important = true
node.raws.important = str
tokens = cache
}
}
if (token[0] !== 'space' && token[0] !== 'comment') {
break
}
}
let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment')
this.raw(node, 'value', tokens)
if (hasWord) {
node.raws.between += firstSpaces
} else {
node.value = firstSpaces + node.value
}
if (node.value.includes(':') && !customProperty) {
this.checkMissedSemicolon(tokens)
}
}
atrule(token) {
let node = new AtRule()
node.name = token[1].slice(1)
if (node.name === '') {
this.unnamedAtrule(node, token)
}
this.init(node, token[2])
let type
let prev
let shift
let last = false
let open = false
let params = []
let brackets = []
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken()
type = token[0]
if (type === '(' || type === '[') {
brackets.push(type === '(' ? ')' : ']')
} else if (type === '{' && brackets.length > 0) {
brackets.push('}')
} else if (type === brackets[brackets.length - 1]) {
brackets.pop()
}
if (brackets.length === 0) {
if (type === ';') {
node.source.end = this.getPosition(token[2])
this.semicolon = true
break
} else if (type === '{') {
open = true
break
} else if (type === '}') {
if (params.length > 0) {
shift = params.length - 1
prev = params[shift]
while (prev && prev[0] === 'space') {
prev = params[--shift]
}
if (prev) {
node.source.end = this.getPosition(prev[3] || prev[2])
}
}
this.end(token)
break
} else {
params.push(token)
}
} else {
params.push(token)
}
if (this.tokenizer.endOfFile()) {
last = true
break
}
}
node.raws.between = this.spacesAndCommentsFromEnd(params)
if (params.length) {
node.raws.afterName = this.spacesAndCommentsFromStart(params)
this.raw(node, 'params', params)
if (last) {
token = params[params.length - 1]
node.source.end = this.getPosition(token[3] || token[2])
this.spaces = node.raws.between
node.raws.between = ''
}
} else {
node.raws.afterName = ''
node.params = ''
}
if (open) {
node.nodes = []
this.current = node
}
}
end(token) {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon
}
this.semicolon = false
this.current.raws.after = (this.current.raws.after || '') + this.spaces
this.spaces = ''
if (this.current.parent) {
this.current.source.end = this.getPosition(token[2])
this.current = this.current.parent
} else {
this.unexpectedClose(token)
}
}
endFile() {
if (this.current.parent) this.unclosedBlock()
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces
}
freeSemicolon(token) {
this.spaces += token[1]
if (this.current.nodes) {
let prev = this.current.nodes[this.current.nodes.length - 1]
if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
prev.raws.ownSemicolon = this.spaces
this.spaces = ''
}
}
}
// Helpers
getPosition(offset) {
let pos = this.input.fromOffset(offset)
return {
offset,
line: pos.line,
column: pos.col
}
}
init(node, offset) {
this.current.push(node)
node.source = {
start: this.getPosition(offset),
input: this.input
}
node.raws.before = this.spaces
this.spaces = ''
if (node.type !== 'comment') this.semicolon = false
}
raw(node, prop, tokens) {
let token, type
let length = tokens.length
let value = ''
let clean = true
let next, prev
let pattern = /^([#.|])?(\w)+/i
for (let i = 0; i < length; i += 1) {
token = tokens[i]
type = token[0]
if (type === 'comment' && node.type === 'rule') {
prev = tokens[i - 1]
next = tokens[i + 1]
if (
prev[0] !== 'space' &&
next[0] !== 'space' &&
pattern.test(prev[1]) &&
pattern.test(next[1])
) {
value += token[1]
} else {
clean = false
}
continue
}
if (type === 'comment' || (type === 'space' && i === length - 1)) {
clean = false
} else {
value += token[1]
}
}
if (!clean) {
let raw = tokens.reduce((all, i) => all + i[1], '')
node.raws[prop] = { value, raw }
}
node[prop] = value
}
spacesAndCommentsFromEnd(tokens) {
let lastTokenType
let spaces = ''
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0]
if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
spaces = tokens.pop()[1] + spaces
}
return spaces
}
spacesAndCommentsFromStart(tokens) {
let next
let spaces = ''
while (tokens.length) {
next = tokens[0][0]
if (next !== 'space' && next !== 'comment') break
spaces += tokens.shift()[1]
}
return spaces
}
spacesFromEnd(tokens) {
let lastTokenType
let spaces = ''
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0]
if (lastTokenType !== 'space') break
spaces = tokens.pop()[1] + spaces
}
return spaces
}
stringFrom(tokens, from) {
let result = ''
for (let i = from; i < tokens.length; i++) {
result += tokens[i][1]
}
tokens.splice(from, tokens.length - from)
return result
}
colon(tokens) {
let brackets = 0
let token, type, prev
for (let [i, element] of tokens.entries()) {
token = element
type = token[0]
if (type === '(') {
brackets += 1
}
if (type === ')') {
brackets -= 1
}
if (brackets === 0 && type === ':') {
if (!prev) {
this.doubleColon(token)
} else if (prev[0] === 'word' && prev[1] === 'progid') {
continue
} else {
return i
}
}
prev = token
}
return false
}
// Errors
unclosedBracket(bracket) {
throw this.input.error('Unclosed bracket', bracket[2])
}
unknownWord(tokens) {
throw this.input.error('Unknown word', tokens[0][2])
}
unexpectedClose(token) {
throw this.input.error('Unexpected }', token[2])
}
unclosedBlock() {
let pos = this.current.source.start
throw this.input.error('Unclosed block', pos.line, pos.column)
}
doubleColon(token) {
throw this.input.error('Double colon', token[2])
}
unnamedAtrule(node, token) {
throw this.input.error('At-rule without name', token[2])
}
precheckMissedSemicolon(/* tokens */) {
// Hook for Safe Parser
}
checkMissedSemicolon(tokens) {
let colon = this.colon(tokens)
if (colon === false) return
let founded = 0
let token
for (let j = colon - 1; j >= 0; j--) {
token = tokens[j]
if (token[0] !== 'space') {
founded += 1
if (founded === 2) break
}
}
throw this.input.error('Missed semicolon', token[2])
}
}
module.exports = Parser

443
assets_old/node_modules/postcss/lib/postcss.d.ts generated vendored Normal file
View file

@ -0,0 +1,443 @@
import { SourceMapGenerator, RawSourceMap } from 'source-map'
import Node, {
Position,
Source,
ChildNode,
NodeErrorOptions,
NodeProps,
ChildProps,
AnyNode
} from './node.js'
import Declaration, { DeclarationProps } from './declaration.js'
import Root, { RootProps } from './root.js'
import Comment, { CommentProps } from './comment.js'
import AtRule, { AtRuleProps } from './at-rule.js'
import Result, { Message } from './result.js'
import LazyResult from './lazy-result.js'
import Rule, { RuleProps } from './rule.js'
import Container, { ContainerProps } from './container.js'
import Warning, { WarningOptions } from './warning.js'
import Input, { FilePosition } from './input.js'
import CssSyntaxError from './css-syntax-error.js'
import list, { List } from './list.js'
import Processor from './processor.js'
export {
WarningOptions,
FilePosition,
Position,
Source,
ChildNode,
AnyNode,
Message,
NodeErrorOptions,
NodeProps,
DeclarationProps,
ContainerProps,
CommentProps,
RuleProps,
ChildProps,
AtRuleProps,
RootProps,
Warning,
CssSyntaxError,
Node,
Container,
list,
Declaration,
Comment,
AtRule,
Rule,
Root,
Result,
LazyResult,
Input
}
export type SourceMap = SourceMapGenerator & {
toJSON(): RawSourceMap
}
export type Helpers = { result: Result; postcss: Postcss } & Postcss
type RootProcessor = (root: Root, helper: Helpers) => Promise<void> | void
type DeclarationProcessor = (
decl: Declaration,
helper: Helpers
) => Promise<void> | void
type RuleProcessor = (rule: Rule, helper: Helpers) => Promise<void> | void
type AtRuleProcessor = (atRule: AtRule, helper: Helpers) => Promise<void> | void
type CommentProcessor = (
comment: Comment,
helper: Helpers
) => Promise<void> | void
interface Processors {
/**
* Will be called on `Root` node once.
*/
Once?: RootProcessor
/**
* Will be called on `Root` node once, when all children will be processed.
*/
OnceExit?: RootProcessor
/**
* Will be called on `Root` node.
*
* Will be called again on children changes.
*/
Root?: RootProcessor
/**
* Will be called on `Root` node, when all children will be processed.
*
* Will be called again on children changes.
*/
RootExit?: RootProcessor
/**
* Will be called on all `Declaration` nodes after listeners
* for `Declaration` event.
*
* Will be called again on node or children changes.
*/
Declaration?: DeclarationProcessor | { [prop: string]: DeclarationProcessor }
/**
* Will be called on all `Declaration` nodes.
*
* Will be called again on node or children changes.
*/
DeclarationExit?:
| DeclarationProcessor
| { [prop: string]: DeclarationProcessor }
/**
* Will be called on all `Rule` nodes.
*
* Will be called again on node or children changes.
*/
Rule?: RuleProcessor
/**
* Will be called on all `Rule` nodes, when all children will be processed.
*
* Will be called again on node or children changes.
*/
RuleExit?: RuleProcessor
/**
* Will be called on all`AtRule` nodes.
*
* Will be called again on node or children changes.
*/
AtRule?: AtRuleProcessor | { [name: string]: AtRuleProcessor }
/**
* Will be called on all `AtRule` nodes, when all children will be processed.
*
* Will be called again on node or children changes.
*/
AtRuleExit?: AtRuleProcessor | { [name: string]: AtRuleProcessor }
/**
* Will be called on all `Comment` nodes.
*
* Will be called again on node or children changes.
*/
Comment?: CommentProcessor
/**
* Will be called on all `Comment` nodes after listeners
* for `Comment` event.
*
* Will be called again on node or children changes.
*/
CommentExit?: CommentProcessor
/**
* Will be called when all other listeners processed the document.
*
* This listener will not be called again.
*/
Exit?: RootProcessor
}
export interface Plugin extends Processors {
postcssPlugin: string
prepare?: (result: Result) => Processors
}
export interface PluginCreator<PluginOptions> {
(opts?: PluginOptions): Plugin | Processor
postcss: true
}
export interface Transformer extends TransformCallback {
postcssPlugin: string
postcssVersion: string
}
export interface TransformCallback {
(root: Root, result: Result): Promise<void> | void
}
export interface OldPlugin<T> extends Transformer {
(opts?: T): Transformer
postcss: Transformer
}
export type AcceptedPlugin =
| Plugin
| PluginCreator<any>
| OldPlugin<any>
| TransformCallback
| {
postcss: TransformCallback | Processor
}
| Processor
export interface Parser {
(
css: string | { toString(): string },
opts?: Pick<ProcessOptions, 'map' | 'from'>
): Root
}
export interface Builder {
(part: string, node?: AnyNode, type?: 'start' | 'end'): void
}
export interface Stringifier {
(node: AnyNode, builder: Builder): void
}
export interface JSONHydrator {
(data: object[]): Node[]
(data: object): Node
}
export interface Syntax {
/**
* Function to generate AST by string.
*/
parse?: Parser
/**
* Class to generate string by AST.
*/
stringify?: Stringifier
}
export interface SourceMapOptions {
/**
* Indicates that the source map should be embedded in the output CSS
* as a Base64-encoded comment. By default, it is `true`.
* But if all previous maps are external, not inline, PostCSS will not embed
* the map even if you do not set this option.
*
* If you have an inline source map, the result.map property will be empty,
* as the source map will be contained within the text of `result.css`.
*/
inline?: boolean
/**
* Source map content from a previous processing step (e.g., Sass).
*
* PostCSS will try to read the previous source map
* automatically (based on comments within the source CSS), but you can use
* this option to identify it manually.
*
* If desired, you can omit the previous map with prev: `false`.
*/
prev?: string | boolean | object | ((file: string) => string)
/**
* Indicates that PostCSS should set the origin content (e.g., Sass source)
* of the source map. By default, it is true. But if all previous maps do not
* contain sources content, PostCSS will also leave it out even if you
* do not set this option.
*/
sourcesContent?: boolean
/**
* Indicates that PostCSS should add annotation comments to the CSS.
* By default, PostCSS will always add a comment with a path
* to the source map. PostCSS will not add annotations to CSS files
* that do not contain any comments.
*
* By default, PostCSS presumes that you want to save the source map as
* `opts.to + '.map'` and will use this path in the annotation comment.
* A different path can be set by providing a string value for annotation.
*
* If you have set `inline: true`, annotation cannot be disabled.
*/
annotation?: string | boolean | ((file: string, root: Root) => string)
/**
* Override `from` in maps sources.
*/
from?: string
/**
* Use absolute path in generated source map.
*/
absolute?: boolean
}
export interface ProcessOptions {
/**
* The path of the CSS source file. You should always set `from`,
* because it is used in source map generation and syntax error messages.
*/
from?: string
/**
* The path where you'll put the output CSS file. You should always set `to`
* to generate correct source maps.
*/
to?: string
/**
* Function to generate AST by string.
*/
parser?: Syntax | Parser
/**
* Class to generate string by AST.
*/
stringifier?: Syntax | Stringifier
/**
* Object with parse and stringify.
*/
syntax?: Syntax
/**
* Source map options
*/
map?: SourceMapOptions | boolean
}
export interface Postcss {
/**
* Create a new `Processor` instance that will apply `plugins`
* as CSS processors.
*
* ```js
* let postcss = require('postcss')
*
* postcss(plugins).process(css, { from, to }).then(result => {
* console.log(result.css)
* })
* ```
*
* @param plugins PostCSS plugins.
* @return Processor to process multiple CSS.
*/
(plugins?: AcceptedPlugin[]): Processor
(...plugins: AcceptedPlugin[]): Processor
/**
* Default function to convert a node tree into a CSS string.
*/
stringify: Stringifier
/**
* Parses source css and returns a new `Root` node,
* which contains the source CSS nodes.
*
* ```js
* // Simple CSS concatenation with source map support
* const root1 = postcss.parse(css1, { from: file1 })
* const root2 = postcss.parse(css2, { from: file2 })
* root1.append(root2).toResult().css
* ```
*/
parse: Parser
/**
* Rehydrate a JSON AST (from `Node#toJSON`) back into the AST classes.
*
* ```js
* const json = root.toJSON()
* // save to file, send by network, etc
* const root2 = postcss.fromJSON(json)
* ```
*/
fromJSON: JSONHydrator
/**
* Contains the `list` module.
*/
list: List
/**
* Creates a new `Comment` node.
*
* @param defaults Properties for the new node.
* @return New comment node
*/
comment(defaults?: CommentProps): Comment
/**
* Creates a new `AtRule` node.
*
* @param defaults Properties for the new node.
* @return New at-rule node.
*/
atRule(defaults?: AtRuleProps): AtRule
/**
* Creates a new `Declaration` node.
*
* @param defaults Properties for the new node.
* @return New declaration node.
*/
decl(defaults?: DeclarationProps): Declaration
/**
* Creates a new `Rule` node.
*
* @param default Properties for the new node.
* @return New rule node.
*/
rule(defaults?: RuleProps): Rule
/**
* Creates a new `Root` node.
*
* @param defaults Properties for the new node.
* @return New root node.
*/
root(defaults?: RootProps): Root
CssSyntaxError: typeof CssSyntaxError
Declaration: typeof Declaration
Container: typeof Container
Comment: typeof Comment
Warning: typeof Warning
AtRule: typeof AtRule
Result: typeof Result
Input: typeof Input
Rule: typeof Rule
Root: typeof Root
Node: typeof Node
}
export const stringify: Stringifier
export const parse: Parser
export const fromJSON: JSONHydrator
export const comment: Postcss['comment']
export const atRule: Postcss['atRule']
export const decl: Postcss['decl']
export const rule: Postcss['rule']
export const root: Postcss['root']
declare const postcss: Postcss
export default postcss

92
assets_old/node_modules/postcss/lib/postcss.js generated vendored Normal file
View file

@ -0,0 +1,92 @@
'use strict'
let CssSyntaxError = require('./css-syntax-error')
let Declaration = require('./declaration')
let LazyResult = require('./lazy-result')
let Container = require('./container')
let Processor = require('./processor')
let stringify = require('./stringify')
let fromJSON = require('./fromJSON')
let Warning = require('./warning')
let Comment = require('./comment')
let AtRule = require('./at-rule')
let Result = require('./result.js')
let Input = require('./input')
let parse = require('./parse')
let list = require('./list')
let Rule = require('./rule')
let Root = require('./root')
let Node = require('./node')
function postcss(...plugins) {
if (plugins.length === 1 && Array.isArray(plugins[0])) {
plugins = plugins[0]
}
return new Processor(plugins)
}
postcss.plugin = function plugin(name, initializer) {
if (console && console.warn) {
console.warn(
name +
': postcss.plugin was deprecated. Migration guide:\n' +
'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
)
if (process.env.LANG && process.env.LANG.startsWith('cn')) {
// istanbul ignore next
console.warn(
name +
': 里面 postcss.plugin 被弃用. 迁移指南:\n' +
'https://www.w3ctech.com/topic/2226'
)
}
}
function creator(...args) {
let transformer = initializer(...args)
transformer.postcssPlugin = name
transformer.postcssVersion = new Processor().version
return transformer
}
let cache
Object.defineProperty(creator, 'postcss', {
get() {
if (!cache) cache = creator()
return cache
}
})
creator.process = function (css, processOpts, pluginOpts) {
return postcss([creator(pluginOpts)]).process(css, processOpts)
}
return creator
}
postcss.stringify = stringify
postcss.parse = parse
postcss.fromJSON = fromJSON
postcss.list = list
postcss.comment = defaults => new Comment(defaults)
postcss.atRule = defaults => new AtRule(defaults)
postcss.decl = defaults => new Declaration(defaults)
postcss.rule = defaults => new Rule(defaults)
postcss.root = defaults => new Root(defaults)
postcss.CssSyntaxError = CssSyntaxError
postcss.Declaration = Declaration
postcss.Container = Container
postcss.Comment = Comment
postcss.Warning = Warning
postcss.AtRule = AtRule
postcss.Result = Result
postcss.Input = Input
postcss.Rule = Rule
postcss.Root = Root
postcss.Node = Node
LazyResult.registerPostcss(postcss)
module.exports = postcss
postcss.default = postcss

27
assets_old/node_modules/postcss/lib/postcss.mjs generated vendored Normal file
View file

@ -0,0 +1,27 @@
import postcss from './postcss.js'
export default postcss
export const stringify = postcss.stringify
export const fromJSON = postcss.fromJSON
export const plugin = postcss.plugin
export const parse = postcss.parse
export const list = postcss.list
export const comment = postcss.comment
export const atRule = postcss.atRule
export const rule = postcss.rule
export const decl = postcss.decl
export const root = postcss.root
export const CssSyntaxError = postcss.CssSyntaxError
export const Declaration = postcss.Declaration
export const Container = postcss.Container
export const Comment = postcss.Comment
export const Warning = postcss.Warning
export const AtRule = postcss.AtRule
export const Result = postcss.Result
export const Input = postcss.Input
export const Rule = postcss.Rule
export const Root = postcss.Root
export const Node = postcss.Node

72
assets_old/node_modules/postcss/lib/previous-map.d.ts generated vendored Normal file
View file

@ -0,0 +1,72 @@
import { SourceMapConsumer } from 'source-map'
import { ProcessOptions } from './postcss.js'
/**
* Source map information from input CSS.
* For example, source map after Sass compiler.
*
* This class will automatically find source map in input CSS or in file system
* near input file (according `from` option).
*
* ```js
* const root = parse(css, { from: 'a.sass.css' })
* root.input.map //=> PreviousMap
* ```
*/
export default class PreviousMap {
/**
* Was source map inlined by data-uri to input CSS.
*/
inline: boolean
/**
* `sourceMappingURL` content.
*/
annotation?: string
/**
* Source map file content.
*/
text?: string
/**
* The directory with source map file, if source map is in separated file.
*/
root?: string
/**
* The CSS source identifier. Contains `Input#file` if the user
* set the `from` option, or `Input#id` if they did not.
*/
file?: string
/**
* Path to source map file.
*/
mapFile?: string
/**
* @param css Input CSS source.
* @param opts Process options.
*/
constructor(css: string, opts?: ProcessOptions)
/**
* Create a instance of `SourceMapGenerator` class
* from the `source-map` library to work with source map information.
*
* It is lazy method, so it will create object only on first call
* and then it will use cache.
*
* @return Object with source map information.
*/
consumer(): SourceMapConsumer
/**
* Does source map contains `sourcesContent` with input source text.
*
* @return Is `sourcesContent` present.
*/
withContent(): boolean
}

143
assets_old/node_modules/postcss/lib/previous-map.js generated vendored Normal file
View file

@ -0,0 +1,143 @@
'use strict'
let { existsSync, readFileSync } = require('fs')
let { dirname, join } = require('path')
let mozilla = require('source-map')
function fromBase64(str) {
if (Buffer) {
return Buffer.from(str, 'base64').toString()
} else {
// istanbul ignore next
return window.atob(str)
}
}
class PreviousMap {
constructor(css, opts) {
if (opts.map === false) return
this.loadAnnotation(css)
this.inline = this.startWith(this.annotation, 'data:')
let prev = opts.map ? opts.map.prev : undefined
let text = this.loadMap(opts.from, prev)
if (!this.mapFile && opts.from) {
this.mapFile = opts.from
}
if (this.mapFile) this.root = dirname(this.mapFile)
if (text) this.text = text
}
consumer() {
if (!this.consumerCache) {
this.consumerCache = new mozilla.SourceMapConsumer(this.text)
}
return this.consumerCache
}
withContent() {
return !!(
this.consumer().sourcesContent &&
this.consumer().sourcesContent.length > 0
)
}
startWith(string, start) {
if (!string) return false
return string.substr(0, start.length) === start
}
getAnnotationURL(sourceMapString) {
return sourceMapString
.match(/\/\*\s*# sourceMappingURL=(.*)\s*\*\//)[1]
.trim()
}
loadAnnotation(css) {
let annotations = css.match(/\/\*\s*# sourceMappingURL=.*\s*\*\//gm)
if (annotations && annotations.length > 0) {
// Locate the last sourceMappingURL to avoid picking up
// sourceMappingURLs from comments, strings, etc.
let lastAnnotation = annotations[annotations.length - 1]
if (lastAnnotation) {
this.annotation = this.getAnnotationURL(lastAnnotation)
}
}
}
decodeInline(text) {
let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/
let baseUri = /^data:application\/json;base64,/
let charsetUri = /^data:application\/json;charset=utf-?8,/
let uri = /^data:application\/json,/
if (charsetUri.test(text) || uri.test(text)) {
return decodeURIComponent(text.substr(RegExp.lastMatch.length))
}
if (baseCharsetUri.test(text) || baseUri.test(text)) {
return fromBase64(text.substr(RegExp.lastMatch.length))
}
let encoding = text.match(/data:application\/json;([^,]+),/)[1]
throw new Error('Unsupported source map encoding ' + encoding)
}
loadFile(path) {
this.root = dirname(path)
if (existsSync(path)) {
this.mapFile = path
return readFileSync(path, 'utf-8').toString().trim()
}
}
loadMap(file, prev) {
if (prev === false) return false
if (prev) {
if (typeof prev === 'string') {
return prev
} else if (typeof prev === 'function') {
let prevPath = prev(file)
if (prevPath) {
let map = this.loadFile(prevPath)
if (!map) {
throw new Error(
'Unable to load previous source map: ' + prevPath.toString()
)
}
return map
}
} else if (prev instanceof mozilla.SourceMapConsumer) {
return mozilla.SourceMapGenerator.fromSourceMap(prev).toString()
} else if (prev instanceof mozilla.SourceMapGenerator) {
return prev.toString()
} else if (this.isMap(prev)) {
return JSON.stringify(prev)
} else {
throw new Error(
'Unsupported previous source map format: ' + prev.toString()
)
}
} else if (this.inline) {
return this.decodeInline(this.annotation)
} else if (this.annotation) {
let map = this.annotation
if (file) map = join(dirname(file), map)
return this.loadFile(map)
}
}
isMap(map) {
if (typeof map !== 'object') return false
return (
typeof map.mappings === 'string' ||
typeof map._mappings === 'string' ||
Array.isArray(map.sections)
)
}
}
module.exports = PreviousMap
PreviousMap.default = PreviousMap

101
assets_old/node_modules/postcss/lib/processor.d.ts generated vendored Normal file
View file

@ -0,0 +1,101 @@
import {
AcceptedPlugin,
Plugin,
ProcessOptions,
Transformer,
TransformCallback
} from './postcss.js'
import LazyResult from './lazy-result.js'
import Result from './result.js'
import Root from './root.js'
/**
* Contains plugins to process CSS. Create one `Processor` instance,
* initialize its plugins, and then use that instance on numerous CSS files.
*
* ```js
* const processor = postcss([autoprefixer, precss])
* processor.process(css1).then(result => console.log(result.css))
* processor.process(css2).then(result => console.log(result.css))
* ```
*/
export default class Processor {
/**
* Current PostCSS version.
*
* ```js
* if (result.processor.version.split('.')[0] !== '6') {
* throw new Error('This plugin works only with PostCSS 6')
* }
* ```
*/
version: string
/**
* Plugins added to this processor.
*
* ```js
* const processor = postcss([autoprefixer, precss])
* processor.plugins.length //=> 2
* ```
*/
plugins: (Plugin | Transformer | TransformCallback)[]
/**
* @param plugins PostCSS plugins
*/
constructor(plugins?: AcceptedPlugin[])
/**
* Adds a plugin to be used as a CSS processor.
*
* PostCSS plugin can be in 4 formats:
* * A plugin in `Plugin` format.
* * A plugin creator function with `pluginCreator.postcss = true`.
* PostCSS will call this function without argument to get plugin.
* * A function. PostCSS will pass the function a @{link Root}
* as the first argument and current `Result` instance
* as the second.
* * Another `Processor` instance. PostCSS will copy plugins
* from that instance into this one.
*
* Plugins can also be added by passing them as arguments when creating
* a `postcss` instance (see [`postcss(plugins)`]).
*
* Asynchronous plugins should return a `Promise` instance.
*
* ```js
* const processor = postcss()
* .use(autoprefixer)
* .use(precss)
* ```
*
* @param plugin PostCSS plugin or `Processor` with plugins.
* @return {Processes} Current processor to make methods chain.
*/
use(plugin: AcceptedPlugin): this
/**
* Parses source CSS and returns a `LazyResult` Promise proxy.
* Because some plugins can be asynchronous it doesnt make
* any transformations. Transformations will be applied
* in the `LazyResult` methods.
*
* ```js
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
* .then(result => {
* console.log(result.css)
* })
* ```
*
* @param css String with input CSS or any object with a `toString()` method,
* like a Buffer. Optionally, senda `Result` instance
* and the processor will take the `Root` from it.
* @param opts Options.
* @return Promise proxy.
*/
process(
css: string | { toString(): string } | Result | LazyResult | Root,
options?: ProcessOptions
): LazyResult
}

70
assets_old/node_modules/postcss/lib/processor.js generated vendored Normal file
View file

@ -0,0 +1,70 @@
'use strict'
let LazyResult = require('./lazy-result')
let Root = require('./root')
class Processor {
constructor(plugins = []) {
this.version = '8.2.9'
this.plugins = this.normalize(plugins)
}
use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]))
return this
}
process(css, opts = {}) {
if (
this.plugins.length === 0 &&
opts.parser === opts.stringifier &&
!opts.hideNothingWarning
) {
if (process.env.NODE_ENV !== 'production') {
if (typeof console !== 'undefined' && console.warn) {
console.warn(
'You did not set any plugins, parser, or stringifier. ' +
'Right now, PostCSS does nothing. Pick plugins for your case ' +
'on https://www.postcss.parts/ and use them in postcss.config.js.'
)
}
}
}
return new LazyResult(this, css, opts)
}
normalize(plugins) {
let normalized = []
for (let i of plugins) {
if (i.postcss === true) {
i = i()
} else if (i.postcss) {
i = i.postcss
}
if (typeof i === 'object' && Array.isArray(i.plugins)) {
normalized = normalized.concat(i.plugins)
} else if (typeof i === 'object' && i.postcssPlugin) {
normalized.push(i)
} else if (typeof i === 'function') {
normalized.push(i)
} else if (typeof i === 'object' && (i.parse || i.stringify)) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
'one of the syntax/parser/stringifier options as outlined ' +
'in your PostCSS runner documentation.'
)
}
} else {
throw new Error(i + ' is not a PostCSS plugin')
}
}
return normalized
}
}
module.exports = Processor
Processor.default = Processor
Root.registerProcessor(Processor)

195
assets_old/node_modules/postcss/lib/result.d.ts generated vendored Normal file
View file

@ -0,0 +1,195 @@
import {
ProcessOptions,
Plugin,
SourceMap,
TransformCallback,
Root,
Node,
Warning,
WarningOptions
} from './postcss.js'
import Processor from './processor.js'
export interface Message {
/**
* Message type.
*/
type: string
/**
* Source PostCSS plugin name.
*/
plugin?: string
[others: string]: any
}
export interface ResultOptions extends ProcessOptions {
/**
* The CSS node that was the source of the warning.
*/
node?: Node
/**
* Name of plugin that created this warning. `Result#warn` will fill it
* automatically with `Plugin#postcssPlugin` value.
*/
plugin?: string
}
/**
* Provides the result of the PostCSS transformations.
*
* A Result instance is returned by `LazyResult#then`
* or `Root#toResult` methods.
*
* ```js
* postcss([autoprefixer]).process(css).then(result => {
* console.log(result.css)
* })
* ```
*
* ```js
* const result2 = postcss.parse(css).toResult()
* ```
*/
export default class Result {
/**
* The Processor instance used for this transformation.
*
* ```js
* for (const plugin of result.processor.plugins) {
* if (plugin.postcssPlugin === 'postcss-bad') {
* throw 'postcss-good is incompatible with postcss-bad'
* }
* })
* ```
*/
processor: Processor
/**
* Contains messages from plugins (e.g., warnings or custom messages).
* Each message should have type and plugin properties.
*
* ```js
* AtRule: {
* import: (atRule, { result }) {
* const importedFile = parseImport(atRule)
* result.messages.push({
* type: 'dependency',
* plugin: 'postcss-import',
* file: importedFile,
* parent: result.opts.from
* })
* }
* }
* ```
*/
messages: Message[]
/**
* Root node after all transformations.
*
* ```js
* root.toResult().root === root
* ```
*/
root: Root
/**
* Options from the `Processor#process` or `Root#toResult` call
* that produced this Result instance.]
*
* ```js
* root.toResult(opts).opts === opts
* ```
*/
opts: ResultOptions
/**
* A CSS string representing of `Result#root`.
*
* ```js
* postcss.parse('a{}').toResult().css //=> "a{}"
* ```
*/
css: string
/**
* An instance of `SourceMapGenerator` class from the `source-map` library,
* representing changes to the `Result#root` instance.
*
* ```js
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
* ```
*
* ```js
* if (result.map) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString())
* }
* ```
*/
map: SourceMap
/**
* Last runned PostCSS plugin.
*/
lastPlugin: Plugin | TransformCallback
/**
* @param processor Processor used for this transformation.
* @param root Root node after all transformations.
* @param opts Options from the `Processor#process` or `Root#toResult`.
*/
constructor(processor: Processor, root: Root, opts: ResultOptions)
/**
* An alias for the `Result#css` property.
* Use it with syntaxes that generate non-CSS output.
*
* ```js
* result.css === result.content
* ```
*/
get content(): string
/**
* Returns for `Result#css` content.
*
* ```js
* result + '' === result.css
* ```
*
* @return String representing of `Result#root`.
*/
toString(): string
/**
* Creates an instance of `Warning` and adds it to `Result#messages`.
*
* ```js
* if (decl.important) {
* result.warn('Avoid !important', { node: decl, word: '!important' })
* }
* ```
*
* @param text Warning message.
* @param opts Warning options.
* @return Created warning.
*/
warn(message: string, options?: WarningOptions): Warning
/**
* Returns warnings from plugins. Filters `Warning` instances
* from `Result#messages`.
*
* ```js
* result.warnings().forEach(warn => {
* console.warn(warn.toString())
* })
* ```
*
* @return Warnings from plugins.
*/
warnings(): Warning[]
}

42
assets_old/node_modules/postcss/lib/result.js generated vendored Normal file
View file

@ -0,0 +1,42 @@
'use strict'
let Warning = require('./warning')
class Result {
constructor(processor, root, opts) {
this.processor = processor
this.messages = []
this.root = root
this.opts = opts
this.css = undefined
this.map = undefined
}
toString() {
return this.css
}
warn(text, opts = {}) {
if (!opts.plugin) {
if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
opts.plugin = this.lastPlugin.postcssPlugin
}
}
let warning = new Warning(text, opts)
this.messages.push(warning)
return warning
}
warnings() {
return this.messages.filter(i => i.type === 'warning')
}
get content() {
return this.css
}
}
module.exports = Result
Result.default = Result

51
assets_old/node_modules/postcss/lib/root.d.ts generated vendored Normal file
View file

@ -0,0 +1,51 @@
import Container, { ContainerProps } from './container.js'
import { ProcessOptions } from './postcss.js'
import Result from './result.js'
interface RootRaws {
/**
* The space symbols after the last child to the end of file.
*/
after?: string
/**
* Is the last child has an (optional) semicolon.
*/
semicolon?: boolean
}
export interface RootProps extends ContainerProps {
raws?: RootRaws
}
/**
* Represents a CSS file and contains all its parsed nodes.
*
* ```js
* const root = postcss.parse('a{color:black} b{z-index:2}')
* root.type //=> 'root'
* root.nodes.length //=> 2
* ```
*/
export default class Root extends Container {
type: 'root'
parent: undefined
raws: RootRaws
constructor(defaults?: RootProps)
/**
* Returns a `Result` instance representing the roots CSS.
*
* ```js
* const root1 = postcss.parse(css1, { from: 'a.css' })
* const root2 = postcss.parse(css2, { from: 'b.css' })
* root1.append(root2)
* const result = root1.toResult({ to: 'all.css', map: true })
* ```
*
* @param opts Options.
* @return Result with current roots CSS.
*/
toResult(options?: ProcessOptions): Result
}

59
assets_old/node_modules/postcss/lib/root.js generated vendored Normal file
View file

@ -0,0 +1,59 @@
'use strict'
let Container = require('./container')
let LazyResult, Processor
class Root extends Container {
constructor(defaults) {
super(defaults)
this.type = 'root'
if (!this.nodes) this.nodes = []
}
removeChild(child, ignore) {
let index = this.index(child)
if (!ignore && index === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[index].raws.before
}
return super.removeChild(child)
}
normalize(child, sample, type) {
let nodes = super.normalize(child)
if (sample) {
if (type === 'prepend') {
if (this.nodes.length > 1) {
sample.raws.before = this.nodes[1].raws.before
} else {
delete sample.raws.before
}
} else if (this.first !== sample) {
for (let node of nodes) {
node.raws.before = sample.raws.before
}
}
}
return nodes
}
toResult(opts = {}) {
let lazy = new LazyResult(new Processor(), this, opts)
return lazy.stringify()
}
}
Root.registerLazyResult = dependant => {
LazyResult = dependant
}
Root.registerProcessor = dependant => {
Processor = dependant
}
module.exports = Root
Root.default = Root

99
assets_old/node_modules/postcss/lib/rule.d.ts generated vendored Normal file
View file

@ -0,0 +1,99 @@
import Container, { ContainerProps } from './container.js'
interface RuleRaws {
/**
* The space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
*/
before?: string
/**
* The space symbols after the last child of the node to the end of the node.
*/
after?: string
/**
* The symbols between the selector and `{` for rules.
*/
between?: string
/**
* Contains `true` if the last child has an (optional) semicolon.
*/
semicolon?: boolean
/**
* Contains `true` if there is semicolon after rule.
*/
ownSemicolon?: string
/**
* The rules selector with comments.
*/
selector?: {
value: string
raw: string
}
}
export interface RuleProps extends ContainerProps {
selector?: string
selectors?: string[]
raws?: RuleRaws
}
/**
* Represents a CSS rule: a selector followed by a declaration block.
*
* ```js
* Once (root, { Rule }) {
* let a = new Rule({ selector: 'a' })
* a.append()
* root.append(a)
* }
* ```
*
* ```js
* const root = postcss.parse('a{}')
* const rule = root.first
* rule.type //=> 'rule'
* rule.toString() //=> 'a{}'
* ```
*/
export default class Rule extends Container {
type: 'rule'
raws: RuleRaws
/**
* The rules full selector represented as a string.
*
* ```js
* const root = postcss.parse('a, b { }')
* const rule = root.first
* rule.selector //=> 'a, b'
* ```
*/
selector: string
/**
* An array containing the rules individual selectors.
* Groups of selectors are split at commas.
*
* ```js
* const root = postcss.parse('a, b { }')
* const rule = root.first
*
* rule.selector //=> 'a, b'
* rule.selectors //=> ['a', 'b']
*
* rule.selectors = ['a', 'strong']
* rule.selector //=> 'a, strong'
* ```
*/
selectors: string[]
constructor(defaults?: RuleProps)
clone(overrides?: Partial<RuleProps>): this
cloneBefore(overrides?: Partial<RuleProps>): this
cloneAfter(overrides?: Partial<RuleProps>): this
}

27
assets_old/node_modules/postcss/lib/rule.js generated vendored Normal file
View file

@ -0,0 +1,27 @@
'use strict'
let Container = require('./container')
let list = require('./list')
class Rule extends Container {
constructor(defaults) {
super(defaults)
this.type = 'rule'
if (!this.nodes) this.nodes = []
}
get selectors() {
return list.comma(this.selector)
}
set selectors(values) {
let match = this.selector ? this.selector.match(/,\s*/) : null
let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen')
this.selector = values.join(sep)
}
}
module.exports = Rule
Rule.default = Rule
Container.registerRule(Rule)

342
assets_old/node_modules/postcss/lib/stringifier.js generated vendored Normal file
View file

@ -0,0 +1,342 @@
'use strict'
const DEFAULT_RAW = {
colon: ': ',
indent: ' ',
beforeDecl: '\n',
beforeRule: '\n',
beforeOpen: ' ',
beforeClose: '\n',
beforeComment: '\n',
after: '\n',
emptyBody: '',
commentLeft: ' ',
commentRight: ' ',
semicolon: false
}
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1)
}
class Stringifier {
constructor(builder) {
this.builder = builder
}
stringify(node, semicolon) {
/* istanbul ignore if */
if (!this[node.type]) {
throw new Error(
'Unknown AST node type ' +
node.type +
'. ' +
'Maybe you need to change PostCSS stringifier.'
)
}
this[node.type](node, semicolon)
}
root(node) {
this.body(node)
if (node.raws.after) this.builder(node.raws.after)
}
comment(node) {
let left = this.raw(node, 'left', 'commentLeft')
let right = this.raw(node, 'right', 'commentRight')
this.builder('/*' + left + node.text + right + '*/', node)
}
decl(node, semicolon) {
let between = this.raw(node, 'between', 'colon')
let string = node.prop + between + this.rawValue(node, 'value')
if (node.important) {
string += node.raws.important || ' !important'
}
if (semicolon) string += ';'
this.builder(string, node)
}
rule(node) {
this.block(node, this.rawValue(node, 'selector'))
if (node.raws.ownSemicolon) {
this.builder(node.raws.ownSemicolon, node, 'end')
}
}
atrule(node, semicolon) {
let name = '@' + node.name
let params = node.params ? this.rawValue(node, 'params') : ''
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName
} else if (params) {
name += ' '
}
if (node.nodes) {
this.block(node, name + params)
} else {
let end = (node.raws.between || '') + (semicolon ? ';' : '')
this.builder(name + params + end, node)
}
}
body(node) {
let last = node.nodes.length - 1
while (last > 0) {
if (node.nodes[last].type !== 'comment') break
last -= 1
}
let semicolon = this.raw(node, 'semicolon')
for (let i = 0; i < node.nodes.length; i++) {
let child = node.nodes[i]
let before = this.raw(child, 'before')
if (before) this.builder(before)
this.stringify(child, last !== i || semicolon)
}
}
block(node, start) {
let between = this.raw(node, 'between', 'beforeOpen')
this.builder(start + between + '{', node, 'start')
let after
if (node.nodes && node.nodes.length) {
this.body(node)
after = this.raw(node, 'after')
} else {
after = this.raw(node, 'after', 'emptyBody')
}
if (after) this.builder(after)
this.builder('}', node, 'end')
}
raw(node, own, detect) {
let value
if (!detect) detect = own
// Already had
if (own) {
value = node.raws[own]
if (typeof value !== 'undefined') return value
}
let parent = node.parent
// Hack for first rule in CSS
if (detect === 'before') {
if (!parent || (parent.type === 'root' && parent.first === node)) {
return ''
}
}
// Floating child without parent
if (!parent) return DEFAULT_RAW[detect]
// Detect style by other nodes
let root = node.root()
if (!root.rawCache) root.rawCache = {}
if (typeof root.rawCache[detect] !== 'undefined') {
return root.rawCache[detect]
}
if (detect === 'before' || detect === 'after') {
return this.beforeAfter(node, detect)
} else {
let method = 'raw' + capitalize(detect)
if (this[method]) {
value = this[method](root, node)
} else {
root.walk(i => {
value = i.raws[own]
if (typeof value !== 'undefined') return false
})
}
}
if (typeof value === 'undefined') value = DEFAULT_RAW[detect]
root.rawCache[detect] = value
return value
}
rawSemicolon(root) {
let value
root.walk(i => {
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon
if (typeof value !== 'undefined') return false
}
})
return value
}
rawEmptyBody(root) {
let value
root.walk(i => {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after
if (typeof value !== 'undefined') return false
}
})
return value
}
rawIndent(root) {
if (root.raws.indent) return root.raws.indent
let value
root.walk(i => {
let p = i.parent
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
let parts = i.raws.before.split('\n')
value = parts[parts.length - 1]
value = value.replace(/\S/g, '')
return false
}
}
})
return value
}
rawBeforeComment(root, node) {
let value
root.walkComments(i => {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '')
}
return false
}
})
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeDecl')
} else if (value) {
value = value.replace(/\S/g, '')
}
return value
}
rawBeforeDecl(root, node) {
let value
root.walkDecls(i => {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '')
}
return false
}
})
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeRule')
} else if (value) {
value = value.replace(/\S/g, '')
}
return value
}
rawBeforeRule(root) {
let value
root.walk(i => {
if (i.nodes && (i.parent !== root || root.first !== i)) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '')
}
return false
}
}
})
if (value) value = value.replace(/\S/g, '')
return value
}
rawBeforeClose(root) {
let value
root.walk(i => {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after
if (value.includes('\n')) {
value = value.replace(/[^\n]+$/, '')
}
return false
}
}
})
if (value) value = value.replace(/\S/g, '')
return value
}
rawBeforeOpen(root) {
let value
root.walk(i => {
if (i.type !== 'decl') {
value = i.raws.between
if (typeof value !== 'undefined') return false
}
})
return value
}
rawColon(root) {
let value
root.walkDecls(i => {
if (typeof i.raws.between !== 'undefined') {
value = i.raws.between.replace(/[^\s:]/g, '')
return false
}
})
return value
}
beforeAfter(node, detect) {
let value
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl')
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment')
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule')
} else {
value = this.raw(node, null, 'beforeClose')
}
let buf = node.parent
let depth = 0
while (buf && buf.type !== 'root') {
depth += 1
buf = buf.parent
}
if (value.includes('\n')) {
let indent = this.raw(node, null, 'indent')
if (indent.length) {
for (let step = 0; step < depth; step++) value += indent
}
}
return value
}
rawValue(node, prop) {
let value = node[prop]
let raw = node.raws[prop]
if (raw && raw.value === value) {
return raw.raw
}
return value
}
}
module.exports = Stringifier

5
assets_old/node_modules/postcss/lib/stringify.d.ts generated vendored Normal file
View file

@ -0,0 +1,5 @@
import { Stringifier } from './postcss.js'
declare const stringify: Stringifier
export default stringify

11
assets_old/node_modules/postcss/lib/stringify.js generated vendored Normal file
View file

@ -0,0 +1,11 @@
'use strict'
let Stringifier = require('./stringifier')
function stringify(node, builder) {
let str = new Stringifier(builder)
str.stringify(node)
}
module.exports = stringify
stringify.default = stringify

3
assets_old/node_modules/postcss/lib/symbols.js generated vendored Normal file
View file

@ -0,0 +1,3 @@
'use strict'
module.exports.isClean = Symbol('isClean')

View file

@ -0,0 +1,70 @@
'use strict'
let { cyan, gray, green, yellow, magenta } = require('colorette')
let tokenizer = require('./tokenize')
let Input
function registerInput(dependant) {
Input = dependant
}
const HIGHLIGHT_THEME = {
'brackets': cyan,
'at-word': cyan,
'comment': gray,
'string': green,
'class': yellow,
'hash': magenta,
'call': cyan,
'(': cyan,
')': cyan,
'{': yellow,
'}': yellow,
'[': yellow,
']': yellow,
':': yellow,
';': yellow
}
function getTokenType([type, value], processor) {
if (type === 'word') {
if (value[0] === '.') {
return 'class'
}
if (value[0] === '#') {
return 'hash'
}
}
if (!processor.endOfFile()) {
let next = processor.nextToken()
processor.back(next)
if (next[0] === 'brackets' || next[0] === '(') return 'call'
}
return type
}
function terminalHighlight(css) {
let processor = tokenizer(new Input(css), { ignoreErrors: true })
let result = ''
while (!processor.endOfFile()) {
let token = processor.nextToken()
let color = HIGHLIGHT_THEME[getTokenType(token, processor)]
if (color) {
result += token[1]
.split(/\r?\n/)
.map(i => color(i))
.join('\n')
} else {
result += token[1]
}
}
return result
}
terminalHighlight.registerInput = registerInput
module.exports = terminalHighlight

266
assets_old/node_modules/postcss/lib/tokenize.js generated vendored Normal file
View file

@ -0,0 +1,266 @@
'use strict'
const SINGLE_QUOTE = "'".charCodeAt(0)
const DOUBLE_QUOTE = '"'.charCodeAt(0)
const BACKSLASH = '\\'.charCodeAt(0)
const SLASH = '/'.charCodeAt(0)
const NEWLINE = '\n'.charCodeAt(0)
const SPACE = ' '.charCodeAt(0)
const FEED = '\f'.charCodeAt(0)
const TAB = '\t'.charCodeAt(0)
const CR = '\r'.charCodeAt(0)
const OPEN_SQUARE = '['.charCodeAt(0)
const CLOSE_SQUARE = ']'.charCodeAt(0)
const OPEN_PARENTHESES = '('.charCodeAt(0)
const CLOSE_PARENTHESES = ')'.charCodeAt(0)
const OPEN_CURLY = '{'.charCodeAt(0)
const CLOSE_CURLY = '}'.charCodeAt(0)
const SEMICOLON = ';'.charCodeAt(0)
const ASTERISK = '*'.charCodeAt(0)
const COLON = ':'.charCodeAt(0)
const AT = '@'.charCodeAt(0)
const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g
const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g
const RE_BAD_BRACKET = /.[\n"'(/\\]/
const RE_HEX_ESCAPE = /[\da-f]/i
module.exports = function tokenizer(input, options = {}) {
let css = input.css.valueOf()
let ignore = options.ignoreErrors
let code, next, quote, content, escape
let escaped, escapePos, prev, n, currentToken
let length = css.length
let pos = 0
let buffer = []
let returned = []
function position() {
return pos
}
function unclosed(what) {
throw input.error('Unclosed ' + what, pos)
}
function endOfFile() {
return returned.length === 0 && pos >= length
}
function nextToken(opts) {
if (returned.length) return returned.pop()
if (pos >= length) return
let ignoreUnclosed = opts ? opts.ignoreUnclosed : false
code = css.charCodeAt(pos)
switch (code) {
case NEWLINE:
case SPACE:
case TAB:
case CR:
case FEED: {
next = pos
do {
next += 1
code = css.charCodeAt(next)
} while (
code === SPACE ||
code === NEWLINE ||
code === TAB ||
code === CR ||
code === FEED
)
currentToken = ['space', css.slice(pos, next)]
pos = next - 1
break
}
case OPEN_SQUARE:
case CLOSE_SQUARE:
case OPEN_CURLY:
case CLOSE_CURLY:
case COLON:
case SEMICOLON:
case CLOSE_PARENTHESES: {
let controlChar = String.fromCharCode(code)
currentToken = [controlChar, controlChar, pos]
break
}
case OPEN_PARENTHESES: {
prev = buffer.length ? buffer.pop()[1] : ''
n = css.charCodeAt(pos + 1)
if (
prev === 'url' &&
n !== SINGLE_QUOTE &&
n !== DOUBLE_QUOTE &&
n !== SPACE &&
n !== NEWLINE &&
n !== TAB &&
n !== FEED &&
n !== CR
) {
next = pos
do {
escaped = false
next = css.indexOf(')', next + 1)
if (next === -1) {
if (ignore || ignoreUnclosed) {
next = pos
break
} else {
unclosed('bracket')
}
}
escapePos = next
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1
escaped = !escaped
}
} while (escaped)
currentToken = ['brackets', css.slice(pos, next + 1), pos, next]
pos = next
} else {
next = css.indexOf(')', pos + 1)
content = css.slice(pos, next + 1)
if (next === -1 || RE_BAD_BRACKET.test(content)) {
currentToken = ['(', '(', pos]
} else {
currentToken = ['brackets', content, pos, next]
pos = next
}
}
break
}
case SINGLE_QUOTE:
case DOUBLE_QUOTE: {
quote = code === SINGLE_QUOTE ? "'" : '"'
next = pos
do {
escaped = false
next = css.indexOf(quote, next + 1)
if (next === -1) {
if (ignore || ignoreUnclosed) {
next = pos + 1
break
} else {
unclosed('string')
}
}
escapePos = next
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1
escaped = !escaped
}
} while (escaped)
currentToken = ['string', css.slice(pos, next + 1), pos, next]
pos = next
break
}
case AT: {
RE_AT_END.lastIndex = pos + 1
RE_AT_END.test(css)
if (RE_AT_END.lastIndex === 0) {
next = css.length - 1
} else {
next = RE_AT_END.lastIndex - 2
}
currentToken = ['at-word', css.slice(pos, next + 1), pos, next]
pos = next
break
}
case BACKSLASH: {
next = pos
escape = true
while (css.charCodeAt(next + 1) === BACKSLASH) {
next += 1
escape = !escape
}
code = css.charCodeAt(next + 1)
if (
escape &&
code !== SLASH &&
code !== SPACE &&
code !== NEWLINE &&
code !== TAB &&
code !== CR &&
code !== FEED
) {
next += 1
if (RE_HEX_ESCAPE.test(css.charAt(next))) {
while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
next += 1
}
if (css.charCodeAt(next + 1) === SPACE) {
next += 1
}
}
}
currentToken = ['word', css.slice(pos, next + 1), pos, next]
pos = next
break
}
default: {
if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
next = css.indexOf('*/', pos + 2) + 1
if (next === 0) {
if (ignore || ignoreUnclosed) {
next = css.length
} else {
unclosed('comment')
}
}
currentToken = ['comment', css.slice(pos, next + 1), pos, next]
pos = next
} else {
RE_WORD_END.lastIndex = pos + 1
RE_WORD_END.test(css)
if (RE_WORD_END.lastIndex === 0) {
next = css.length - 1
} else {
next = RE_WORD_END.lastIndex - 2
}
currentToken = ['word', css.slice(pos, next + 1), pos, next]
buffer.push(currentToken)
pos = next
}
break
}
}
pos++
return currentToken
}
function back(token) {
returned.push(token)
}
return {
back,
nextToken,
endOfFile,
position
}
}

12
assets_old/node_modules/postcss/lib/warn-once.js generated vendored Normal file
View file

@ -0,0 +1,12 @@
'use strict'
let printed = {}
module.exports = function warnOnce(message) {
if (printed[message]) return
printed[message] = true
if (typeof console !== 'undefined' && console.warn) {
console.warn(message)
}
}

104
assets_old/node_modules/postcss/lib/warning.d.ts generated vendored Normal file
View file

@ -0,0 +1,104 @@
import Node from './node.js'
export interface WarningOptions {
/**
* CSS node that caused the warning.
*/
node?: Node
/**
* Word in CSS source that caused the warning.
*/
word?: string
/**
* Index in CSS node string that caused the warning.
*/
index?: number
/**
* Name of the plugin that created this warning. `Result#warn` fills
* this property automatically.
*/
plugin?: string
}
/**
* Represents a plugins warning. It can be created using `Node#warn`.
*
* ```js
* if (decl.important) {
* decl.warn(result, 'Avoid !important', { word: '!important' })
* }
* ```
*/
export default class Warning {
/**
* Type to filter warnings from `Result#messages`.
* Always equal to `"warning"`.
*/
type: 'warning'
/**
* The warning message.
*
* ```js
* warning.text //=> 'Try to avoid !important'
* ```
*/
text: string
/**
* The name of the plugin that created this warning.
* When you call `Node#warn` it will fill this property automatically.
*
* ```js
* warning.plugin //=> 'postcss-important'
* ```
*/
plugin: string
/**
* Contains the CSS node that caused the warning.
*
* ```js
* warning.node.toString() //=> 'color: white !important'
* ```
*/
node: Node
/**
* Line in the input file with this warnings source.
*
* ```js
* warning.line //=> 5
* ```
*/
line: number
/**
* Column in the input file with this warnings source.
*
* ```js
* warning.column //=> 6
* ```
*/
column: number
/**
* @param text Warning message.
* @param opts Warning options.
*/
constructor(text: string, opts?: WarningOptions)
/**
* Returns a warning position and message.
*
* ```js
* warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
* ```
*
* @return Warning position and message.
*/
toString(): string
}

35
assets_old/node_modules/postcss/lib/warning.js generated vendored Normal file
View file

@ -0,0 +1,35 @@
'use strict'
class Warning {
constructor(text, opts = {}) {
this.type = 'warning'
this.text = text
if (opts.node && opts.node.source) {
let pos = opts.node.positionBy(opts)
this.line = pos.line
this.column = pos.column
}
for (let opt in opts) this[opt] = opts[opt]
}
toString() {
if (this.node) {
return this.node.error(this.text, {
plugin: this.plugin,
index: this.index,
word: this.word
}).message
}
if (this.plugin) {
return this.plugin + ': ' + this.text
}
return this.text
}
}
module.exports = Warning
Warning.default = Warning

View file

@ -0,0 +1,301 @@
# Change Log
## 0.5.6
* Fix for regression when people were using numbers as names in source maps. See
#236.
## 0.5.5
* Fix "regression" of unsupported, implementation behavior that half the world
happens to have come to depend on. See #235.
* Fix regression involving function hoisting in SpiderMonkey. See #233.
## 0.5.4
* Large performance improvements to source-map serialization. See #228 and #229.
## 0.5.3
* Do not include unnecessary distribution files. See
commit ef7006f8d1647e0a83fdc60f04f5a7ca54886f86.
## 0.5.2
* Include browser distributions of the library in package.json's `files`. See
issue #212.
## 0.5.1
* Fix latent bugs in IndexedSourceMapConsumer.prototype._parseMappings. See
ff05274becc9e6e1295ed60f3ea090d31d843379.
## 0.5.0
* Node 0.8 is no longer supported.
* Use webpack instead of dryice for bundling.
* Big speedups serializing source maps. See pull request #203.
* Fix a bug with `SourceMapConsumer.prototype.sourceContentFor` and sources that
explicitly start with the source root. See issue #199.
## 0.4.4
* Fix an issue where using a `SourceMapGenerator` after having created a
`SourceMapConsumer` from it via `SourceMapConsumer.fromSourceMap` failed. See
issue #191.
* Fix an issue with where `SourceMapGenerator` would mistakenly consider
different mappings as duplicates of each other and avoid generating them. See
issue #192.
## 0.4.3
* A very large number of performance improvements, particularly when parsing
source maps. Collectively about 75% of time shaved off of the source map
parsing benchmark!
* Fix a bug in `SourceMapConsumer.prototype.allGeneratedPositionsFor` and fuzzy
searching in the presence of a column option. See issue #177.
* Fix a bug with joining a source and its source root when the source is above
the root. See issue #182.
* Add the `SourceMapConsumer.prototype.hasContentsOfAllSources` method to
determine when all sources' contents are inlined into the source map. See
issue #190.
## 0.4.2
* Add an `.npmignore` file so that the benchmarks aren't pulled down by
dependent projects. Issue #169.
* Add an optional `column` argument to
`SourceMapConsumer.prototype.allGeneratedPositionsFor` and better handle lines
with no mappings. Issues #172 and #173.
## 0.4.1
* Fix accidentally defining a global variable. #170.
## 0.4.0
* The default direction for fuzzy searching was changed back to its original
direction. See #164.
* There is now a `bias` option you can supply to `SourceMapConsumer` to control
the fuzzy searching direction. See #167.
* About an 8% speed up in parsing source maps. See #159.
* Added a benchmark for parsing and generating source maps.
## 0.3.0
* Change the default direction that searching for positions fuzzes when there is
not an exact match. See #154.
* Support for environments using json2.js for JSON serialization. See #156.
## 0.2.0
* Support for consuming "indexed" source maps which do not have any remote
sections. See pull request #127. This introduces a minor backwards
incompatibility if you are monkey patching `SourceMapConsumer.prototype`
methods.
## 0.1.43
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
#148 for some discussion and issues #150, #151, and #152 for implementations.
## 0.1.42
* Fix an issue where `SourceNode`s from different versions of the source-map
library couldn't be used in conjunction with each other. See issue #142.
## 0.1.41
* Fix a bug with getting the source content of relative sources with a "./"
prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).
* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
column span of each mapping.
* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
all generated positions associated with a given original source and line.
## 0.1.40
* Performance improvements for parsing source maps in SourceMapConsumer.
## 0.1.39
* Fix a bug where setting a source's contents to null before any source content
had been set before threw a TypeError. See issue #131.
## 0.1.38
* Fix a bug where finding relative paths from an empty path were creating
absolute paths. See issue #129.
## 0.1.37
* Fix a bug where if the source root was an empty string, relative source paths
would turn into absolute source paths. Issue #124.
## 0.1.36
* Allow the `names` mapping property to be an empty string. Issue #121.
## 0.1.35
* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
to specify a path that relative sources in the second parameter should be
relative to. Issue #105.
* If no file property is given to a `SourceMapGenerator`, then the resulting
source map will no longer have a `null` file property. The property will
simply not exist. Issue #104.
* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
Issue #116.
## 0.1.34
* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.
* Fix bug involving source contents and the
`SourceMapGenerator.prototype.applySourceMap`. Issue #100.
## 0.1.33
* Fix some edge cases surrounding path joining and URL resolution.
* Add a third parameter for relative path to
`SourceMapGenerator.prototype.applySourceMap`.
* Fix issues with mappings and EOLs.
## 0.1.32
* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
(issue 92).
* Fixed test runner to actually report number of failed tests as its process
exit code.
* Fixed a typo when reporting bad mappings (issue 87).
## 0.1.31
* Delay parsing the mappings in SourceMapConsumer until queried for a source
location.
* Support Sass source maps (which at the time of writing deviate from the spec
in small ways) in SourceMapConsumer.
## 0.1.30
* Do not join source root with a source, when the source is a data URI.
* Extend the test runner to allow running single specific test files at a time.
* Performance improvements in `SourceNode.prototype.walk` and
`SourceMapConsumer.prototype.eachMapping`.
* Source map browser builds will now work inside Workers.
* Better error messages when attempting to add an invalid mapping to a
`SourceMapGenerator`.
## 0.1.29
* Allow duplicate entries in the `names` and `sources` arrays of source maps
(usually from TypeScript) we are parsing. Fixes github issue 72.
## 0.1.28
* Skip duplicate mappings when creating source maps from SourceNode; github
issue 75.
## 0.1.27
* Don't throw an error when the `file` property is missing in SourceMapConsumer,
we don't use it anyway.
## 0.1.26
* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.
## 0.1.25
* Make compatible with browserify
## 0.1.24
* Fix issue with absolute paths and `file://` URIs. See
https://bugzilla.mozilla.org/show_bug.cgi?id=885597
## 0.1.23
* Fix issue with absolute paths and sourcesContent, github issue 64.
## 0.1.22
* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.
## 0.1.21
* Fixed handling of sources that start with a slash so that they are relative to
the source root's host.
## 0.1.20
* Fixed github issue #43: absolute URLs aren't joined with the source root
anymore.
## 0.1.19
* Using Travis CI to run tests.
## 0.1.18
* Fixed a bug in the handling of sourceRoot.
## 0.1.17
* Added SourceNode.fromStringWithSourceMap.
## 0.1.16
* Added missing documentation.
* Fixed the generating of empty mappings in SourceNode.
## 0.1.15
* Added SourceMapGenerator.applySourceMap.
## 0.1.14
* The sourceRoot is now handled consistently.
## 0.1.13
* Added SourceMapGenerator.fromSourceMap.
## 0.1.12
* SourceNode now generates empty mappings too.
## 0.1.11
* Added name support to SourceNode.
## 0.1.10
* Added sourcesContent support to the customer and generator.

View file

@ -0,0 +1,28 @@
Copyright (c) 2009-2011, Mozilla Foundation and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the Mozilla Foundation nor the names of project
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View file

@ -0,0 +1,742 @@
# Source Map
[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
[![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map)
This is a library to generate and consume the source map format
[described here][format].
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
## Use with Node
$ npm install source-map
## Use on the Web
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
--------------------------------------------------------------------------------
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Examples](#examples)
- [Consuming a source map](#consuming-a-source-map)
- [Generating a source map](#generating-a-source-map)
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
- [API](#api)
- [SourceMapConsumer](#sourcemapconsumer)
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
- [SourceMapGenerator](#sourcemapgenerator)
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
- [SourceNode](#sourcenode)
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Examples
### Consuming a source map
```js
var rawSourceMap = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: 'http://example.com/www/js/',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
var smc = new SourceMapConsumer(rawSourceMap);
console.log(smc.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(smc.originalPositionFor({
line: 2,
column: 28
}));
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(smc.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
// { line: 2, column: 28 }
smc.eachMapping(function (m) {
// ...
});
```
### Generating a source map
In depth guide:
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
#### With SourceNode (high level API)
```js
function compile(ast) {
switch (ast.type) {
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), " + ", compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error("Bad AST");
}
}
var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
file: 'add.js'
}));
// { code: '40 + 2',
// map: [object SourceMapGenerator] }
```
#### With SourceMapGenerator (low level API)
```js
var map = new SourceMapGenerator({
file: "source-mapped.js"
});
map.addMapping({
generated: {
line: 10,
column: 35
},
source: "foo.js",
original: {
line: 33,
column: 2
},
name: "christopher"
});
console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
```
## API
Get a reference to the module:
```js
// Node.js
var sourceMap = require('source-map');
// Browser builds
var sourceMap = window.sourceMap;
// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
```
### SourceMapConsumer
A SourceMapConsumer instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.
#### new SourceMapConsumer(rawSourceMap)
The only parameter is the raw source map (either as a string which can be
`JSON.parse`'d, or an object). According to the spec, source maps have the
following attributes:
* `version`: Which version of the source map spec this map is following.
* `sources`: An array of URLs to the original source files.
* `names`: An array of identifiers which can be referenced by individual
mappings.
* `sourceRoot`: Optional. The URL root from which all sources are relative.
* `sourcesContent`: Optional. An array of contents of the original source files.
* `mappings`: A string of base64 VLQs which contain the actual mappings.
* `file`: Optional. The generated filename this source map is associated with.
```js
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
```
#### SourceMapConsumer.prototype.computeColumnSpans()
Compute the last column for each generated mapping. The last column is
inclusive.
```js
// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
consumer.computeColumnSpans();
// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1,
// lastColumn: 9 },
// { line: 2,
// column: 10,
// lastColumn: 19 },
// { line: 2,
// column: 20,
// lastColumn: Infinity } ]
```
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
Returns the original source, line, and column information for the generated
source's line and column positions provided. The only argument is an object with
the following properties:
* `line`: The line number in the generated source. Line numbers in
this library are 1-based (note that the underlying source map
specification uses 0-based line numbers -- this library handles the
translation).
* `column`: The column number in the generated source. Column numbers
in this library are 0-based.
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
element that is smaller than or greater than the one we are searching for,
respectively, if the exact element cannot be found. Defaults to
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
and an object is returned with the following properties:
* `source`: The original source file, or null if this information is not
available.
* `line`: The line number in the original source, or null if this information is
not available. The line number is 1-based.
* `column`: The column number in the original source, or null if this
information is not available. The column number is 0-based.
* `name`: The original identifier, or null if this information is not available.
```js
consumer.originalPositionFor({ line: 2, column: 10 })
// { source: 'foo.coffee',
// line: 2,
// column: 2,
// name: null }
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
// { source: null,
// line: null,
// column: null,
// name: null }
```
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: The column number in the original source. The column
number is 0-based.
and an object is returned with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
// { line: 1,
// column: 56 }
```
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
Returns all generated line and column information for the original source, line,
and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next closest line
that has any mappings. Otherwise, returns all mappings corresponding to the
given line and either the column we are searching for or the next closest column
that has any offsets.
The only argument is an object with the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: Optional. The column number in the original source. The
column number is 0-based.
and an array of objects is returned, each with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
```
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
Return true if we have the embedded source content for every source listed in
the source map, false otherwise.
In other words, if this method returns `true`, then
`consumer.sourceContentFor(s)` will succeed for every source `s` in
`consumer.sources`.
```js
// ...
if (consumer.hasContentsOfAllSources()) {
consumerReadyCallback(consumer);
} else {
fetchSources(consumer, consumerReadyCallback);
}
// ...
```
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
Returns the original source content for the source provided. The only
argument is the URL of the original source file.
If the source content for the given source is not found, then an error is
thrown. Optionally, pass `true` as the second param to have `null` returned
instead.
```js
consumer.sources
// [ "my-cool-lib.clj" ]
consumer.sourceContentFor("my-cool-lib.clj")
// "..."
consumer.sourceContentFor("this is not in the source map");
// Error: "this is not in the source map" is not in the source map
consumer.sourceContentFor("this is not in the source map", true);
// null
```
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.
* `callback`: The function that is called with each mapping. Mappings have the
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
name }`
* `context`: Optional. If specified, this object will be the value of `this`
every time that `callback` is called.
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
`SourceMapConsumer.GENERATED_ORDER`.
```js
consumer.eachMapping(function (m) { console.log(m); })
// ...
// { source: 'illmatic.js',
// generatedLine: 1,
// generatedColumn: 0,
// originalLine: 1,
// originalColumn: 0,
// name: null }
// { source: 'illmatic.js',
// generatedLine: 2,
// generatedColumn: 0,
// originalLine: 2,
// originalColumn: 0,
// name: null }
// ...
```
### SourceMapGenerator
An instance of the SourceMapGenerator represents a source map which is being
built incrementally.
#### new SourceMapGenerator([startOfSourceMap])
You may pass an object with the following properties:
* `file`: The filename of the generated source that this source map is
associated with.
* `sourceRoot`: A root for all relative URLs in this source map.
* `skipValidation`: Optional. When `true`, disables validation of mappings as
they are added. This can improve performance but should be used with
discretion, as a last resort. Even then, one should avoid using this flag when
running tests, if possible.
```js
var generator = new sourceMap.SourceMapGenerator({
file: "my-generated-javascript-file.js",
sourceRoot: "http://example.com/app/js/"
});
```
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
* `sourceMapConsumer` The SourceMap.
```js
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
```
#### SourceMapGenerator.prototype.addMapping(mapping)
Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping object
should have the following properties:
* `generated`: An object with the generated line and column positions.
* `original`: An object with the original line and column positions.
* `source`: The original source file (relative to the sourceRoot).
* `name`: An optional original token name for this mapping.
```js
generator.addMapping({
source: "module-one.scm",
original: { line: 128, column: 0 },
generated: { line: 3, column: 456 }
})
```
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for an original source file.
* `sourceFile` the URL of the original source file.
* `sourceContent` the content of the source file.
```js
generator.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
Applies a SourceMap for a source file to the SourceMap.
Each mapping to the supplied source file is rewritten using the
supplied SourceMap. Note: The resolution for the resulting mappings
is the minimum of this map and the supplied map.
* `sourceMapConsumer`: The SourceMap to be applied.
* `sourceFile`: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.
This parameter is needed when the two SourceMaps aren't in the same
directory, and the SourceMap to be applied contains relative source
paths. If so, those relative source paths need to be rewritten
relative to the SourceMap.
If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
#### SourceMapGenerator.prototype.toString()
Renders the source map being generated to a string.
```js
generator.toString()
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
```
### SourceNode
SourceNodes provide a way to abstract over interpolating and/or concatenating
snippets of generated JavaScript source code, while maintaining the line and
column information associated between those snippets and the original source
code. This is useful as the final intermediate representation a compiler might
use before outputting the generated JS and source map.
#### new SourceNode([line, column, source[, chunk[, name]]])
* `line`: The original line number associated with this source node, or null if
it isn't associated with an original line. The line number is 1-based.
* `column`: The original column number associated with this source node, or null
if it isn't associated with an original column. The column number
is 0-based.
* `source`: The original source's filename; null if no filename is provided.
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
below.
* `name`: Optional. The original identifier.
```js
var node = new SourceNode(1, 2, "a.cpp", [
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
]);
```
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
Creates a SourceNode from generated code and a SourceMapConsumer.
* `code`: The generated code
* `sourceMapConsumer` The SourceMap for the generated code
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
should be relative to.
```js
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
consumer);
```
#### SourceNode.prototype.add(chunk)
Add a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.add(" + ");
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
```
#### SourceNode.prototype.prepend(chunk)
Prepend a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
```
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for a source file. This will be added to the
`SourceMap` in the `sourcesContent` field.
* `sourceFile`: The filename of the source file
* `sourceContent`: The content of the source file
```js
node.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceNode.prototype.walk(fn)
Walk over the tree of JS snippets in this node and its children. The walking
function is called once for each snippet of JS and is passed that snippet and
the its original associated source's line/column location.
* `fn`: The traversal function.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
```
#### SourceNode.prototype.walkSourceContents(fn)
Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.
* `fn`: The traversal function.
```js
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");
var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c
```
#### SourceNode.prototype.join(sep)
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
between each of this source node's children.
* `sep`: The separator.
```js
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
var joinedNode = node.join(" ");
```
#### SourceNode.prototype.replaceRight(pattern, replacement)
Call `String.prototype.replace` on the very right-most source snippet. Useful
for trimming white space from the end of a source node, etc.
* `pattern`: The pattern to replace.
* `replacement`: The thing to replace the pattern with.
```js
// Trim trailing white space.
node.replaceRight(/\s*$/, "");
```
#### SourceNode.prototype.toString()
Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toString()
// 'unodostresquatro'
```
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
Returns the string representation of this tree of source nodes, plus a
SourceMapGenerator which contains all the mappings between the generated and
original sources.
The arguments are the same as those to `new SourceMapGenerator`.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toStringWithSourceMap({ file: "my-output-file.js" })
// { code: 'unodostresquatro',
// map: [object SourceMapGenerator] }
```

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,121 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
var has = Object.prototype.hasOwnProperty;
var hasNativeMap = typeof Map !== "undefined";
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = hasNativeMap ? new Map() : Object.create(null);
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Return how many unique items are in this ArraySet. If duplicates have been
* added, than those do not count towards the size.
*
* @returns Number
*/
ArraySet.prototype.size = function ArraySet_size() {
return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
if (hasNativeMap) {
this._set.set(aStr, idx);
} else {
this._set[sStr] = idx;
}
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
if (hasNativeMap) {
return this._set.has(aStr);
} else {
var sStr = util.toSetString(aStr);
return has.call(this._set, sStr);
}
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (hasNativeMap) {
var idx = this._set.get(aStr);
if (idx >= 0) {
return idx;
}
} else {
var sStr = util.toSetString(aStr);
if (has.call(this._set, sStr)) {
return this._set[sStr];
}
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;

View file

@ -0,0 +1,140 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var base64 = require('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string via the out parameter.
*/
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aIndex;
};

View file

@ -0,0 +1,67 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function (number) {
if (0 <= number && number < intToCharMap.length) {
return intToCharMap[number];
}
throw new TypeError("Must be between 0 and 63: " + number);
};
/**
* Decode a single base 64 character code digit to an integer. Returns -1 on
* failure.
*/
exports.decode = function (charCode) {
var bigA = 65; // 'A'
var bigZ = 90; // 'Z'
var littleA = 97; // 'a'
var littleZ = 122; // 'z'
var zero = 48; // '0'
var nine = 57; // '9'
var plus = 43; // '+'
var slash = 47; // '/'
var littleOffset = 26;
var numberOffset = 52;
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
if (bigA <= charCode && charCode <= bigZ) {
return (charCode - bigA);
}
// 26 - 51: abcdefghijklmnopqrstuvwxyz
if (littleA <= charCode && charCode <= littleZ) {
return (charCode - littleA + littleOffset);
}
// 52 - 61: 0123456789
if (zero <= charCode && charCode <= nine) {
return (charCode - zero + numberOffset);
}
// 62: +
if (charCode == plus) {
return 62;
}
// 63: /
if (charCode == slash) {
return 63;
}
// Invalid base64 digit.
return -1;
};

View file

@ -0,0 +1,111 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
}
else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
} else {
return mid;
}
}
else {
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
} else {
return aLow < 0 ? -1 : aLow;
}
}
}
/**
* This is an implementation of binary search which will always try and return
* the index of the closest element if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
*/
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}
// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}
return index;
};

View file

@ -0,0 +1,79 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a neglibable overhead in general
* case for a large speedup in case of mappings being added in order.
*/
function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = {generatedLine: -1, generatedColumn: 0};
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach =
function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
MappingList.prototype.add = function MappingList_add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
};
exports.MappingList = MappingList;

View file

@ -0,0 +1,114 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
// It turns out that some (most?) JavaScript engines don't self-host
// `Array.prototype.sort`. This makes sense because C++ will likely remain
// faster than JS when doing raw CPU-intensive sorting. However, when using a
// custom comparator function, calling back and forth between the VM's C++ and
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
// worse generated code for the comparator function than would be optimal. In
// fact, when sorting with a comparator, these costs outweigh the benefits of
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
// a ~3500ms mean speed-up in `bench/bench.html`.
/**
* Swap the elements indexed by `x` and `y` in the array `ary`.
*
* @param {Array} ary
* The array.
* @param {Number} x
* The index of the first item.
* @param {Number} y
* The index of the second item.
*/
function swap(ary, x, y) {
var temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
/**
* Returns a random integer within the range `low .. high` inclusive.
*
* @param {Number} low
* The lower bound on the range.
* @param {Number} high
* The upper bound on the range.
*/
function randomIntInRange(low, high) {
return Math.round(low + (Math.random() * (high - low)));
}
/**
* The Quick Sort algorithm.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
* @param {Number} p
* Start index of the array
* @param {Number} r
* End index of the array
*/
function doQuickSort(ary, comparator, p, r) {
// If our lower bound is less than our upper bound, we (1) partition the
// array into two pieces and (2) recurse on each half. If it is not, this is
// the empty array and our base case.
if (p < r) {
// (1) Partitioning.
//
// The partitioning chooses a pivot between `p` and `r` and moves all
// elements that are less than or equal to the pivot to the before it, and
// all the elements that are greater than it after it. The effect is that
// once partition is done, the pivot is in the exact place it will be when
// the array is put in sorted order, and it will not need to be moved
// again. This runs in O(n) time.
// Always choose a random pivot so that an input array which is reverse
// sorted does not cause O(n^2) running time.
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
// Immediately after `j` is incremented in this loop, the following hold
// true:
//
// * Every element in `ary[p .. i]` is less than or equal to the pivot.
//
// * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
// (2) Recurse on each half.
doQuickSort(ary, comparator, p, q - 1);
doQuickSort(ary, comparator, q + 1, r);
}
}
/**
* Sort the given array in-place with the given comparator function.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
*/
exports.quickSort = function (ary, comparator) {
doQuickSort(ary, comparator, 0, ary.length - 1);
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,425 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var base64VLQ = require('./base64-vlq');
var util = require('./util');
var ArraySet = require('./array-set').ArraySet;
var MappingList = require('./mapping-list').MappingList;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. You may pass an object with the following
* properties:
*
* - file: The filename of the generated source.
* - sourceRoot: A root for all relative URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var sourceRelative = sourceFile;
if (sourceRoot !== null) {
sourceRelative = util.relative(sourceRoot, sourceFile);
}
if (!generator._sources.has(sourceRelative)) {
generator._sources.add(sourceRelative);
}
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot != null) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = Object.create(null);
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param aSourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
var sourceFile = aSourceFile;
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error(
'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
'or the source map\'s "file" property. Both were omitted.'
);
}
sourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "sourceFile" relative if an absolute Url is passed.
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "sourceFile"
this._mappings.unsortedForEach(function (mapping) {
if (mapping.source === sourceFile && mapping.originalLine != null) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source != null) {
// Copy mapping
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util.join(aSourceMapPath, mapping.source)
}
if (sourceRoot != null) {
mapping.source = util.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name != null) {
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aSourceMapPath != null) {
sourceFile = util.join(aSourceMapPath, sourceFile);
}
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
// When aOriginal is truthy but has empty values for .line and .column,
// it is most likely a programmer error. In this case we throw a very
// specific error message to try to guide them the right way.
// For example: https://github.com/Polymer/polymer-bundler/pull/519
if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
throw new Error(
'original.line and original.column are not numbers -- you probably meant to omit ' +
'the original mapping entirely and only map the generated position. If so, pass ' +
'null for the original mapping instead of an object with empty or null values.'
);
}
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var next;
var mapping;
var nameIdx;
var sourceIdx;
var mappings = this._mappings.toArray();
for (var i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = ''
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
continue;
}
next += ',';
}
}
next += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
exports.SourceMapGenerator = SourceMapGenerator;

View file

@ -0,0 +1,413 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
var util = require('./util');
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
var REGEX_NEWLINE = /(\r?\n)/;
// Newline character code for charCodeAt() comparisons
var NEWLINE_CODE = 10;
// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
var isSourceNode = "$$$isSourceNode$$$";
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
* @param aRelativePath Optional. The path that relative sources in the
* SourceMapConsumer should be relative to.
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are accessed by calling `shiftNextLine`.
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var remainingLinesIndex = 0;
var shiftNextLine = function() {
var lineContents = getNextLine();
// The last line of a file might not have a newline.
var newLine = getNextLine() || "";
return lineContents + newLine;
function getNextLine() {
return remainingLinesIndex < remainingLines.length ?
remainingLines[remainingLinesIndex++] : undefined;
}
};
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping !== null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
// Associate first line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[remainingLinesIndex] || '';
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
// No more remaining code, continue
lastMapping = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[remainingLinesIndex] || '';
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
if (remainingLinesIndex < remainingLines.length) {
if (lastMapping) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.splice(remainingLinesIndex).join(""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
var source = aRelativePath
? util.join(aRelativePath, mapping.source)
: mapping.source;
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;

View file

@ -0,0 +1,488 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = '';
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ':';
}
url += '//';
if (aParsedUrl.auth) {
url += aParsedUrl.auth + '@';
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
function normalize(aPath) {
var path = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
var isAbsolute = exports.isAbsolute(path);
var parts = path.split(/\/+/);
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part === '.') {
parts.splice(i, 1);
} else if (part === '..') {
up++;
} else if (up > 0) {
if (part === '') {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join('/');
if (path === '') {
path = isAbsolute ? '/' : '.';
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
}
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || '/';
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/'
? aPath
: normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
exports.isAbsolute = function (aPath) {
return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
};
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, '');
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
var level = 0;
while (aPath.indexOf(aRoot + '/') !== 0) {
var index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
var supportsNullProto = (function () {
var obj = Object.create(null);
return !('__proto__' in obj);
}());
function identity (s) {
return s;
}
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
if (isProtoString(aStr)) {
return '$' + aStr;
}
return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s) {
if (!s) {
return false;
}
var length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
s.charCodeAt(length - 2) !== 95 /* '_' */ ||
s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
s.charCodeAt(length - 4) !== 116 /* 't' */ ||
s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
s.charCodeAt(length - 8) !== 95 /* '_' */ ||
s.charCodeAt(length - 9) !== 95 /* '_' */) {
return false;
}
for (var i = length - 10; i >= 0; i--) {
if (s.charCodeAt(i) !== 36 /* '$' */) {
return false;
}
}
return true;
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings with deflated source and name indices where
* the generated positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 === null) {
return 1; // aStr2 !== null
}
if (aStr2 === null) {
return -1; // aStr1 !== null
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
/**
* Comparator between two mappings with inflated source and name strings where
* the generated positions are compared.
*/
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
/**
* Strip any JSON XSSI avoidance prefix from the string (as documented
* in the source maps specification), and then parse the string as
* JSON.
*/
function parseSourceMapInput(str) {
return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
}
exports.parseSourceMapInput = parseSourceMapInput;
/**
* Compute the URL of a source given the the source root, the source's
* URL, and the source map's URL.
*/
function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
sourceURL = sourceURL || '';
if (sourceRoot) {
// This follows what Chrome does.
if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
sourceRoot += '/';
}
// The spec says:
// Line 4: An optional source root, useful for relocating source
// files on a server or removing repeated values in the
// “sources” entry. This value is prepended to the individual
// entries in the “source” field.
sourceURL = sourceRoot + sourceURL;
}
// Historically, SourceMapConsumer did not take the sourceMapURL as
// a parameter. This mode is still somewhat supported, which is why
// this code block is conditional. However, it's preferable to pass
// the source map URL to SourceMapConsumer, so that this function
// can implement the source URL resolution algorithm as outlined in
// the spec. This block is basically the equivalent of:
// new URL(sourceURL, sourceMapURL).toString()
// ... except it avoids using URL, which wasn't available in the
// older releases of node still supported by this library.
//
// The spec says:
// If the sources are not absolute URLs after prepending of the
// “sourceRoot”, the sources are resolved relative to the
// SourceMap (like resolving script src in a html document).
if (sourceMapURL) {
var parsed = urlParse(sourceMapURL);
if (!parsed) {
throw new Error("sourceMapURL could not be parsed");
}
if (parsed.path) {
// Strip the last path component, but keep the "/".
var index = parsed.path.lastIndexOf('/');
if (index >= 0) {
parsed.path = parsed.path.substring(0, index + 1);
}
}
sourceURL = join(urlGenerate(parsed), sourceURL);
}
return normalize(sourceURL);
}
exports.computeSourceURL = computeSourceURL;

View file

@ -0,0 +1,73 @@
{
"name": "source-map",
"description": "Generates and consumes source maps",
"version": "0.6.1",
"homepage": "https://github.com/mozilla/source-map",
"author": "Nick Fitzgerald <nfitzgerald@mozilla.com>",
"contributors": [
"Tobias Koppers <tobias.koppers@googlemail.com>",
"Duncan Beevers <duncan@dweebd.com>",
"Stephen Crane <scrane@mozilla.com>",
"Ryan Seddon <seddon.ryan@gmail.com>",
"Miles Elam <miles.elam@deem.com>",
"Mihai Bazon <mihai.bazon@gmail.com>",
"Michael Ficarra <github.public.email@michael.ficarra.me>",
"Todd Wolfson <todd@twolfson.com>",
"Alexander Solovyov <alexander@solovyov.net>",
"Felix Gnass <fgnass@gmail.com>",
"Conrad Irwin <conrad.irwin@gmail.com>",
"usrbincc <usrbincc@yahoo.com>",
"David Glasser <glasser@davidglasser.net>",
"Chase Douglas <chase@newrelic.com>",
"Evan Wallace <evan.exe@gmail.com>",
"Heather Arthur <fayearthur@gmail.com>",
"Hugh Kennedy <hughskennedy@gmail.com>",
"David Glasser <glasser@davidglasser.net>",
"Simon Lydell <simon.lydell@gmail.com>",
"Jmeas Smith <jellyes2@gmail.com>",
"Michael Z Goddard <mzgoddard@gmail.com>",
"azu <azu@users.noreply.github.com>",
"John Gozde <john@gozde.ca>",
"Adam Kirkton <akirkton@truefitinnovation.com>",
"Chris Montgomery <christopher.montgomery@dowjones.com>",
"J. Ryan Stinnett <jryans@gmail.com>",
"Jack Herrington <jherrington@walmartlabs.com>",
"Chris Truter <jeffpalentine@gmail.com>",
"Daniel Espeset <daniel@danielespeset.com>",
"Jamie Wong <jamie.lf.wong@gmail.com>",
"Eddy Bruël <ejpbruel@mozilla.com>",
"Hawken Rives <hawkrives@gmail.com>",
"Gilad Peleg <giladp007@gmail.com>",
"djchie <djchie.dev@gmail.com>",
"Gary Ye <garysye@gmail.com>",
"Nicolas Lalevée <nicolas.lalevee@hibnet.org>"
],
"repository": {
"type": "git",
"url": "http://github.com/mozilla/source-map.git"
},
"main": "./source-map.js",
"files": [
"source-map.js",
"source-map.d.ts",
"lib/",
"dist/source-map.debug.js",
"dist/source-map.js",
"dist/source-map.min.js",
"dist/source-map.min.js.map"
],
"engines": {
"node": ">=0.10.0"
},
"license": "BSD-3-Clause",
"scripts": {
"test": "npm run build && node test/run-tests.js",
"build": "webpack --color",
"toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md"
},
"devDependencies": {
"doctoc": "^0.15.0",
"webpack": "^1.12.0"
},
"typings": "source-map"
}

View file

@ -0,0 +1,98 @@
export interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
}
export interface RawSourceMap extends StartOfSourceMap {
version: string;
sources: string[];
names: string[];
sourcesContent?: string[];
mappings: string;
}
export interface Position {
line: number;
column: number;
}
export interface LineRange extends Position {
lastColumn: number;
}
export interface FindPosition extends Position {
// SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND
bias?: number;
}
export interface SourceFindPosition extends FindPosition {
source: string;
}
export interface MappedPosition extends Position {
source: string;
name?: string;
}
export interface MappingItem {
source: string;
generatedLine: number;
generatedColumn: number;
originalLine: number;
originalColumn: number;
name: string;
}
export class SourceMapConsumer {
static GENERATED_ORDER: number;
static ORIGINAL_ORDER: number;
static GREATEST_LOWER_BOUND: number;
static LEAST_UPPER_BOUND: number;
constructor(rawSourceMap: RawSourceMap);
computeColumnSpans(): void;
originalPositionFor(generatedPosition: FindPosition): MappedPosition;
generatedPositionFor(originalPosition: SourceFindPosition): LineRange;
allGeneratedPositionsFor(originalPosition: MappedPosition): Position[];
hasContentsOfAllSources(): boolean;
sourceContentFor(source: string, returnNullOnMissing?: boolean): string;
eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void;
}
export interface Mapping {
generated: Position;
original: Position;
source: string;
name?: string;
}
export class SourceMapGenerator {
constructor(startOfSourceMap?: StartOfSourceMap);
static fromSourceMap(sourceMapConsumer: SourceMapConsumer): SourceMapGenerator;
addMapping(mapping: Mapping): void;
setSourceContent(sourceFile: string, sourceContent: string): void;
applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void;
toString(): string;
}
export interface CodeWithSourceMap {
code: string;
map: SourceMapGenerator;
}
export class SourceNode {
constructor();
constructor(line: number, column: number, source: string);
constructor(line: number, column: number, source: string, chunk?: string, name?: string);
static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode;
add(chunk: string): void;
prepend(chunk: string): void;
setSourceContent(sourceFile: string, sourceContent: string): void;
walk(fn: (chunk: string, mapping: MappedPosition) => void): void;
walkSourceContents(fn: (file: string, content: string) => void): void;
join(sep: string): SourceNode;
replaceRight(pattern: string, replacement: string): SourceNode;
toString(): string;
toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap;
}

View file

@ -0,0 +1,8 @@
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;

48
assets_old/node_modules/postcss/package.json generated vendored Normal file
View file

@ -0,0 +1,48 @@
{
"name": "postcss",
"version": "8.2.9",
"description": "Tool for transforming styles with JS plugins",
"engines": {
"node": "^10 || ^12 || >=14"
},
"exports": {
".": {
"require": "./lib/postcss.js",
"import": "./lib/postcss.mjs",
"types": "./lib/postcss.d.ts"
},
"./": "./"
},
"main": "./lib/postcss.js",
"types": "./lib/postcss.d.ts",
"keywords": [
"css",
"postcss",
"rework",
"preprocessor",
"parser",
"source map",
"transform",
"manipulation",
"transpiler"
],
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
"author": "Andrey Sitnik <andrey@sitnik.ru>",
"license": "MIT",
"homepage": "https://postcss.org/",
"repository": "postcss/postcss",
"dependencies": {
"colorette": "^1.2.2",
"nanoid": "^3.1.22",
"source-map": "^0.6.1"
},
"browser": {
"./lib/terminal-highlight": false,
"colorette": false,
"fs": false,
"path": false
}
}