pax_global_header 0000666 0000000 0000000 00000000064 14511774173 0014524 g ustar 00root root 0000000 0000000 52 comment=63c1388fc0ccf77408b405bcc133cbdb7ea6cb83
magic-string-0.30.5/ 0000775 0000000 0000000 00000000000 14511774173 0014175 5 ustar 00root root 0000000 0000000 magic-string-0.30.5/.eslintrc 0000664 0000000 0000000 00000002005 14511774173 0016016 0 ustar 00root root 0000000 0000000 {
"rules": {
"indent": [ 2, "tab", { "SwitchCase": 1 }],
"quotes": [ 2, "single" ],
"semi": [ 2, "always" ],
"keyword-spacing": [ 2, { "before": true, "after": true } ],
"space-before-blocks": [ 2, "always" ],
"no-mixed-spaces-and-tabs": [ 2, "smart-tabs" ],
"object-shorthand": [2, "always" ],
"no-const-assign": 2,
"no-unused-vars": 2,
"no-class-assign": 2,
"no-this-before-super": 2,
"no-var": 2,
"quote-props": [ 2, "as-needed" ],
"one-var": [ 2, "never" ],
"prefer-arrow-callback": 2,
"prefer-const": 2,
"arrow-spacing": 2,
"no-cond-assign": 0,
"no-constant-condition": 0
},
"env": {
"es6": true,
"browser": true
},
"globals": {
"DEBUG": true,
"process": true,
"Buffer": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
}
}
magic-string-0.30.5/.github/ 0000775 0000000 0000000 00000000000 14511774173 0015535 5 ustar 00root root 0000000 0000000 magic-string-0.30.5/.github/workflows/ 0000775 0000000 0000000 00000000000 14511774173 0017572 5 ustar 00root root 0000000 0000000 magic-string-0.30.5/.github/workflows/test.yml 0000664 0000000 0000000 00000001345 14511774173 0021277 0 ustar 00root root 0000000 0000000 name: Test
on:
push:
branches:
- main
- master
pull_request:
branches:
- main
- master
jobs:
build:
runs-on: ${{ matrix.os }}
timeout-minutes: 10
strategy:
matrix:
node_version: [14.x, 16.x, 18.x, 20.x]
os: [ubuntu-latest, windows-latest, macos-latest]
fail-fast: false
steps:
- uses: actions/checkout@v2
- name: Set node version to ${{ matrix.node_version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node_version }}
- name: Install
run: npm i
- name: Lint
if: ${{ matrix.node_version == '14.x' }}
run: npm run lint
- name: Test
run: npm test
magic-string-0.30.5/.gitignore 0000664 0000000 0000000 00000000115 14511774173 0016162 0 ustar 00root root 0000000 0000000 .DS_Store
node_modules
sandbox
.gobbl*
.tmp
!.babelrc
coverage
dist
yarn.lock magic-string-0.30.5/CHANGELOG.md 0000664 0000000 0000000 00000044566 14511774173 0016025 0 ustar 00root root 0000000 0000000 ## [0.30.5](https://github.com/rich-harris/magic-string/compare/v0.30.4...v0.30.5) (2023-10-12)
### Bug Fixes
* update `sourcesContent` type ([#263](https://github.com/rich-harris/magic-string/issues/263)) ([0e2068d](https://github.com/rich-harris/magic-string/commit/0e2068d6cee9d53c7a242b95f56ea99be3248142))
## [0.30.4](https://github.com/rich-harris/magic-string/compare/v0.30.3...v0.30.4) (2023-09-29)
### Bug Fixes
* correct mappings for update containing new line ([#261](https://github.com/rich-harris/magic-string/issues/261)) ([adaece9](https://github.com/rich-harris/magic-string/commit/adaece9f2370fd1266e89f2fc84c294e1f1b935c))
* use global `btoa`, support services worker, close [#258](https://github.com/rich-harris/magic-string/issues/258) ([#259](https://github.com/rich-harris/magic-string/issues/259)) ([2dea20b](https://github.com/rich-harris/magic-string/commit/2dea20bab7ca0f776013826074d474f476d281bc))
## [0.30.3](https://github.com/rich-harris/magic-string/compare/v0.30.2...v0.30.3) (2023-08-21)
### Bug Fixes
* trim replaced content with space ([#257](https://github.com/rich-harris/magic-string/issues/257)) ([8088f53](https://github.com/rich-harris/magic-string/commit/8088f53873da13c81877a05ab4549fce86f537b5))
## [0.30.2](https://github.com/rich-harris/magic-string/compare/v0.30.1...v0.30.2) (2023-07-28)
### Features
* hires boundary ([#255](https://github.com/rich-harris/magic-string/issues/255)) ([a63d5f2](https://github.com/rich-harris/magic-string/commit/a63d5f25308ff1965ae676e2aa5311417279e7d4))
## [0.30.1](https://github.com/rich-harris/magic-string/compare/v0.30.0...v0.30.1) (2023-07-04)
### Bug Fixes
* expose .d.ts as cjs version ([#253](https://github.com/rich-harris/magic-string/issues/253)) ([262e113](https://github.com/rich-harris/magic-string/commit/262e113ee25e9c7d317282b3015102ec932ae2f5))
# [0.30.0](https://github.com/rich-harris/magic-string/compare/v0.29.0...v0.30.0) (2023-02-22)
### Bug Fixes
* `null` is invalid for `sources` and `file` ([#242](https://github.com/rich-harris/magic-string/issues/242)) ([d4e9c31](https://github.com/rich-harris/magic-string/commit/d4e9c31082491cfa177b31ce725c9ce39491d549))
### Features
* add the ability to ignore-list sources ([#243](https://github.com/rich-harris/magic-string/issues/243)) ([e238f04](https://github.com/rich-harris/magic-string/commit/e238f04be31ec9a3e19b18b75bb5d859f9cb2654))
# [0.29.0](https://github.com/rich-harris/magic-string/compare/v0.28.0...v0.29.0) (2023-02-11)
### Features
* **x_google_ignoreList:** initial support for ignore lists ([3c711cd](https://github.com/rich-harris/magic-string/commit/3c711cd56de6c9735f92e41e457353005c2c0d1c))
# [0.28.0](https://github.com/rich-harris/magic-string/compare/v0.27.0...v0.28.0) (2023-02-11)
### Bug Fixes
* **typings:** sourcesContent may contain null ([#235](https://github.com/rich-harris/magic-string/issues/235)) ([c2b652a](https://github.com/rich-harris/magic-string/commit/c2b652a0d353f183ca991d0b59a7ad0250a52735))
# [0.27.0](https://github.com/rich-harris/magic-string/compare/v0.26.7...v0.27.0) (2022-12-03)
### Performance Improvements
* use @jridgewell/sourcemap-codec ([e68f3e0](https://github.com/rich-harris/magic-string/commit/e68f3e05fe6d87acc1c41eddae97fc32e004320b))
## [0.26.7](https://github.com/rich-harris/magic-string/compare/v0.26.6...v0.26.7) (2022-10-09)
### Bug Fixes
* avoid mutating provided options ([#227](https://github.com/rich-harris/magic-string/issues/227)) ([01d033e](https://github.com/rich-harris/magic-string/commit/01d033e6e8630ef1d0482d9a3899f1da2bf933d5))
## [0.26.6](https://github.com/rich-harris/magic-string/compare/v0.26.5...v0.26.6) (2022-10-05)
### Features
* add `update` method as safer alternative to `overwrite` ([#212](https://github.com/rich-harris/magic-string/issues/212)) ([9a312e3](https://github.com/rich-harris/magic-string/commit/9a312e37a02629f7496c6cfcf307832e991669a3))
## [0.26.5](https://github.com/rich-harris/magic-string/compare/v0.26.4...v0.26.5) (2022-09-30)
### Bug Fixes
* update typescript definition file to contain `replaceAll()` ([#224](https://github.com/rich-harris/magic-string/issues/224)) ([45a4921](https://github.com/rich-harris/magic-string/commit/45a49214ba244b906f4d20450debc8edcc06e2a8))
## [0.26.4](https://github.com/rich-harris/magic-string/compare/v0.26.3...v0.26.4) (2022-09-22)
### Features
* fix `.replace()` when searching string, add `.replaceAll()` ([#222](https://github.com/rich-harris/magic-string/issues/222)) ([04a05bd](https://github.com/rich-harris/magic-string/commit/04a05bdc9bf56e00e616a0ae07923fbd9b63fbd0))
### Performance Improvements
* avoiding use of Object.defineProperty in Chunk constructor ([#219](https://github.com/rich-harris/magic-string/issues/219)) ([130794b](https://github.com/rich-harris/magic-string/commit/130794bb8bfd9f21eb1f50c36a1da8eb5443d256))
## [0.26.3](https://github.com/rich-harris/magic-string/compare/v0.26.2...v0.26.3) (2022-08-30)
### Performance Improvements
* delay guess encoded ([#216](https://github.com/rich-harris/magic-string/issues/216)) ([69b13c7](https://github.com/rich-harris/magic-string/commit/69b13c7a09af742e4f31cf419e8f96e6db32ab5a))
## [0.26.2](https://github.com/rich-harris/magic-string/compare/v0.26.1...v0.26.2) (2022-05-11)
### Bug Fixes
* specify types in exports ([#214](https://github.com/rich-harris/magic-string/issues/214)) ([985e7b4](https://github.com/rich-harris/magic-string/commit/985e7b4d8a6fd5911d2ad2e6524999e9198a6b9f))
## [0.26.1](https://github.com/rich-harris/magic-string/compare/v0.26.0...v0.26.1) (2022-03-03)
### Bug Fixes
* **replace:** match replacer function signature with spec ([902541f](https://github.com/rich-harris/magic-string/commit/902541fdff3998e3c957908de10769d2af1a3c70))
# [0.26.0](https://github.com/rich-harris/magic-string/compare/v0.25.9...v0.26.0) (2022-03-03)
## BREAKING CHANGES
* Support of Node.js v10 is dropped. Now `magic-string` requires Node.js v12 or higher. ([#204](https://github.com/Rich-Harris/magic-string/pull/204))
* ESM bundle is now shipped with `.mjs` extension ([#197](https://github.com/Rich-Harris/magic-string/pull/197))
```diff
- "module": "dist/magic-string.es.js",
+ "module": "dist/magic-string.es.mjs",
+ "exports": {
+ "./package.json": "./package.json",
+ ".": {
+ "import": "./dist/magic-string.es.mjs",
+ "require": "./dist/magic-string.cjs.js"
+ }
+ },
```
### Features
* new `hasChanged` method ([#202](https://github.com/rich-harris/magic-string/issues/202)) ([5f2dba7](https://github.com/rich-harris/magic-string/commit/5f2dba72774c444538ed10aa5f2096104cb0b4bb))
* support `replace` method ([#203](https://github.com/rich-harris/magic-string/issues/203)) ([cd74ea2](https://github.com/rich-harris/magic-string/commit/cd74ea2e374f526079ae1a9b9f29bc9cc2fd2ac3))
## [0.25.9](https://github.com/rich-harris/magic-string/compare/v0.25.8...v0.25.9) (2022-03-03)
### Bug Fixes
* allowed overwrite across moved content preceded by split ([#192](https://github.com/rich-harris/magic-string/issues/192)) ([403fa86](https://github.com/rich-harris/magic-string/commit/403fa86b3dcc73f6b2eff177218b7bd4d3128f63))
* **types:** make options partial by default ([2815e77](https://github.com/rich-harris/magic-string/commit/2815e77dd20ff9f776282420eaacfb4aa9e70cd7))
* use defineProperty for appending prop in `storeName` ([#194](https://github.com/rich-harris/magic-string/issues/194)) ([96b7cd3](https://github.com/rich-harris/magic-string/commit/96b7cd37016c1e3fd7037b3910ae56f806a9c09f))
## [0.25.8](https://github.com/rich-harris/magic-string/compare/v0.25.7...v0.25.8) (2022-03-02)
### Bug Fixes
* **types:** mark `MagicString` options as optional ([#183](https://github.com/rich-harris/magic-string/issues/183)) ([15c3e66](https://github.com/rich-harris/magic-string/commit/15c3e6691a2cce79d5298af15fd8a2b02facef88))
## 0.25.7
* fix bundle mappings after remove and move in multiple sources ([#172](https://github.com/Rich-Harris/magic-string/issues/172))
## 0.25.6
* Use bitwise operators for small performance boost ([#171](https://github.com/Rich-Harris/magic-string/pull/171))
## 0.25.5
* Use a bitset to reduce memory consumption ([#167](https://github.com/Rich-Harris/magic-string/issues/167))
## 0.25.4
* Clone `intro` and `outro` ([#162](https://github.com/Rich-Harris/magic-string/issues/162))
## 0.25.3
* Fix typing of `SourceMap.version`.
## 0.25.2
* Remove deprecated `new Buffer(...)`
* Handle characters outside Latin1 range when generating a sourcemap in browser ([#154](https://github.com/Rich-Harris/magic-string/issues/154))
## 0.25.1
* Additional types for index.d.ts ([#148](https://github.com/Rich-Harris/magic-string/pull/148))
## 0.25.0
* Add `length` method ([#145](https://github.com/Rich-Harris/magic-string/pull/145))
* Fix trimming chunks with intro/outro ([#144](https://github.com/Rich-Harris/magic-string/pull/144))
## 0.24.1
* Add `lastLine` and `lastChar` methods ([#142](https://github.com/Rich-Harris/magic-string/pull/142))
## 0.24.0
* Add `isEmpty` methods ([#137](https://github.com/Rich-Harris/magic-string/pull/137))
* Fix a potential race condition ([#136](https://github.com/Rich-Harris/magic-string/pull/136))
* Fix CJS/ES bundles inlining `sourcemap-codec` in 0.23.2.
## 0.23.2
* Add `generateDecodedMap` methods ([#134](https://github.com/Rich-Harris/magic-string/pull/134))
## 0.23.1
* Performance ([#132](https://github.com/Rich-Harris/magic-string/pull/132))
## 0.23.0
* Use `sourcemap-codec` for improved performance ([#133](https://github.com/Rich-Harris/magic-string/pull/133))
## 0.22.5
* Add TypeScript interfaces used by rollup ([#131](https://github.com/Rich-Harris/magic-string/pull/131))
* Remove src directory from npm package
## 0.22.4
* `contentOnly` and `storeName` are both optional
## 0.22.3
* Add `original` to TS definitions
## 0.22.2
* Avoid `declare module` ([#127](https://github.com/Rich-Harris/magic-string/pull/127))
## 0.22.1
* Update TypeScript definitions ([#124](https://github.com/Rich-Harris/magic-string/pull/124))
## 0.22.0
* Prevent `overwrite` state corruption ([#115](https://github.com/Rich-Harris/magic-string/issues/115))
* Various bugfixes ([#126](https://github.com/Rich-Harris/magic-string/pull/126))
## 0.21.3
* Clone `indentExclusionRanges` correctly ([#122](https://github.com/Rich-Harris/magic-string/pull/122))
* Fix more typings ([#122](https://github.com/Rich-Harris/magic-string/pull/122))
## 0.21.2
* Add `default` property referencing self in index-legacy.js, to work around TypeScript bug ([#121](https://github.com/Rich-Harris/magic-string/pull/121))
## 0.21.1
* Add typings file to package
## 0.21.0
* Add TypeScript bindings ([#119](https://github.com/Rich-Harris/magic-string/pull/119))
## 0.20.0
* The fourth argument to `overwrite` is a `{storeName, contentOnly}` options object. `storeName: true` is equivalent to `true` before. `contentOnly` will preserve existing appends/prepends to the chunk in question
## 0.19.1
* Prevent overwrites across a split point (i.e. following a `move`)
* Implement `remove` separately to `overwrite`
## 0.19.0
* More accurate bundle sourcemaps ([#114](https://github.com/Rich-Harris/magic-string/pull/114))
## 0.18.0
* Optimisation – remove empty chunks following `overwrite` or `remove` ([#113](https://github.com/Rich-Harris/magic-string/pull/113))
## 0.17.0
* Add `appendLeft`, `appendRight`, `prependLeft`, `prependRight` methods ([#109](https://github.com/Rich-Harris/magic-string/issues/109))
* `insertLeft` and `insertRight` are deprecated in favour of `appendLeft` and `prependRight` respectively
## 0.16.0
* Include inserts in range for `overwrite` and `remove` operations ([#89](https://github.com/Rich-Harris/magic-string/pull/89))
* Make options optional for `bundle.generateMap(...)` ([#73](https://github.com/Rich-Harris/magic-string/pull/73))
## 0.15.2
* Generate correct bundle sourcemap with prepended/appended content
## 0.15.1
* Minor sourcemap fixes
## 0.15.0
* Use named export of `Bundle` in ES build, so ES consumers of magic-string can tree-shake it out
## 0.14.0
* Throw if overwrite of zero-length range is attempted
* Correctly handle redundant move operations
## 0.13.1
* Fix a bevy of `s.slice()` issues ([#62](https://github.com/Rich-Harris/magic-string/pull/62))
## 0.13.0
* Breaking: `insertAfter` is now `insertLeft`, `insertBefore` is now `insertRight`
* Breaking: `insert` is no longer available. Use `insertLeft` and `insertRight`
* Significant performance improvements
## 0.12.1
* Fix sourcemap generation with `insertAfter` and `insertBefore`
## 0.12.0
* Add `insertAfter` and `insertBefore` methods
## 0.11.4
* Fix two regression bugs with `trim()`
* More informative error message on illegal removals
## 0.11.3
* Fix trim methods to ensure correct sourcemaps with trimmed content ([#53](https://github.com/Rich-Harris/magic-string/pull/53))
## 0.11.2
* Support sourcemaps with moved content
## 0.11.1
* Use `findIndex` helper for 0.12 support
## 0.11.0
* Add experimental `move()` method
* Refactor internals to support `move()`
## 0.10.2
* Do not overwrite inserts at the end of patched ranges ([#35](https://github.com/Rich-Harris/magic-string/pull/35))
## 0.10.1
* Zero-length inserts are not removed on adjacent overwrites
## 0.10.0
* Complete rewrite, resulting in ~40x speed increase ([#30](https://github.com/Rich-Harris/magic-string/pull/30))
* Breaking – `magicString.locate` and `locateOrigin` are deprecated
* More forgiving rules about contiguous patches, and which ranges are valid with `magicString.slice(...)`
## 0.9.1
* Update deps
## 0.9.0
* Update build process
## 0.8.0
* Add an ES6 build, change default UMD build to CommonJS (but keeping existing UMD build with bundled dependencies)
* Make properties non-enumerable, for cleaner logging
* Update dependencies
## 0.7.0
* The `names` array is populated when generating sourcemaps, and mappings include name indices where appropriate ([#16](https://github.com/Rich-Harris/magic-string/issues/16))
* Replaced content is mapped correctly in sourcemaps ([#15](https://github.com/Rich-Harris/magic-string/issues/15))
## 0.6.6
* Adjust mappings correctly when removing replaced content
* Error correctly when removed characters are used as slice anchors
## 0.6.5
* Fix `jsnext:main` in package.json
## 0.6.4
* Fix bug with positive integer coercion
## 0.6.3
* Intro content is correctly indented
* Content following an intro with trailing newline is correctly indented
## 0.6.2
* Noop indents are still chainable (fixes bug introduced in 0.6.1)
## 0.6.1
* Indenting with an empty string is a noop
## 0.6.0
* Use rollup for bundling, instead of esperanto
## 0.5.3
* Correct sourcemap generation with bundles containing varied separators
* `s.clone()` clones indent exclusion ranges and sourcemap locations
## 0.5.2
* `s.slice()` accepts negative numbers, and the second argument can be omitted (means 'original string length'), just like `String.prototype.slice`
* More informative error message when trying to overwrite content illegally
## 0.5.1
* Allow bundle separator to be the empty string
* Indenting is handled correctly with empty string separator
## 0.5.0
* `s.replace()` is deprecated in favour of `s.overwrite()` (identical signature)
* `bundle.addSource()` can take a `MagicString` instance as its sole argument, for convenience
* The `options` in `new MagicString(str, options)` can include `filename` and `indentExclusionRanges` options, which will be used when bundling
* New method: `s.snip( start, end )`
## 0.4.9
* `file` option is optional when generating a bundle sourcemap
## 0.4.7
* Repeated insertions at position 0 behave the same as other positions ([#10](https://github.com/Rich-Harris/magic-string/pull/10))
## 0.4.6
* Overlapping ranges can be removed
* Non-string content is rejected ([#9](https://github.com/Rich-Harris/magic-string/pull/9))
## 0.4.5
* Implement `source.addSourcemapLocation()`
## 0.4.4
* Another Windows fix, this time for file paths when bundling
## 0.4.3
* Handle Windows-style CRLF newlines when determining whether a line is empty
## 0.4.2
* Fix typo in package.json (d'oh again)
* Use only relative paths for internal modules - makes bundling with dependents (i.e. esperanto) possible
## 0.4.1
* Includes correct files in npm package (d'oh)
## 0.4.0
* Using experimental Esperanto feature ([esperantojs/esperanto#68](https://github.com/esperantojs/esperanto/issues/68)) to generate version with `vlq` dependency included
## 0.3.1
* Fixes a bug whereby multiple insertions at the same location would cause text to repeat ([#5](https://github.com/Rich-Harris/magic-string/issues/5))
## 0.3.0
* Breaking change - `source.indentStr` is `null` if no lines are indented. Use `source.getIndentString()` for the old behaviour (guess, and if no lines are indented, return `\t`)
* `bundle.getIndentString()` ignores sources with no indented lines when guessing indentation ([#3](https://github.com/Rich-Harris/magic-string/issues/3))
## 0.2.7
* `source.trimLines()` removes empty lines from start/end of source, leaving other whitespace untouched
* Indentation is not added to an empty source
## 0.2.6
* Performance improvement - adjustments are only made when necessary
## 0.2.5
* Single spaces are ignored when guessing indentation - experience shows these are more likely to be e.g. JSDoc comments than actual indentation
* `bundle.addSource()` can take an `indentExclusionRanges` option
## 0.2.4
* Empty lines are not indented
## 0.2.3
* Fixes edge case with bundle sourcemaps
## 0.2.2
* Make `sources` paths in sourcemaps relative to `options.file`
## 0.2.1
* Minor fix for `bundle.indent()`
## 0.2.0
* Implement `MagicString.Bundle` for concatenating magic strings
## 0.1.10
* Fix sourcemap encoding
## 0.1.9
* Better performance when indenting large chunks of code
## 0.1.8
* Sourcemaps generated with `s.generateMap()` have a `toUrl()` method that generates a DataURI
## 0.1.7
* Implement `s.insert( index, content )` - roughly equivalent to `s.replace( index, index, content )`
## 0.1.6
* Version bump for npm's benefit
## 0.1.5
* `s.indent({ exclude: [ x, y ] })` prevents lines between (original) characters `x` and `y` from being indented. Multiple exclusion ranges are also supported (e.g. `exclude: [[a, b], [c, d]]`)
## 0.1.4
* `s.locate()` doesn't throw out-of-bound error if index is equal to original string's length
## 0.1.3
* `s.trim()` returns `this` (i.e. is chainable)
## 0.1.2
* Implement `s.slice()`
## 0.1.1
* Implement `s.trim()`
## 0.1.0
* First release
magic-string-0.30.5/LICENSE 0000664 0000000 0000000 00000002033 14511774173 0015200 0 ustar 00root root 0000000 0000000 Copyright 2018 Rich Harris
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.
magic-string-0.30.5/README.md 0000664 0000000 0000000 00000027111 14511774173 0015456 0 ustar 00root root 0000000 0000000 # magic-string
Suppose you have some source code. You want to make some light modifications to it - replacing a few characters here and there, wrapping it with a header and footer, etc - and ideally you'd like to generate a [source map](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/) at the end of it. You've thought about using something like [recast](https://github.com/benjamn/recast) (which allows you to generate an AST from some JavaScript, manipulate it, and reprint it with a sourcemap without losing your comments and formatting), but it seems like overkill for your needs (or maybe the source code isn't JavaScript).
Your requirements are, frankly, rather niche. But they're requirements that I also have, and for which I made magic-string. It's a small, fast utility for manipulating strings and generating sourcemaps.
## Installation
magic-string works in both node.js and browser environments. For node, install with npm:
```bash
npm i magic-string
```
To use in browser, grab the [magic-string.umd.js](https://unpkg.com/magic-string/dist/magic-string.umd.js) file and add it to your page:
```html
```
(It also works with various module systems, if you prefer that sort of thing - it has a dependency on [vlq](https://github.com/Rich-Harris/vlq).)
## Usage
These examples assume you're in node.js, or something similar:
```js
import MagicString from 'magic-string';
import fs from 'fs'
const s = new MagicString('problems = 99');
s.update(0, 8, 'answer');
s.toString(); // 'answer = 99'
s.update(11, 13, '42'); // character indices always refer to the original string
s.toString(); // 'answer = 42'
s.prepend('var ').append(';'); // most methods are chainable
s.toString(); // 'var answer = 42;'
const map = s.generateMap({
source: 'source.js',
file: 'converted.js.map',
includeContent: true
}); // generates a v3 sourcemap
fs.writeFileSync('converted.js', s.toString());
fs.writeFileSync('converted.js.map', map.toString());
```
You can pass an options argument:
```js
const s = new MagicString(someCode, {
// these options will be used if you later call `bundle.addSource( s )` - see below
filename: 'foo.js',
indentExclusionRanges: [/*...*/],
// market source as ignore in DevTools, see below #Bundling
ignoreList: false
});
```
## Methods
### s.addSourcemapLocation( index )
Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is `false` (see below).
### s.append( content )
Appends the specified content to the end of the string. Returns `this`.
### s.appendLeft( index, content )
Appends the specified `content` at the `index` in the original string. If a range *ending* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependLeft(...)`.
### s.appendRight( index, content )
Appends the specified `content` at the `index` in the original string. If a range *starting* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependRight(...)`.
### s.clone()
Does what you'd expect.
### s.generateDecodedMap( options )
Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. See `generateMap` documentation below for options details. Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
### s.generateMap( options )
Generates a [version 3 sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). All options are, well, optional:
* `file` - the filename where you plan to write the sourcemap
* `source` - the filename of the file containing the original source
* `includeContent` - whether to include the original content in the map's `sourcesContent` array
* `hires` - whether the mapping should be high-resolution. Hi-res mappings map every single character, meaning (for example) your devtools will always be able to pinpoint the exact location of function calls and so on. With lo-res mappings, devtools may only be able to identify the correct line - but they're quicker to generate and less bulky. You can also set `"boundary"` to generate a semi-hi-res mappings segmented per word boundary instead of per character, suitable for string semantics that are separated by words. If sourcemap locations have been specified with `s.addSourcemapLocation()`, they will be used here.
The returned sourcemap has two (non-enumerable) methods attached for convenience:
* `toString` - returns the equivalent of `JSON.stringify(map)`
* `toUrl` - returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
```js
code += '\n//# sourceMappingURL=' + map.toUrl();
```
### s.hasChanged()
Indicates if the string has been changed.
### s.indent( prefix[, options] )
Prefixes each line of the string with `prefix`. If `prefix` is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. Returns `this`.
The `options` argument can have an `exclude` property, which is an array of `[start, end]` character ranges. These ranges will be excluded from the indentation - useful for (e.g.) multiline strings.
### s.insertLeft( index, content )
**DEPRECATED** since 0.17 – use `s.appendLeft(...)` instead
### s.insertRight( index, content )
**DEPRECATED** since 0.17 – use `s.prependRight(...)` instead
### s.isEmpty()
Returns true if the resulting source is empty (disregarding white space).
### s.locate( index )
**DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30)
### s.locateOrigin( index )
**DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30)
### s.move( start, end, index )
Moves the characters from `start` and `end` to `index`. Returns `this`.
### s.overwrite( start, end, content[, options] )
Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in that range. The same restrictions as `s.remove()` apply. Returns `this`.
The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and a `contentOnly` property which determines whether only the content is overwritten, or anything that was appended/prepended to the range as well.
It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
### s.prepend( content )
Prepends the string with the specified content. Returns `this`.
### s.prependLeft ( index, content )
Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
### s.prependRight ( index, content )
Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
### s.replace( regexpOrString, substitution )
String replacement with RegExp or string. When using a RegExp, replacer function is also supported. Returns `this`.
```ts
import MagicString from 'magic-string'
const s = new MagicString(source)
s.replace('foo', 'bar')
s.replace(/foo/g, 'bar')
s.replace(/(\w)(\d+)/g, (_, $1, $2) => $1.toUpperCase() + $2)
```
The differences from [`String.replace`]((https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)):
- It will always match against the **original string**
- It mutates the magic string state (use `.clone()` to be immutable)
### s.replaceAll( regexpOrString, substitution )
Same as `s.replace`, but replace all matched strings instead of just one.
If `substitution` is a regex, then it must have the global (`g`) flag set, or a `TypeError` is thrown. Matches the behavior of the bultin [`String.property.replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll).
### s.remove( start, end )
Removes the characters from `start` to `end` (of the original string, **not** the generated string). Removing the same content twice, or making removals that partially overlap, will cause an error. Returns `this`.
### s.slice( start, end )
Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. Throws error if the indices are for characters that were already removed.
### s.snip( start, end )
Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
### s.toString()
Returns the generated string.
### s.trim([ charType ])
Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. Returns `this`.
### s.trimStart([ charType ])
Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. Returns `this`.
### s.trimEnd([ charType ])
Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. Returns `this`.
### s.trimLines()
Removes empty lines from the start and end. Returns `this`.
### s.update( start, end, content[, options] )
Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. Returns `this`.
The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and an `overwrite` property which defaults to `false` and determines whether anything that was appended/prepended to the range will be overwritten along with the original content.
`s.update(start, end, content)` is equivalent to `s.overwrite(start, end, content, { contentOnly: true })`.
## Bundling
To concatenate several sources, use `MagicString.Bundle`:
```js
const bundle = new MagicString.Bundle();
bundle.addSource({
filename: 'foo.js',
content: new MagicString('var answer = 42;')
});
bundle.addSource({
filename: 'bar.js',
content: new MagicString('console.log( answer )')
});
// Sources can be marked as ignore-listed, which provides a hint to debuggers
// to not step into this code and also don't show the source files depending
// on user preferences.
bundle.addSource({
filename: 'some-3rdparty-library.js',
content: new MagicString('function myLib(){}'),
ignoreList: false // <--
})
// Advanced: a source can include an `indentExclusionRanges` property
// alongside `filename` and `content`. This will be passed to `s.indent()`
// - see documentation above
bundle.indent() // optionally, pass an indent string, otherwise it will be guessed
.prepend('(function () {\n')
.append('}());');
bundle.toString();
// (function () {
// var answer = 42;
// console.log( answer );
// }());
// options are as per `s.generateMap()` above
const map = bundle.generateMap({
file: 'bundle.js',
includeContent: true,
hires: true
});
```
As an alternative syntax, if you a) don't have `filename` or `indentExclusionRanges` options, or b) passed those in when you used `new MagicString(...)`, you can simply pass the `MagicString` instance itself:
```js
const bundle = new MagicString.Bundle();
const source = new MagicString(someCode, {
filename: 'foo.js'
});
bundle.addSource(source);
```
## License
MIT
magic-string-0.30.5/benchmark/ 0000775 0000000 0000000 00000000000 14511774173 0016127 5 ustar 00root root 0000000 0000000 magic-string-0.30.5/benchmark/data-min.js 0000664 0000000 0000000 00000043247 14511774173 0020171 0 ustar 00root root 0000000 0000000 /* eslint-disable */
import{encode as k}from"sourcemap-codec";class p{constructor(t){this.bits=t instanceof p?t.bits.slice():[]}add(t){this.bits[t>>5]|=1<<(t&31)}has(t){return!!(this.bits[t>>5]&1<<(t&31))}}class g{constructor(t,e,n){this.start=t,this.end=e,this.original=n,this.intro="",this.outro="",this.content=n,this.storeName=!1,this.edited=!1,Object.defineProperties(this,{previous:{writable:!0,value:null},next:{writable:!0,value:null}})}appendLeft(t){this.outro+=t}appendRight(t){this.intro=this.intro+t}clone(){const t=new g(this.start,this.end,this.original);return t.intro=this.intro,t.outro=this.outro,t.content=this.content,t.storeName=this.storeName,t.edited=this.edited,t}contains(t){return this.start{throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.")};typeof window<"u"&&typeof window.btoa=="function"?w=l=>window.btoa(unescape(encodeURIComponent(l))):typeof Buffer=="function"&&(w=l=>Buffer.from(l,"utf-8").toString("base64"));class b{constructor(t){this.version=3,this.file=t.file,this.sources=t.sources,this.sourcesContent=t.sourcesContent,this.names=t.names,this.mappings=k(t.mappings)}toString(){return JSON.stringify(this)}toUrl(){return"data:application/json;charset=utf-8;base64,"+w(this.toString())}}function L(l){const t=l.split(`
`),e=t.filter(r=>/^\t+/.test(r)),n=t.filter(r=>/^ {2,}/.test(r));if(e.length===0&&n.length===0)return null;if(e.length>=n.length)return" ";const i=n.reduce((r,s)=>{const h=/^ +/.exec(s)[0].length;return Math.min(h,r)},1/0);return new Array(i+1).join(" ")}function E(l,t){const e=l.split(/[/\\]/),n=t.split(/[/\\]/);for(e.pop();e[0]===n[0];)e.shift(),n.shift();if(e.length){let i=e.length;for(;i--;)e[i]=".."}return e.concat(n).join("/")}const R=Object.prototype.toString;function x(l){return R.call(l)==="[object Object]"}function C(l){const t=l.split(`
`),e=[];for(let n=0,i=0;n>1;i=0&&r.push(i),this.rawSegments.push(r)}else this.pending&&this.rawSegments.push(this.pending);this.advance(e),this.pending=null}addUneditedChunk(t,e,n,i,r){let s=e.start,h=!0;for(;s1){for(let n=0;n{const h=r(s.start);s.intro.length&&i.advance(s.intro),s.edited?i.addEdit(e,s.content,h,s.storeName?n.indexOf(s.original):-1):i.addUneditedChunk(e,s,this.original,h,this.sourcemapLocations),s.outro.length&&i.advance(s.outro)}),{file:t.file?t.file.split(/[/\\]/).pop():null,sources:[t.source?E(t.file||"",t.source):null],sourcesContent:t.includeContent?[this.original]:[null],names:n,mappings:i.raw}}generateMap(t){return new b(this.generateDecodedMap(t))}getIndentString(){return this.indentStr===null?" ":this.indentStr}indent(t,e){const n=/^[^\r\n]/gm;if(x(t)&&(e=t,t=void 0),t=t!==void 0?t:this.indentStr||" ",t==="")return this;e=e||{};const i={};e.exclude&&(typeof e.exclude[0]=="number"?[e.exclude]:e.exclude).forEach(u=>{for(let m=u[0];mr?`${t}${a}`:(r=!0,a);this.intro=this.intro.replace(n,s);let h=0,o=this.firstChunk;for(;o;){const a=o.end;if(o.edited)i[h]||(o.content=o.content.replace(n,s),o.content.length&&(r=o.content[o.content.length-1]===`
`));else for(h=o.start;h=t&&n<=e)throw new Error("Cannot move a selection inside itself");this._split(t),this._split(e),this._split(n);const i=this.byStart[t],r=this.byEnd[e],s=i.previous,h=r.next,o=this.byStart[n];if(!o&&r===this.lastChunk)return this;const a=o?o.previous:this.lastChunk;return s&&(s.next=h),h&&(h.previous=s),a&&(a.next=i),o&&(o.previous=r),i.previous||(this.firstChunk=r.next),r.next||(this.lastChunk=i.previous,this.lastChunk.next=null),i.previous=a,r.next=o||null,a||(this.firstChunk=i),o||(this.lastChunk=r),this}overwrite(t,e,n,i){if(typeof n!="string")throw new TypeError("replacement content must be a string");for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length;if(e>this.original.length)throw new Error("end is out of bounds");if(t===e)throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");this._split(t),this._split(e),i===!0&&(c.storeName||(console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"),c.storeName=!0),i={storeName:!0});const r=i!==void 0?i.storeName:!1,s=i!==void 0?i.contentOnly:!1;if(r){const a=this.original.slice(t,e);Object.defineProperty(this.storedNames,a,{writable:!0,value:!0,enumerable:!0})}const h=this.byStart[t],o=this.byEnd[e];if(h){let a=h;for(;a!==o;){if(a.next!==this.byStart[a.end])throw new Error("Cannot overwrite across a split point");a=a.next,a.edit("",!1)}h.edit(n,r,s)}else{const a=new g(t,e,"").edit(n,r);o.next=a,a.previous=o}return this}prepend(t){if(typeof t!="string")throw new TypeError("outro content must be a string");return this.intro=t+this.intro,this}prependLeft(t,e){if(typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);const n=this.byEnd[t];return n?n.prependLeft(e):this.intro=e+this.intro,this}prependRight(t,e){if(typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);const n=this.byStart[t];return n?n.prependRight(e):this.outro=e+this.outro,this}remove(t,e){for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length;if(t===e)return this;if(t<0||e>this.original.length)throw new Error("Character is out of bounds");if(t>e)throw new Error("end must be greater than start");this._split(t),this._split(e);let n=this.byStart[t];for(;n;)n.intro="",n.outro="",n.edit(""),n=e>n.end?this.byStart[n.end]:null;return this}lastChar(){if(this.outro.length)return this.outro[this.outro.length-1];let t=this.lastChunk;do{if(t.outro.length)return t.outro[t.outro.length-1];if(t.content.length)return t.content[t.content.length-1];if(t.intro.length)return t.intro[t.intro.length-1]}while(t=t.previous);return this.intro.length?this.intro[this.intro.length-1]:""}lastLine(){let t=this.outro.lastIndexOf(d);if(t!==-1)return this.outro.substr(t+1);let e=this.outro,n=this.lastChunk;do{if(n.outro.length>0){if(t=n.outro.lastIndexOf(d),t!==-1)return n.outro.substr(t+1)+e;e=n.outro+e}if(n.content.length>0){if(t=n.content.lastIndexOf(d),t!==-1)return n.content.substr(t+1)+e;e=n.content+e}if(n.intro.length>0){if(t=n.intro.lastIndexOf(d),t!==-1)return n.intro.substr(t+1)+e;e=n.intro+e}}while(n=n.previous);return t=this.intro.lastIndexOf(d),t!==-1?this.intro.substr(t+1)+e:this.intro+e}slice(t=0,e=this.original.length){for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length;let n="",i=this.firstChunk;for(;i&&(i.start>t||i.end<=t);){if(i.start=e)return n;i=i.next}if(i&&i.edited&&i.start!==t)throw new Error(`Cannot use replaced character ${t} as slice start anchor.`);const r=i;for(;i;){i.intro&&(r!==i||i.start===t)&&(n+=i.intro);const s=i.start=e;if(s&&i.edited&&i.end!==e)throw new Error(`Cannot use replaced character ${e} as slice end anchor.`);const h=r===i?t-i.start:0,o=s?i.content.length+e-i.end:i.content.length;if(n+=i.content.slice(h,o),i.outro&&(!s||i.end===e)&&(n+=i.outro),s)break;i=i.next}return n}snip(t,e){const n=this.clone();return n.remove(0,t),n.remove(e,n.original.length),n}_split(t){if(this.byStart[t]||this.byEnd[t])return;let e=this.lastSearchedChunk;const n=t>e.end;for(;e;){if(e.contains(t))return this._splitChunk(e,t);e=n?this.byStart[e.end]:this.byEnd[e.start]}}_splitChunk(t,e){if(t.edited&&t.content.length){const i=C(this.original)(e);throw new Error(`Cannot split a chunk that has already been edited (${i.line}:${i.column} \u2013 "${t.original}")`)}const n=t.split(e);return this.byEnd[e]=t,this.byStart[e]=n,this.byEnd[n.end]=n,t===this.lastChunk&&(this.lastChunk=n),this.lastSearchedChunk=t,!0}toString(){let t=this.intro,e=this.firstChunk;for(;e;)t+=e.toString(),e=e.next;return t+this.outro}isEmpty(){let t=this.firstChunk;do if(t.intro.length&&t.intro.trim()||t.content.length&&t.content.trim()||t.outro.length&&t.outro.trim())return!1;while(t=t.next);return!0}length(){let t=this.firstChunk,e=0;do e+=t.intro.length+t.content.length+t.outro.length;while(t=t.next);return e}trimLines(){return this.trim("[\\r\\n]")}trim(t){return this.trimStart(t).trimEnd(t)}trimEndAborted(t){const e=new RegExp((t||"\\s")+"+$");if(this.outro=this.outro.replace(e,""),this.outro.length)return!0;let n=this.lastChunk;do{const i=n.end,r=n.trimEnd(e);if(n.end!==i&&(this.lastChunk===n&&(this.lastChunk=n.next),this.byEnd[n.end]=n,this.byStart[n.next.start]=n.next,this.byEnd[n.next.end]=n.next),r)return!0;n=n.previous}while(n);return!1}trimEnd(t){return this.trimEndAborted(t),this}trimStartAborted(t){const e=new RegExp("^"+(t||"\\s")+"+");if(this.intro=this.intro.replace(e,""),this.intro.length)return!0;let n=this.firstChunk;do{const i=n.end,r=n.trimStart(e);if(n.end!==i&&(n===this.lastChunk&&(this.lastChunk=n.next),this.byEnd[n.end]=n,this.byStart[n.next.start]=n.next,this.byEnd[n.next.end]=n.next),r)return!0;n=n.next}while(n);return!1}trimStart(t){return this.trimStartAborted(t),this}hasChanged(){return this.original!==this.toString()}replace(t,e){function n(r,s){return typeof e=="string"?e.replace(/\$(\$|&|\d+)/g,(h,o)=>o==="$"?"$":o==="&"?r[0]:+o{s.index!=null&&this.overwrite(s.index,s.index+s[0].length,n(s,this.original))});else{const r=this.original.match(t);r&&r.index!=null&&this.overwrite(r.index,r.index+r[0].length,n(r,this.original))}return this}}const v=Object.prototype.hasOwnProperty;class S{constructor(t={}){this.intro=t.intro||"",this.separator=t.separator!==void 0?t.separator:`
`,this.sources=[],this.uniqueSources=[],this.uniqueSourceIndexByFilename={}}addSource(t){if(t instanceof f)return this.addSource({content:t,filename:t.filename,separator:this.separator});if(!x(t)||!t.content)throw new Error("bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`");if(["filename","indentExclusionRanges","separator"].forEach(e=>{v.call(t,e)||(t[e]=t.content[e])}),t.separator===void 0&&(t.separator=this.separator),t.filename)if(!v.call(this.uniqueSourceIndexByFilename,t.filename))this.uniqueSourceIndexByFilename[t.filename]=this.uniqueSources.length,this.uniqueSources.push({filename:t.filename,content:t.content.original});else{const e=this.uniqueSources[this.uniqueSourceIndexByFilename[t.filename]];if(t.content.original!==e.content)throw new Error(`Illegal source: same filename (${t.filename}), different contents`)}return this.sources.push(t),this}append(t,e){return this.addSource({content:new f(t),separator:e&&e.separator||""}),this}clone(){const t=new S({intro:this.intro,separator:this.separator});return this.sources.forEach(e=>{t.addSource({filename:e.filename,content:e.content.clone(),separator:e.separator})}),t}generateDecodedMap(t={}){const e=[];this.sources.forEach(i=>{Object.keys(i.content.storedNames).forEach(r=>{~e.indexOf(r)||e.push(r)})});const n=new y(t.hires);return this.intro&&n.advance(this.intro),this.sources.forEach((i,r)=>{r>0&&n.advance(this.separator);const s=i.filename?this.uniqueSourceIndexByFilename[i.filename]:-1,h=i.content,o=C(h.original);h.intro&&n.advance(h.intro),h.firstChunk.eachNext(a=>{const u=o(a.start);a.intro.length&&n.advance(a.intro),i.filename?a.edited?n.addEdit(s,a.content,u,a.storeName?e.indexOf(a.original):-1):n.addUneditedChunk(s,a,h.original,u,h.sourcemapLocations):n.advance(a.content),a.outro.length&&n.advance(a.outro)}),h.outro&&n.advance(h.outro)}),{file:t.file?t.file.split(/[/\\]/).pop():null,sources:this.uniqueSources.map(i=>t.file?E(t.file,i.filename):i.filename),sourcesContent:this.uniqueSources.map(i=>t.includeContent?i.content:null),names:e,mappings:n.raw}}generateMap(t){return new b(this.generateDecodedMap(t))}getIndentString(){const t={};return this.sources.forEach(e=>{const n=e.content.indentStr;n!==null&&(t[n]||(t[n]=0),t[n]+=1)}),Object.keys(t).sort((e,n)=>t[e]-t[n])[0]||" "}indent(t){if(arguments.length||(t=this.getIndentString()),t==="")return this;let e=!this.intro||this.intro.slice(-1)===`
`;return this.sources.forEach((n,i)=>{const r=n.separator!==void 0?n.separator:this.separator,s=e||i>0&&/\r?\n$/.test(r);n.content.indent(t,{exclude:n.indentExclusionRanges,indentStart:s}),e=n.content.lastChar()===`
`}),this.intro&&(this.intro=t+this.intro.replace(/^[^\n]/gm,(n,i)=>i>0?t+n:n)),this}prepend(t){return this.intro=t+this.intro,this}toString(){const t=this.sources.map((e,n)=>{const i=e.separator!==void 0?e.separator:this.separator;return(n>0?i:"")+e.content.toString()}).join("");return this.intro+t}isEmpty(){return!(this.intro.length&&this.intro.trim()||this.sources.some(t=>!t.content.isEmpty()))}length(){return this.sources.reduce((t,e)=>t+e.content.length(),this.intro.length)}trimLines(){return this.trim("[\\r\\n]")}trim(t){return this.trimStart(t).trimEnd(t)}trimStart(t){const e=new RegExp("^"+(t||"\\s")+"+");if(this.intro=this.intro.replace(e,""),!this.intro){let n,i=0;do if(n=this.sources[i++],!n)break;while(!n.content.trimStartAborted(t))}return this}trimEnd(t){const e=new RegExp((t||"\\s")+"+$");let n,i=this.sources.length-1;do if(n=this.sources[i--],!n){this.intro=this.intro.replace(e,"");break}while(!n.content.trimEndAborted(t));return this}}export{S as Bundle,b as SourceMap,f as default};
magic-string-0.30.5/benchmark/data.js 0000664 0000000 0000000 00000101222 14511774173 0017374 0 ustar 00root root 0000000 0000000 /* eslint-disable */
import { encode } from "sourcemap-codec";
class BitSet {
constructor(arg) {
this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
}
add(n2) {
this.bits[n2 >> 5] |= 1 << (n2 & 31);
}
has(n2) {
return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
}
}
class Chunk {
constructor(start, end, content) {
this.start = start;
this.end = end;
this.original = content;
this.intro = "";
this.outro = "";
this.content = content;
this.storeName = false;
this.edited = false;
Object.defineProperties(this, {
previous: { writable: true, value: null },
next: { writable: true, value: null }
});
}
appendLeft(content) {
this.outro += content;
}
appendRight(content) {
this.intro = this.intro + content;
}
clone() {
const chunk = new Chunk(this.start, this.end, this.original);
chunk.intro = this.intro;
chunk.outro = this.outro;
chunk.content = this.content;
chunk.storeName = this.storeName;
chunk.edited = this.edited;
return chunk;
}
contains(index) {
return this.start < index && index < this.end;
}
eachNext(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.next;
}
}
eachPrevious(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.previous;
}
}
edit(content, storeName, contentOnly) {
this.content = content;
if (!contentOnly) {
this.intro = "";
this.outro = "";
}
this.storeName = storeName;
this.edited = true;
return this;
}
prependLeft(content) {
this.outro = content + this.outro;
}
prependRight(content) {
this.intro = content + this.intro;
}
split(index) {
const sliceIndex = index - this.start;
const originalBefore = this.original.slice(0, sliceIndex);
const originalAfter = this.original.slice(sliceIndex);
this.original = originalBefore;
const newChunk = new Chunk(index, this.end, originalAfter);
newChunk.outro = this.outro;
this.outro = "";
this.end = index;
if (this.edited) {
newChunk.edit("", false);
this.content = "";
} else {
this.content = originalBefore;
}
newChunk.next = this.next;
if (newChunk.next)
newChunk.next.previous = newChunk;
newChunk.previous = this;
this.next = newChunk;
return newChunk;
}
toString() {
return this.intro + this.content + this.outro;
}
trimEnd(rx) {
this.outro = this.outro.replace(rx, "");
if (this.outro.length)
return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
this.split(this.start + trimmed.length).edit("", void 0, true);
}
return true;
} else {
this.edit("", void 0, true);
this.intro = this.intro.replace(rx, "");
if (this.intro.length)
return true;
}
}
trimStart(rx) {
this.intro = this.intro.replace(rx, "");
if (this.intro.length)
return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
this.split(this.end - trimmed.length);
this.edit("", void 0, true);
}
return true;
} else {
this.edit("", void 0, true);
this.outro = this.outro.replace(rx, "");
if (this.outro.length)
return true;
}
}
}
let _btoa = () => {
throw new Error("Unsupported environment: `btoa` or `Buffer` should be supported.");
};
if (typeof Buffer === "function") {
_btoa = (str) => Buffer.from(str, "utf-8").toString("base64");
} else if (typeof btoa === "function") {
_btoa = btoa;
}
class SourceMap {
constructor(properties) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = encode(properties.mappings);
}
toString() {
return JSON.stringify(this);
}
toUrl() {
return "data:application/json;charset=utf-8;base64," + _btoa(this.toString());
}
}
function guessIndent(code) {
const lines = code.split("\n");
const tabbed = lines.filter((line) => /^\t+/.test(line));
const spaced = lines.filter((line) => /^ {2,}/.test(line));
if (tabbed.length === 0 && spaced.length === 0) {
return null;
}
if (tabbed.length >= spaced.length) {
return " ";
}
const min = spaced.reduce((previous, current) => {
const numSpaces = /^ +/.exec(current)[0].length;
return Math.min(numSpaces, previous);
}, Infinity);
return new Array(min + 1).join(" ");
}
function getRelativePath(from, to) {
const fromParts = from.split(/[/\\]/);
const toParts = to.split(/[/\\]/);
fromParts.pop();
while (fromParts[0] === toParts[0]) {
fromParts.shift();
toParts.shift();
}
if (fromParts.length) {
let i = fromParts.length;
while (i--)
fromParts[i] = "..";
}
return fromParts.concat(toParts).join("/");
}
const toString = Object.prototype.toString;
function isObject(thing) {
return toString.call(thing) === "[object Object]";
}
function getLocator(source) {
const originalLines = source.split("\n");
const lineOffsets = [];
for (let i = 0, pos = 0; i < originalLines.length; i++) {
lineOffsets.push(pos);
pos += originalLines[i].length + 1;
}
return function locate(index) {
let i = 0;
let j = lineOffsets.length;
while (i < j) {
const m = i + j >> 1;
if (index < lineOffsets[m]) {
j = m;
} else {
i = m + 1;
}
}
const line = i - 1;
const column = index - lineOffsets[line];
return { line, column };
};
}
class Mappings {
constructor(hires) {
this.hires = hires;
this.generatedCodeLine = 0;
this.generatedCodeColumn = 0;
this.raw = [];
this.rawSegments = this.raw[this.generatedCodeLine] = [];
this.pending = null;
}
addEdit(sourceIndex, content, loc, nameIndex) {
if (content.length) {
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
if (nameIndex >= 0) {
segment.push(nameIndex);
}
this.rawSegments.push(segment);
} else if (this.pending) {
this.rawSegments.push(this.pending);
}
this.advance(content);
this.pending = null;
}
addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
let originalCharIndex = chunk.start;
let first = true;
while (originalCharIndex < chunk.end) {
if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
}
if (original[originalCharIndex] === "\n") {
loc.line += 1;
loc.column = 0;
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
first = true;
} else {
loc.column += 1;
this.generatedCodeColumn += 1;
first = false;
}
originalCharIndex += 1;
}
this.pending = null;
}
advance(str) {
if (!str)
return;
const lines = str.split("\n");
if (lines.length > 1) {
for (let i = 0; i < lines.length - 1; i++) {
this.generatedCodeLine++;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
}
this.generatedCodeColumn = 0;
}
this.generatedCodeColumn += lines[lines.length - 1].length;
}
}
const n = "\n";
const warned = {
insertLeft: false,
insertRight: false,
storeName: false
};
class MagicString {
constructor(string, options = {}) {
const chunk = new Chunk(0, string.length, string);
Object.defineProperties(this, {
original: { writable: true, value: string },
outro: { writable: true, value: "" },
intro: { writable: true, value: "" },
firstChunk: { writable: true, value: chunk },
lastChunk: { writable: true, value: chunk },
lastSearchedChunk: { writable: true, value: chunk },
byStart: { writable: true, value: {} },
byEnd: { writable: true, value: {} },
filename: { writable: true, value: options.filename },
indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
sourcemapLocations: { writable: true, value: new BitSet() },
storedNames: { writable: true, value: {} },
indentStr: { writable: true, value: guessIndent(string) }
});
this.byStart[0] = chunk;
this.byEnd[string.length] = chunk;
}
addSourcemapLocation(char) {
this.sourcemapLocations.add(char);
}
append(content) {
if (typeof content !== "string")
throw new TypeError("outro content must be a string");
this.outro += content;
return this;
}
appendLeft(index, content) {
if (typeof content !== "string")
throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) {
chunk.appendLeft(content);
} else {
this.intro += content;
}
return this;
}
appendRight(index, content) {
if (typeof content !== "string")
throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) {
chunk.appendRight(content);
} else {
this.outro += content;
}
return this;
}
clone() {
const cloned = new MagicString(this.original, { filename: this.filename });
let originalChunk = this.firstChunk;
let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
while (originalChunk) {
cloned.byStart[clonedChunk.start] = clonedChunk;
cloned.byEnd[clonedChunk.end] = clonedChunk;
const nextOriginalChunk = originalChunk.next;
const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
if (nextClonedChunk) {
clonedChunk.next = nextClonedChunk;
nextClonedChunk.previous = clonedChunk;
clonedChunk = nextClonedChunk;
}
originalChunk = nextOriginalChunk;
}
cloned.lastChunk = clonedChunk;
if (this.indentExclusionRanges) {
cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
}
cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
cloned.intro = this.intro;
cloned.outro = this.outro;
return cloned;
}
generateDecodedMap(options) {
options = options || {};
const sourceIndex = 0;
const names = Object.keys(this.storedNames);
const mappings = new Mappings(options.hires);
const locate = getLocator(this.original);
if (this.intro) {
mappings.advance(this.intro);
}
this.firstChunk.eachNext((chunk) => {
const loc = locate(chunk.start);
if (chunk.intro.length)
mappings.advance(chunk.intro);
if (chunk.edited) {
mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
} else {
mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
}
if (chunk.outro.length)
mappings.advance(chunk.outro);
});
return {
file: options.file ? options.file.split(/[/\\]/).pop() : null,
sources: [options.source ? getRelativePath(options.file || "", options.source) : null],
sourcesContent: options.includeContent ? [this.original] : [null],
names,
mappings: mappings.raw
};
}
generateMap(options) {
return new SourceMap(this.generateDecodedMap(options));
}
getIndentString() {
return this.indentStr === null ? " " : this.indentStr;
}
indent(indentStr, options) {
const pattern = /^[^\r\n]/gm;
if (isObject(indentStr)) {
options = indentStr;
indentStr = void 0;
}
indentStr = indentStr !== void 0 ? indentStr : this.indentStr || " ";
if (indentStr === "")
return this;
options = options || {};
const isExcluded = {};
if (options.exclude) {
const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
exclusions.forEach((exclusion) => {
for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
isExcluded[i] = true;
}
});
}
let shouldIndentNextCharacter = options.indentStart !== false;
const replacer = (match) => {
if (shouldIndentNextCharacter)
return `${indentStr}${match}`;
shouldIndentNextCharacter = true;
return match;
};
this.intro = this.intro.replace(pattern, replacer);
let charIndex = 0;
let chunk = this.firstChunk;
while (chunk) {
const end = chunk.end;
if (chunk.edited) {
if (!isExcluded[charIndex]) {
chunk.content = chunk.content.replace(pattern, replacer);
if (chunk.content.length) {
shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
}
}
} else {
charIndex = chunk.start;
while (charIndex < end) {
if (!isExcluded[charIndex]) {
const char = this.original[charIndex];
if (char === "\n") {
shouldIndentNextCharacter = true;
} else if (char !== "\r" && shouldIndentNextCharacter) {
shouldIndentNextCharacter = false;
if (charIndex === chunk.start) {
chunk.prependRight(indentStr);
} else {
this._splitChunk(chunk, charIndex);
chunk = chunk.next;
chunk.prependRight(indentStr);
}
}
}
charIndex += 1;
}
}
charIndex = chunk.end;
chunk = chunk.next;
}
this.outro = this.outro.replace(pattern, replacer);
return this;
}
insert() {
throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
}
insertLeft(index, content) {
if (!warned.insertLeft) {
console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
warned.insertLeft = true;
}
return this.appendLeft(index, content);
}
insertRight(index, content) {
if (!warned.insertRight) {
console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
warned.insertRight = true;
}
return this.prependRight(index, content);
}
move(start, end, index) {
if (index >= start && index <= end)
throw new Error("Cannot move a selection inside itself");
this._split(start);
this._split(end);
this._split(index);
const first = this.byStart[start];
const last = this.byEnd[end];
const oldLeft = first.previous;
const oldRight = last.next;
const newRight = this.byStart[index];
if (!newRight && last === this.lastChunk)
return this;
const newLeft = newRight ? newRight.previous : this.lastChunk;
if (oldLeft)
oldLeft.next = oldRight;
if (oldRight)
oldRight.previous = oldLeft;
if (newLeft)
newLeft.next = first;
if (newRight)
newRight.previous = last;
if (!first.previous)
this.firstChunk = last.next;
if (!last.next) {
this.lastChunk = first.previous;
this.lastChunk.next = null;
}
first.previous = newLeft;
last.next = newRight || null;
if (!newLeft)
this.firstChunk = first;
if (!newRight)
this.lastChunk = last;
return this;
}
overwrite(start, end, content, options) {
if (typeof content !== "string")
throw new TypeError("replacement content must be a string");
while (start < 0)
start += this.original.length;
while (end < 0)
end += this.original.length;
if (end > this.original.length)
throw new Error("end is out of bounds");
if (start === end)
throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");
this._split(start);
this._split(end);
if (options === true) {
if (!warned.storeName) {
console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
warned.storeName = true;
}
options = { storeName: true };
}
const storeName = options !== void 0 ? options.storeName : false;
const contentOnly = options !== void 0 ? options.contentOnly : false;
if (storeName) {
const original = this.original.slice(start, end);
Object.defineProperty(this.storedNames, original, {
writable: true,
value: true,
enumerable: true
});
}
const first = this.byStart[start];
const last = this.byEnd[end];
if (first) {
let chunk = first;
while (chunk !== last) {
if (chunk.next !== this.byStart[chunk.end]) {
throw new Error("Cannot overwrite across a split point");
}
chunk = chunk.next;
chunk.edit("", false);
}
first.edit(content, storeName, contentOnly);
} else {
const newChunk = new Chunk(start, end, "").edit(content, storeName);
last.next = newChunk;
newChunk.previous = last;
}
return this;
}
prepend(content) {
if (typeof content !== "string")
throw new TypeError("outro content must be a string");
this.intro = content + this.intro;
return this;
}
prependLeft(index, content) {
if (typeof content !== "string")
throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) {
chunk.prependLeft(content);
} else {
this.intro = content + this.intro;
}
return this;
}
prependRight(index, content) {
if (typeof content !== "string")
throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) {
chunk.prependRight(content);
} else {
this.outro = content + this.outro;
}
return this;
}
remove(start, end) {
while (start < 0)
start += this.original.length;
while (end < 0)
end += this.original.length;
if (start === end)
return this;
if (start < 0 || end > this.original.length)
throw new Error("Character is out of bounds");
if (start > end)
throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.intro = "";
chunk.outro = "";
chunk.edit("");
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
lastChar() {
if (this.outro.length)
return this.outro[this.outro.length - 1];
let chunk = this.lastChunk;
do {
if (chunk.outro.length)
return chunk.outro[chunk.outro.length - 1];
if (chunk.content.length)
return chunk.content[chunk.content.length - 1];
if (chunk.intro.length)
return chunk.intro[chunk.intro.length - 1];
} while (chunk = chunk.previous);
if (this.intro.length)
return this.intro[this.intro.length - 1];
return "";
}
lastLine() {
let lineIndex = this.outro.lastIndexOf(n);
if (lineIndex !== -1)
return this.outro.substr(lineIndex + 1);
let lineStr = this.outro;
let chunk = this.lastChunk;
do {
if (chunk.outro.length > 0) {
lineIndex = chunk.outro.lastIndexOf(n);
if (lineIndex !== -1)
return chunk.outro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.outro + lineStr;
}
if (chunk.content.length > 0) {
lineIndex = chunk.content.lastIndexOf(n);
if (lineIndex !== -1)
return chunk.content.substr(lineIndex + 1) + lineStr;
lineStr = chunk.content + lineStr;
}
if (chunk.intro.length > 0) {
lineIndex = chunk.intro.lastIndexOf(n);
if (lineIndex !== -1)
return chunk.intro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.intro + lineStr;
}
} while (chunk = chunk.previous);
lineIndex = this.intro.lastIndexOf(n);
if (lineIndex !== -1)
return this.intro.substr(lineIndex + 1) + lineStr;
return this.intro + lineStr;
}
slice(start = 0, end = this.original.length) {
while (start < 0)
start += this.original.length;
while (end < 0)
end += this.original.length;
let result = "";
let chunk = this.firstChunk;
while (chunk && (chunk.start > start || chunk.end <= start)) {
if (chunk.start < end && chunk.end >= end) {
return result;
}
chunk = chunk.next;
}
if (chunk && chunk.edited && chunk.start !== start)
throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
const startChunk = chunk;
while (chunk) {
if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
result += chunk.intro;
}
const containsEnd = chunk.start < end && chunk.end >= end;
if (containsEnd && chunk.edited && chunk.end !== end)
throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
const sliceStart = startChunk === chunk ? start - chunk.start : 0;
const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
result += chunk.content.slice(sliceStart, sliceEnd);
if (chunk.outro && (!containsEnd || chunk.end === end)) {
result += chunk.outro;
}
if (containsEnd) {
break;
}
chunk = chunk.next;
}
return result;
}
snip(start, end) {
const clone = this.clone();
clone.remove(0, start);
clone.remove(end, clone.original.length);
return clone;
}
_split(index) {
if (this.byStart[index] || this.byEnd[index])
return;
let chunk = this.lastSearchedChunk;
const searchForward = index > chunk.end;
while (chunk) {
if (chunk.contains(index))
return this._splitChunk(chunk, index);
chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
}
}
_splitChunk(chunk, index) {
if (chunk.edited && chunk.content.length) {
const loc = getLocator(this.original)(index);
throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`);
}
const newChunk = chunk.split(index);
this.byEnd[index] = chunk;
this.byStart[index] = newChunk;
this.byEnd[newChunk.end] = newChunk;
if (chunk === this.lastChunk)
this.lastChunk = newChunk;
this.lastSearchedChunk = chunk;
return true;
}
toString() {
let str = this.intro;
let chunk = this.firstChunk;
while (chunk) {
str += chunk.toString();
chunk = chunk.next;
}
return str + this.outro;
}
isEmpty() {
let chunk = this.firstChunk;
do {
if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
return false;
} while (chunk = chunk.next);
return true;
}
length() {
let chunk = this.firstChunk;
let length = 0;
do {
length += chunk.intro.length + chunk.content.length + chunk.outro.length;
} while (chunk = chunk.next);
return length;
}
trimLines() {
return this.trim("[\\r\\n]");
}
trim(charType) {
return this.trimStart(charType).trimEnd(charType);
}
trimEndAborted(charType) {
const rx = new RegExp((charType || "\\s") + "+$");
this.outro = this.outro.replace(rx, "");
if (this.outro.length)
return true;
let chunk = this.lastChunk;
do {
const end = chunk.end;
const aborted = chunk.trimEnd(rx);
if (chunk.end !== end) {
if (this.lastChunk === chunk) {
this.lastChunk = chunk.next;
}
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted)
return true;
chunk = chunk.previous;
} while (chunk);
return false;
}
trimEnd(charType) {
this.trimEndAborted(charType);
return this;
}
trimStartAborted(charType) {
const rx = new RegExp("^" + (charType || "\\s") + "+");
this.intro = this.intro.replace(rx, "");
if (this.intro.length)
return true;
let chunk = this.firstChunk;
do {
const end = chunk.end;
const aborted = chunk.trimStart(rx);
if (chunk.end !== end) {
if (chunk === this.lastChunk)
this.lastChunk = chunk.next;
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted)
return true;
chunk = chunk.next;
} while (chunk);
return false;
}
trimStart(charType) {
this.trimStartAborted(charType);
return this;
}
hasChanged() {
return this.original !== this.toString();
}
replace(searchValue, replacement) {
function getReplacement(match, str) {
if (typeof replacement === "string") {
return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
if (i === "$")
return "$";
if (i === "&")
return match[0];
const num = +i;
if (num < match.length)
return match[+i];
return `$${i}`;
});
} else {
return replacement(...match, match.index, str, match.groups);
}
}
function matchAll(re, str) {
let match;
const matches = [];
while (match = re.exec(str)) {
matches.push(match);
}
return matches;
}
if (typeof searchValue !== "string" && searchValue.global) {
const matches = matchAll(searchValue, this.original);
matches.forEach((match) => {
if (match.index != null)
this.overwrite(match.index, match.index + match[0].length, getReplacement(match, this.original));
});
} else {
const match = this.original.match(searchValue);
if (match && match.index != null)
this.overwrite(match.index, match.index + match[0].length, getReplacement(match, this.original));
}
return this;
}
}
const hasOwnProp = Object.prototype.hasOwnProperty;
class Bundle {
constructor(options = {}) {
this.intro = options.intro || "";
this.separator = options.separator !== void 0 ? options.separator : "\n";
this.sources = [];
this.uniqueSources = [];
this.uniqueSourceIndexByFilename = {};
}
addSource(source) {
if (source instanceof MagicString) {
return this.addSource({
content: source,
filename: source.filename,
separator: this.separator
});
}
if (!isObject(source) || !source.content) {
throw new Error("bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`");
}
["filename", "indentExclusionRanges", "separator"].forEach((option) => {
if (!hasOwnProp.call(source, option))
source[option] = source.content[option];
});
if (source.separator === void 0) {
source.separator = this.separator;
}
if (source.filename) {
if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
this.uniqueSources.push({ filename: source.filename, content: source.content.original });
} else {
const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
if (source.content.original !== uniqueSource.content) {
throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
}
}
}
this.sources.push(source);
return this;
}
append(str, options) {
this.addSource({
content: new MagicString(str),
separator: options && options.separator || ""
});
return this;
}
clone() {
const bundle = new Bundle({
intro: this.intro,
separator: this.separator
});
this.sources.forEach((source) => {
bundle.addSource({
filename: source.filename,
content: source.content.clone(),
separator: source.separator
});
});
return bundle;
}
generateDecodedMap(options = {}) {
const names = [];
this.sources.forEach((source) => {
Object.keys(source.content.storedNames).forEach((name) => {
if (!~names.indexOf(name))
names.push(name);
});
});
const mappings = new Mappings(options.hires);
if (this.intro) {
mappings.advance(this.intro);
}
this.sources.forEach((source, i) => {
if (i > 0) {
mappings.advance(this.separator);
}
const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
const magicString = source.content;
const locate = getLocator(magicString.original);
if (magicString.intro) {
mappings.advance(magicString.intro);
}
magicString.firstChunk.eachNext((chunk) => {
const loc = locate(chunk.start);
if (chunk.intro.length)
mappings.advance(chunk.intro);
if (source.filename) {
if (chunk.edited) {
mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
} else {
mappings.addUneditedChunk(sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations);
}
} else {
mappings.advance(chunk.content);
}
if (chunk.outro.length)
mappings.advance(chunk.outro);
});
if (magicString.outro) {
mappings.advance(magicString.outro);
}
});
return {
file: options.file ? options.file.split(/[/\\]/).pop() : null,
sources: this.uniqueSources.map((source) => {
return options.file ? getRelativePath(options.file, source.filename) : source.filename;
}),
sourcesContent: this.uniqueSources.map((source) => {
return options.includeContent ? source.content : null;
}),
names,
mappings: mappings.raw
};
}
generateMap(options) {
return new SourceMap(this.generateDecodedMap(options));
}
getIndentString() {
const indentStringCounts = {};
this.sources.forEach((source) => {
const indentStr = source.content.indentStr;
if (indentStr === null)
return;
if (!indentStringCounts[indentStr])
indentStringCounts[indentStr] = 0;
indentStringCounts[indentStr] += 1;
});
return Object.keys(indentStringCounts).sort((a, b) => {
return indentStringCounts[a] - indentStringCounts[b];
})[0] || " ";
}
indent(indentStr) {
if (!arguments.length) {
indentStr = this.getIndentString();
}
if (indentStr === "")
return this;
let trailingNewline = !this.intro || this.intro.slice(-1) === "\n";
this.sources.forEach((source, i) => {
const separator = source.separator !== void 0 ? source.separator : this.separator;
const indentStart = trailingNewline || i > 0 && /\r?\n$/.test(separator);
source.content.indent(indentStr, {
exclude: source.indentExclusionRanges,
indentStart
});
trailingNewline = source.content.lastChar() === "\n";
});
if (this.intro) {
this.intro = indentStr + this.intro.replace(/^[^\n]/gm, (match, index) => {
return index > 0 ? indentStr + match : match;
});
}
return this;
}
prepend(str) {
this.intro = str + this.intro;
return this;
}
toString() {
const body = this.sources.map((source, i) => {
const separator = source.separator !== void 0 ? source.separator : this.separator;
const str = (i > 0 ? separator : "") + source.content.toString();
return str;
}).join("");
return this.intro + body;
}
isEmpty() {
if (this.intro.length && this.intro.trim())
return false;
if (this.sources.some((source) => !source.content.isEmpty()))
return false;
return true;
}
length() {
return this.sources.reduce((length, source) => length + source.content.length(), this.intro.length);
}
trimLines() {
return this.trim("[\\r\\n]");
}
trim(charType) {
return this.trimStart(charType).trimEnd(charType);
}
trimStart(charType) {
const rx = new RegExp("^" + (charType || "\\s") + "+");
this.intro = this.intro.replace(rx, "");
if (!this.intro) {
let source;
let i = 0;
do {
source = this.sources[i++];
if (!source) {
break;
}
} while (!source.content.trimStartAborted(charType));
}
return this;
}
trimEnd(charType) {
const rx = new RegExp((charType || "\\s") + "+$");
let source;
let i = this.sources.length - 1;
do {
source = this.sources[i--];
if (!source) {
this.intro = this.intro.replace(rx, "");
break;
}
} while (!source.content.trimEndAborted(charType));
return this;
}
}
export {
Bundle,
SourceMap,
MagicString as default
};
magic-string-0.30.5/benchmark/index.mjs 0000664 0000000 0000000 00000003571 14511774173 0017757 0 ustar 00root root 0000000 0000000 import Benchmark from 'benchmark';
import MagicString from '../dist/magic-string.es.mjs';
import fs from 'fs/promises';
Benchmark.support.decompilation = false;
console.log(`node ${process.version}\n`);
function runWithInstance(name, inputs, func, setup) {
const ss = [];
new Benchmark(
name,
{
setup: () => {
for (const [i, input] of inputs.entries()) {
ss[i] = new MagicString(input);
if (setup) {
setup(ss[i]);
}
}
},
fn: () => {
for (const i of inputs.keys()) {
func(ss[i]);
}
}
}
).on('complete', (event) => {
console.log(String(event.target));
}).on('error', (event) => {
console.error(event.target.error);
}).run();
}
async function bench() {
const inputs = await Promise.all(
['data.js', 'data-min.js'].map(
(file) => fs.readFile(new URL(file, import.meta.url), 'utf-8')
)
);
new Benchmark('construct', {
fn: () => {
for (const input of inputs) {
new MagicString(input);
}
}
}).on('complete', (event) => {
console.log(String(event.target));
}).on('error', (event) => {
console.error(event.target.error);
}).run();
runWithInstance('append', inputs, s => {
s.append(';"append";');
});
runWithInstance('indent', inputs, s => {
s.indent();
});
runWithInstance('generateMap (no edit)', inputs, s => {
s.generateMap();
});
runWithInstance('generateMap (edit)', inputs, s => {
s.generateMap();
}, s => {
s.replace(/replacement/g, 'replacement\nReplacement');
});
runWithInstance('generateDecodedMap (no edit)', inputs, s => {
s.generateDecodedMap();
});
runWithInstance('generateDecodedMap (edit)', inputs, s => {
s.generateDecodedMap();
}, s => {
s.replace(/replacement/g, 'replacement\nReplacement');
});
const size = 1000000;
runWithInstance('overwrite', ['a'.repeat(size)], s => {
for (let i = 1; i < size; i+=2) {
s.overwrite(i, i+1, 'b');
}
});
}
bench();
magic-string-0.30.5/example/ 0000775 0000000 0000000 00000000000 14511774173 0015630 5 ustar 00root root 0000000 0000000 magic-string-0.30.5/example/app.inlinemap.js 0000664 0000000 0000000 00000001042 14511774173 0020716 0 ustar 00root root 0000000 0000000 var answer = 'yes';
console.log( answer );
//# sourceMappingURL=app.js.map
//#sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwLmpzLm1hcCIsInNvdXJjZXMiOlsiYXBwLnNvdXJjZS5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgZm9vID0gJ3llcyc7XG5jb25zb2xlLmxvZyggZm9vICk7Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLENBQUMsQ0FBQyxDQUFDLENBQUMsTUFBRyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztBQUNoQixDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLE1BQUcsQ0FBQyxDQUFDIn0= magic-string-0.30.5/example/app.js 0000664 0000000 0000000 00000000112 14511774173 0016740 0 ustar 00root root 0000000 0000000 var answer = 'yes';
console.log( answer );
//# sourceMappingURL=app.js.map magic-string-0.30.5/example/app.js.map 0000664 0000000 0000000 00000000461 14511774173 0017523 0 ustar 00root root 0000000 0000000 {"version":3,"file":"app.js.map","sources":["app.source.js"],"sourcesContent":["var foo = 'yes';\nconsole.log( foo );"],"names":[],"mappings":"AAAA,CAAC,CAAC,CAAC,CAAC,MAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAG,CAAC,CAAC"} magic-string-0.30.5/example/app.source.js 0000664 0000000 0000000 00000000044 14511774173 0020243 0 ustar 00root root 0000000 0000000 var foo = 'yes';
console.log( foo ); magic-string-0.30.5/example/build.js 0000664 0000000 0000000 00000001517 14511774173 0017271 0 ustar 00root root 0000000 0000000 var fs = require( 'fs' ),
MagicString = require( '../' );
process.chdir( __dirname );
fs.readFile( 'app.source.js', function ( err, result ) {
var source,
magicString,
pattern = /foo/g,
match,
transpiled,
map;
if ( err ) throw err;
source = result.toString();
magicString = new MagicString( result.toString() );
while ( match = pattern.exec( source ) ) {
magicString.overwrite( match.index, match.index + 3, 'answer' );
}
transpiled = magicString.toString() + '\n//# sourceMappingURL=app.js.map';
map = magicString.generateMap({
file: 'app.js.map',
source: 'app.source.js',
includeContent: true,
hires: true
});
fs.writeFileSync( 'app.js', transpiled );
fs.writeFileSync( 'app.js.map', JSON.stringify(map) );
fs.writeFileSync( 'app.inlinemap.js', transpiled + '\n//#sourceMappingURL=' + map.toUrl() );
});
magic-string-0.30.5/example/index.html 0000664 0000000 0000000 00000000050 14511774173 0017620 0 ustar 00root root 0000000 0000000