Initial commit (from f5274cbdce4ae7c9e4b937dcdf95ac70ae436d5f)

This commit is contained in:
anaarmas
2020-04-28 16:46:47 +02:00
commit 28ccc3db2d
13974 changed files with 2618436 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
3d1d5533ca7904f38987f652b68e127201c3a7b3
+593
View File
@@ -0,0 +1,593 @@
<a name="25.3.0"></a>
# [25.3.0](https://github.com/kulshekhar/ts-jest/compare/25.2.1...25.3.0) (2020-03-30)
### Bug Fixes
* add jest-config to dependencies list ([6d9e0d8](https://github.com/kulshekhar/ts-jest/commit/6d9e0d8))
* always do type check for all files provided to ts-jest transformer ([#1450](https://github.com/kulshekhar/ts-jest/issues/1450)) ([107e062](https://github.com/kulshekhar/ts-jest/commit/107e062))
* **docs:** correct changelog, correct version in package.json ([#1406](https://github.com/kulshekhar/ts-jest/issues/1406)) ([542e181](https://github.com/kulshekhar/ts-jest/commit/542e181))
### Chores
* **config:** improve diagnostics message ([#1444](https://github.com/kulshekhar/ts-jest/issues/1444)) ([96cd9b3](https://github.com/kulshekhar/ts-jest/commit/96cd9b3))
### Features
* **compiler:** expose internal ts `Program` via ConfigSet `TsCompiler` ([#1433](https://github.com/kulshekhar/ts-jest/issues/1433)) ([7153246](https://github.com/kulshekhar/ts-jest/commit/7153246))
* **config:** add incremental option ([#1418](https://github.com/kulshekhar/ts-jest/issues/1418)) ([5a69bce](https://github.com/kulshekhar/ts-jest/commit/5a69bce))
### BREAKING CHANGES
* **config:** This will affect to any snapshots or assertion against diagnostics messages
<a name="25.2.1"></a>
## [25.2.1](https://github.com/kulshekhar/ts-jest/compare/v25.2.0...25.2.1) (2020-02-21)
### Bug Fixes
* **compiler:** allow transformation of typescript files in node_modules ([#1385](https://github.com/kulshekhar/ts-jest/issues/1385)) ([814405e](https://github.com/kulshekhar/ts-jest/commit/814405e))
* **docs:** fixing slack link and some minor typos in documenation ([#1404](https://github.com/kulshekhar/ts-jest/issues/1404)) ([3e2e008](https://github.com/kulshekhar/ts-jest/commit/3e2e008))
* **transformer:** add deepUnmock to hoist method list ([#1372](https://github.com/kulshekhar/ts-jest/issues/1372)) ([0fbbc00](https://github.com/kulshekhar/ts-jest/commit/0fbbc00))
* **util:** use resolve package typescript package in yarn workspaces ([#1377](https://github.com/kulshekhar/ts-jest/issues/1377)) ([a63808c](https://github.com/kulshekhar/ts-jest/commit/a63808c))
<a name="25.2.0"></a>
# [25.2.0](https://github.com/kulshekhar/ts-jest/compare/v25.1.0...v25.2.0) (2020-02-03)
### Bug Fixes
* **config:** comment out unused codes ([dff1332](https://github.com/kulshekhar/ts-jest/commit/dff1332))
* **config:** pass plain config object to babel-jest transformer ([e0895da](https://github.com/kulshekhar/ts-jest/commit/e0895da))
* **config:** remove unused codes ([7aa3928](https://github.com/kulshekhar/ts-jest/commit/7aa3928))
* **config:** remove unused import ([81897e1](https://github.com/kulshekhar/ts-jest/commit/81897e1))
* **test:** improve unit tests for babel config ([ebd9380](https://github.com/kulshekhar/ts-jest/commit/ebd9380))
* **test:** update snapshot ([0e1190d](https://github.com/kulshekhar/ts-jest/commit/0e1190d))
<a name="25.1.0"></a>
# [25.1.0](https://github.com/kulshekhar/ts-jest/compare/v25.0.0...v25.1.0) (2020-01-30)
### Bug Fixes
* jest 25 type definitions ([ba82a9e](https://github.com/kulshekhar/ts-jest/commit/ba82a9e))
<a name="25.0.0"></a>
# [25.0.0](https://github.com/kulshekhar/ts-jest/compare/v24.3.0...v25.0.0) (2020-01-23)
### Bug Fixes
* Fix tests for version checks v2 ([154f1d6](https://github.com/kulshekhar/ts-jest/commit/154f1d6))
* Try to fix snapshots ([ea0ea50](https://github.com/kulshekhar/ts-jest/commit/ea0ea50))
* Try to fix snapshots v2 ([82445bb](https://github.com/kulshekhar/ts-jest/commit/82445bb))
### Features
* support Jest 25 ([ffc2cfe](https://github.com/kulshekhar/ts-jest/commit/ffc2cfe))
<a name="24.3.0"></a>
# [24.3.0](https://github.com/kulshekhar/ts-jest/compare/v24.2.0...v24.3.0) (2020-01-07)
### Bug Fixes
* **config:** support babel config file path as string ([#1332](https://github.com/kulshekhar/ts-jest/issues/1332)) ([78a53c2](https://github.com/kulshekhar/ts-jest/commit/78a53c2))
<a name="24.2.0"></a>
# [24.2.0](https://github.com/kulshekhar/ts-jest/compare/v24.1.0...v24.2.0) (2019-11-22)
### Bug Fixes
* **compiler:** pass filename to sha function instead of file extension ([ac1ac97](https://github.com/kulshekhar/ts-jest/commit/ac1ac97))
* **transformers:** hoist jest.enableAutomock and jest.disableAutomock ([ac50bc3](https://github.com/kulshekhar/ts-jest/commit/ac50bc3))
* typescript serviceHost cache miss on Windows operating systems ([26ee731](https://github.com/kulshekhar/ts-jest/commit/26ee731))
<a name="24.1.0"></a>
# [24.1.0](https://github.com/kulshekhar/ts-jest/compare/v24.0.2...v24.1.0) (2019-09-12)
### Bug Fixes
* **perf:** add cache for fs calls ([#908](https://github.com/kulshekhar/ts-jest/issues/908)) ([3dada81](https://github.com/kulshekhar/ts-jest/commit/3dada81))
* [#825](https://github.com/kulshekhar/ts-jest/issues/825) handle symlinked modules (ala pnpm) correctly ([e190b23](https://github.com/kulshekhar/ts-jest/commit/e190b23))
* handle tsBuildInfoFile option ([f9583e9](https://github.com/kulshekhar/ts-jest/commit/f9583e9)), closes [#1095](https://github.com/kulshekhar/ts-jest/issues/1095)
* **types:** unforce esModuleInterop in tsconfig.json ([c2d39b6](https://github.com/kulshekhar/ts-jest/commit/c2d39b6))
<a name="24.0.2"></a>
## [24.0.2](https://github.com/kulshekhar/ts-jest/compare/v24.0.1...v24.0.2) (2019-04-05)
<a name="24.0.1"></a>
## [24.0.1](https://github.com/kulshekhar/ts-jest/compare/v24.0.0...v24.0.1) (2019-03-30)
### Bug Fixes
* update call to globIgnore ([#1002](https://github.com/kulshekhar/ts-jest/issues/1002)) ([#1003](https://github.com/kulshekhar/ts-jest/issues/1003)) ([05b63af](https://github.com/kulshekhar/ts-jest/commit/05b63af))
### Features
* **config:** specify package.json location ([#823](https://github.com/kulshekhar/ts-jest/issues/823)) ([#1013](https://github.com/kulshekhar/ts-jest/issues/1013)) ([fb7dd55](https://github.com/kulshekhar/ts-jest/commit/fb7dd55))
<a name="24.0.0"></a>
# [24.0.0](https://github.com/kulshekhar/ts-jest/compare/v23.10.5...v24.0.0) (2019-02-18)
### Bug Fixes
* cli test ([1d67101](https://github.com/kulshekhar/ts-jest/commit/1d67101))
* module tests and some snapshots ([999f889](https://github.com/kulshekhar/ts-jest/commit/999f889))
* remove unused snapshots ([108b08b](https://github.com/kulshekhar/ts-jest/commit/108b08b))
* some tests ([d0f2231](https://github.com/kulshekhar/ts-jest/commit/d0f2231))
* test command ([8372b5e](https://github.com/kulshekhar/ts-jest/commit/8372b5e))
* test path for windows (attempt 1) ([6824ac4](https://github.com/kulshekhar/ts-jest/commit/6824ac4))
* test path for windows (attempt 2) ([eb2fc8a](https://github.com/kulshekhar/ts-jest/commit/eb2fc8a))
### Features
* **jest:** bump to 24 ([defcb77](https://github.com/kulshekhar/ts-jest/commit/defcb77))
<a name="23.10.4"></a>
## [23.10.4](https://github.com/kulshekhar/ts-jest/compare/v23.10.3...v23.10.4) (2018-10-06)
### Bug Fixes
* **cache:** adds project's dep versions to cache key ([6cacbea](https://github.com/kulshekhar/ts-jest/commit/6cacbea)), closes [#785](https://github.com/kulshekhar/ts-jest/issues/785)
* **cli:** change options to better reflect the new presets ([68abcfb](https://github.com/kulshekhar/ts-jest/commit/68abcfb))
* **helpers:** deprecate import from ts-jest, now ts-jest/utils ([33ff29f](https://github.com/kulshekhar/ts-jest/commit/33ff29f)), closes [#782](https://github.com/kulshekhar/ts-jest/issues/782)
* **typings:** typo in presets definition file ([53767ab](https://github.com/kulshekhar/ts-jest/commit/53767ab))
* **typings:** wrong import in preset typings + test ([94dc4e7](https://github.com/kulshekhar/ts-jest/commit/94dc4e7))
<a name="23.10.3"></a>
## [23.10.3](https://github.com/kulshekhar/ts-jest/compare/v23.10.2...v23.10.3) (2018-09-30)
### Bug Fixes
* **compiler:** do not force module kind if piping babel ([acebc8c](https://github.com/kulshekhar/ts-jest/commit/acebc8c)), closes [#767](https://github.com/kulshekhar/ts-jest/issues/767)
### Features
* **helpers:** adds a mocked test helper for mock typings ([f976135](https://github.com/kulshekhar/ts-jest/commit/f976135)), closes [#576](https://github.com/kulshekhar/ts-jest/issues/576)
<a name="23.10.2"></a>
## [23.10.2](https://github.com/kulshekhar/ts-jest/compare/v23.10.1...v23.10.2) (2018-09-26)
### Bug Fixes
* **cache:** resolved tsconfig in cache key + pkg digest ([e891608](https://github.com/kulshekhar/ts-jest/commit/e891608)), closes [#749](https://github.com/kulshekhar/ts-jest/issues/749)
* **cli:** resets testMatch if using testRegex option ([31ad0aa](https://github.com/kulshekhar/ts-jest/commit/31ad0aa)), closes [#756](https://github.com/kulshekhar/ts-jest/issues/756)
* **diagnostics:** throws only for category warning and error ([bb28849](https://github.com/kulshekhar/ts-jest/commit/bb28849)), closes [#748](https://github.com/kulshekhar/ts-jest/issues/748)
* **import:** wrong error message when a module exists but fails ([e0d6c57](https://github.com/kulshekhar/ts-jest/commit/e0d6c57))
* **preset:** createJestPreset fails with base and no array ([3c325e8](https://github.com/kulshekhar/ts-jest/commit/3c325e8))
### Features
* **cli:** CLI 'config:migrate' now detects best preset ([febd8d3](https://github.com/kulshekhar/ts-jest/commit/febd8d3))
* **preset:** adds 2 presets along the default one ([9f3d759](https://github.com/kulshekhar/ts-jest/commit/9f3d759))
* **preset:** adds presets typings and export all presets ([f55d895](https://github.com/kulshekhar/ts-jest/commit/f55d895))
* **typings:** emit declaration files, filtering out internals ([4f10f7e](https://github.com/kulshekhar/ts-jest/commit/4f10f7e)), closes [#745](https://github.com/kulshekhar/ts-jest/issues/745)
<a name="23.10.1"></a>
## [23.10.1](https://github.com/kulshekhar/ts-jest/compare/v23.10.0...v23.10.1) (2018-09-20)
### Bug Fixes
* **compile:** js files were never transpiled thru TS ([374dca1](https://github.com/kulshekhar/ts-jest/commit/374dca1)), closes [#740](https://github.com/kulshekhar/ts-jest/issues/740)
* **config:** warn instead of forcing ESM interoperability ([a2a4be2](https://github.com/kulshekhar/ts-jest/commit/a2a4be2))
* **windows:** normalize paths ([c12dfff](https://github.com/kulshekhar/ts-jest/commit/c12dfff))
<a name="23.10.0"></a>
# [23.10.0](https://github.com/kulshekhar/ts-jest/compare/v23.10.0-beta.6...v23.10.0) (2018-09-19)
### Bug Fixes
* **babel:** fixes the babel 6 hack ([c8d51cf](https://github.com/kulshekhar/ts-jest/commit/c8d51cf))
* **config:** jsx should also be considered as js files ([6c32a93](https://github.com/kulshekhar/ts-jest/commit/6c32a93))
### Features
* **hints:** warns if transform matches js without allowJs ([952cc87](https://github.com/kulshekhar/ts-jest/commit/952cc87))
<a name="23.10.0-beta.6"></a>
# [23.10.0-beta.6](https://github.com/kulshekhar/ts-jest/compare/v23.10.0-beta.5...v23.10.0-beta.6) (2018-09-13)
### Bug Fixes
* **babel:** instrumentation was done twice when using babel ([659a7fb](https://github.com/kulshekhar/ts-jest/commit/659a7fb)), closes [#713](https://github.com/kulshekhar/ts-jest/issues/713)
* **cache:** includes all parameters in cache key computing ([70e1867](https://github.com/kulshekhar/ts-jest/commit/70e1867))
* **e2e:** fixes the eval tool (not used yet) ([939d13a](https://github.com/kulshekhar/ts-jest/commit/939d13a))
<a name="23.10.0-beta.5"></a>
# [23.10.0-beta.5](https://github.com/kulshekhar/ts-jest/compare/v23.10.0-beta.4...v23.10.0-beta.5) (2018-09-12)
### Bug Fixes
* **package:** fixes the outdated package-lock ([c5a5b7a](https://github.com/kulshekhar/ts-jest/commit/c5a5b7a))
### Features
* **diagnostics:** add option to enable/disable first-TS-error-throws ([2c840c2](https://github.com/kulshekhar/ts-jest/commit/2c840c2))
<a name="23.10.0-beta.4"></a>
# [23.10.0-beta.4](https://github.com/kulshekhar/ts-jest/compare/v23.10.0-beta.3...v23.10.0-beta.4) (2018-09-06)
### Bug Fixes
* **config:** fixes a bug in the tsconfig file resolver ([3910f2c](https://github.com/kulshekhar/ts-jest/commit/3910f2c))
<a name="23.10.0-beta.3"></a>
# [23.10.0-beta.3](https://github.com/kulshekhar/ts-jest/compare/v23.10.0-beta.2...v23.10.0-beta.3) (2018-09-06)
### Bug Fixes
* **config:** fixes a bug in path resolver ([ceb0424](https://github.com/kulshekhar/ts-jest/commit/ceb0424))
### Features
* **cli:** adds a cli tool to migrate old config ([714f5f0](https://github.com/kulshekhar/ts-jest/commit/714f5f0))
* **cli:** ads a simple config:init helper + tests ([6700522](https://github.com/kulshekhar/ts-jest/commit/6700522))
* **config:** exposes custom transformers to config for presets ([885bc44](https://github.com/kulshekhar/ts-jest/commit/885bc44))
* **logger:** adds ts-jest version in the logger's context ([bb0c06e](https://github.com/kulshekhar/ts-jest/commit/bb0c06e))
### Performance Improvements
* **bundle:** improves bundle size ([34eedc3](https://github.com/kulshekhar/ts-jest/commit/34eedc3))
<a name="23.10.0-beta.2"></a>
# [23.10.0-beta.2](https://github.com/kulshekhar/ts-jest/compare/v23.10.0-beta.1...v23.10.0-beta.2) (2018-09-02)
### Bug Fixes
* **caching:** fixes a possible cache collision ([9c38694](https://github.com/kulshekhar/ts-jest/commit/9c38694))
* **testing:** change logging level for some utility ([16f125a](https://github.com/kulshekhar/ts-jest/commit/16f125a))
### Features
* **config:** typeCheck default to true (langauge service) ([623b2f4](https://github.com/kulshekhar/ts-jest/commit/623b2f4))
### BREAKING CHANGES
* **config:** Language service will be used by default from now on
<a name="23.10.0-beta.1"></a>
# [23.10.0-beta.1](https://github.com/kulshekhar/ts-jest/compare/v23.1.4...v23.10.0-beta.1) (2018-09-01)
### Bug Fixes
* **ci:** can't use runInBand for e2e: cache collision ([db650f4](https://github.com/kulshekhar/ts-jest/commit/db650f4))
* **ci:** do not run e2e sub-tests in band ([18ad865](https://github.com/kulshekhar/ts-jest/commit/18ad865))
* **ci:** ensure npm is present with ci ([edb6eda](https://github.com/kulshekhar/ts-jest/commit/edb6eda))
* **logger:** removes cyclic imports ([5ef980f](https://github.com/kulshekhar/ts-jest/commit/5ef980f))
* babel-config + adds test ([12146c3](https://github.com/kulshekhar/ts-jest/commit/12146c3))
* fixes js style to be node < 10 compatible ([83d7517](https://github.com/kulshekhar/ts-jest/commit/83d7517))
* hoisting per level + memoize fix ([31847b0](https://github.com/kulshekhar/ts-jest/commit/31847b0))
* jest 22 did not have default config ([cbaddc3](https://github.com/kulshekhar/ts-jest/commit/cbaddc3))
* makes node 6 happy ([f6f82b8](https://github.com/kulshekhar/ts-jest/commit/f6f82b8))
* makes node6 happy ([f170285](https://github.com/kulshekhar/ts-jest/commit/f170285))
* makes window happy ([36fbebe](https://github.com/kulshekhar/ts-jest/commit/36fbebe))
* node 6 unhappy again... ([703ad0b](https://github.com/kulshekhar/ts-jest/commit/703ad0b))
* normalizes bundle hash on any node version ([ce7afaf](https://github.com/kulshekhar/ts-jest/commit/ce7afaf))
* npm coming with node 6 doesn't talk `ci` ([b87198d](https://github.com/kulshekhar/ts-jest/commit/b87198d))
* source maps ([89a30c9](https://github.com/kulshekhar/ts-jest/commit/89a30c9))
* typos + node 6 compat ([0ed1587](https://github.com/kulshekhar/ts-jest/commit/0ed1587))
* updates templates ([f2e1da2](https://github.com/kulshekhar/ts-jest/commit/f2e1da2))
* uses cross-platform spawn + fix pkg versions ([ac1599c](https://github.com/kulshekhar/ts-jest/commit/ac1599c))
* we are not writing files, use normalized EOL ([47fff43](https://github.com/kulshekhar/ts-jest/commit/47fff43))
* **tests:** CI fixes ([34a41ea](https://github.com/kulshekhar/ts-jest/commit/34a41ea))
* **tests:** detect npm version to use or not ci ([683a1e5](https://github.com/kulshekhar/ts-jest/commit/683a1e5))
* **tests:** do not use babel in our tests + new API for simple ([3e4de3e](https://github.com/kulshekhar/ts-jest/commit/3e4de3e))
* **tests:** more sanitizing for windows compat ([faae274](https://github.com/kulshekhar/ts-jest/commit/faae274))
### Features
* **config:** adds a helper to build moduleNameMapper from paths ([7b8598e](https://github.com/kulshekhar/ts-jest/commit/7b8598e)), closes [#364](https://github.com/kulshekhar/ts-jest/issues/364)
* **logging:** improves log messages + tests ([5d03c4d](https://github.com/kulshekhar/ts-jest/commit/5d03c4d))
* adds logging + better hashing ([4322701](https://github.com/kulshekhar/ts-jest/commit/4322701))
* allow env var to add diagnostic codes to ignore ([777edf5](https://github.com/kulshekhar/ts-jest/commit/777edf5))
* cache key + tests ([bd55448](https://github.com/kulshekhar/ts-jest/commit/bd55448))
* diagnostics, different compilers, ... ([f26ebf0](https://github.com/kulshekhar/ts-jest/commit/f26ebf0))
* directly writes to stdio so jest does not swallow ([6a7f01f](https://github.com/kulshekhar/ts-jest/commit/6a7f01f))
* handles stringifyContentPathRegex ([3fcb4bd](https://github.com/kulshekhar/ts-jest/commit/3fcb4bd))
* hoisting + tests + many other things ([6186e84](https://github.com/kulshekhar/ts-jest/commit/6186e84))
* io serializer + other test utils ([d03e0e7](https://github.com/kulshekhar/ts-jest/commit/d03e0e7))
* jest preset ([beb50b5](https://github.com/kulshekhar/ts-jest/commit/beb50b5))
* warn about unsupported versions ([1103071](https://github.com/kulshekhar/ts-jest/commit/1103071))
* **test:** jest serializers ([dfa9c0f](https://github.com/kulshekhar/ts-jest/commit/dfa9c0f))
* **tests:** more test tools + adds test related to debuggin issues ([8dcafca](https://github.com/kulshekhar/ts-jest/commit/8dcafca))
### Performance Improvements
* **babel:** uses babel-jest cache key as part of ours ([f51c4a7](https://github.com/kulshekhar/ts-jest/commit/f51c4a7))
* **cache:** share config-sets for parallel test running ([090ca7b](https://github.com/kulshekhar/ts-jest/commit/090ca7b))
* **tests:** run e2e tests in band ([b3e94ff](https://github.com/kulshekhar/ts-jest/commit/b3e94ff))
* detects changes in templates and bundle ([2a3da21](https://github.com/kulshekhar/ts-jest/commit/2a3da21))
* do not type check if fileName doesn't match ([cc45adc](https://github.com/kulshekhar/ts-jest/commit/cc45adc))
* faster tests ([37a0187](https://github.com/kulshekhar/ts-jest/commit/37a0187))
* improves speed of local test after 1st run ([cc04021](https://github.com/kulshekhar/ts-jest/commit/cc04021))
* more cleaning ([c48f7b8](https://github.com/kulshekhar/ts-jest/commit/c48f7b8))
* trying to improve travis-ci conf ([e4b4d95](https://github.com/kulshekhar/ts-jest/commit/e4b4d95))
<a name="23.1.3"></a>
## [23.1.3](https://github.com/kulshekhar/ts-jest/compare/v23.1.2...v23.1.3) (2018-08-06)
### Bug Fixes
* allow (but deprecate) use of old preprocessor.js ([a65079f](https://github.com/kulshekhar/ts-jest/commit/a65079f))
* big refactor + fixes (mainly cache key + coverage) ([e46caae](https://github.com/kulshekhar/ts-jest/commit/e46caae))
* fixes coverage and tests ([09500c2](https://github.com/kulshekhar/ts-jest/commit/09500c2))
* gracefully load [@babel](https://github.com/babel)/core or babel-core ([98b2410](https://github.com/kulshekhar/ts-jest/commit/98b2410))
* hack for babel < 6 so that breakpoints do work ([90c74ef](https://github.com/kulshekhar/ts-jest/commit/90c74ef)), closes [#627](https://github.com/kulshekhar/ts-jest/issues/627)
* resolves correctly config file path (fix [#636](https://github.com/kulshekhar/ts-jest/issues/636)) ([5ab100c](https://github.com/kulshekhar/ts-jest/commit/5ab100c))
* test rootDir to handle preset-angular ([8a6a8f7](https://github.com/kulshekhar/ts-jest/commit/8a6a8f7))
* wrong error message ([c955083](https://github.com/kulshekhar/ts-jest/commit/c955083))
* **html:** correctly transforms html source when needed ([9a2d74f](https://github.com/kulshekhar/ts-jest/commit/9a2d74f))
* **lint:** fixes tslint script & lint issues ([60ab36e](https://github.com/kulshekhar/ts-jest/commit/60ab36e))
* **package:** update fs-extra to version 6.0.1 ([7e73536](https://github.com/kulshekhar/ts-jest/commit/7e73536))
* **package:** update pkg-dir to version 3.0.0 ([3fb8f9f](https://github.com/kulshekhar/ts-jest/commit/3fb8f9f))
* **package:** update yargs to version 12.0.1 ([390ffcd](https://github.com/kulshekhar/ts-jest/commit/390ffcd))
* **source-maps:** fix source maps options/calls ([76e27c1](https://github.com/kulshekhar/ts-jest/commit/76e27c1))
* Typo in utils.ts ([#534](https://github.com/kulshekhar/ts-jest/issues/534)) ([a650260](https://github.com/kulshekhar/ts-jest/commit/a650260))
### Performance Improvements
* do not hash cache key, jest does it underneath ([fbe4f1f](https://github.com/kulshekhar/ts-jest/commit/fbe4f1f))
<a name="22.4.5"></a>
## [22.4.5](https://github.com/kulshekhar/ts-jest/compare/v22.4.4...v22.4.5) (2018-05-05)
<a name="22.4.1"></a>
## [22.4.1](https://github.com/kulshekhar/ts-jest/compare/v22.4.0...v22.4.1) (2018-03-02)
### Bug Fixes
* **package:** update source-map-support to version 0.5.0 ([f0aab12](https://github.com/kulshekhar/ts-jest/commit/f0aab12))
* **package:** update yargs to version 10.0.3 ([5cdf969](https://github.com/kulshekhar/ts-jest/commit/5cdf969))
* **package:** update yargs to version 11.0.0 ([7e9ce40](https://github.com/kulshekhar/ts-jest/commit/7e9ce40))
* add startDir to if-clause ([eed5311](https://github.com/kulshekhar/ts-jest/commit/eed5311))
* **package:** update yargs to version 9.0.1 ([#326](https://github.com/kulshekhar/ts-jest/issues/326)) ([8bf9924](https://github.com/kulshekhar/ts-jest/commit/8bf9924))
### Features
* add option to run TypeScript diagnostics ([13b77d9](https://github.com/kulshekhar/ts-jest/commit/13b77d9))
<a name="21.0.1"></a>
## [21.0.1](https://github.com/kulshekhar/ts-jest/compare/v21.0.0...v21.0.1) (2017-09-14)
<a name="21.0.0"></a>
# [21.0.0](https://github.com/kulshekhar/ts-jest/compare/v20.0.14...v21.0.0) (2017-09-05)
<a name="20.0.14"></a>
## [20.0.14](https://github.com/kulshekhar/ts-jest/compare/v20.0.13...v20.0.14) (2017-09-01)
<a name="20.0.13"></a>
## [20.0.13](https://github.com/kulshekhar/ts-jest/compare/v20.0.12...v20.0.13) (2017-08-30)
<a name="20.0.12"></a>
## [20.0.12](https://github.com/kulshekhar/ts-jest/compare/v20.0.11...v20.0.12) (2017-08-30)
<a name="20.0.11"></a>
## [20.0.11](https://github.com/kulshekhar/ts-jest/compare/v20.0.9...v20.0.11) (2017-08-29)
<a name="20.0.9"></a>
## [20.0.9](https://github.com/kulshekhar/ts-jest/compare/20.0.9...v20.0.9) (2017-08-04)
### Bug Fixes
* **package:** update fs-extra to version 4.0.0 ([5be18fb](https://github.com/kulshekhar/ts-jest/commit/5be18fb))
<a name="20.0.7"></a>
## [20.0.7](https://github.com/kulshekhar/ts-jest/compare/17.0.3...20.0.7) (2017-07-07)
### Bug Fixes
* peer dependency against Typescript 2.x ([cb08128](https://github.com/kulshekhar/ts-jest/commit/cb08128))
* remove outDir when collecting coverage ([c076956](https://github.com/kulshekhar/ts-jest/commit/c076956))
* **package:** update fs-extra to version 3.0.0 ([906be12](https://github.com/kulshekhar/ts-jest/commit/906be12))
* **package:** update yargs to version 8.0.1 ([0b2ea98](https://github.com/kulshekhar/ts-jest/commit/0b2ea98))
### Features
* export transpileIfTypescript ([6f835af](https://github.com/kulshekhar/ts-jest/commit/6f835af))
<a name="17.0.3"></a>
## [17.0.3](https://github.com/kulshekhar/ts-jest/compare/17.0.2...17.0.3) (2016-12-01)
<a name="17.0.2"></a>
## [17.0.2](https://github.com/kulshekhar/ts-jest/compare/17.0.1...17.0.2) (2016-12-01)
<a name="17.0.1"></a>
## [17.0.1](https://github.com/kulshekhar/ts-jest/compare/17.0.0...17.0.1) (2016-11-30)
<a name="17.0.0"></a>
# [17.0.0](https://github.com/kulshekhar/ts-jest/compare/0.1.13...17.0.0) (2016-11-09)
<a name="0.1.13"></a>
## [0.1.13](https://github.com/kulshekhar/ts-jest/compare/0.1.12...0.1.13) (2016-11-07)
<a name="0.1.12"></a>
## [0.1.12](https://github.com/kulshekhar/ts-jest/compare/0.1.11...0.1.12) (2016-11-03)
<a name="0.1.11"></a>
## [0.1.11](https://github.com/kulshekhar/ts-jest/compare/0.1.10...0.1.11) (2016-10-27)
<a name="0.1.10"></a>
## [0.1.10](https://github.com/kulshekhar/ts-jest/compare/0.1.9...0.1.10) (2016-10-26)
<a name="0.1.9"></a>
## [0.1.9](https://github.com/kulshekhar/ts-jest/compare/0.1.8...0.1.9) (2016-10-24)
<a name="0.1.8"></a>
## [0.1.8](https://github.com/kulshekhar/ts-jest/compare/0.1.7...0.1.8) (2016-10-14)
<a name="0.1.7"></a>
## [0.1.7](https://github.com/kulshekhar/ts-jest/compare/0.1.6...0.1.7) (2016-10-10)
<a name="0.1.6"></a>
## [0.1.6](https://github.com/kulshekhar/ts-jest/compare/0.1.5...0.1.6) (2016-10-08)
<a name="0.1.5"></a>
## [0.1.5](https://github.com/kulshekhar/ts-jest/compare/0.1.4...0.1.5) (2016-09-22)
<a name="0.1.4"></a>
## [0.1.4](https://github.com/kulshekhar/ts-jest/compare/0.1.3...0.1.4) (2016-09-16)
<a name="0.1.3"></a>
## [0.1.3](https://github.com/kulshekhar/ts-jest/compare/0.1.2...0.1.3) (2016-08-31)
<a name="0.1.2"></a>
## [0.1.2](https://github.com/kulshekhar/ts-jest/compare/0.1.1...0.1.2) (2016-08-31)
<a name="0.1.1"></a>
## [0.1.1](https://github.com/kulshekhar/ts-jest/compare/0.1.0...0.1.1) (2016-08-31)
<a name="0.1.0"></a>
# [0.1.0](https://github.com/kulshekhar/ts-jest/compare/0.0.1...0.1.0) (2016-08-31)
<a name="0.0.1"></a>
## [0.0.1](https://github.com/kulshekhar/ts-jest/compare/0.0.0...0.0.1) (2016-08-30)
<a name="0.0.0"></a>
# 0.0.0 (2016-08-30)
+67
View File
@@ -0,0 +1,67 @@
# Contributing
When contributing to this repository, please first discuss the change you wish to make via [slack](https://bit.ly/3bRHFPQ) or [issue](https://github.com/kulshekhar/ts-jest/issues) with the owners of this repository before making a change.
Please note we have a code of conduct, please follow it in all your interactions with the project.
## Pull Request Process
1. Ensure the tests are passing and that you have latest `master` branch merged in.
2. Update the `docs/` with details of your changes if required.
3. If possible, squash your commits. There must be only one commit in your PR (until a review). Then after each review requesting changes, DO NOT squash your commits with the one before the review, so that we can see intermediate modifications.
4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you do not have permission to do that, you may request the second reviewer to merge it for you.
## Code of Conduct
### Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
### Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
### Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
### Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at kulshekhar@gmail.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016-2018
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.
+64
View File
@@ -0,0 +1,64 @@
# ts-jest [![npm version](https://badge.fury.io/js/ts-jest.svg)](https://badge.fury.io/js/ts-jest) [![NPM downloads](https://img.shields.io/npm/dm/ts-jest.svg?style=flat)](https://npmjs.org/package/ts-jest) [![Known Vulnerabilities](https://snyk.io/test/github/kulshekhar/ts-jest/badge.svg)](https://snyk.io/test/github/kulshekhar/ts-jest) [![Coverage Status](https://coveralls.io/repos/github/kulshekhar/ts-jest/badge.svg?branch=master)](https://coveralls.io/github/kulshekhar/ts-jest?branch=master) [![Dependabot Status](https://api.dependabot.com/badges/status?host=github&repo=kulshekhar/ts-jest)](https://dependabot.com) [![Build Status](https://travis-ci.com/kulshekhar/ts-jest.svg?branch=master)](https://travis-ci.com/kulshekhar/ts-jest)
<img src="./icon.png" align="right" title="ts-jest Logo" width="128" height="128">
**`ts-jest`** is a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript.
It supports all features of TypeScript including type-checking. [Read more about Babel7 + `preset-typescript` **vs** TypeScript (and `ts-jest`)](https://kulshekhar.github.io/ts-jest/user/babel7-or-ts).
---
| We are not doing semantic versioning and `23.10` is a re-write, run `npm i -D ts-jest@"<23.10.0"` to go back to the previous version |
|---|
[<img src="./docs/assets/img/documentation.png" align="left" height="24"> View the online documentation (usage & technical)](https://kulshekhar.github.io/ts-jest)
[<img src="./docs/assets/img/slack.png" align="left" height="24"> Ask for some help in the `ts-jest` community of Slack](https://bit.ly/3bRHFPQ)
[<img src="./docs/assets/img/troubleshooting.png" align="left" height="24"> Before reporting any issue, be sure to check the troubleshooting page](TROUBLESHOOTING.md)
[<img src="./docs/assets/img/pull-request.png" align="left" height="24"> We're looking for collaborators! Want to help improve `ts-jest`?](https://github.com/kulshekhar/ts-jest/issues/223)
---
## Getting Started
These instructions will get you setup to use `ts-jest` in your project. For more detailed documentation, please check [online documentation](https://kulshekhar.github.io/ts-jest).
| | using npm | using yarn |
|---:|---|---|
| **Prerequisites** | `npm i -D jest typescript` | `yarn add --dev jest typescript` |
| **Installing** | `npm i -D ts-jest @types/jest` | `yarn add --dev ts-jest @types/jest` |
| **Creating config** | `npx ts-jest config:init` | `yarn ts-jest config:init` |
| **Running tests** | `npm t` or `npx jest` | `yarn test` or `yarn jest` |
## Built With
* [TypeScript](https://www.typescriptlang.org/) - JavaScript that scales
* [Jest](https://jestjs.io/) - Delightful JavaScript Testing
* [`ts-jest`](https://kulshekhar.github.io/ts-jest) - Jest processor for TypeScript _(yes, `ts-jest` uses itself for its tests)_
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
## Versioning
We **DO NOT** use [SemVer](http://semver.org/) for versioning. Though you can think about SemVer when reading our version, except our major number follows the one of Jest. For the versions available, see the [tags on this repository](https://github.com/kulshekhar/ts-jest/tags).
## Authors/maintainers
* **Kulshekhar Kabra** - [kulshekhar](https://github.com/kulshekhar)
* **Gustav Wengel** - [GeeWee](https://github.com/GeeWee)
* **Ahn** - [ahnpnl](https://github.com/ahnpnl)
* **Huafu Gandon** - [huafu](https://github.com/huafu)
See also the list of [contributors](https://github.com/kulshekhar/ts-jest/contributors) who participated in this project.
## Supporters
- [JetBrains](https://www.jetbrains.com/?from=ts-jest) has been kind enough to support ts-jest with an [open source license](https://www.jetbrains.com/community/opensource/?from=ts-jest).
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
+41
View File
@@ -0,0 +1,41 @@
# Troubleshooting
## Running ts-jest on CI tools
### PROBLEM
Cannot find module "" from ""
### SOLUTION
- Check if `rootDir` is referenced correctly. If not add this on your existing jest configuration.
```javascipt
module.exports = {
...
roots: ["<rootDir>"]
}
```
- Check if module directories are included on your jest configuration. If not add this on your existing jest configuration.
```javascipt
module.exports = {
...
moduleDirectories: ["node_modules","<module-directory>"],
modulePaths: ["<path-of-module>"],
}
```
- Check if module name is properly mapped and can be referenced by jest. If not, you can define moduleNameMapper for your jest configuration.
```javascipt
module.exports = {
...
moduleNameMapper: {
"<import-path>": "<rootDir>/<real-physical-path>",
},
}
```
- Check github folder names if its identical to you local folder names. Sometimes github never updates your folder names even if you rename it locally. If this happens rename your folders via github or use this command `git mv <source> <destination>` and commit changes.
Generated Vendored Executable
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
require('./dist/cli').processArgv()
+1
View File
@@ -0,0 +1 @@
export {};
+152
View File
@@ -0,0 +1,152 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = require("fs");
var json5_1 = require("json5");
var path_1 = require("path");
var presets_1 = require("../helpers/presets");
exports.run = function (args) { return __awaiter(void 0, void 0, void 0, function () {
var file, filePath, name, isPackage, exists, pkgFile, hasPackage, _a, jestPreset, askedTsconfig, force, jsdom, tsconfig, pkgJson, jsFilesProcessor, shouldPostProcessWithBabel, preset, body, base, tsJestConf, content;
return __generator(this, function (_b) {
file = args._[0] || 'jest.config.js';
filePath = path_1.join(process.cwd(), file);
name = path_1.basename(file);
isPackage = name === 'package.json';
exists = fs_1.existsSync(filePath);
pkgFile = isPackage ? filePath : path_1.join(process.cwd(), 'package.json');
hasPackage = isPackage || fs_1.existsSync(pkgFile);
_a = args.jestPreset, jestPreset = _a === void 0 ? true : _a, askedTsconfig = args.tsconfig, force = args.force, jsdom = args.jsdom;
tsconfig = askedTsconfig === 'tsconfig.json' ? undefined : askedTsconfig;
pkgJson = hasPackage ? JSON.parse(fs_1.readFileSync(pkgFile, 'utf8')) : {};
jsFilesProcessor = args.js, shouldPostProcessWithBabel = args.babel;
if (jsFilesProcessor == null) {
jsFilesProcessor = shouldPostProcessWithBabel ? 'babel' : undefined;
}
else if (shouldPostProcessWithBabel == null) {
shouldPostProcessWithBabel = jsFilesProcessor === 'babel';
}
if (jsFilesProcessor === 'babel') {
preset = presets_1.jsWIthBabel;
}
else if (jsFilesProcessor === 'ts') {
preset = presets_1.jsWithTs;
}
else {
preset = presets_1.defaults;
}
if (isPackage && !exists) {
throw new Error("File " + file + " does not exists.");
}
else if (!isPackage && exists && !force) {
throw new Error("Configuration file " + file + " already exists.");
}
if (!isPackage && !name.endsWith('.js')) {
throw new TypeError("Configuration file " + file + " must be a .js file or the package.json.");
}
if (hasPackage && pkgJson.jest) {
if (force && !isPackage) {
delete pkgJson.jest;
fs_1.writeFileSync(pkgFile, JSON.stringify(pkgJson, undefined, ' '));
}
else if (!force) {
throw new Error("A Jest configuration is already set in " + pkgFile + ".");
}
}
if (isPackage) {
base = jestPreset ? { preset: preset.name } : __assign({}, preset.value);
if (!jsdom)
base.testEnvironment = 'node';
if (tsconfig || shouldPostProcessWithBabel) {
tsJestConf = {};
base.globals = { 'ts-jest': tsJestConf };
if (tsconfig)
tsJestConf.tsconfig = tsconfig;
if (shouldPostProcessWithBabel)
tsJestConf.babelConfig = true;
}
body = JSON.stringify(__assign(__assign({}, pkgJson), { jest: base }), undefined, ' ');
}
else {
content = [];
if (!jestPreset) {
content.push(preset.jsImport('tsjPreset') + ";", '');
}
content.push('module.exports = {');
if (jestPreset) {
content.push(" preset: '" + preset.name + "',");
}
else {
content.push(" ...tsjPreset,");
}
if (!jsdom)
content.push(" testEnvironment: 'node',");
if (tsconfig || shouldPostProcessWithBabel) {
content.push(" globals: {");
content.push(" 'ts-jest': {");
if (tsconfig)
content.push(" tsconfig: " + json5_1.stringify(tsconfig) + ",");
if (shouldPostProcessWithBabel)
content.push(" babelConfig: true,");
content.push(" },");
content.push(" },");
}
content.push('};');
body = content.join('\n');
}
fs_1.writeFileSync(filePath, body);
process.stderr.write("\nJest configuration written to \"" + filePath + "\".\n");
return [2];
});
}); };
exports.help = function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
process.stdout.write("\nUsage:\n ts-jest config:init [options] [<config-file>]\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n Default: jest.config.js\n\nOptions:\n --force Discard any existing Jest config\n --js ts|babel Process .js files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n --tsconfig <file> Path to the tsconfig.json file\n --babel Pipe babel-jest after ts-jest\n --jsdom Use jsdom as test environment instead of node\n");
return [2];
});
}); };
+1
View File
@@ -0,0 +1 @@
export {};
+217
View File
@@ -0,0 +1,217 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var stringifyJson = require("fast-json-stable-stringify");
var fs_1 = require("fs");
var json5_1 = require("json5");
var path_1 = require("path");
var backports_1 = require("../../util/backports");
var presets_1 = require("../helpers/presets");
exports.run = function (args) { return __awaiter(void 0, void 0, void 0, function () {
var nullLogger, file, filePath, footNotes, name, isPackage, actualConfig, migratedConfig, presetName, preset, jsTransformers, jsWithTs, jsWithBabel, presetValue, migratedValue, presetValue, migratedValue, before, after, stringify, prefix;
return __generator(this, function (_a) {
nullLogger = bs_logger_1.createLogger({ targets: [] });
file = args._[0];
filePath = path_1.resolve(process.cwd(), file);
footNotes = [];
if (!fs_1.existsSync(filePath)) {
throw new Error("Configuration file " + file + " does not exists.");
}
name = path_1.basename(file);
isPackage = name === 'package.json';
if (!/\.(js|json)$/.test(name)) {
throw new TypeError("Configuration file " + file + " must be a JavaScript or JSON file.");
}
actualConfig = require(filePath);
if (isPackage) {
actualConfig = actualConfig.jest;
}
if (!actualConfig)
actualConfig = {};
migratedConfig = backports_1.backportJestConfig(nullLogger, actualConfig);
if (!migratedConfig.preset && args.jestPreset) {
if (args.js) {
presetName = args.js === 'babel' ? "ts-jest/presets/js-with-babel" : "ts-jest/presets/js-with-ts";
}
else {
jsTransformers = Object.keys(migratedConfig.transform || {}).reduce(function (list, pattern) {
if (RegExp(pattern.replace(/^<rootDir>\/?/, '/dummy-project/')).test('/dummy-project/src/foo.js')) {
var transformer = migratedConfig.transform[pattern];
if (/\bbabel-jest\b/.test(transformer))
transformer = 'babel-jest';
else if (/\ts-jest\b/.test(transformer))
transformer = 'ts-jest';
return __spread(list, [transformer]);
}
return list;
}, []);
jsWithTs = jsTransformers.includes('ts-jest');
jsWithBabel = jsTransformers.includes('babel-jest');
if (jsWithBabel && !jsWithTs) {
presetName = "ts-jest/presets/js-with-babel";
}
else if (jsWithTs && !jsWithBabel) {
presetName = "ts-jest/presets/js-with-ts";
}
else {
presetName = "ts-jest/presets/default";
}
}
presetName = presetName || "ts-jest/presets/default";
preset = presets_1.allPresets[presetName];
footNotes.push("Detected preset '" + preset.label + "' as the best matching preset for your configuration.\nVisit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more information about presets.\n");
}
else if (migratedConfig.preset && migratedConfig.preset.startsWith('ts-jest')) {
if (args.jestPreset === false) {
delete migratedConfig.preset;
}
else {
preset = presets_1.allPresets[migratedConfig.preset] || presets_1.defaults;
}
}
if (preset)
migratedConfig.preset = preset.name;
if (migratedConfig.moduleFileExtensions && migratedConfig.moduleFileExtensions.length && preset) {
presetValue = dedupSort(preset.value.moduleFileExtensions || []).join('::');
migratedValue = dedupSort(migratedConfig.moduleFileExtensions).join('::');
if (presetValue === migratedValue) {
delete migratedConfig.moduleFileExtensions;
}
}
if (migratedConfig.testRegex && preset) {
migratedConfig.testMatch = null;
}
else if (migratedConfig.testMatch && migratedConfig.testMatch.length && preset) {
presetValue = dedupSort(preset.value.testMatch || []).join('::');
migratedValue = dedupSort(migratedConfig.testMatch).join('::');
if (presetValue === migratedValue) {
delete migratedConfig.testMatch;
}
}
if (migratedConfig.transform) {
Object.keys(migratedConfig.transform).forEach(function (key) {
var val = migratedConfig.transform[key];
if (typeof val === 'string' && /\/?ts-jest(?:\/preprocessor\.js)?$/.test(val)) {
;
migratedConfig.transform[key] = 'ts-jest';
}
});
}
if (preset &&
migratedConfig.transform &&
stringifyJson(migratedConfig.transform) === stringifyJson(preset.value.transform)) {
delete migratedConfig.transform;
}
cleanupConfig(actualConfig);
cleanupConfig(migratedConfig);
before = stringifyJson(actualConfig);
after = stringifyJson(migratedConfig);
if (after === before) {
process.stderr.write("\nNo migration needed for given Jest configuration\n ");
return [2];
}
stringify = /\.json$/.test(file) ? JSON.stringify : json5_1.stringify;
prefix = /\.json$/.test(file) ? '"jest": ' : 'module.exports = ';
if (preset && migratedConfig.transform) {
footNotes.push("\nI couldn't check if your \"transform\" value is the same as mine which is: " + stringify(preset.value.transform, undefined, ' ') + "\nIf it is the case, you can safely remove the \"transform\" from what I've migrated.\n");
}
process.stderr.write("\nMigrated Jest configuration:\n");
process.stdout.write("" + prefix + stringify(migratedConfig, undefined, ' ') + "\n");
if (footNotes.length) {
process.stderr.write("\n" + footNotes.join('\n') + "\n");
}
return [2];
});
}); };
function cleanupConfig(config) {
if (config.globals) {
if (config.globals['ts-jest'] && Object.keys(config.globals['ts-jest']).length === 0) {
delete config.globals['ts-jest'];
}
if (Object.keys(config.globals).length === 0) {
delete config.globals;
}
}
if (config.transform && Object.keys(config.transform).length === 0) {
delete config.transform;
}
if (config.moduleFileExtensions) {
config.moduleFileExtensions = dedupSort(config.moduleFileExtensions);
if (config.moduleFileExtensions.length === 0)
delete config.moduleFileExtensions;
}
if (config.testMatch) {
config.testMatch = dedupSort(config.testMatch);
if (config.testMatch.length === 0)
delete config.testMatch;
}
if (config.preset === "ts-jest/presets/default")
config.preset = presets_1.defaults.name;
}
function dedupSort(arr) {
return arr
.filter(function (s, i, a) { return a.findIndex(function (e) { return s.toString() === e.toString(); }) === i; })
.sort(function (a, b) { return (a.toString() > b.toString() ? 1 : a.toString() < b.toString() ? -1 : 0); });
}
exports.help = function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
process.stdout.write("\nUsage:\n ts-jest config:migrate [options] <config-file>\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n\nOptions:\n --js ts|babel Process .js files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n");
return [2];
});
}); };
+1
View File
@@ -0,0 +1 @@
export {};
+45
View File
@@ -0,0 +1,45 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = function (_) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
process.stdout.write("\nUsage:\n ts-jest command [options] [...args]\n\nCommands:\n config:init Creates initial Jest configuration\n config:migrate Migrates a given Jest configuration\n help [command] Show this help, or help about a command\n\nExample:\n ts-jest help config:migrate\n");
return [2];
});
}); };
exports.help = exports.run;
+1
View File
@@ -0,0 +1 @@
export {};
+33
View File
@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var definePreset = function (fullName) { return ({
fullName: fullName,
get name() {
return this.isDefault ? 'ts-jest' : fullName;
},
get label() {
return fullName.split('/').pop();
},
get jsVarName() {
return this.isDefault
? 'defaults'
: fullName
.split('/')
.pop()
.replace(/\-([a-z])/g, function (_, l) { return l.toUpperCase(); });
},
get value() {
return require("../../../" + fullName.replace(/^ts-jest\//, '') + "/jest-preset");
},
jsImport: function (varName) {
if (varName === void 0) { varName = 'tsjPreset'; }
return "const { " + this.jsVarName + ": " + varName + " } = require('ts-jest/presets')";
},
get isDefault() {
return fullName === "ts-jest/presets/default";
},
}); };
exports.allPresets = {};
exports.defaults = (exports.allPresets["ts-jest/presets/default"] = definePreset("ts-jest/presets/default"));
exports.jsWithTs = (exports.allPresets["ts-jest/presets/js-with-ts"] = definePreset("ts-jest/presets/js-with-ts"));
exports.jsWIthBabel = (exports.allPresets["ts-jest/presets/js-with-babel"] = definePreset("ts-jest/presets/js-with-babel"));
+1
View File
@@ -0,0 +1 @@
export {};
+103
View File
@@ -0,0 +1,103 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var yargsParser = require("yargs-parser");
var logger_1 = require("../util/logger");
var VALID_COMMANDS = ['help', 'config:migrate', 'config:init'];
var logger = logger_1.rootLogger.child((_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'cli', _a[bs_logger_1.LogContexts.application] = 'ts-jest', _a));
function cli(args) {
return __awaiter(this, void 0, void 0, function () {
var parsedArgv, command, isHelp, _a, run, help, cmd;
return __generator(this, function (_b) {
parsedArgv = yargsParser(args, {
boolean: ['dry-run', 'jest-preset', 'allow-js', 'diff', 'babel', 'force', 'jsdom'],
string: ['tsconfig', 'js'],
count: ['verbose'],
alias: { verbose: ['v'] },
default: { jestPreset: true, verbose: 0 },
coerce: {
js: function (val) {
var res = val.trim().toLowerCase();
if (!['babel', 'ts'].includes(res))
throw new Error("The 'js' option must be 'babel' or 'ts', given: '" + val + "'.");
return res;
},
},
});
if (parsedArgv.allowJs != null) {
if (parsedArgv.js)
throw new Error("The 'allowJs' and 'js' options cannot be set together.");
parsedArgv.js = parsedArgv.allowJs ? 'ts' : undefined;
}
command = parsedArgv._.shift();
isHelp = command === 'help';
if (isHelp)
command = parsedArgv._.shift();
if (!VALID_COMMANDS.includes(command))
command = 'help';
_a = require("./" + command.replace(/:/g, '/')), run = _a.run, help = _a.help;
cmd = isHelp && command !== 'help' ? help : run;
return [2, cmd(parsedArgv, logger)];
});
});
}
function processArgv() {
return __awaiter(this, void 0, void 0, function () {
var err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4, cli(process.argv.slice(2))];
case 1:
_a.sent();
process.exit(0);
return [3, 3];
case 2:
err_1 = _a.sent();
logger.fatal(err_1.message);
process.exit(1);
return [3, 3];
case 3: return [2];
}
});
});
}
exports.processArgv = processArgv;
+1
View File
@@ -0,0 +1 @@
export {};
+128
View File
@@ -0,0 +1,128 @@
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs_1 = require("fs");
var mkdirp = require("mkdirp");
var path_1 = require("path");
var sha1_1 = require("../util/sha1");
var language_service_1 = require("./language-service");
var program_1 = require("./program");
var transpile_module_1 = require("./transpile-module");
function updateOutput(outputText, normalizedFileName, sourceMap, getExtension) {
var base = path_1.basename(normalizedFileName);
var base64Map = Buffer.from(updateSourceMap(sourceMap, normalizedFileName), 'utf8').toString('base64');
var sourceMapContent = "data:application/json;charset=utf-8;base64," + base64Map;
var sourceMapLength = (base + ".map").length + (getExtension(normalizedFileName).length - path_1.extname(normalizedFileName).length);
return outputText.slice(0, -sourceMapLength) + sourceMapContent;
}
var updateSourceMap = function (sourceMapText, normalizedFileName) {
var sourceMap = JSON.parse(sourceMapText);
sourceMap.file = normalizedFileName;
sourceMap.sources = [normalizedFileName];
delete sourceMap.sourceRoot;
return JSON.stringify(sourceMap);
};
var getCacheName = function (sourceCode, normalizedFileName) {
return sha1_1.sha1(normalizedFileName, '\x00', sourceCode);
};
var isValidCacheContent = function (contents) {
return /(?:9|0=|Q==)$/.test(contents.slice(-3));
};
var readThrough = function (cachedir, memoryCache, compileFn, getExtension, logger) {
if (!cachedir) {
return function (code, fileName, lineOffset) {
var normalizedFileName = path_1.normalize(fileName);
logger.debug({ normalizedFileName: normalizedFileName }, 'readThrough(): no cache');
var _a = __read(compileFn(code, normalizedFileName, lineOffset), 2), value = _a[0], sourceMap = _a[1];
var output = updateOutput(value, fileName, sourceMap, getExtension);
memoryCache.outputs[normalizedFileName] = output;
return output;
};
}
mkdirp.sync(cachedir);
return function (code, fileName, lineOffset) {
var normalizedFileName = path_1.normalize(fileName), cachePath = path_1.join(cachedir, getCacheName(code, normalizedFileName)), extension = getExtension(normalizedFileName), outputPath = "" + cachePath + extension;
try {
var output_1 = fs_1.readFileSync(outputPath, 'utf8');
if (isValidCacheContent(output_1)) {
logger.debug({ normalizedFileName: normalizedFileName }, 'readThrough(): cache hit');
memoryCache.outputs[normalizedFileName] = output_1;
return output_1;
}
}
catch (err) { }
logger.debug({ fileName: fileName }, 'readThrough(): cache miss');
var _a = __read(compileFn(code, normalizedFileName, lineOffset), 2), value = _a[0], sourceMap = _a[1], output = updateOutput(value, normalizedFileName, sourceMap, getExtension);
logger.debug({ normalizedFileName: normalizedFileName, outputPath: outputPath }, 'readThrough(): writing caches');
memoryCache.outputs[normalizedFileName] = output;
fs_1.writeFileSync(outputPath, output);
return output;
};
};
exports.createCompiler = function (configs) {
var e_1, _a;
var logger = configs.logger.child({ namespace: 'ts-compiler' });
var _b = configs.typescript, compilerOptions = _b.options, fileNames = _b.fileNames, tsJest = configs.tsJest;
var cachedir = configs.tsCacheDir, ts = configs.compilerModule, extensions = ['.ts', '.tsx'], memoryCache = {
contents: Object.create(null),
versions: Object.create(null),
outputs: Object.create(null),
};
if (compilerOptions.allowJs) {
extensions.push('.js');
extensions.push('.jsx');
}
try {
for (var fileNames_1 = __values(fileNames), fileNames_1_1 = fileNames_1.next(); !fileNames_1_1.done; fileNames_1_1 = fileNames_1.next()) {
var path = fileNames_1_1.value;
memoryCache.versions[path_1.normalize(path)] = 1;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (fileNames_1_1 && !fileNames_1_1.done && (_a = fileNames_1.return)) _a.call(fileNames_1);
}
finally { if (e_1) throw e_1.error; }
}
var getExtension = compilerOptions.jsx === ts.JsxEmit.Preserve
? function (path) { return (/\.[tj]sx$/.test(path) ? '.jsx' : '.js'); }
: function (_) { return '.js'; };
var compilerInstance;
if (!tsJest.isolatedModules) {
compilerInstance = !tsJest.compilerHost
? language_service_1.compileUsingLanguageService(configs, logger, memoryCache)
: program_1.compileUsingProgram(configs, logger, memoryCache);
}
else {
compilerInstance = transpile_module_1.compileUsingTranspileModule(configs, logger);
}
var compile = readThrough(cachedir, memoryCache, compilerInstance.compileFn, getExtension, logger);
return { cwd: configs.cwd, compile: compile, program: compilerInstance.program, diagnose: compilerInstance.diagnoseFn };
};
+1
View File
@@ -0,0 +1 @@
export {};
+94
View File
@@ -0,0 +1,94 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var memoize = require("lodash.memoize");
var path_1 = require("path");
var messages_1 = require("../util/messages");
var hasOwn = Object.prototype.hasOwnProperty;
exports.compileUsingLanguageService = function (configs, logger, memoryCache) {
var _a;
logger.debug('compileUsingLanguageService(): create typescript compiler');
var ts = configs.compilerModule, cwd = configs.cwd, options = configs.typescript.options, serviceHostTraceCtx = (_a = {
namespace: 'ts:serviceHost',
call: null
},
_a[bs_logger_1.LogContexts.logLevel] = bs_logger_1.LogLevels.trace,
_a);
var projectVersion = 1;
var updateMemoryCache = function (code, fileName) {
var _a;
logger.debug({ fileName: fileName }, "updateMemoryCache(): update memory cache for language service");
var fileVersion = (_a = memoryCache.versions[fileName]) !== null && _a !== void 0 ? _a : 0, isFileInCache = fileVersion !== 0;
if (!isFileInCache) {
memoryCache.versions[fileName] = 1;
}
if (memoryCache.contents[fileName] !== code) {
memoryCache.contents[fileName] = code;
memoryCache.versions[fileName] = fileVersion + 1;
projectVersion++;
}
};
var serviceHost = {
getProjectVersion: function () { return String(projectVersion); },
getScriptFileNames: function () { return Object.keys(memoryCache.versions); },
getScriptVersion: function (fileName) {
var normalizedFileName = path_1.normalize(fileName), version = memoryCache.versions[normalizedFileName];
return version === undefined ? undefined : String(version);
},
getScriptSnapshot: function (fileName) {
var normalizedFileName = path_1.normalize(fileName), hit = hasOwn.call(memoryCache.contents, normalizedFileName);
logger.trace({ normalizedFileName: normalizedFileName, cacheHit: hit }, "getScriptSnapshot():", 'cache', hit ? 'hit' : 'miss');
if (!hit) {
memoryCache.contents[normalizedFileName] = ts.sys.readFile(normalizedFileName);
}
var contents = memoryCache.contents[normalizedFileName];
if (contents === undefined) {
return;
}
return ts.ScriptSnapshot.fromString(contents);
},
fileExists: memoize(ts.sys.fileExists),
readFile: logger.wrap(serviceHostTraceCtx, 'readFile', memoize(ts.sys.readFile)),
readDirectory: memoize(ts.sys.readDirectory),
getDirectories: memoize(ts.sys.getDirectories),
directoryExists: memoize(ts.sys.directoryExists),
realpath: memoize(ts.sys.realpath),
getNewLine: function () { return '\n'; },
getCurrentDirectory: function () { return cwd; },
getCompilationSettings: function () { return options; },
getDefaultLibFileName: function () { return ts.getDefaultLibFilePath(options); },
getCustomTransformers: function () { return configs.tsCustomTransformers; },
};
logger.debug('compileUsingLanguageService(): creating language service');
var service = ts.createLanguageService(serviceHost);
return {
compileFn: function (code, fileName) {
var normalizedFileName = path_1.normalize(fileName);
logger.debug({ normalizedFileName: normalizedFileName }, 'compileFn(): compiling using language service');
updateMemoryCache(code, normalizedFileName);
var output = service.getEmitOutput(normalizedFileName);
if (output.emitSkipped) {
throw new TypeError(path_1.relative(cwd, normalizedFileName) + ": Emit skipped for language service");
}
if (!output.outputFiles.length) {
throw new TypeError(messages_1.interpolate("Unable to require `.d.ts` file for file: {{file}}.\nThis is usually the result of a faulty configuration or import. Make sure there is a `.js`, `.json` or another executable extension available alongside `{{file}}`.", {
file: path_1.basename(normalizedFileName),
}));
}
return [output.outputFiles[1].text, output.outputFiles[0].text];
},
diagnoseFn: function (code, filePath) {
var normalizedFileName = path_1.normalize(filePath);
updateMemoryCache(code, normalizedFileName);
if (configs.shouldReportDiagnostic(normalizedFileName)) {
logger.debug({ normalizedFileName: normalizedFileName }, 'compileFn(): computing diagnostics for language service');
var diagnostics = service
.getCompilerOptionsDiagnostics()
.concat(service.getSyntacticDiagnostics(normalizedFileName))
.concat(service.getSemanticDiagnostics(normalizedFileName));
configs.raiseDiagnostics(diagnostics, normalizedFileName, logger);
}
},
program: service.getProgram(),
};
};
+1
View File
@@ -0,0 +1 @@
export {};
+123
View File
@@ -0,0 +1,123 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var memoize = require("lodash.memoize");
var path_1 = require("path");
var messages_1 = require("../util/messages");
var hasOwn = Object.prototype.hasOwnProperty;
exports.compileUsingProgram = function (configs, logger, memoryCache) {
var _a;
logger.debug('compileUsingProgram(): create typescript compiler');
var ts = configs.compilerModule, cwd = configs.cwd, _b = configs.typescript, options = _b.options, projectReferences = _b.projectReferences, errors = _b.errors, incremental = configs.tsJest.incremental;
var compilerHostTraceCtx = (_a = {
namespace: 'ts:compilerHost',
call: null
},
_a[bs_logger_1.LogContexts.logLevel] = bs_logger_1.LogLevels.trace,
_a), sys = __assign(__assign({}, ts.sys), { readFile: logger.wrap(compilerHostTraceCtx, 'readFile', memoize(ts.sys.readFile)), readDirectory: memoize(ts.sys.readDirectory), getDirectories: memoize(ts.sys.getDirectories), fileExists: memoize(ts.sys.fileExists), directoryExists: memoize(ts.sys.directoryExists), resolvePath: memoize(ts.sys.resolvePath), realpath: memoize(ts.sys.realpath), getCurrentDirectory: function () { return cwd; }, getNewLine: function () { return '\n'; }, getCanonicalFileName: function (fileName) {
return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
} });
var builderProgram, program, host;
if (incremental) {
host = ts.createIncrementalCompilerHost(options, sys);
builderProgram = ts.createIncrementalProgram({
rootNames: Object.keys(memoryCache.versions),
options: options,
host: host,
configFileParsingDiagnostics: errors,
projectReferences: projectReferences,
});
program = builderProgram.getProgram();
}
else {
host = __assign(__assign({}, sys), { getSourceFile: function (fileName, languageVersion) {
var contents = ts.sys.readFile(fileName);
if (contents === undefined)
return;
return ts.createSourceFile(fileName, contents, languageVersion);
}, getDefaultLibFileName: function () { return ts.getDefaultLibFilePath(options); }, useCaseSensitiveFileNames: function () { return sys.useCaseSensitiveFileNames; } });
program = ts.createProgram({
rootNames: Object.keys(memoryCache.versions),
options: options,
host: host,
configFileParsingDiagnostics: errors,
projectReferences: projectReferences,
});
}
var customTransformers = configs.tsCustomTransformers, updateMemoryCache = function (code, fileName) {
logger.debug({ fileName: fileName }, "updateMemoryCache(): update memory cache for " + (incremental ? 'incremental program' : 'program'));
var sourceFile = incremental ? builderProgram.getSourceFile(fileName) : program.getSourceFile(fileName);
if (!hasOwn.call(memoryCache.versions, fileName)) {
memoryCache.versions[fileName] = 1;
}
if (memoryCache.contents[fileName] !== code) {
memoryCache.contents[fileName] = code;
memoryCache.versions[fileName] = (memoryCache.versions[fileName] || 0) + 1;
}
if (sourceFile === undefined || sourceFile.text !== code || program.isSourceFileFromExternalLibrary(sourceFile)) {
var programOptions = {
rootNames: Object.keys(memoryCache.versions),
options: options,
host: host,
configFileParsingDiagnostics: errors,
projectReferences: projectReferences,
};
if (incremental) {
builderProgram = ts.createIncrementalProgram(programOptions);
program = builderProgram.getProgram();
}
else {
program = ts.createProgram(__assign(__assign({}, programOptions), { oldProgram: program }));
}
}
};
return {
compileFn: function (code, fileName) {
var normalizedFileName = path_1.normalize(fileName), output = ['', ''];
logger.debug({ normalizedFileName: normalizedFileName }, "compileFn(): compiling using " + (incremental ? 'incremental program' : 'program'));
updateMemoryCache(code, normalizedFileName);
var sourceFile = incremental
? builderProgram.getSourceFile(normalizedFileName)
: program.getSourceFile(normalizedFileName);
if (!sourceFile)
throw new TypeError("Unable to read file: " + fileName);
var result = incremental
? builderProgram.emit(sourceFile, function (path, file, _writeByteOrderMark) {
output[path.endsWith('.map') ? 1 : 0] = file;
}, undefined, undefined, customTransformers)
: program.emit(sourceFile, function (path, file, _writeByteOrderMark) {
output[path.endsWith('.map') ? 1 : 0] = file;
}, undefined, undefined, customTransformers);
if (result.emitSkipped) {
throw new TypeError(path_1.relative(cwd, fileName) + ": Emit skipped");
}
if (output[0] === '') {
throw new TypeError(messages_1.interpolate("Unable to require `.d.ts` file for file: {{file}}.\nThis is usually the result of a faulty configuration or import. Make sure there is a `.js`, `.json` or another executable extension available alongside `{{file}}`.", {
file: path_1.basename(normalizedFileName),
}));
}
return output;
},
diagnoseFn: function (code, filePath) {
var normalizedFileName = path_1.normalize(filePath);
updateMemoryCache(code, normalizedFileName);
if (configs.shouldReportDiagnostic(normalizedFileName)) {
logger.debug({ normalizedFileName: normalizedFileName }, "compileFn(): computing diagnostics for " + (incremental ? 'incremental program' : 'program'));
var sourceFile = program.getSourceFile(normalizedFileName), diagnostics = program.getSemanticDiagnostics(sourceFile).concat(program.getSyntacticDiagnostics(sourceFile));
configs.raiseDiagnostics(diagnostics, normalizedFileName, logger);
}
},
program: program,
};
};
+1
View File
@@ -0,0 +1 @@
export {};
+21
View File
@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var path_1 = require("path");
exports.compileUsingTranspileModule = function (configs, logger) {
logger.debug('compileUsingTranspileModule(): create typescript compiler');
return {
compileFn: function (code, fileName) {
logger.debug({ fileName: fileName }, 'getOutput(): compiling as isolated module');
var normalizedFileName = path_1.normalize(fileName), result = configs.compilerModule.transpileModule(code, {
fileName: normalizedFileName,
transformers: configs.tsCustomTransformers,
compilerOptions: configs.typescript.options,
reportDiagnostics: configs.shouldReportDiagnostic(normalizedFileName),
});
if (result.diagnostics && configs.shouldReportDiagnostic(normalizedFileName)) {
configs.raiseDiagnostics(result.diagnostics, normalizedFileName, logger);
}
return [result.outputText, result.sourceMapText];
},
};
};
+35
View File
@@ -0,0 +1,35 @@
import { Config } from '@jest/types';
import { Logger } from 'bs-logger';
import { CompilerOptions, CustomTransformers, ParsedCommandLine } from 'typescript';
import { AstTransformerDesc, BabelConfig, BabelJestTransformer, TTypeScript, TsCompiler, TsJestConfig, TsJestGlobalOptions, TsJestHooksMap } from '../types';
export declare class ConfigSet {
readonly parentOptions?: TsJestGlobalOptions | undefined;
get projectPackageJson(): Record<string, any>;
get projectDependencies(): Record<string, string>;
get jest(): Config.ProjectConfig;
get tsJest(): TsJestConfig;
get typescript(): ParsedCommandLine;
get tsconfig(): any;
get versions(): Record<string, string>;
get babel(): BabelConfig | undefined;
get compilerModule(): TTypeScript;
get babelJestTransformer(): BabelJestTransformer | undefined;
get tsCompiler(): TsCompiler;
get astTransformers(): AstTransformerDesc[];
get tsCustomTransformers(): CustomTransformers;
get hooks(): TsJestHooksMap;
get shouldReportDiagnostic(): (filePath: string) => boolean;
get shouldStringifyContent(): (filePath: string) => boolean;
get tsCacheDir(): string | undefined;
get overriddenCompilerOptions(): Partial<CompilerOptions>;
get rootDir(): string;
get cwd(): string;
get tsJestDigest(): string;
get cacheKey(): string;
readonly logger: Logger;
constructor(jestConfig: Config.ProjectConfig, parentOptions?: TsJestGlobalOptions | undefined, parentLogger?: Logger);
resolvePath(inputPath: string, { throwIfMissing, nodeResolve }?: {
throwIfMissing?: boolean;
nodeResolve?: boolean;
}): string;
}
+776
View File
@@ -0,0 +1,776 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var fs_1 = require("fs");
var json5 = require("json5");
var path_1 = require("path");
var __1 = require("..");
var instance_1 = require("../compiler/instance");
var transformers_1 = require("../transformers");
var backports_1 = require("../util/backports");
var get_package_version_1 = require("../util/get-package-version");
var importer_1 = require("../util/importer");
var json_1 = require("../util/json");
var jsonable_value_1 = require("../util/jsonable-value");
var logger_1 = require("../util/logger");
var memoize_1 = require("../util/memoize");
var messages_1 = require("../util/messages");
var normalize_slashes_1 = require("../util/normalize-slashes");
var sha1_1 = require("../util/sha1");
var ts_error_1 = require("../util/ts-error");
var logger = logger_1.rootLogger.child({ namespace: 'config' });
exports.MATCH_NOTHING = /a^/;
exports.IGNORE_DIAGNOSTIC_CODES = [
6059,
18002,
18003,
];
var normalizeRegex = function (pattern) {
return pattern ? (typeof pattern === 'string' ? pattern : pattern.source) : undefined;
};
var toDiagnosticCode = function (code) {
return code ? parseInt(("" + code).trim().replace(/^TS/, ''), 10) || undefined : undefined;
};
var toDiagnosticCodeList = function (items, into) {
var e_1, _a;
if (into === void 0) { into = []; }
if (!Array.isArray(items))
items = [items];
try {
for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
var item = items_1_1.value;
if (!item)
continue;
if (Array.isArray(item)) {
toDiagnosticCodeList(item, into);
continue;
}
else if (typeof item === 'string') {
var children = item.trim().split(/\s*,\s*/g);
if (children.length > 1) {
toDiagnosticCodeList(children, into);
continue;
}
item = children[0];
}
if (!item)
continue;
var code = toDiagnosticCode(item);
if (code && !into.includes(code))
into.push(code);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
}
finally { if (e_1) throw e_1.error; }
}
return into;
};
var ConfigSet = (function () {
function ConfigSet(jestConfig, parentOptions, parentLogger) {
var _a;
this.parentOptions = parentOptions;
this._jestConfig = jestConfig;
this.logger = parentLogger ? parentLogger.child((_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'config', _a)) : logger;
}
Object.defineProperty(ConfigSet.prototype, "projectPackageJson", {
get: function () {
var packageJson = this.tsJest.packageJson;
if (packageJson && packageJson.kind === 'inline') {
return packageJson.value;
}
if (packageJson && packageJson.kind === 'file' && packageJson.value) {
var path = this.resolvePath(packageJson.value);
if (fs_1.existsSync(path)) {
return require(path);
}
this.logger.warn("Unable to find the root of the project where ts-jest has been installed.");
return {};
}
var tsJestRoot = path_1.resolve(__dirname, '..', '..');
var pkgPath = path_1.resolve(tsJestRoot, '..', '..', 'package.json');
if (fs_1.existsSync(pkgPath)) {
return require(pkgPath);
}
if (fs_1.realpathSync(this.rootDir) === fs_1.realpathSync(tsJestRoot)) {
pkgPath = path_1.resolve(tsJestRoot, 'package.json');
if (fs_1.existsSync(pkgPath)) {
return require(pkgPath);
}
}
this.logger.warn("Unable to find the root of the project where ts-jest has been installed.");
return {};
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "projectDependencies", {
get: function () {
var pkg = this.projectPackageJson;
var names = Object.keys(__assign(__assign(__assign(__assign({}, pkg.optionalDependencies), pkg.peerDependencies), pkg.devDependencies), pkg.dependencies));
return names.reduce(function (map, name) {
var version = get_package_version_1.getPackageVersion(name);
if (version)
map[name] = version;
return map;
}, {});
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "jest", {
get: function () {
var _a;
var config = backports_1.backportJestConfig(this.logger, this._jestConfig);
if (this.parentOptions) {
var globals = (_a = config.globals) !== null && _a !== void 0 ? _a : {};
globals['ts-jest'] = __assign(__assign({}, this.parentOptions), globals['ts-jest']);
}
this.logger.debug({ jestConfig: config }, 'normalized jest config');
return config;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "tsJest", {
get: function () {
var _this = this;
var _a, _b, _c;
var parsedConfig = this.jest;
var _d = parsedConfig.globals, globals = _d === void 0 ? {} : _d;
var options = __assign({}, globals['ts-jest']);
var tsConfigOpt = options.tsConfig;
var tsConfig;
if (typeof tsConfigOpt === 'string' || tsConfigOpt == null || tsConfigOpt === true) {
tsConfig = {
kind: 'file',
value: typeof tsConfigOpt === 'string' ? this.resolvePath(tsConfigOpt) : undefined,
};
}
else if (typeof tsConfigOpt === 'object') {
tsConfig = {
kind: 'inline',
value: tsConfigOpt,
};
}
var packageJsonOpt = options.packageJson;
var packageJson;
if (typeof packageJsonOpt === 'string' || packageJsonOpt == null || packageJsonOpt === true) {
packageJson = {
kind: 'file',
value: typeof packageJsonOpt === 'string' ? this.resolvePath(packageJsonOpt) : undefined,
};
}
else if (typeof packageJsonOpt === 'object') {
packageJson = {
kind: 'inline',
value: packageJsonOpt,
};
}
var transformers = (options.astTransformers || []).map(function (mod) { return _this.resolvePath(mod, { nodeResolve: true }); });
var babelConfigOpt = options.babelConfig;
var babelConfig;
if (typeof babelConfigOpt === 'string' || babelConfigOpt === true) {
babelConfig = {
kind: 'file',
value: babelConfigOpt === true ? undefined : this.resolvePath(babelConfigOpt),
};
}
else if (babelConfigOpt) {
babelConfig = {
kind: 'inline',
value: babelConfigOpt,
};
}
var diagnostics;
var _e = options.diagnostics, diagnosticsOpt = _e === void 0 ? true : _e;
var ignoreList = [exports.IGNORE_DIAGNOSTIC_CODES, process.env.TS_JEST_IGNORE_DIAGNOSTICS];
if (diagnosticsOpt === true || diagnosticsOpt == null) {
diagnostics = { ignoreCodes: [], pretty: true, throws: true };
}
else if (diagnosticsOpt === false) {
diagnostics = {
throws: false,
pretty: true,
ignoreCodes: [],
pathRegex: exports.MATCH_NOTHING.source,
};
}
else {
ignoreList.push(diagnosticsOpt.ignoreCodes);
diagnostics = {
pretty: diagnosticsOpt.pretty == null ? true : !!diagnosticsOpt.pretty,
ignoreCodes: [],
pathRegex: normalizeRegex(diagnosticsOpt.pathRegex),
throws: !diagnosticsOpt.warnOnly,
};
}
diagnostics.ignoreCodes = toDiagnosticCodeList(ignoreList);
var stringifyContentPathRegex = normalizeRegex(options.stringifyContentPathRegex);
var res = {
tsConfig: tsConfig,
compilerHost: (_a = options.compilerHost) !== null && _a !== void 0 ? _a : false,
incremental: (_b = options.incremental) !== null && _b !== void 0 ? _b : true,
packageJson: packageJson,
babelConfig: babelConfig,
diagnostics: diagnostics,
isolatedModules: !!options.isolatedModules,
compiler: (_c = options.compiler) !== null && _c !== void 0 ? _c : 'typescript',
transformers: transformers,
stringifyContentPathRegex: stringifyContentPathRegex,
};
this.logger.debug({ tsJestConfig: res }, 'normalized ts-jest config');
return res;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "typescript", {
get: function () {
return this._typescript.resolved;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "tsconfig", {
get: function () {
return this._typescript.input;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "versions", {
get: function () {
var modules = ['jest', this.tsJest.compiler];
if (this.tsJest.babelConfig) {
modules.push('@babel/core', 'babel-jest');
}
return modules.reduce(function (map, name) {
var _a;
map[name] = (_a = get_package_version_1.getPackageVersion(name)) !== null && _a !== void 0 ? _a : '-';
return map;
}, { 'ts-jest': __1.version });
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "_typescript", {
get: function () {
var tsConfig = this.tsJest.tsConfig;
var configFilePath = tsConfig && tsConfig.kind === 'file' ? tsConfig.value : undefined;
var result = this.readTsConfig(tsConfig && tsConfig.kind === 'inline' ? tsConfig.value : undefined, configFilePath, tsConfig == null);
this.raiseDiagnostics(result.resolved.errors, configFilePath);
this.logger.debug({ tsconfig: result }, 'normalized typescript config');
return result;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "raiseDiagnostics", {
get: function () {
var _this = this;
var _a = this, createTsError = _a.createTsError, filterDiagnostics = _a.filterDiagnostics, throws = _a.tsJest.diagnostics.throws, DiagnosticCategory = _a.compilerModule.DiagnosticCategory;
return function (diagnostics, filePath, logger) {
if (logger === void 0) { logger = _this.logger; }
var filteredDiagnostics = filterDiagnostics(diagnostics, filePath);
if (!filteredDiagnostics.length)
return;
var error = createTsError(filteredDiagnostics);
var importantCategories = [DiagnosticCategory.Warning, DiagnosticCategory.Error];
if (throws && filteredDiagnostics.some(function (d) { return importantCategories.includes(d.category); })) {
throw error;
}
logger.warn({ error: error }, error.message);
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "babel", {
get: function () {
var babelConfig = this.tsJest.babelConfig;
if (babelConfig == null) {
this.logger.debug('babel is disabled');
return;
}
var base = { cwd: this.cwd };
if (babelConfig.kind === 'file') {
if (babelConfig.value) {
if (path_1.extname(babelConfig.value) === '.js') {
base = __assign(__assign({}, base), require(babelConfig.value));
}
else {
base = __assign(__assign({}, base), json5.parse(fs_1.readFileSync(babelConfig.value, 'utf8')));
}
}
}
else if (babelConfig.kind === 'inline') {
base = __assign(__assign({}, base), babelConfig.value);
}
this.logger.debug({ babelConfig: base }, 'normalized babel config via ts-jest option');
return base;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "compilerModule", {
get: function () {
return importer_1.importer.typescript("Using \"ts-jest\" requires this package to be installed.", this.tsJest.compiler);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "babelJestTransformer", {
get: function () {
var babel = this.babel;
if (!babel)
return;
this.logger.debug('creating babel-jest transformer');
return importer_1.importer.babelJest("Using \"babel-jest\" requires this package to be installed.").createTransformer(babel);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "tsCompiler", {
get: function () {
return instance_1.createCompiler(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "astTransformers", {
get: function () {
return __spread(transformers_1.internals, this.tsJest.transformers.map(function (m) { return require(m); }));
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "tsCustomTransformers", {
get: function () {
var _this = this;
return {
before: this.astTransformers.map(function (t) { return t.factory(_this); }),
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "hooks", {
get: function () {
var hooksFile = process.env.TS_JEST_HOOKS;
if (hooksFile) {
hooksFile = path_1.resolve(this.cwd, hooksFile);
return importer_1.importer.tryTheseOr(hooksFile, {});
}
return {};
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "filterDiagnostics", {
get: function () {
var _a = this, ignoreCodes = _a.tsJest.diagnostics.ignoreCodes, shouldReportDiagnostic = _a.shouldReportDiagnostic;
return function (diagnostics, filePath) {
if (filePath && !shouldReportDiagnostic(filePath))
return [];
return diagnostics.filter(function (diagnostic) {
var _a;
if (((_a = diagnostic.file) === null || _a === void 0 ? void 0 : _a.fileName) && !shouldReportDiagnostic(diagnostic.file.fileName)) {
return false;
}
return ignoreCodes.indexOf(diagnostic.code) === -1;
});
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "shouldReportDiagnostic", {
get: function () {
var pathRegex = this.tsJest.diagnostics.pathRegex;
if (pathRegex) {
var regex_1 = new RegExp(pathRegex);
return function (file) { return regex_1.test(file); };
}
else {
return function () { return true; };
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "shouldStringifyContent", {
get: function () {
var stringifyContentPathRegex = this.tsJest.stringifyContentPathRegex;
if (stringifyContentPathRegex) {
var regex_2 = new RegExp(stringifyContentPathRegex);
return function (file) { return regex_2.test(file); };
}
else {
return function () { return false; };
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "createTsError", {
get: function () {
var _this = this;
var pretty = this.tsJest.diagnostics.pretty;
var formatDiagnostics = pretty
? this.compilerModule.formatDiagnosticsWithColorAndContext
: this.compilerModule.formatDiagnostics;
var diagnosticHost = {
getNewLine: function () { return '\n'; },
getCurrentDirectory: function () { return _this.cwd; },
getCanonicalFileName: function (path) { return path; },
};
return function (diagnostics) {
var diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
var diagnosticCodes = diagnostics.map(function (x) { return x.code; });
return new ts_error_1.TSError(diagnosticText, diagnosticCodes);
};
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "tsCacheDir", {
get: function () {
if (!this.jest.cache) {
logger.debug('file caching disabled');
return;
}
var cacheSuffix = sha1_1.sha1(json_1.stringify({
version: this.compilerModule.version,
digest: this.tsJestDigest,
dependencies: this.projectDependencies,
compiler: this.tsJest.compiler,
compilerOptions: this.typescript.options,
isolatedModules: this.tsJest.isolatedModules,
diagnostics: this.tsJest.diagnostics,
}));
var res = path_1.join(this.jest.cacheDirectory, 'ts-jest', cacheSuffix.substr(0, 2), cacheSuffix.substr(2));
logger.debug({ cacheDirectory: res }, 'will use file caching');
return res;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "overriddenCompilerOptions", {
get: function () {
var options = {
sourceMap: true,
inlineSourceMap: false,
inlineSources: true,
declaration: false,
noEmit: false,
removeComments: false,
out: undefined,
outFile: undefined,
composite: undefined,
declarationDir: undefined,
declarationMap: undefined,
emitDeclarationOnly: undefined,
sourceRoot: undefined,
tsBuildInfoFile: undefined,
};
if (!this.tsJest.babelConfig) {
options.module = this.compilerModule.ModuleKind.CommonJS;
}
return options;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "rootDir", {
get: function () {
return path_1.normalize(this.jest.rootDir || this.cwd);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "cwd", {
get: function () {
return path_1.normalize(this.jest.cwd || process.cwd());
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "tsJestDigest", {
get: function () {
return __1.digest;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "jsonValue", {
get: function () {
var jest = __assign({}, this.jest);
var globals = (jest.globals = __assign({}, jest.globals));
delete jest.name;
delete jest.cacheDirectory;
delete globals['ts-jest'];
return new jsonable_value_1.JsonableValue({
versions: this.versions,
projectDepVersions: this.projectDependencies,
digest: this.tsJestDigest,
transformers: this.astTransformers.map(function (t) { return t.name + "@" + t.version; }),
jest: jest,
tsJest: this.tsJest,
babel: this.babel,
tsconfig: this.typescript.options,
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConfigSet.prototype, "cacheKey", {
get: function () {
return this.jsonValue.serialized;
},
enumerable: true,
configurable: true
});
ConfigSet.prototype.makeDiagnostic = function (code, messageText, options) {
if (options === void 0) { options = {}; }
var _a = options.category, category = _a === void 0 ? this.compilerModule.DiagnosticCategory.Warning : _a, file = options.file, start = options.start, length = options.length;
return {
code: code,
messageText: messageText,
category: category,
file: file,
start: start,
length: length,
};
};
ConfigSet.prototype.readTsConfig = function (compilerOptions, resolvedConfigFile, noProject) {
var e_2, _a;
var config = { compilerOptions: {} };
var basePath = normalize_slashes_1.normalizeSlashes(this.rootDir);
var configFileName;
var ts = this.compilerModule;
var input;
if (noProject) {
input = { compilerOptions: __assign({}, compilerOptions) };
}
else {
configFileName = resolvedConfigFile
? normalize_slashes_1.normalizeSlashes(resolvedConfigFile)
: ts.findConfigFile(normalize_slashes_1.normalizeSlashes(this.rootDir), ts.sys.fileExists);
if (configFileName) {
this.logger.debug({ tsConfigFileName: configFileName }, 'readTsConfig(): reading', configFileName);
var result_1 = ts.readConfigFile(configFileName, ts.sys.readFile);
if (result_1.error) {
return {
resolved: { errors: [result_1.error], fileNames: [], options: {} },
};
}
config = result_1.config;
input = __assign(__assign({}, result_1.config), { compilerOptions: __assign(__assign({}, (result_1.config && result_1.config.compilerOptions)), compilerOptions) });
basePath = normalize_slashes_1.normalizeSlashes(path_1.dirname(configFileName));
}
}
config.compilerOptions = __assign(__assign({}, config.compilerOptions), compilerOptions);
var result = ts.parseJsonConfigFileContent(config, ts.sys, basePath, undefined, configFileName);
var forcedOptions = this.overriddenCompilerOptions;
var finalOptions = result.options;
if (finalOptions.target === undefined) {
finalOptions.target = ts.ScriptTarget.ES5;
}
var target = finalOptions.target;
var defaultModule = [ts.ScriptTarget.ES3, ts.ScriptTarget.ES5].includes(target)
? ts.ModuleKind.CommonJS
: ts.ModuleKind.ESNext;
var moduleValue = finalOptions.module == null ? defaultModule : finalOptions.module;
if ('module' in forcedOptions &&
moduleValue !== forcedOptions.module &&
!(finalOptions.esModuleInterop || finalOptions.allowSyntheticDefaultImports)) {
result.errors.push(this.makeDiagnostic(151001, "If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.", {
category: ts.DiagnosticCategory.Message,
}));
if (!('allowSyntheticDefaultImports' in config.compilerOptions)) {
finalOptions.allowSyntheticDefaultImports = true;
}
}
try {
for (var _b = __values(Object.keys(forcedOptions)), _c = _b.next(); !_c.done; _c = _b.next()) {
var key = _c.value;
var val = forcedOptions[key];
if (val === undefined) {
delete finalOptions[key];
}
else {
finalOptions[key] = val;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_2) throw e_2.error; }
}
return { input: input, resolved: result };
};
ConfigSet.prototype.resolvePath = function (inputPath, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.throwIfMissing, throwIfMissing = _c === void 0 ? true : _c, _d = _b.nodeResolve, nodeResolve = _d === void 0 ? false : _d;
var path = inputPath;
var nodeResolved = false;
if (path.startsWith('<rootDir>')) {
path = path_1.resolve(path_1.join(this.rootDir, path.substr(9)));
}
else if (!path_1.isAbsolute(path)) {
if (!path.startsWith('.') && nodeResolve) {
try {
path = require.resolve(path);
nodeResolved = true;
}
catch (_) { }
}
if (!nodeResolved) {
path = path_1.resolve(this.cwd, path);
}
}
if (!nodeResolved && nodeResolve) {
try {
path = require.resolve(path);
nodeResolved = true;
}
catch (_) { }
}
if (throwIfMissing && !fs_1.existsSync(path)) {
throw new Error(messages_1.interpolate("File not found: {{inputPath}} (resolved as: {{resolvedPath}})", { inputPath: inputPath, resolvedPath: path }));
}
this.logger.debug({ fromPath: inputPath, toPath: path }, 'resolved path from', inputPath, 'to', path);
return path;
};
ConfigSet.prototype.toJSON = function () {
return this.jsonValue.value;
};
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "projectPackageJson", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "projectDependencies", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "jest", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "tsJest", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "versions", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "_typescript", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "raiseDiagnostics", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "babel", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "compilerModule", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "babelJestTransformer", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "tsCompiler", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "astTransformers", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "tsCustomTransformers", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "hooks", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "filterDiagnostics", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "shouldReportDiagnostic", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "shouldStringifyContent", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "createTsError", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "tsCacheDir", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "overriddenCompilerOptions", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "rootDir", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "cwd", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "tsJestDigest", null);
__decorate([
memoize_1.Memoize()
], ConfigSet.prototype, "jsonValue", null);
return ConfigSet;
}());
exports.ConfigSet = ConfigSet;
+10
View File
@@ -0,0 +1,10 @@
import { Config } from '@jest/types';
export interface TsJestPresets {
transform: Config.InitialOptions['transform'];
testMatch?: string[];
moduleFileExtensions?: string[];
}
export interface CreateJestPresetOptions {
allowJs?: boolean;
}
export declare function createJestPreset({ allowJs }?: CreateJestPresetOptions, from?: Config.InitialOptions): TsJestPresets;
+23
View File
@@ -0,0 +1,23 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var logger_1 = require("../util/logger");
var logger = logger_1.rootLogger.child({ namespace: 'jest-preset' });
function createJestPreset(_a, from) {
var _b;
var _c = (_a === void 0 ? {} : _a).allowJs, allowJs = _c === void 0 ? false : _c;
if (from === void 0) { from = {}; }
logger.debug({ allowJs: allowJs }, 'creating jest presets', allowJs ? 'handling' : 'not handling', 'JavaScript files');
return __assign(__assign({ transform: __assign(__assign({}, from.transform), (_b = {}, _b[allowJs ? '^.+\\.[tj]sx?$' : '^.+\\.tsx?$'] = 'ts-jest', _b)) }, (from.testMatch ? { testMatch: from.testMatch } : undefined)), (from.moduleFileExtensions ? { moduleFileExtensions: from.moduleFileExtensions } : undefined));
}
exports.createJestPreset = createJestPreset;
+5
View File
@@ -0,0 +1,5 @@
export declare const pathsToModuleNameMapper: (mapping: import("typescript").MapLike<string[]>, { prefix }?: {
prefix?: string | undefined;
}) => {
[key: string]: string | string[];
} | undefined;
+63
View File
@@ -0,0 +1,63 @@
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var logger_1 = require("../util/logger");
var messages_1 = require("../util/messages");
var escapeRegex = function (str) { return str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&'); };
var logger = logger_1.rootLogger.child((_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'path-mapper', _a));
exports.pathsToModuleNameMapper = function (mapping, _a) {
var e_1, _b;
var _c = (_a === void 0 ? {} : _a).prefix, prefix = _c === void 0 ? '' : _c;
var jestMap = {};
try {
for (var _d = __values(Object.keys(mapping)), _e = _d.next(); !_e.done; _e = _d.next()) {
var fromPath = _e.value;
var pattern = void 0;
var toPaths = mapping[fromPath];
if (toPaths.length === 0) {
logger.warn(messages_1.interpolate("Not mapping \"{{path}}\" because it has no target.", { path: fromPath }));
continue;
}
else if (toPaths.length > 1) {
logger.warn(messages_1.interpolate("Mapping only to first target of \"{{path}}\" because it has more than one ({{count}}).", {
path: fromPath,
count: toPaths.length,
}));
}
var target = toPaths[0];
var segments = fromPath.split(/\*/g);
if (segments.length === 1) {
pattern = "^" + escapeRegex(fromPath) + "$";
jestMap[pattern] = "" + prefix + target;
}
else if (segments.length === 2) {
pattern = "^" + escapeRegex(segments[0]) + "(.*)" + escapeRegex(segments[1]) + "$";
jestMap[pattern] = "" + prefix + target.replace(/\*/g, '$1');
}
else {
logger.warn(messages_1.interpolate("Not mapping \"{{path}}\" because it has more than one star (`*`).", { path: fromPath }));
continue;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
}
finally { if (e_1) throw e_1.error; }
}
return jestMap;
};
+16
View File
@@ -0,0 +1,16 @@
import { createJestPreset as createJestPresetCore } from './config/create-jest-preset';
import { TsJestTransformer } from './ts-jest-transformer';
import { TsJestGlobalOptions } from './types';
import { mocked as mockedCore } from './util/testing';
export declare const mocked: typeof mockedCore;
export declare const createJestPreset: typeof createJestPresetCore;
export declare const pathsToModuleNameMapper: (mapping: import("typescript").MapLike<string[]>, { prefix }?: {
prefix?: string | undefined;
}) => {
[key: string]: string | string[];
} | undefined;
export declare const version: string;
export declare const digest: string;
export declare function createTransformer(baseConfig?: TsJestGlobalOptions): TsJestTransformer;
declare const jestPreset: import("./config/create-jest-preset").TsJestPresets;
export { jestPreset, };
+74
View File
@@ -0,0 +1,74 @@
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var fs_1 = require("fs");
var path_1 = require("path");
var create_jest_preset_1 = require("./config/create-jest-preset");
var paths_to_module_name_mapper_1 = require("./config/paths-to-module-name-mapper");
var ts_jest_transformer_1 = require("./ts-jest-transformer");
var logger_1 = require("./util/logger");
var messages_1 = require("./util/messages");
var testing_1 = require("./util/testing");
var version_checkers_1 = require("./util/version-checkers");
var warn = logger_1.rootLogger.child((_a = {}, _a[bs_logger_1.LogContexts.logLevel] = bs_logger_1.LogLevels.warn, _a));
var helperMoved = function (name, helper) {
return warn.wrap(messages_1.interpolate("The `{{helper}}` helper has been moved to `ts-jest/utils`. Use `import { {{helper}} } from 'ts-jest/utils'` instead.", { helper: name }), helper);
};
exports.mocked = helperMoved('mocked', testing_1.mocked);
exports.createJestPreset = helperMoved('createJestPreset', create_jest_preset_1.createJestPreset);
exports.pathsToModuleNameMapper = helperMoved('pathsToModuleNameMapper', paths_to_module_name_mapper_1.pathsToModuleNameMapper);
exports.version = require('../package.json').version;
exports.digest = fs_1.readFileSync(path_1.resolve(__dirname, '..', '.ts-jest-digest'), 'utf8');
var transformer;
function defaultTransformer() {
return transformer || (transformer = createTransformer());
}
function createTransformer(baseConfig) {
version_checkers_1.VersionCheckers.jest.warn();
return new ts_jest_transformer_1.TsJestTransformer(baseConfig);
}
exports.createTransformer = createTransformer;
function process() {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return (_a = defaultTransformer()).process.apply(_a, __spread(args));
}
exports.process = process;
function getCacheKey() {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return (_a = defaultTransformer()).getCacheKey.apply(_a, __spread(args));
}
exports.getCacheKey = getCacheKey;
exports.canInstrument = false;
var jestPreset = create_jest_preset_1.createJestPreset();
exports.jestPreset = jestPreset;
exports.__singleton = function () { return transformer; };
exports.__resetModule = function () { return (transformer = undefined); };
+1
View File
@@ -0,0 +1 @@
export {};
+81
View File
@@ -0,0 +1,81 @@
"use strict";
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var HOIST_METHODS = ['mock', 'unmock', 'enableAutomock', 'disableAutomock', 'deepUnmock'];
exports.name = 'hoisting-jest-mock';
exports.version = 1;
function factory(cs) {
var logger = cs.logger.child({ namespace: 'ts-hoisting' });
var ts = cs.compilerModule;
function shouldHoistExpression(expression) {
return (ts.isCallExpression(expression) &&
ts.isPropertyAccessExpression(expression.expression) &&
HOIST_METHODS.includes(expression.expression.name.text) &&
((ts.isIdentifier(expression.expression.expression) && expression.expression.expression.text === 'jest') ||
shouldHoistExpression(expression.expression.expression)));
}
function shouldHoistNode(node) {
return ts.isExpressionStatement(node) && shouldHoistExpression(node.expression);
}
function createVisitor(ctx, _) {
var level = 0;
var hoisted = [];
var enter = function () {
level++;
if (hoisted[level]) {
hoisted[level].splice(0, hoisted[level].length);
}
};
var exit = function () { return level--; };
var hoist = function (node) {
if (hoisted[level]) {
hoisted[level].push(node);
}
else {
hoisted[level] = [node];
}
};
var visitor = function (node) {
enter();
var resultNode = ts.visitEachChild(node, visitor, ctx);
if (hoisted[level] && hoisted[level].length) {
var hoistedStmts_1 = hoisted[level];
var otherStmts = resultNode.statements.filter(function (s) { return !hoistedStmts_1.includes(s); });
var newNode = ts.getMutableClone(resultNode);
newNode.statements = ts.createNodeArray(__spread(hoistedStmts_1, otherStmts));
resultNode = newNode;
}
exit();
if (shouldHoistNode(resultNode)) {
hoist(resultNode);
}
return resultNode;
};
return visitor;
}
return function (ctx) {
var _a;
return logger.wrap((_a = {}, _a[bs_logger_1.LogContexts.logLevel] = bs_logger_1.LogLevels.debug, _a.call = null, _a), 'visitSourceFileNode(): hoisting', function (sf) { return ts.visitNode(sf, createVisitor(ctx, sf)); });
};
}
exports.factory = factory;
+1
View File
@@ -0,0 +1 @@
export {};
+4
View File
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var hoisting = require("./hoist-jest");
exports.internals = [hoisting];
+16
View File
@@ -0,0 +1,16 @@
import { TransformOptions, TransformedSource, Transformer } from '@jest/transform/build/types';
import { Config } from '@jest/types';
import { ConfigSet } from './config/config-set';
import { TsJestGlobalOptions } from './types';
export declare class TsJestTransformer implements Transformer {
private readonly logger;
private readonly id;
private readonly options;
constructor(baseOptions?: TsJestGlobalOptions);
configsFor(jestConfig: Config.ProjectConfig | string): ConfigSet;
process(input: string, filePath: Config.Path, jestConfig: Config.ProjectConfig, transformOptions?: TransformOptions): TransformedSource | string;
getCacheKey(fileContent: string, filePath: string, jestConfigStr: string, transformOptions?: {
instrument?: boolean;
rootDir?: string;
}): string;
}
+130
View File
@@ -0,0 +1,130 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require("util");
var config_set_1 = require("./config/config-set");
var json_1 = require("./util/json");
var jsonable_value_1 = require("./util/jsonable-value");
var logger_1 = require("./util/logger");
var messages_1 = require("./util/messages");
var sha1_1 = require("./util/sha1");
var INSPECT_CUSTOM = util_1.inspect.custom || 'inspect';
function checkDefinitionFile(filePath) {
return filePath.endsWith('.d.ts');
}
function checkJsFile(filePath) {
return !checkDefinitionFile(filePath) && /\.jsx?$/.test(filePath);
}
function checkTsFile(filePath) {
return !checkDefinitionFile(filePath) && /\.tsx?$/.test(filePath);
}
var TsJestTransformer = (function () {
function TsJestTransformer(baseOptions) {
if (baseOptions === void 0) { baseOptions = {}; }
this.options = __assign({}, baseOptions);
this.id = TsJestTransformer._nextTransformerId;
this.logger = logger_1.rootLogger.child({
transformerId: this.id,
namespace: 'jest-transformer',
});
this.logger.debug({ baseOptions: baseOptions }, 'created new transformer');
}
Object.defineProperty(TsJestTransformer, "_nextTransformerId", {
get: function () {
return ++TsJestTransformer._lastTransformerId;
},
enumerable: true,
configurable: true
});
TsJestTransformer.prototype[INSPECT_CUSTOM] = function () {
return "[object TsJestTransformer<#" + this.id + ">]";
};
TsJestTransformer.prototype.configsFor = function (jestConfig) {
var csi;
var jestConfigObj;
if (typeof jestConfig === 'string') {
csi = TsJestTransformer._configSetsIndex.find(function (cs) { return cs.jestConfig.serialized === jestConfig; });
if (csi)
return csi.configSet;
jestConfigObj = json_1.parse(jestConfig);
}
else {
csi = TsJestTransformer._configSetsIndex.find(function (cs) { return cs.jestConfig.value === jestConfig; });
if (csi)
return csi.configSet;
var serialized_1 = json_1.stringify(jestConfig);
csi = TsJestTransformer._configSetsIndex.find(function (cs) { return cs.jestConfig.serialized === serialized_1; });
if (csi) {
csi.jestConfig.value = jestConfig;
return csi.configSet;
}
jestConfigObj = jestConfig;
}
this.logger.info("no matching config-set found, creating a new one");
var configSet = new config_set_1.ConfigSet(jestConfigObj, this.options, this.logger);
TsJestTransformer._configSetsIndex.push({
jestConfig: new jsonable_value_1.JsonableValue(jestConfigObj),
configSet: configSet,
});
return configSet;
};
TsJestTransformer.prototype.process = function (input, filePath, jestConfig, transformOptions) {
this.logger.debug({ fileName: filePath, transformOptions: transformOptions }, 'processing', filePath);
var result;
var source = input, configs = this.configsFor(jestConfig), hooks = configs.hooks, stringify = configs.shouldStringifyContent(filePath), babelJest = stringify ? undefined : configs.babelJestTransformer, isDefinitionFile = checkDefinitionFile(filePath), isJsFile = checkJsFile(filePath), isTsFile = checkTsFile(filePath);
if (stringify) {
result = "module.exports=" + JSON.stringify(source);
}
else if (isDefinitionFile) {
result = '';
}
else if (!configs.typescript.options.allowJs && isJsFile) {
this.logger.warn({ fileName: filePath }, messages_1.interpolate("Got a `.js` file to compile while `allowJs` option is not set to `true` (file: {{path}}). To fix this:\n - if you want TypeScript to process JS files, set `allowJs` to `true` in your TypeScript config (usually tsconfig.json)\n - if you do not want TypeScript to process your `.js` files, in your Jest config change the `transform` key which value is `ts-jest` so that it does not match `.js` files anymore", { path: filePath }));
result = source;
}
else if (isJsFile || isTsFile) {
result = configs.tsCompiler.compile(source, filePath);
}
else {
var message = babelJest ? "Got a unknown file type to compile (file: {{path}}). To fix this, in your Jest config change the `transform` key which value is `ts-jest` so that it does not match this kind of files anymore. If you still want Babel to process it, add another entry to the `transform` option with value `babel-jest` which key matches this type of files." : "Got a unknown file type to compile (file: {{path}}). To fix this, in your Jest config change the `transform` key which value is `ts-jest` so that it does not match this kind of files anymore.";
this.logger.warn({ fileName: filePath }, messages_1.interpolate(message, { path: filePath }));
result = source;
}
if (babelJest) {
this.logger.debug({ fileName: filePath }, 'calling babel-jest processor');
result = babelJest.process(result, filePath, jestConfig, __assign(__assign({}, transformOptions), { instrument: false }));
}
if (hooks.afterProcess) {
this.logger.debug({ fileName: filePath, hookName: 'afterProcess' }, 'calling afterProcess hook');
var newResult = hooks.afterProcess([input, filePath, jestConfig, transformOptions], result);
if (newResult !== undefined) {
return newResult;
}
}
return result;
};
TsJestTransformer.prototype.getCacheKey = function (fileContent, filePath, jestConfigStr, transformOptions) {
if (transformOptions === void 0) { transformOptions = {}; }
this.logger.debug({ fileName: filePath, transformOptions: transformOptions }, 'computing cache key for', filePath);
var configs = this.configsFor(jestConfigStr);
var _a = transformOptions.instrument, instrument = _a === void 0 ? false : _a, _b = transformOptions.rootDir, rootDir = _b === void 0 ? configs.rootDir : _b;
if (configs.tsCompiler.diagnose && (checkJsFile(filePath) || checkTsFile(filePath))) {
configs.tsCompiler.diagnose(fileContent, filePath);
}
return sha1_1.sha1(configs.cacheKey, '\x00', rootDir, '\x00', "instrument:" + (instrument ? 'on' : 'off'), '\x00', fileContent, '\x00', filePath);
};
TsJestTransformer._configSetsIndex = [];
TsJestTransformer._lastTransformerId = 0;
return TsJestTransformer;
}());
exports.TsJestTransformer = TsJestTransformer;
+75
View File
@@ -0,0 +1,75 @@
import { CompilerOptions, SourceFile, TransformerFactory } from 'typescript';
import * as _ts from 'typescript';
import { ConfigSet } from './config/config-set';
export interface TsJestGlobalOptions {
tsConfig?: boolean | string | CompilerOptions;
packageJson?: boolean | string | object;
isolatedModules?: boolean;
compilerHost?: boolean;
incremental?: boolean;
compiler?: string;
astTransformers?: string[];
diagnostics?: boolean | {
pretty?: boolean;
ignoreCodes?: number | string | (number | string)[];
pathRegex?: RegExp | string;
warnOnly?: boolean;
};
babelConfig?: boolean | string | BabelConfig;
stringifyContentPathRegex?: string | RegExp;
}
interface TsJestConfig$tsConfig$file {
kind: 'file';
value: string | undefined;
}
interface TsJestConfig$tsConfig$inline {
kind: 'inline';
value: CompilerOptions;
}
declare type TsJestConfig$tsConfig = TsJestConfig$tsConfig$file | TsJestConfig$tsConfig$inline | undefined;
interface TsJestConfig$diagnostics {
pretty: boolean;
ignoreCodes: number[];
pathRegex?: string | undefined;
throws: boolean;
}
interface TsJestConfig$babelConfig$file {
kind: 'file';
value: string | undefined;
}
interface TsJestConfig$babelConfig$inline {
kind: 'inline';
value: BabelConfig;
}
declare type TsJestConfig$babelConfig = TsJestConfig$babelConfig$file | TsJestConfig$babelConfig$inline | undefined;
interface TsJestConfig$packageJson$file {
kind: 'file';
value: string | undefined;
}
interface TsJestConfig$packageJson$inline {
kind: 'inline';
value: any;
}
declare type TsJestConfig$packageJson = TsJestConfig$packageJson$file | TsJestConfig$packageJson$inline | undefined;
declare type TsJestConfig$stringifyContentPathRegex = string | undefined;
export interface TsJestConfig {
tsConfig: TsJestConfig$tsConfig;
packageJson: TsJestConfig$packageJson;
isolatedModules: boolean;
compilerHost: boolean;
incremental: boolean;
compiler: string;
diagnostics: TsJestConfig$diagnostics;
babelConfig: TsJestConfig$babelConfig;
transformers: string[];
stringifyContentPathRegex: TsJestConfig$stringifyContentPathRegex;
}
export interface TsCompiler {
program: _ts.Program | undefined;
}
export interface AstTransformerDesc {
name: string;
version: number;
factory(cs: ConfigSet): TransformerFactory<SourceFile>;
}
export {};
+2
View File
@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
+1
View File
@@ -0,0 +1 @@
export {};
+101
View File
@@ -0,0 +1,101 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var messages_1 = require("./messages");
var context = (_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'backports', _a);
exports.backportJestConfig = function (logger, config) {
logger.debug(__assign(__assign({}, context), { config: config }), 'backporting config');
var _a = (config || {}).globals, globals = _a === void 0 ? {} : _a;
var _b = globals["ts-jest"], tsJest = _b === void 0 ? {} : _b;
var mergeTsJest = {};
var hadWarnings = false;
var warnConfig = function (oldPath, newPath, note) {
hadWarnings = true;
logger.warn(context, messages_1.interpolate(note ? "\"[jest-config].{{oldPath}}\" is deprecated, use \"[jest-config].{{newPath}}\" instead.\n \u21B3 {{note}}" : "\"[jest-config].{{oldPath}}\" is deprecated, use \"[jest-config].{{newPath}}\" instead.", {
oldPath: oldPath,
newPath: newPath,
note: note,
}));
};
if ('__TS_CONFIG__' in globals) {
warnConfig('globals.__TS_CONFIG__', 'globals.ts-jest.tsConfig');
if (typeof globals.__TS_CONFIG__ === 'object') {
mergeTsJest.tsConfig = globals.__TS_CONFIG__;
}
delete globals.__TS_CONFIG__;
}
if ('__TRANSFORM_HTML__' in globals) {
warnConfig('globals.__TRANSFORM_HTML__', 'globals.ts-jest.stringifyContentPathRegex');
if (globals.__TRANSFORM_HTML__) {
mergeTsJest.stringifyContentPathRegex = '\\.html?$';
}
delete globals.__TRANSFORM_HTML__;
}
if ('typeCheck' in tsJest) {
warnConfig('globals.ts-jest.typeCheck', 'globals.ts-jest.isolatedModules');
mergeTsJest.isolatedModules = !tsJest.typeCheck;
delete tsJest.typeCheck;
}
if ('tsConfigFile' in tsJest) {
warnConfig('globals.ts-jest.tsConfigFile', 'globals.ts-jest.tsConfig');
if (tsJest.tsConfigFile) {
mergeTsJest.tsConfig = tsJest.tsConfigFile;
}
delete tsJest.tsConfigFile;
}
if ('enableTsDiagnostics' in tsJest) {
warnConfig('globals.ts-jest.enableTsDiagnostics', 'globals.ts-jest.diagnostics');
if (tsJest.enableTsDiagnostics) {
mergeTsJest.diagnostics = { warnOnly: true };
if (typeof tsJest.enableTsDiagnostics === 'string')
mergeTsJest.diagnostics.pathRegex = tsJest.enableTsDiagnostics;
}
else {
mergeTsJest.diagnostics = false;
}
delete tsJest.enableTsDiagnostics;
}
if ('useBabelrc' in tsJest) {
warnConfig('globals.ts-jest.useBabelrc', 'globals.ts-jest.babelConfig', "See `babel-jest` related issue: https://github.com/facebook/jest/issues/3845");
if (tsJest.useBabelrc != null) {
mergeTsJest.babelConfig = tsJest.useBabelrc ? true : {};
}
delete tsJest.useBabelrc;
}
if ('skipBabel' in tsJest) {
warnConfig('globals.ts-jest.skipBabel', 'globals.ts-jest.babelConfig');
if (tsJest.skipBabel === false && !mergeTsJest.babelConfig) {
mergeTsJest.babelConfig = true;
}
delete tsJest.skipBabel;
}
if (hadWarnings) {
logger.warn(context, "Your Jest configuration is outdated. Use the CLI to help migrating it: ts-jest config:migrate <config-file>.");
}
return __assign(__assign({}, config), { globals: __assign(__assign({}, globals), { 'ts-jest': __assign(__assign({}, mergeTsJest), tsJest) }) });
};
exports.backportTsJestDebugEnvVar = function (logger) {
if ('TS_JEST_DEBUG' in process.env) {
var shouldLog = !/^\s*(?:0|f(?:alse)?|no?|disabled?|off|)\s*$/i.test(process.env.TS_JEST_DEBUG || '');
delete process.env.TS_JEST_DEBUG;
if (shouldLog) {
process.env.TS_JEST_LOG = "ts-jest.log,stderr:warn";
}
logger.warn(context, messages_1.interpolate("Using env. var \"{{old}}\" is deprecated, use \"{{new}}\" instead.", {
old: 'TS_JEST_DEBUG',
new: 'TS_JEST_LOG',
}));
}
};
+3
View File
@@ -0,0 +1,3 @@
export { mocked } from './testing';
export { createJestPreset } from '../config/create-jest-preset';
export { pathsToModuleNameMapper } from '../config/paths-to-module-name-mapper';
+8
View File
@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var testing_1 = require("./testing");
exports.mocked = testing_1.mocked;
var create_jest_preset_1 = require("../config/create-jest-preset");
exports.createJestPreset = create_jest_preset_1.createJestPreset;
var paths_to_module_name_mapper_1 = require("../config/paths-to-module-name-mapper");
exports.pathsToModuleNameMapper = paths_to_module_name_mapper_1.pathsToModuleNameMapper;
+1
View File
@@ -0,0 +1 @@
export {};
+10
View File
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getPackageVersion(moduleName) {
try {
return require(moduleName + "/package.json").version;
}
catch (err) { }
return;
}
exports.getPackageVersion = getPackageVersion;
+1
View File
@@ -0,0 +1 @@
export {};
+198
View File
@@ -0,0 +1,198 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var logger_1 = require("./logger");
var memoize_1 = require("./memoize");
var messages_1 = require("./messages");
var version_checkers_1 = require("./version-checkers");
var logger = logger_1.rootLogger.child({ namespace: 'Importer' });
var passThru = function (action) { return function (input) {
action();
return input;
}; };
var Importer = (function () {
function Importer(_patches) {
if (_patches === void 0) { _patches = {}; }
this._patches = _patches;
}
Object.defineProperty(Importer, "instance", {
get: function () {
logger.debug('creating Importer singleton');
return new Importer({
'@babel/core': [passThru(version_checkers_1.VersionCheckers.babelCore.warn)],
'babel-jest': [passThru(version_checkers_1.VersionCheckers.babelJest.warn)],
typescript: [passThru(version_checkers_1.VersionCheckers.typescript.warn)],
jest: [passThru(version_checkers_1.VersionCheckers.jest.warn)],
});
},
enumerable: true,
configurable: true
});
Importer.prototype.babelJest = function (why) {
return this._import(why, 'babel-jest');
};
Importer.prototype.babelCore = function (why) {
return this._import(why, '@babel/core');
};
Importer.prototype.typescript = function (why, which) {
return this._import(why, which);
};
Importer.prototype.tryThese = function (moduleName) {
var fallbacks = [];
for (var _i = 1; _i < arguments.length; _i++) {
fallbacks[_i - 1] = arguments[_i];
}
var name;
var loaded;
var tries = __spread([moduleName], fallbacks);
while ((name = tries.shift()) !== undefined) {
var req = requireWrapper(name);
var contextReq = __assign({}, req);
delete contextReq.exports;
if (req.exists) {
loaded = req;
if (loaded.error) {
logger.error({ requireResult: contextReq }, "failed loading module '" + name + "'", loaded.error.message);
}
else {
logger.debug({ requireResult: contextReq }, 'loaded module', name);
loaded.exports = this._patch(name, loaded.exports);
}
break;
}
else {
logger.debug({ requireResult: contextReq }, "module '" + name + "' not found");
continue;
}
}
return loaded;
};
Importer.prototype.tryTheseOr = function (moduleNames, missingResult, allowLoadError) {
if (allowLoadError === void 0) { allowLoadError = false; }
var args = Array.isArray(moduleNames) ? moduleNames : [moduleNames];
var result = this.tryThese.apply(this, __spread(args));
if (!result)
return missingResult;
if (!result.error)
return result.exports;
if (allowLoadError)
return missingResult;
throw result.error;
};
Importer.prototype._patch = function (name, unpatched) {
if (name in this._patches) {
logger.debug('patching', name);
return this._patches[name].reduce(function (mod, patcher) { return patcher(mod); }, unpatched);
}
return unpatched;
};
Importer.prototype._import = function (why, moduleName, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.alternatives, alternatives = _c === void 0 ? [] : _c, _d = _b.installTip, installTip = _d === void 0 ? moduleName : _d;
var res = this.tryThese.apply(this, __spread([moduleName], alternatives));
if (res && res.exists) {
if (!res.error)
return res.exports;
throw new Error(messages_1.interpolate("Loading module {{module}} failed with error: {{error}}", { module: res.given, error: res.error.message }));
}
var msg = alternatives.length ? "Unable to load any of these modules: {{module}}. {{reason}}. To fix it:\n{{fix}}" : "Unable to load the module {{module}}. {{reason}} To fix it:\n{{fix}}";
var loadModule = __spread([moduleName], alternatives).map(function (m) { return "\"" + m + "\""; }).join(', ');
if (typeof installTip === 'string') {
installTip = [{ module: installTip, label: "install \"" + installTip + "\"" }];
}
var fix = installTip
.map(function (tip) {
return " " + (installTip.length === 1 ? '↳' : '•') + " " + messages_1.interpolate("{{label}}: `npm i -D {{module}}` (or `yarn add --dev {{module}}`)", tip);
})
.join('\n');
throw new Error(messages_1.interpolate(msg, {
module: loadModule,
reason: why,
fix: fix,
}));
};
__decorate([
memoize_1.Memoize(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return args.join(':');
})
], Importer.prototype, "tryThese", null);
__decorate([
memoize_1.Memoize(function (name) { return name; })
], Importer.prototype, "_patch", null);
__decorate([
memoize_1.Memoize()
], Importer, "instance", null);
return Importer;
}());
exports.Importer = Importer;
exports.importer = Importer.instance;
function requireWrapper(moduleName) {
var path;
var exists = false;
try {
path = resolveModule(moduleName);
exists = true;
}
catch (error) {
return { error: error, exists: exists, given: moduleName };
}
var result = { exists: exists, path: path, given: moduleName };
try {
result.exports = requireModule(path);
}
catch (error) {
try {
result.exports = requireModule(moduleName);
}
catch (error) {
result.error = error;
}
}
return result;
}
var requireModule = function (mod) { return require(mod); };
var resolveModule = function (mod) { return require.resolve(mod, { paths: [process.cwd(), __dirname] }); };
function __requireModule(localRequire, localResolve) {
requireModule = localRequire;
resolveModule = localResolve;
}
exports.__requireModule = __requireModule;
+1
View File
@@ -0,0 +1 @@
export {};
+31
View File
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var stableStringify = require("fast-json-stable-stringify");
var UNDEFINED = 'undefined';
function stringify(input) {
return input === undefined ? UNDEFINED : stableStringify(input);
}
exports.stringify = stringify;
function parse(input) {
return input === UNDEFINED ? undefined : JSON.parse(input);
}
exports.parse = parse;
function normalize(input, _a) {
var _b = (_a === void 0 ? {} : _a).parse, parser = _b === void 0 ? parse : _b;
var result;
if (normalize.cache.has(input)) {
result = normalize.cache.get(input);
}
else {
var data = parser(input);
result = stringify(data);
if (result === input)
result = undefined;
normalize.cache.set(input, result);
}
return result === undefined ? input : result;
}
exports.normalize = normalize;
(function (normalize) {
normalize.cache = new Map();
})(normalize = exports.normalize || (exports.normalize = {}));
+1
View File
@@ -0,0 +1 @@
export {};
+34
View File
@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var json_1 = require("./json");
var JsonableValue = (function () {
function JsonableValue(value) {
this.value = value;
}
Object.defineProperty(JsonableValue.prototype, "value", {
get: function () {
return this._value;
},
set: function (value) {
this._value = value;
this._serialized = json_1.stringify(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(JsonableValue.prototype, "serialized", {
get: function () {
return this._serialized;
},
enumerable: true,
configurable: true
});
JsonableValue.prototype.valueOf = function () {
return this._value;
};
JsonableValue.prototype.toString = function () {
return this._serialized;
};
return JsonableValue;
}());
exports.JsonableValue = JsonableValue;
+1
View File
@@ -0,0 +1 @@
export {};
+21
View File
@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bs_logger_1 = require("bs-logger");
var backports_1 = require("./backports");
var original = process.env.TS_JEST_LOG;
var buildOptions = function () {
var _a;
return ({
context: (_a = {},
_a[bs_logger_1.LogContexts.package] = 'ts-jest',
_a[bs_logger_1.LogContexts.logLevel] = bs_logger_1.LogLevels.trace,
_a.version = require('../../package.json').version,
_a),
targets: process.env.TS_JEST_LOG || undefined,
});
};
exports.rootLogger = bs_logger_1.createLogger(buildOptions());
backports_1.backportTsJestDebugEnvVar(exports.rootLogger);
if (original !== process.env.TS_JEST_LOG) {
exports.rootLogger = bs_logger_1.createLogger(buildOptions());
}
+1
View File
@@ -0,0 +1 @@
export {};
+47
View File
@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var cacheProp = Symbol.for('[memoize]');
function Memoize(keyBuilder) {
return function (_, propertyKey, descriptor) {
if (descriptor.value != null) {
descriptor.value = memoize(propertyKey, descriptor.value, keyBuilder || (function (v) { return v; }));
}
else if (descriptor.get != null) {
descriptor.get = memoize(propertyKey, descriptor.get, keyBuilder || (function () { return propertyKey; }));
}
};
}
exports.Memoize = Memoize;
function ensureCache(target, reset) {
if (reset === void 0) { reset = false; }
if (reset || !target[cacheProp]) {
Object.defineProperty(target, cacheProp, {
value: Object.create(null),
configurable: true,
});
}
return target[cacheProp];
}
function ensureChildCache(target, key, reset) {
if (reset === void 0) { reset = false; }
var dict = ensureCache(target);
if (reset || !dict[key]) {
dict[key] = new Map();
}
return dict[key];
}
function memoize(namespace, func, keyBuilder) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var cache = ensureChildCache(this, namespace);
var key = keyBuilder.apply(this, args);
if (cache.has(key))
return cache.get(key);
var res = func.apply(this, args);
cache.set(key, res);
return res;
};
}
+1
View File
@@ -0,0 +1 @@
export {};
+7
View File
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function interpolate(msg, vars) {
if (vars === void 0) { vars = {}; }
return msg.replace(/\{\{([^\}]+)\}\}/g, function (_, key) { return (key in vars ? vars[key] : _); });
}
exports.interpolate = interpolate;
+1
View File
@@ -0,0 +1 @@
export {};
+6
View File
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function normalizeSlashes(value) {
return value.replace(/\\/g, '/');
}
exports.normalizeSlashes = normalizeSlashes;
+1
View File
@@ -0,0 +1 @@
export {};
+31
View File
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var crypto_1 = require("crypto");
exports.cache = Object.create(null);
function sha1() {
var data = [];
for (var _i = 0; _i < arguments.length; _i++) {
data[_i] = arguments[_i];
}
var canCache = data.length === 1 && typeof data[0] === 'string';
var cacheKey;
if (canCache) {
cacheKey = data[0];
if (cacheKey in exports.cache) {
return exports.cache[cacheKey];
}
}
var hash = crypto_1.createHash('sha1');
data.forEach(function (item) {
if (typeof item === 'string')
hash.update(item, 'utf8');
else
hash.update(item);
});
var res = hash.digest('hex').toString();
if (canCache) {
exports.cache[cacheKey] = res;
}
return res;
}
exports.sha1 = sha1;
+34
View File
@@ -0,0 +1,34 @@
/// <reference types="jest" />
declare type MockableFunction = (...args: any[]) => any;
declare type MethodKeysOf<T> = {
[K in keyof T]: T[K] extends MockableFunction ? K : never;
}[keyof T];
declare type PropertyKeysOf<T> = {
[K in keyof T]: T[K] extends MockableFunction ? never : K;
}[keyof T];
declare type ArgumentsOf<T> = T extends (...args: infer A) => any ? A : never;
declare type ConstructorArgumentsOf<T> = T extends new (...args: infer A) => any ? A : never;
interface MockWithArgs<T extends MockableFunction> extends jest.MockInstance<ReturnType<T>, ArgumentsOf<T>> {
new (...args: ConstructorArgumentsOf<T>): T;
(...args: ArgumentsOf<T>): ReturnType<T>;
}
declare type MaybeMockedConstructor<T> = T extends new (...args: any[]) => infer R ? jest.MockInstance<R, ConstructorArgumentsOf<T>> : {};
declare type MockedFunction<T extends MockableFunction> = MockWithArgs<T> & {
[K in keyof T]: T[K];
};
declare type MockedFunctionDeep<T extends MockableFunction> = MockWithArgs<T> & MockedObjectDeep<T>;
declare type MockedObject<T> = MaybeMockedConstructor<T> & {
[K in MethodKeysOf<T>]: T[K] extends MockableFunction ? MockedFunction<T[K]> : T[K];
} & {
[K in PropertyKeysOf<T>]: T[K];
};
declare type MockedObjectDeep<T> = MaybeMockedConstructor<T> & {
[K in MethodKeysOf<T>]: T[K] extends MockableFunction ? MockedFunctionDeep<T[K]> : T[K];
} & {
[K in PropertyKeysOf<T>]: MaybeMockedDeep<T[K]>;
};
export declare type MaybeMockedDeep<T> = T extends MockableFunction ? MockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
export declare type MaybeMocked<T> = T extends MockableFunction ? MockedFunction<T> : T extends object ? MockedObject<T> : T;
export declare function mocked<T>(item: T, deep?: false): MaybeMocked<T>;
export declare function mocked<T>(item: T, deep: true): MaybeMockedDeep<T>;
export {};
+7
View File
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function mocked(item, _deep) {
if (_deep === void 0) { _deep = false; }
return item;
}
exports.mocked = mocked;
+1
View File
@@ -0,0 +1 @@
export {};
+40
View File
@@ -0,0 +1,40 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var make_error_1 = require("make-error");
var util_1 = require("util");
var logger_1 = require("./logger");
var messages_1 = require("./messages");
var logger = logger_1.rootLogger.child({ namespace: 'TSError' });
exports.INSPECT_CUSTOM = util_1.inspect.custom || 'inspect';
var TSError = (function (_super) {
__extends(TSError, _super);
function TSError(diagnosticText, diagnosticCodes) {
var _this = _super.call(this, messages_1.interpolate("{{diagnostics}}", {
diagnostics: diagnosticText.trim(),
})) || this;
_this.diagnosticText = diagnosticText;
_this.diagnosticCodes = diagnosticCodes;
_this.name = 'TSError';
logger.debug({ diagnosticCodes: diagnosticCodes, diagnosticText: diagnosticText }, 'created new TSError');
Object.defineProperty(_this, 'stack', { value: '' });
return _this;
}
TSError.prototype[exports.INSPECT_CUSTOM] = function () {
return this.diagnosticText;
};
return TSError;
}(make_error_1.BaseError));
exports.TSError = TSError;
+1
View File
@@ -0,0 +1 @@
export {};
+56
View File
@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var semver_1 = require("semver");
var get_package_version_1 = require("./get-package-version");
var logger_1 = require("./logger");
var messages_1 = require("./messages");
var logger = logger_1.rootLogger.child({ namespace: 'versions' });
exports.VersionCheckers = {
jest: createVersionChecker('jest', ">=25 <26"),
typescript: createVersionChecker('typescript', ">=2.7 <4"),
babelJest: createVersionChecker('babel-jest', ">=25 <26"),
babelCore: createVersionChecker('@babel/core', ">=7.0.0-beta.0 <8"),
};
function checkVersion(name, expectedRange, action) {
if (action === void 0) { action = 'warn'; }
var version = get_package_version_1.getPackageVersion(name);
var success = !!version && semver_1.satisfies(version, expectedRange);
logger.debug({
actualVersion: version,
expectedVersion: expectedRange,
}, 'checking version of %s: %s', name, success ? 'OK' : 'NOT OK');
if (!action || success)
return success;
var message = messages_1.interpolate(version ? "Version {{actualVersion}} of {{module}} installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version ({{expectedVersion}}). Please do not report issues in ts-jest if you are using unsupported versions." : "Module {{module}} is not installed. If you're experiencing issues, consider installing a supported version ({{expectedVersion}}).", {
module: name,
actualVersion: version || '??',
expectedVersion: rangeToHumanString(expectedRange),
});
if (action === 'warn') {
logger.warn(message);
}
else if (action === 'throw') {
logger.fatal(message);
throw new RangeError(message);
}
return success;
}
function rangeToHumanString(versionRange) {
return new semver_1.Range(versionRange).toString();
}
function createVersionChecker(moduleName, expectedVersion) {
var memo;
var warn = function () {
if (memo !== undefined)
return memo;
return (memo = checkVersion(moduleName, expectedVersion, 'warn'));
};
var raise = function () { return checkVersion(moduleName, expectedVersion, 'throw'); };
return {
raise: raise,
warn: warn,
forget: function () {
memo = undefined;
},
};
}
+1
View File
@@ -0,0 +1 @@
module.exports = require('./presets/default/jest-preset')
+1
View File
@@ -0,0 +1 @@
../mkdirp/bin/cmd.js
+1
View File
@@ -0,0 +1 @@
../semver/bin/semver.js
+15
View File
@@ -0,0 +1,15 @@
# Changers Lorgs!
## 1.0
Full rewrite. Essentially a brand new module.
- Return a promise instead of taking a callback.
- Use native `fs.mkdir(path, { recursive: true })` when available.
- Drop support for outdated Node.js versions. (Technically still works on
Node.js v8, but only 10 and above are officially supported.)
## 0.x
Original and most widely used recursive directory creation implementation
in JavaScript, dating back to 2010.
+21
View File
@@ -0,0 +1,21 @@
Copyright James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me)
This project is free software released under the MIT license:
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.
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env node
const usage = () => `
usage: mkdirp [DIR1,DIR2..] {OPTIONS}
Create each supplied directory including any necessary parent directories
that don't yet exist.
If the directory already exists, do nothing.
OPTIONS are:
-m<mode> If a directory needs to be created, set the mode as an octal
--mode=<mode> permission string.
-v --version Print the mkdirp version number
-h --help Print this helpful banner
-p --print Print the first directories created for each path provided
--manual Use manual implementation, even if native is available
`
const dirs = []
const opts = {}
let print = false
let dashdash = false
let manual = false
for (const arg of process.argv.slice(2)) {
if (dashdash)
dirs.push(arg)
else if (arg === '--')
dashdash = true
else if (arg === '--manual')
manual = true
else if (/^-h/.test(arg) || /^--help/.test(arg)) {
console.log(usage())
process.exit(0)
} else if (arg === '-v' || arg === '--version') {
console.log(require('../package.json').version)
process.exit(0)
} else if (arg === '-p' || arg === '--print') {
print = true
} else if (/^-m/.test(arg) || /^--mode=/.test(arg)) {
const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8)
if (isNaN(mode)) {
console.error(`invalid mode argument: ${arg}\nMust be an octal number.`)
process.exit(1)
}
opts.mode = mode
} else
dirs.push(arg)
}
const mkdirp = require('../')
const impl = manual ? mkdirp.manual : mkdirp
if (dirs.length === 0)
console.error(usage())
Promise.all(dirs.map(dir => impl(dir, opts)))
.then(made => print ? made.forEach(m => m && console.log(m)) : null)
.catch(er => {
console.error(er.message)
if (er.code)
console.error(' code: ' + er.code)
process.exit(1)
})
+31
View File
@@ -0,0 +1,31 @@
const optsArg = require('./lib/opts-arg.js')
const pathArg = require('./lib/path-arg.js')
const {mkdirpNative, mkdirpNativeSync} = require('./lib/mkdirp-native.js')
const {mkdirpManual, mkdirpManualSync} = require('./lib/mkdirp-manual.js')
const {useNative, useNativeSync} = require('./lib/use-native.js')
const mkdirp = (path, opts) => {
path = pathArg(path)
opts = optsArg(opts)
return useNative(opts)
? mkdirpNative(path, opts)
: mkdirpManual(path, opts)
}
const mkdirpSync = (path, opts) => {
path = pathArg(path)
opts = optsArg(opts)
return useNativeSync(opts)
? mkdirpNativeSync(path, opts)
: mkdirpManualSync(path, opts)
}
mkdirp.sync = mkdirpSync
mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts))
mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts))
mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts))
mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts))
module.exports = mkdirp
+29
View File
@@ -0,0 +1,29 @@
const {dirname} = require('path')
const findMade = (opts, parent, path = undefined) => {
// we never want the 'made' return value to be a root directory
if (path === parent)
return Promise.resolve()
return opts.statAsync(parent).then(
st => st.isDirectory() ? path : undefined, // will fail later
er => er.code === 'ENOENT'
? findMade(opts, dirname(parent), parent)
: undefined
)
}
const findMadeSync = (opts, parent, path = undefined) => {
if (path === parent)
return undefined
try {
return opts.statSync(parent).isDirectory() ? path : undefined
} catch (er) {
return er.code === 'ENOENT'
? findMadeSync(opts, dirname(parent), parent)
: undefined
}
}
module.exports = {findMade, findMadeSync}
+64
View File
@@ -0,0 +1,64 @@
const {dirname} = require('path')
const mkdirpManual = (path, opts, made) => {
opts.recursive = false
const parent = dirname(path)
if (parent === path) {
return opts.mkdirAsync(path, opts).catch(er => {
// swallowed by recursive implementation on posix systems
// any other error is a failure
if (er.code !== 'EISDIR')
throw er
})
}
return opts.mkdirAsync(path, opts).then(() => made || path, er => {
if (er.code === 'ENOENT')
return mkdirpManual(parent, opts)
.then(made => mkdirpManual(path, opts, made))
if (er.code !== 'EEXIST' && er.code !== 'EROFS')
throw er
return opts.statAsync(path).then(st => {
if (st.isDirectory())
return made
else
throw er
}, () => { throw er })
})
}
const mkdirpManualSync = (path, opts, made) => {
const parent = dirname(path)
opts.recursive = false
if (parent === path) {
try {
return opts.mkdirSync(path, opts)
} catch (er) {
// swallowed by recursive implementation on posix systems
// any other error is a failure
if (er.code !== 'EISDIR')
throw er
else
return
}
}
try {
opts.mkdirSync(path, opts)
return made || path
} catch (er) {
if (er.code === 'ENOENT')
return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made))
if (er.code !== 'EEXIST' && er.code !== 'EROFS')
throw er
try {
if (!opts.statSync(path).isDirectory())
throw er
} catch (_) {
throw er
}
}
}
module.exports = {mkdirpManual, mkdirpManualSync}
+39
View File
@@ -0,0 +1,39 @@
const {dirname} = require('path')
const {findMade, findMadeSync} = require('./find-made.js')
const {mkdirpManual, mkdirpManualSync} = require('./mkdirp-manual.js')
const mkdirpNative = (path, opts) => {
opts.recursive = true
const parent = dirname(path)
if (parent === path)
return opts.mkdirAsync(path, opts)
return findMade(opts, path).then(made =>
opts.mkdirAsync(path, opts).then(() => made)
.catch(er => {
if (er.code === 'ENOENT')
return mkdirpManual(path, opts)
else
throw er
}))
}
const mkdirpNativeSync = (path, opts) => {
opts.recursive = true
const parent = dirname(path)
if (parent === path)
return opts.mkdirSync(path, opts)
const made = findMadeSync(opts, path)
try {
opts.mkdirSync(path, opts)
return made
} catch (er) {
if (er.code === 'ENOENT')
return mkdirpManualSync(path, opts)
else
throw er
}
}
module.exports = {mkdirpNative, mkdirpNativeSync}
+23
View File
@@ -0,0 +1,23 @@
const { promisify } = require('util')
const fs = require('fs')
const optsArg = opts => {
if (!opts)
opts = { mode: 0o777 & (~process.umask()), fs }
else if (typeof opts === 'object')
opts = { mode: 0o777 & (~process.umask()), fs, ...opts }
else if (typeof opts === 'number')
opts = { mode: opts, fs }
else if (typeof opts === 'string')
opts = { mode: parseInt(opts, 8), fs }
else
throw new TypeError('invalid options argument')
opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir
opts.mkdirAsync = promisify(opts.mkdir)
opts.stat = opts.stat || opts.fs.stat || fs.stat
opts.statAsync = promisify(opts.stat)
opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync
opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync
return opts
}
module.exports = optsArg
+29
View File
@@ -0,0 +1,29 @@
const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform
const { resolve, parse } = require('path')
const pathArg = path => {
if (/\0/.test(path)) {
// simulate same failure that node raises
throw Object.assign(
new TypeError('path must be a string without null bytes'),
{
path,
code: 'ERR_INVALID_ARG_VALUE',
}
)
}
path = resolve(path)
if (platform === 'win32') {
const badWinChars = /[*|"<>?:]/
const {root} = parse(path)
if (badWinChars.test(path.substr(root.length))) {
throw Object.assign(new Error('Illegal characters in path.'), {
path,
code: 'EINVAL',
})
}
}
return path
}
module.exports = pathArg
+10
View File
@@ -0,0 +1,10 @@
const fs = require('fs')
const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version
const versArr = version.replace(/^v/, '').split('.')
const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12
const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir
const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync
module.exports = {useNative, useNativeSync}
+52
View File
@@ -0,0 +1,52 @@
{
"bin": {
"mkdirp": "bin/cmd.js"
},
"bugs": {
"url": "https://github.com/isaacs/node-mkdirp/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Recursively mkdir, like `mkdir -p`",
"devDependencies": {
"require-inject": "^1.4.4",
"tap": "^14.10.6"
},
"engines": {
"node": ">=10"
},
"files": [
"bin",
"lib",
"index.js"
],
"homepage": "https://github.com/isaacs/node-mkdirp#readme",
"keywords": [
"mkdir",
"directory",
"make dir",
"make",
"dir",
"recursive",
"native"
],
"license": "MIT",
"main": "index.js",
"name": "mkdirp",
"repository": {
"type": "git",
"url": "git+https://github.com/isaacs/node-mkdirp.git"
},
"scripts": {
"postpublish": "git push origin --follow-tags",
"postversion": "npm publish",
"preversion": "npm test",
"snap": "tap",
"test": "tap"
},
"tap": {
"check-coverage": true,
"coverage-map": "map.js"
},
"version": "1.0.3"
}
+266
View File
@@ -0,0 +1,266 @@
# mkdirp
Like `mkdir -p`, but in Node.js!
Now with a modern API and no\* bugs!
<small>\* may contain some bugs</small>
# example
## pow.js
```js
const mkdirp = require('mkdirp')
// return value is a Promise resolving to the first directory created
mkdirp('/tmp/foo/bar/baz').then(made =>
console.log(`made directories, starting with ${made}`))
```
Output (where `/tmp/foo` already exists)
```
made directories, starting with /tmp/foo/bar
```
Or, if you don't have time to wait around for promises:
```js
const mkdirp = require('mkdirp')
// return value is the first directory created
const made = mkdirp.sync('/tmp/foo/bar/baz')
console.log(`made directories, starting with ${made}`)
```
And now /tmp/foo/bar/baz exists, huzzah!
# methods
```js
const mkdirp = require('mkdirp')
```
## mkdirp(dir, [opts]) -> Promise<String | undefined>
Create a new directory and any necessary subdirectories at `dir` with octal
permission string `opts.mode`. If `opts` is a string or number, it will be
treated as the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0o777 &
(~process.umask())`.
Promise resolves to first directory `made` that had to be created, or
`undefined` if everything already exists. Promise rejects if any errors
are encountered. Note that, in the case of promise rejection, some
directories _may_ have been created, as recursive directory creation is not
an atomic operation.
You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdir(path, opts, cb)`
and `opts.fs.stat(path, cb)`.
You can also override just one or the other of `mkdir` and `stat` by
passing in `opts.stat` or `opts.mkdir`, or providing an `fs` option that
only overrides one of these.
## mkdirp.sync(dir, opts) -> String|null
Synchronously create a new directory and any necessary subdirectories at
`dir` with octal permission string `opts.mode`. If `opts` is a string or
number, it will be treated as the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0o777 &
(~process.umask())`.
Returns the first directory that had to be created, or undefined if
everything already exists.
You can optionally pass in an alternate `fs` implementation by passing in
`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)`
and `opts.fs.statSync(path)`.
You can also override just one or the other of `mkdirSync` and `statSync`
by passing in `opts.statSync` or `opts.mkdirSync`, or providing an `fs`
option that only overrides one of these.
## mkdirp.manual, mkdirp.manualSync
Use the manual implementation (not the native one). This is the default
when the native implementation is not available or the stat/mkdir
implementation is overridden.
## mkdirp.native, mkdirp.nativeSync
Use the native implementation (not the manual one). This is the default
when the native implementation is available and stat/mkdir are not
overridden.
# implementation
On Node.js v10.12.0 and above, use the native `fs.mkdir(p,
{recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has been
overridden by an option.
## native implementation
- If the path is a root directory, then pass it to the underlying
implementation and return the result/error. (In this case, it'll either
succeed or fail, but we aren't actually creating any dirs.)
- Walk up the path statting each directory, to find the first path that
will be created, `made`.
- Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`)
- If error, raise it to the caller.
- Return `made`.
## manual implementation
- Call underlying `fs.mkdir` implementation, with `recursive: false`
- If error:
- If path is a root directory, raise to the caller and do not handle it
- If ENOENT, mkdirp parent dir, store result as `made`
- stat(path)
- If error, raise original `mkdir` error
- If directory, return `made`
- Else, raise original `mkdir` error
- else
- return `undefined` if a root dir, or `made` if set, or `path`
## windows vs unix caveat
On Windows file systems, attempts to create a root directory (ie, a drive
letter or root UNC path) will fail. If the root directory exists, then it
will fail with `EPERM`. If the root directory does not exist, then it will
fail with `ENOENT`.
On posix file systems, attempts to create a root directory (in recursive
mode) will succeed silently, as it is treated like just another directory
that already exists. (In non-recursive mode, of course, it fails with
`EEXIST`.)
In order to preserve this system-specific behavior (and because it's not as
if we can create the parent of a root directory anyway), attempts to create
a root directory are passed directly to the `fs` implementation, and any
errors encountered are not handled.
## native error caveat
The native implementation (as of at least Node.js v13.4.0) does not provide
appropriate errors in some cases (see
[nodejs/node#31481](https://github.com/nodejs/node/issues/31481) and
[nodejs/node#28015](https://github.com/nodejs/node/issues/28015)).
In order to work around this issue, the native implementation will fall
back to the manual implementation if an `ENOENT` error is encountered.
# choosing a recursive mkdir implementation
There are a few to choose from! Use the one that suits your needs best :D
## use `fs.mkdir(path, {recursive: true}, cb)` if:
- You wish to optimize performance even at the expense of other factors.
- You don't need to know the first dir created.
- You are ok with getting `ENOENT` as the error when some other problem is
the actual cause.
- You can limit your platforms to Node.js v10.12 and above.
- You're ok with using callbacks instead of promises.
- You don't need/want a CLI.
- You don't need to override the `fs` methods in use.
## use this module (mkdirp 1.x) if:
- You need to know the first directory that was created.
- You wish to use the native implementation if available, but fall back
when it's not.
- You prefer promise-returning APIs to callback-taking APIs.
- You want more useful error messages than the native recursive mkdir
provides (at least as of Node.js v13.4), and are ok with re-trying on
`ENOENT` to achieve this.
- You need (or at least, are ok with) a CLI.
- You need to override the `fs` methods in use.
## use [`make-dir`](http://npm.im/make-dir) if:
- You do not need to know the first dir created (and wish to save a few
`stat` calls when using the native implementation for this reason).
- You wish to use the native implementation if available, but fall back
when it's not.
- You prefer promise-returning APIs to callback-taking APIs.
- You are ok with occasionally getting `ENOENT` errors for failures that
are actually related to something other than a missing file system entry.
- You don't need/want a CLI.
- You need to override the `fs` methods in use.
## use mkdirp 0.x if:
- You need to know the first directory that was created.
- You need (or at least, are ok with) a CLI.
- You need to override the `fs` methods in use.
- You're ok with using callbacks instead of promises.
- You are not running on Windows, where the root-level ENOENT errors can
lead to infinite regress.
- You think vinyl just sounds warmer and richer for some weird reason.
- You are supporting truly ancient Node.js versions, before even the advent
of a `Promise` language primitive. (Please don't. You deserve better.)
# cli
This package also ships with a `mkdirp` command.
```
$ mkdirp -h
usage: mkdirp [DIR1,DIR2..] {OPTIONS}
Create each supplied directory including any necessary parent directories
that don't yet exist.
If the directory already exists, do nothing.
OPTIONS are:
-m<mode> If a directory needs to be created, set the mode as an octal
--mode=<mode> permission string.
-v --version Print the mkdirp version number
-h --help Print this helpful banner
-p --print Print the first directories created for each path provided
--manual Use manual implementation, even if native is available
```
# install
With [npm](http://npmjs.org) do:
```
npm install mkdirp
```
to get the library locally, or
```
npm install -g mkdirp
```
to get the command everywhere, or
```
npx mkdirp ...
```
to run the command without installing it globally.
# platform support
This module works on node v8, but only v10 and above are officially
supported, as Node v8 reached its LTS end of life 2020-01-01, which is in
the past, as of this writing.
# license
MIT
+70
View File
@@ -0,0 +1,70 @@
# changes log
## 6.2.0
* Coerce numbers to strings when passed to semver.coerce()
* Add `rtl` option to coerce from right to left
## 6.1.3
* Handle X-ranges properly in includePrerelease mode
## 6.1.2
* Do not throw when testing invalid version strings
## 6.1.1
* Add options support for semver.coerce()
* Handle undefined version passed to Range.test
## 6.1.0
* Add semver.compareBuild function
* Support `*` in semver.intersects
## 6.0
* Fix `intersects` logic.
This is technically a bug fix, but since it is also a change to behavior
that may require users updating their code, it is marked as a major
version increment.
## 5.7
* Add `minVersion` method
## 5.6
* Move boolean `loose` param to an options object, with
backwards-compatibility protection.
* Add ability to opt out of special prerelease version handling with
the `includePrerelease` option flag.
## 5.5
* Add version coercion capabilities
## 5.4
* Add intersection checking
## 5.3
* Add `minSatisfying` method
## 5.2
* Add `prerelease(v)` that returns prerelease components
## 5.1
* Add Backus-Naur for ranges
* Remove excessively cute inspection methods
## 5.0
* Remove AMD/Browserified build artifacts
* Fix ltr and gtr when using the `*` range
* Fix for range `*` with a prerelease identifier
+15
View File
@@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+443
View File
@@ -0,0 +1,443 @@
semver(1) -- The semantic versioner for npm
===========================================
## Install
```bash
npm install semver
````
## Usage
As a node module:
```js
const semver = require('semver')
semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean(' =v1.2.3 ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true
semver.minVersion('>=1.0.0') // '1.0.0'
semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
```
As a command-line utility:
```
$ semver -h
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, or prerelease. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.
```
## Versions
A "version" is described by the `v2.0.0` specification found at
<https://semver.org/>.
A leading `"="` or `"v"` character is stripped off and ignored.
## Ranges
A `version range` is a set of `comparators` which specify versions
that satisfy the range.
A `comparator` is composed of an `operator` and a `version`. The set
of primitive `operators` is:
* `<` Less than
* `<=` Less than or equal to
* `>` Greater than
* `>=` Greater than or equal to
* `=` Equal. If no operator is specified, then equality is assumed,
so this operator is optional, but MAY be included.
For example, the comparator `>=1.2.7` would match the versions
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
or `1.1.0`.
Comparators can be joined by whitespace to form a `comparator set`,
which is satisfied by the **intersection** of all of the comparators
it includes.
A range is composed of one or more comparator sets, joined by `||`. A
version matches a range if and only if every comparator in at least
one of the `||`-separated comparator sets is satisfied by the version.
For example, the range `>=1.2.7 <1.3.0` would match the versions
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
or `1.1.0`.
The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.
### Prerelease Tags
If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
it will only be allowed to satisfy comparator sets if at least one
comparator with the same `[major, minor, patch]` tuple also has a
prerelease tag.
For example, the range `>1.2.3-alpha.3` would be allowed to match the
version `1.2.3-alpha.7`, but it would *not* be satisfied by
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
than" `1.2.3-alpha.3` according to the SemVer sort rules. The version
range only accepts prerelease tags on the `1.2.3` version. The
version `3.4.5` *would* satisfy the range, because it does not have a
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.
The purpose for this behavior is twofold. First, prerelease versions
frequently are updated very quickly, and contain many breaking changes
that are (by the author's design) not yet fit for public consumption.
Therefore, by default, they are excluded from range matching
semantics.
Second, a user who has opted into using a prerelease version has
clearly indicated the intent to use *that specific* set of
alpha/beta/rc versions. By including a prerelease tag in the range,
the user is indicating that they are aware of the risk. However, it
is still not appropriate to assume that they have opted into taking a
similar risk on the *next* set of prerelease versions.
Note that this behavior can be suppressed (treating all prerelease
versions as if they were normal versions, for the purpose of range
matching) by setting the `includePrerelease` flag on the options
object to any
[functions](https://github.com/npm/node-semver#functions) that do
range matching.
#### Prerelease Identifiers
The method `.inc` takes an additional `identifier` string argument that
will append the value of the string as a prerelease identifier:
```javascript
semver.inc('1.2.3', 'prerelease', 'beta')
// '1.2.4-beta.0'
```
command-line example:
```bash
$ semver 1.2.3 -i prerelease --preid beta
1.2.4-beta.0
```
Which then can be used to increment further:
```bash
$ semver 1.2.4-beta.0 -i prerelease
1.2.4-beta.1
```
### Advanced Range Syntax
Advanced range syntax desugars to primitive comparators in
deterministic ways.
Advanced ranges may be combined in the same way as primitive
comparators using white space or `||`.
#### Hyphen Ranges `X.Y.Z - A.B.C`
Specifies an inclusive set.
* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`
If a partial version is provided as the first version in the inclusive
range, then the missing pieces are replaced with zeroes.
* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`
If a partial version is provided as the second version in the
inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0`
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.
* `*` := `>=0.0.0` (Any version satisfies)
* `1.x` := `>=1.0.0 <2.0.0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions)
A partial version range is treated as an X-Range, so the special
character is in fact optional.
* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0`
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
Allows patch-level changes if a minor version is specified on the
comparator. Allows minor-level changes if not.
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`
Allows changes that do not modify the left-most non-zero element in the
`[major, minor, patch]` tuple. In other words, this allows patch and
minor updates for versions `1.0.0` and above, patch updates for
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.
Many authors treat a `0.x` version as if the `x` were the major
"breaking-change" indicator.
Caret ranges are ideal when an author may make breaking changes
between `0.2.4` and `0.3.0` releases, which is a common practice.
However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.
* `^1.2.3` := `>=1.2.3 <2.0.0`
* `^0.2.3` := `>=0.2.3 <0.3.0`
* `^0.0.3` := `>=0.0.3 <0.0.4`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the
`0.0.3` version *only* will be allowed, if they are greater than or
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.
* `^1.2.x` := `>=1.2.0 <2.0.0`
* `^0.0.x` := `>=0.0.0 <0.1.0`
* `^0.0` := `>=0.0.0 <0.1.0`
A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.
* `^1.x` := `>=1.0.0 <2.0.0`
* `^0.x` := `>=0.0.0 <1.0.0`
### Range Grammar
Putting all this together, here is a Backus-Naur grammar for ranges,
for the benefit of parser authors:
```bnf
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+
```
## Functions
All methods and classes take a final `options` object argument. All
options in this object are `false` by default. The options supported
are:
- `loose` Be more forgiving about not-quite-valid semver strings.
(Any resulting output will always be 100% strict compliant, of
course.) For backwards compatibility reasons, if the `options`
argument is a boolean value instead of an object, it is interpreted
to be the `loose` param.
- `includePrerelease` Set to suppress the [default
behavior](https://github.com/npm/node-semver#prerelease-tags) of
excluding prerelease tagged versions from ranges unless they are
explicitly opted into.
Strict-mode Comparators and Ranges will be strict about the SemVer
strings that they parse.
* `valid(v)`: Return the parsed version, or null if it's not valid.
* `inc(v, release)`: Return the version incremented by the release
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
`prepatch`, or `prerelease`), or null if it's not valid
* `premajor` in one call will bump the version up to the next major
version and down to a prerelease of that major version.
`preminor`, and `prepatch` work the same way.
* If called from a non-prerelease version, the `prerelease` will work the
same as `prepatch`. It increments the patch version, then makes a
prerelease. If the input version is already a prerelease it simply
increments it.
* `prerelease(v)`: Returns an array of prerelease components, or null
if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
* `major(v)`: Return the major version number.
* `minor(v)`: Return the minor version number.
* `patch(v)`: Return the patch version number.
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
or comparators intersect.
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
a `SemVer` object or `null`.
### Comparison
* `gt(v1, v2)`: `v1 > v2`
* `gte(v1, v2)`: `v1 >= v2`
* `lt(v1, v2)`: `v1 < v2`
* `lte(v1, v2)`: `v1 <= v2`
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
even if they're not the exact same string. You already know how to
compare strings.
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
the corresponding function above. `"==="` and `"!=="` do simple
string comparison, but are included for completeness. Throws if an
invalid comparison string is provided.
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions
in descending order when passed to `Array.sort()`.
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
are equal. Sorts in ascending order if passed to `Array.sort()`.
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `diff(v1, v2)`: Returns difference between two versions by the release type
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
or null if the versions are the same.
### Comparators
* `intersects(comparator)`: Return true if the comparators intersect
### Ranges
* `validRange(range)`: Return the valid range or null if it's not valid
* `satisfies(version, range)`: Return true if the version satisfies the
range.
* `maxSatisfying(versions, range)`: Return the highest version in the list
that satisfies the range, or `null` if none of them do.
* `minSatisfying(versions, range)`: Return the lowest version in the list
that satisfies the range, or `null` if none of them do.
* `minVersion(range)`: Return the lowest version that can possibly match
the given range.
* `gtr(version, range)`: Return `true` if version is greater than all the
versions possible in the range.
* `ltr(version, range)`: Return `true` if version is less than all the
versions possible in the range.
* `outside(version, range, hilo)`: Return true if the version is outside
the bounds of the range in either the high or low direction. The
`hilo` argument must be either the string `'>'` or `'<'`. (This is
the function called by `gtr` and `ltr`.)
* `intersects(range)`: Return true if any of the ranges comparators intersect
Note that, since ranges may be non-contiguous, a version might not be
greater than a range, less than a range, *or* satisfy a range! For
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
until `2.0.0`, so the version `1.2.10` would not be greater than the
range (because `2.0.1` satisfies, which is higher), nor less than the
range (since `1.2.8` satisfies, which is lower), and it also does not
satisfy the range.
If you want to know if a version satisfies or does not satisfy a
range, use the `satisfies(version, range)` function.
### Coercion
* `coerce(version, options)`: Coerces a string to semver if possible
This aims to provide a very forgiving translation of a non-semver string to
semver. It looks for the first digit in a string, and consumes all
remaining characters which satisfy at least a partial semver (e.g., `1`,
`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
`3.4.0`). Only text which lacks digits will fail coercion (`version one`
is not valid). The maximum length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).
If the `options.rtl` flag is set, then `coerce` will return the right-most
coercible tuple that does not share an ending index with a longer coercible
tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
any other overlapping SemVer tuple.
### Clean
* `clean(version)`: Clean a string to be a valid semver if possible
This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges.
ex.
* `s.clean(' = v 2.1.5foo')`: `null`
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean(' = v 2.1.5-foo')`: `null`
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean('=v2.1.5')`: `'2.1.5'`
* `s.clean(' =v2.1.5')`: `2.1.5`
* `s.clean(' 2.1.5 ')`: `'2.1.5'`
* `s.clean('~1.0.0')`: `null`
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.
var argv = process.argv.slice(2)
var versions = []
var range = []
var inc = null
var version = require('../package.json').version
var loose = false
var includePrerelease = false
var coerce = false
var rtl = false
var identifier
var semver = require('../semver')
var reverse = false
var options = {}
main()
function main () {
if (!argv.length) return help()
while (argv.length) {
var a = argv.shift()
var indexOfEqualSign = a.indexOf('=')
if (indexOfEqualSign !== -1) {
a = a.slice(0, indexOfEqualSign)
argv.unshift(a.slice(indexOfEqualSign + 1))
}
switch (a) {
case '-rv': case '-rev': case '--rev': case '--reverse':
reverse = true
break
case '-l': case '--loose':
loose = true
break
case '-p': case '--include-prerelease':
includePrerelease = true
break
case '-v': case '--version':
versions.push(argv.shift())
break
case '-i': case '--inc': case '--increment':
switch (argv[0]) {
case 'major': case 'minor': case 'patch': case 'prerelease':
case 'premajor': case 'preminor': case 'prepatch':
inc = argv.shift()
break
default:
inc = 'patch'
break
}
break
case '--preid':
identifier = argv.shift()
break
case '-r': case '--range':
range.push(argv.shift())
break
case '-c': case '--coerce':
coerce = true
break
case '--rtl':
rtl = true
break
case '--ltr':
rtl = false
break
case '-h': case '--help': case '-?':
return help()
default:
versions.push(a)
break
}
}
var options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl }
versions = versions.map(function (v) {
return coerce ? (semver.coerce(v, options) || { version: v }).version : v
}).filter(function (v) {
return semver.valid(v)
})
if (!versions.length) return fail()
if (inc && (versions.length !== 1 || range.length)) { return failInc() }
for (var i = 0, l = range.length; i < l; i++) {
versions = versions.filter(function (v) {
return semver.satisfies(v, range[i], options)
})
if (!versions.length) return fail()
}
return success(versions)
}
function failInc () {
console.error('--inc can only be used on a single version with no range')
fail()
}
function fail () { process.exit(1) }
function success () {
var compare = reverse ? 'rcompare' : 'compare'
versions.sort(function (a, b) {
return semver[compare](a, b, options)
}).map(function (v) {
return semver.clean(v, options)
}).map(function (v) {
return inc ? semver.inc(v, inc, options, identifier) : v
}).forEach(function (v, i, _) { console.log(v) })
}
function help () {
console.log(['SemVer ' + version,
'',
'A JavaScript implementation of the https://semver.org/ specification',
'Copyright Isaac Z. Schlueter',
'',
'Usage: semver [options] <version> [<version> [...]]',
'Prints valid versions sorted by SemVer precedence',
'',
'Options:',
'-r --range <range>',
' Print versions that match the specified range.',
'',
'-i --increment [<level>]',
' Increment a version by the specified level. Level can',
' be one of: major, minor, patch, premajor, preminor,',
" prepatch, or prerelease. Default level is 'patch'.",
' Only one version may be specified.',
'',
'--preid <identifier>',
' Identifier to be used to prefix premajor, preminor,',
' prepatch or prerelease version increments.',
'',
'-l --loose',
' Interpret versions and ranges loosely',
'',
'-p --include-prerelease',
' Always include prerelease versions in range matching',
'',
'-c --coerce',
' Coerce a string into SemVer if possible',
' (does not imply --loose)',
'',
'--rtl',
' Coerce version strings right to left',
'',
'--ltr',
' Coerce version strings left to right (default)',
'',
'Program exits successfully if any valid version satisfies',
'all supplied ranges, and prints all satisfying versions.',
'',
'If no satisfying versions are found, then exits failure.',
'',
'Versions are printed in ascending order, so supplying',
'multiple versions to the utility will just sort them.'
].join('\n'))
}
+37
View File
@@ -0,0 +1,37 @@
{
"bin": {
"semver": "bin/semver.js"
},
"bugs": {
"url": "https://github.com/npm/node-semver/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "The semantic version parser used by npm.",
"devDependencies": {
"tap": "^14.3.1"
},
"files": [
"bin",
"range.bnf",
"semver.js"
],
"homepage": "https://github.com/npm/node-semver#readme",
"license": "ISC",
"main": "semver.js",
"name": "semver",
"repository": {
"type": "git",
"url": "git+https://github.com/npm/node-semver.git"
},
"scripts": {
"postpublish": "git push origin --follow-tags",
"postversion": "npm publish",
"preversion": "npm test",
"test": "tap"
},
"tap": {
"check-coverage": true
},
"version": "6.3.0"
}
+16
View File
@@ -0,0 +1,16 @@
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | [1-9] ( [0-9] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+
File diff suppressed because it is too large Load Diff
+594
View File
@@ -0,0 +1,594 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [18.1.2](https://www.github.com/yargs/yargs-parser/compare/v18.1.1...v18.1.2) (2020-03-26)
### Bug Fixes
* **array, nargs:** support -o=--value and --option=--value format ([#262](https://www.github.com/yargs/yargs-parser/issues/262)) ([41d3f81](https://www.github.com/yargs/yargs-parser/commit/41d3f8139e116706b28de9b0de3433feb08d2f13))
### [18.1.1](https://www.github.com/yargs/yargs-parser/compare/v18.1.0...v18.1.1) (2020-03-16)
### Bug Fixes
* \_\_proto\_\_ will now be replaced with \_\_\_proto\_\_\_ in parse ([#258](https://www.github.com/yargs/yargs-parser/issues/258)), patching a potential
prototype pollution vulnerability. This was reported by the Snyk Security Research Team.([63810ca](https://www.github.com/yargs/yargs-parser/commit/63810ca1ae1a24b08293a4d971e70e058c7a41e2))
## [18.1.0](https://www.github.com/yargs/yargs-parser/compare/v18.0.0...v18.1.0) (2020-03-07)
### Features
* introduce single-digit boolean aliases ([#255](https://www.github.com/yargs/yargs-parser/issues/255)) ([9c60265](https://www.github.com/yargs/yargs-parser/commit/9c60265fd7a03cb98e6df3e32c8c5e7508d9f56f))
## [18.0.0](https://www.github.com/yargs/yargs-parser/compare/v17.1.0...v18.0.0) (2020-03-02)
### ⚠ BREAKING CHANGES
* the narg count is now enforced when parsing arrays.
### Features
* NaN can now be provided as a value for nargs, indicating "at least" one value is expected for array ([#251](https://www.github.com/yargs/yargs-parser/issues/251)) ([9db4be8](https://www.github.com/yargs/yargs-parser/commit/9db4be81417a2c7097128db34d86fe70ef4af70c))
## [17.1.0](https://www.github.com/yargs/yargs-parser/compare/v17.0.1...v17.1.0) (2020-03-01)
### Features
* introduce greedy-arrays config, for specifying whether arrays consume multiple positionals ([#249](https://www.github.com/yargs/yargs-parser/issues/249)) ([60e880a](https://www.github.com/yargs/yargs-parser/commit/60e880a837046314d89fa4725f923837fd33a9eb))
### [17.0.1](https://www.github.com/yargs/yargs-parser/compare/v17.0.0...v17.0.1) (2020-02-29)
### Bug Fixes
* normalized keys were not enumerable ([#247](https://www.github.com/yargs/yargs-parser/issues/247)) ([57119f9](https://www.github.com/yargs/yargs-parser/commit/57119f9f17cf27499bd95e61c2f72d18314f11ba))
## [17.0.0](https://www.github.com/yargs/yargs-parser/compare/v16.1.0...v17.0.0) (2020-02-10)
### ⚠ BREAKING CHANGES
* this reverts parsing behavior of booleans to that of yargs@14
* objects used during parsing are now created with a null
prototype. There may be some scenarios where this change in behavior
leaks externally.
### Features
* boolean arguments will not be collected into an implicit array ([#236](https://www.github.com/yargs/yargs-parser/issues/236)) ([34c4e19](https://www.github.com/yargs/yargs-parser/commit/34c4e19bae4e7af63e3cb6fa654a97ed476e5eb5))
* introduce nargs-eats-options config option ([#246](https://www.github.com/yargs/yargs-parser/issues/246)) ([d50822a](https://www.github.com/yargs/yargs-parser/commit/d50822ac10e1b05f2e9643671ca131ac251b6732))
### Bug Fixes
* address bugs with "uknown-options-as-args" ([bc023e3](https://www.github.com/yargs/yargs-parser/commit/bc023e3b13e20a118353f9507d1c999bf388a346))
* array should take precedence over nargs, but enforce nargs ([#243](https://www.github.com/yargs/yargs-parser/issues/243)) ([4cbc188](https://www.github.com/yargs/yargs-parser/commit/4cbc188b7abb2249529a19c090338debdad2fe6c))
* support keys that collide with object prototypes ([#234](https://www.github.com/yargs/yargs-parser/issues/234)) ([1587b6d](https://www.github.com/yargs/yargs-parser/commit/1587b6d91db853a9109f1be6b209077993fee4de))
* unknown options terminated with digits now handled by unknown-options-as-args ([#238](https://www.github.com/yargs/yargs-parser/issues/238)) ([d36cdfa](https://www.github.com/yargs/yargs-parser/commit/d36cdfa854254d7c7e0fe1d583818332ac46c2a5))
## [16.1.0](https://www.github.com/yargs/yargs-parser/compare/v16.0.0...v16.1.0) (2019-11-01)
### ⚠ BREAKING CHANGES
* populate error if incompatible narg/count or array/count options are used (#191)
### Features
* options that have had their default value used are now tracked ([#211](https://www.github.com/yargs/yargs-parser/issues/211)) ([a525234](https://www.github.com/yargs/yargs-parser/commit/a525234558c847deedd73f8792e0a3b77b26e2c0))
* populate error if incompatible narg/count or array/count options are used ([#191](https://www.github.com/yargs/yargs-parser/issues/191)) ([84a401f](https://www.github.com/yargs/yargs-parser/commit/84a401f0fa3095e0a19661670d1570d0c3b9d3c9))
### Reverts
* revert 16.0.0 CHANGELOG entry ([920320a](https://www.github.com/yargs/yargs-parser/commit/920320ad9861bbfd58eda39221ae211540fc1daf))
## [15.0.0](https://github.com/yargs/yargs-parser/compare/v14.0.0...v15.0.0) (2019-10-07)
### Features
* rework `collect-unknown-options` into `unknown-options-as-args`, providing more comprehensive functionality ([ef771ca](https://github.com/yargs/yargs-parser/commit/ef771ca))
### BREAKING CHANGES
* rework `collect-unknown-options` into `unknown-options-as-args`, providing more comprehensive functionality
## [14.0.0](https://github.com/yargs/yargs-parser/compare/v13.1.1...v14.0.0) (2019-09-06)
### Bug Fixes
* boolean arrays with default values ([#185](https://github.com/yargs/yargs-parser/issues/185)) ([7d42572](https://github.com/yargs/yargs-parser/commit/7d42572))
* boolean now behaves the same as other array types ([#184](https://github.com/yargs/yargs-parser/issues/184)) ([17ca3bd](https://github.com/yargs/yargs-parser/commit/17ca3bd))
* eatNargs() for 'opt.narg === 0' and boolean typed options ([#188](https://github.com/yargs/yargs-parser/issues/188)) ([c5a1db0](https://github.com/yargs/yargs-parser/commit/c5a1db0))
* maybeCoerceNumber now takes precedence over coerce return value ([#182](https://github.com/yargs/yargs-parser/issues/182)) ([2f26436](https://github.com/yargs/yargs-parser/commit/2f26436))
* take into account aliases when appending arrays from config object ([#199](https://github.com/yargs/yargs-parser/issues/199)) ([f8a2d3f](https://github.com/yargs/yargs-parser/commit/f8a2d3f))
### Features
* add configuration option to "collect-unknown-options" ([#181](https://github.com/yargs/yargs-parser/issues/181)) ([7909cc4](https://github.com/yargs/yargs-parser/commit/7909cc4))
* maybeCoerceNumber() now takes into account arrays ([#187](https://github.com/yargs/yargs-parser/issues/187)) ([31c204b](https://github.com/yargs/yargs-parser/commit/31c204b))
### BREAKING CHANGES
* unless "parse-numbers" is set to "false", arrays of numeric strings are now parsed as numbers, rather than strings.
* we have dropped the broken "defaulted" functionality; we would like to revisit adding this in the future.
* maybeCoerceNumber now takes precedence over coerce return value (#182)
### [13.1.1](https://www.github.com/yargs/yargs-parser/compare/v13.1.0...v13.1.1) (2019-06-10)
### Bug Fixes
* convert values to strings when tokenizing ([#167](https://www.github.com/yargs/yargs-parser/issues/167)) ([57b7883](https://www.github.com/yargs/yargs-parser/commit/57b7883))
* nargs should allow duplicates when duplicate-arguments-array=false ([#164](https://www.github.com/yargs/yargs-parser/issues/164)) ([47ccb0b](https://www.github.com/yargs/yargs-parser/commit/47ccb0b))
* should populate "_" when given config with "short-option-groups" false ([#179](https://www.github.com/yargs/yargs-parser/issues/179)) ([6055974](https://www.github.com/yargs/yargs-parser/commit/6055974))
## [13.1.0](https://github.com/yargs/yargs-parser/compare/v13.0.0...v13.1.0) (2019-05-05)
### Features
* add `strip-aliased` and `strip-dashed` configuration options. ([#172](https://github.com/yargs/yargs-parser/issues/172)) ([a3936aa](https://github.com/yargs/yargs-parser/commit/a3936aa))
* support boolean which do not consume next argument. ([#171](https://github.com/yargs/yargs-parser/issues/171)) ([0ae7fcb](https://github.com/yargs/yargs-parser/commit/0ae7fcb))
<a name="13.0.0"></a>
# [13.0.0](https://github.com/yargs/yargs-parser/compare/v12.0.0...v13.0.0) (2019-02-02)
### Features
* don't coerce number from string with leading '0' or '+' ([#158](https://github.com/yargs/yargs-parser/issues/158)) ([18d0fd5](https://github.com/yargs/yargs-parser/commit/18d0fd5))
### BREAKING CHANGES
* options with leading '+' or '0' now parse as strings
<a name="12.0.0"></a>
# [12.0.0](https://github.com/yargs/yargs-parser/compare/v11.1.1...v12.0.0) (2019-01-29)
### Bug Fixes
* better handling of quoted strings ([#153](https://github.com/yargs/yargs-parser/issues/153)) ([2fb71b2](https://github.com/yargs/yargs-parser/commit/2fb71b2))
### Features
* default value is now used if no right-hand value provided for numbers/strings ([#156](https://github.com/yargs/yargs-parser/issues/156)) ([5a7c46a](https://github.com/yargs/yargs-parser/commit/5a7c46a))
### BREAKING CHANGES
* a flag with no right-hand value no longer populates defaulted options with `undefined`.
* quotes at beginning and endings of strings are not removed during parsing.
<a name="11.1.1"></a>
## [11.1.1](https://github.com/yargs/yargs-parser/compare/v11.1.0...v11.1.1) (2018-11-19)
### Bug Fixes
* ensure empty string is added into argv._ ([#140](https://github.com/yargs/yargs-parser/issues/140)) ([79cda98](https://github.com/yargs/yargs-parser/commit/79cda98))
### Reverts
* make requiresArg work in conjunction with arrays ([#136](https://github.com/yargs/yargs-parser/issues/136)) ([f4a3063](https://github.com/yargs/yargs-parser/commit/f4a3063))
<a name="11.1.0"></a>
# [11.1.0](https://github.com/yargs/yargs-parser/compare/v11.0.0...v11.1.0) (2018-11-10)
### Bug Fixes
* handling of one char alias ([#139](https://github.com/yargs/yargs-parser/issues/139)) ([ee56e31](https://github.com/yargs/yargs-parser/commit/ee56e31))
### Features
* add halt-at-non-option configuration option ([#130](https://github.com/yargs/yargs-parser/issues/130)) ([a849fce](https://github.com/yargs/yargs-parser/commit/a849fce))
<a name="11.0.0"></a>
# [11.0.0](https://github.com/yargs/yargs-parser/compare/v10.1.0...v11.0.0) (2018-10-06)
### Bug Fixes
* flatten-duplicate-arrays:false for more than 2 arrays ([#128](https://github.com/yargs/yargs-parser/issues/128)) ([2bc395f](https://github.com/yargs/yargs-parser/commit/2bc395f))
* hyphenated flags combined with dot notation broke parsing ([#131](https://github.com/yargs/yargs-parser/issues/131)) ([dc788da](https://github.com/yargs/yargs-parser/commit/dc788da))
* make requiresArg work in conjunction with arrays ([#136](https://github.com/yargs/yargs-parser/issues/136)) ([77ae1d4](https://github.com/yargs/yargs-parser/commit/77ae1d4))
### Chores
* update dependencies ([6dc42a1](https://github.com/yargs/yargs-parser/commit/6dc42a1))
### Features
* also add camelCase array options ([#125](https://github.com/yargs/yargs-parser/issues/125)) ([08c0117](https://github.com/yargs/yargs-parser/commit/08c0117))
* array.type can now be provided, supporting coercion ([#132](https://github.com/yargs/yargs-parser/issues/132)) ([4b8cfce](https://github.com/yargs/yargs-parser/commit/4b8cfce))
### BREAKING CHANGES
* drops Node 4 support
* the argv object is now populated differently (correctly) when hyphens and dot notation are used in conjunction.
<a name="10.1.0"></a>
# [10.1.0](https://github.com/yargs/yargs-parser/compare/v10.0.0...v10.1.0) (2018-06-29)
### Features
* add `set-placeholder-key` configuration ([#123](https://github.com/yargs/yargs-parser/issues/123)) ([19386ee](https://github.com/yargs/yargs-parser/commit/19386ee))
<a name="10.0.0"></a>
# [10.0.0](https://github.com/yargs/yargs-parser/compare/v9.0.2...v10.0.0) (2018-04-04)
### Bug Fixes
* do not set boolean flags if not defined in `argv` ([#119](https://github.com/yargs/yargs-parser/issues/119)) ([f6e6599](https://github.com/yargs/yargs-parser/commit/f6e6599))
### BREAKING CHANGES
* `boolean` flags defined without a `default` value will now behave like other option type and won't be set in the parsed results when the user doesn't set the corresponding CLI arg.
Previous behavior:
```js
var parse = require('yargs-parser');
parse('--flag', {boolean: ['flag']});
// => { _: [], flag: true }
parse('--no-flag', {boolean: ['flag']});
// => { _: [], flag: false }
parse('', {boolean: ['flag']});
// => { _: [], flag: false }
```
New behavior:
```js
var parse = require('yargs-parser');
parse('--flag', {boolean: ['flag']});
// => { _: [], flag: true }
parse('--no-flag', {boolean: ['flag']});
// => { _: [], flag: false }
parse('', {boolean: ['flag']});
// => { _: [] } => flag not set similarly to other option type
```
<a name="9.0.2"></a>
## [9.0.2](https://github.com/yargs/yargs-parser/compare/v9.0.1...v9.0.2) (2018-01-20)
### Bug Fixes
* nargs was still aggressively consuming too many arguments ([9b28aad](https://github.com/yargs/yargs-parser/commit/9b28aad))
<a name="9.0.1"></a>
## [9.0.1](https://github.com/yargs/yargs-parser/compare/v9.0.0...v9.0.1) (2018-01-20)
### Bug Fixes
* nargs was consuming too many arguments ([4fef206](https://github.com/yargs/yargs-parser/commit/4fef206))
<a name="9.0.0"></a>
# [9.0.0](https://github.com/yargs/yargs-parser/compare/v8.1.0...v9.0.0) (2018-01-20)
### Features
* narg arguments no longer consume flag arguments ([#114](https://github.com/yargs/yargs-parser/issues/114)) ([60bb9b3](https://github.com/yargs/yargs-parser/commit/60bb9b3))
### BREAKING CHANGES
* arguments of form --foo, -abc, will no longer be consumed by nargs
<a name="8.1.0"></a>
# [8.1.0](https://github.com/yargs/yargs-parser/compare/v8.0.0...v8.1.0) (2017-12-20)
### Bug Fixes
* allow null config values ([#108](https://github.com/yargs/yargs-parser/issues/108)) ([d8b14f9](https://github.com/yargs/yargs-parser/commit/d8b14f9))
* ensure consistent parsing of dot-notation arguments ([#102](https://github.com/yargs/yargs-parser/issues/102)) ([c9bd79c](https://github.com/yargs/yargs-parser/commit/c9bd79c))
* implement [@antoniom](https://github.com/antoniom)'s fix for camel-case expansion ([3087e1d](https://github.com/yargs/yargs-parser/commit/3087e1d))
* only run coercion functions once, despite aliases. ([#76](https://github.com/yargs/yargs-parser/issues/76)) ([#103](https://github.com/yargs/yargs-parser/issues/103)) ([507aaef](https://github.com/yargs/yargs-parser/commit/507aaef))
* scientific notation circumvented bounds check ([#110](https://github.com/yargs/yargs-parser/issues/110)) ([3571f57](https://github.com/yargs/yargs-parser/commit/3571f57))
* tokenizer should ignore spaces at the beginning of the argString ([#106](https://github.com/yargs/yargs-parser/issues/106)) ([f34ead9](https://github.com/yargs/yargs-parser/commit/f34ead9))
### Features
* make combining arrays a configurable option ([#111](https://github.com/yargs/yargs-parser/issues/111)) ([c8bf536](https://github.com/yargs/yargs-parser/commit/c8bf536))
* merge array from arguments with array from config ([#83](https://github.com/yargs/yargs-parser/issues/83)) ([806ddd6](https://github.com/yargs/yargs-parser/commit/806ddd6))
<a name="8.0.0"></a>
# [8.0.0](https://github.com/yargs/yargs-parser/compare/v7.0.0...v8.0.0) (2017-10-05)
### Bug Fixes
* Ignore multiple spaces between arguments. ([#100](https://github.com/yargs/yargs-parser/issues/100)) ([d137227](https://github.com/yargs/yargs-parser/commit/d137227))
### Features
* allow configuration of prefix for boolean negation ([#94](https://github.com/yargs/yargs-parser/issues/94)) ([00bde7d](https://github.com/yargs/yargs-parser/commit/00bde7d))
* reworking how numbers are parsed ([#104](https://github.com/yargs/yargs-parser/issues/104)) ([fba00eb](https://github.com/yargs/yargs-parser/commit/fba00eb))
### BREAKING CHANGES
* strings that fail `Number.isSafeInteger()` are no longer coerced into numbers.
<a name="7.0.0"></a>
# [7.0.0](https://github.com/yargs/yargs-parser/compare/v6.0.1...v7.0.0) (2017-05-02)
### Chores
* revert populate-- logic ([#91](https://github.com/yargs/yargs-parser/issues/91)) ([6003e6d](https://github.com/yargs/yargs-parser/commit/6003e6d))
### BREAKING CHANGES
* populate-- now defaults to false.
<a name="6.0.1"></a>
## [6.0.1](https://github.com/yargs/yargs-parser/compare/v6.0.0...v6.0.1) (2017-05-01)
### Bug Fixes
* default '--' to undefined when not provided; this is closer to the array API ([#90](https://github.com/yargs/yargs-parser/issues/90)) ([4e739cc](https://github.com/yargs/yargs-parser/commit/4e739cc))
<a name="6.0.0"></a>
# [6.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v6.0.0) (2017-05-01)
### Bug Fixes
* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f))
* parsing hints should apply for dot notation keys ([#86](https://github.com/yargs/yargs-parser/issues/86)) ([3e47d62](https://github.com/yargs/yargs-parser/commit/3e47d62))
### Chores
* upgrade to newest version of camelcase ([#87](https://github.com/yargs/yargs-parser/issues/87)) ([f1903aa](https://github.com/yargs/yargs-parser/commit/f1903aa))
### Features
* add -- option which allows arguments after the -- flag to be returned separated from positional arguments ([#84](https://github.com/yargs/yargs-parser/issues/84)) ([2572ca8](https://github.com/yargs/yargs-parser/commit/2572ca8))
* when parsing stops, we now populate "--" by default ([#88](https://github.com/yargs/yargs-parser/issues/88)) ([cd666db](https://github.com/yargs/yargs-parser/commit/cd666db))
### BREAKING CHANGES
* rather than placing arguments in "_", when parsing is stopped via "--"; we now populate an array called "--" by default.
* camelcase now requires Node 4+.
* environment variables will now override config files (args, env, config-file, config-object)
<a name="5.0.0"></a>
# [5.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v5.0.0) (2017-02-18)
### Bug Fixes
* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f))
### BREAKING CHANGES
* environment variables will now override config files (args, env, config-file, config-object)
<a name="4.2.1"></a>
## [4.2.1](https://github.com/yargs/yargs-parser/compare/v4.2.0...v4.2.1) (2017-01-02)
### Bug Fixes
* flatten/duplicate regression ([#75](https://github.com/yargs/yargs-parser/issues/75)) ([68d68a0](https://github.com/yargs/yargs-parser/commit/68d68a0))
<a name="4.2.0"></a>
# [4.2.0](https://github.com/yargs/yargs-parser/compare/v4.1.0...v4.2.0) (2016-12-01)
### Bug Fixes
* inner objects in configs had their keys appended to top-level key when dot-notation was disabled ([#72](https://github.com/yargs/yargs-parser/issues/72)) ([0b1b5f9](https://github.com/yargs/yargs-parser/commit/0b1b5f9))
### Features
* allow multiple arrays to be provided, rather than always combining ([#71](https://github.com/yargs/yargs-parser/issues/71)) ([0f0fb2d](https://github.com/yargs/yargs-parser/commit/0f0fb2d))
<a name="4.1.0"></a>
# [4.1.0](https://github.com/yargs/yargs-parser/compare/v4.0.2...v4.1.0) (2016-11-07)
### Features
* apply coercions to default options ([#65](https://github.com/yargs/yargs-parser/issues/65)) ([c79052b](https://github.com/yargs/yargs-parser/commit/c79052b))
* handle dot notation boolean options ([#63](https://github.com/yargs/yargs-parser/issues/63)) ([02c3545](https://github.com/yargs/yargs-parser/commit/02c3545))
<a name="4.0.2"></a>
## [4.0.2](https://github.com/yargs/yargs-parser/compare/v4.0.1...v4.0.2) (2016-09-30)
### Bug Fixes
* whoops, let's make the assign not change the Object key order ([29d069a](https://github.com/yargs/yargs-parser/commit/29d069a))
<a name="4.0.1"></a>
## [4.0.1](https://github.com/yargs/yargs-parser/compare/v4.0.0...v4.0.1) (2016-09-30)
### Bug Fixes
* lodash.assign was deprecated ([#59](https://github.com/yargs/yargs-parser/issues/59)) ([5e7eb11](https://github.com/yargs/yargs-parser/commit/5e7eb11))
<a name="4.0.0"></a>
# [4.0.0](https://github.com/yargs/yargs-parser/compare/v3.2.0...v4.0.0) (2016-09-26)
### Bug Fixes
* coerce should be applied to the final objects and arrays created ([#57](https://github.com/yargs/yargs-parser/issues/57)) ([4ca69da](https://github.com/yargs/yargs-parser/commit/4ca69da))
### BREAKING CHANGES
* coerce is no longer applied to individual arguments in an implicit array.
<a name="3.2.0"></a>
# [3.2.0](https://github.com/yargs/yargs-parser/compare/v3.1.0...v3.2.0) (2016-08-13)
### Features
* coerce full array instead of each element ([#51](https://github.com/yargs/yargs-parser/issues/51)) ([cc4dc56](https://github.com/yargs/yargs-parser/commit/cc4dc56))
<a name="3.1.0"></a>
# [3.1.0](https://github.com/yargs/yargs-parser/compare/v3.0.0...v3.1.0) (2016-08-09)
### Bug Fixes
* address pkgConf parsing bug outlined in [#37](https://github.com/yargs/yargs-parser/issues/37) ([#45](https://github.com/yargs/yargs-parser/issues/45)) ([be76ee6](https://github.com/yargs/yargs-parser/commit/be76ee6))
* better parsing of negative values ([#44](https://github.com/yargs/yargs-parser/issues/44)) ([2e43692](https://github.com/yargs/yargs-parser/commit/2e43692))
* check aliases when guessing defaults for arguments fixes [#41](https://github.com/yargs/yargs-parser/issues/41) ([#43](https://github.com/yargs/yargs-parser/issues/43)) ([f3e4616](https://github.com/yargs/yargs-parser/commit/f3e4616))
### Features
* added coerce option, for providing specialized argument parsing ([#42](https://github.com/yargs/yargs-parser/issues/42)) ([7b49cd2](https://github.com/yargs/yargs-parser/commit/7b49cd2))
<a name="3.0.0"></a>
# [3.0.0](https://github.com/yargs/yargs-parser/compare/v2.4.1...v3.0.0) (2016-08-07)
### Bug Fixes
* parsing issue with numeric character in group of options ([#19](https://github.com/yargs/yargs-parser/issues/19)) ([f743236](https://github.com/yargs/yargs-parser/commit/f743236))
* upgraded lodash.assign ([5d7fdf4](https://github.com/yargs/yargs-parser/commit/5d7fdf4))
### BREAKING CHANGES
* subtle change to how values are parsed in a group of single-character arguments.
* _first released in 3.1.0, better handling of negative values should be considered a breaking change._
<a name="2.4.1"></a>
## [2.4.1](https://github.com/yargs/yargs-parser/compare/v2.4.0...v2.4.1) (2016-07-16)
### Bug Fixes
* **count:** do not increment a default value ([#39](https://github.com/yargs/yargs-parser/issues/39)) ([b04a189](https://github.com/yargs/yargs-parser/commit/b04a189))
<a name="2.4.0"></a>
# [2.4.0](https://github.com/yargs/yargs-parser/compare/v2.3.0...v2.4.0) (2016-04-11)
### Features
* **environment:** Support nested options in environment variables ([#26](https://github.com/yargs/yargs-parser/issues/26)) thanks [@elas7](https://github.com/elas7) \o/ ([020778b](https://github.com/yargs/yargs-parser/commit/020778b))
<a name="2.3.0"></a>
# [2.3.0](https://github.com/yargs/yargs-parser/compare/v2.2.0...v2.3.0) (2016-04-09)
### Bug Fixes
* **boolean:** fix for boolean options with non boolean defaults (#20) ([2dbe86b](https://github.com/yargs/yargs-parser/commit/2dbe86b)), closes [(#20](https://github.com/(/issues/20)
* **package:** remove tests from tarball ([0353c0d](https://github.com/yargs/yargs-parser/commit/0353c0d))
* **parsing:** handle calling short option with an empty string as the next value. ([a867165](https://github.com/yargs/yargs-parser/commit/a867165))
* boolean flag when next value contains the strings 'true' or 'false'. ([69941a6](https://github.com/yargs/yargs-parser/commit/69941a6))
* update dependencies; add standard-version bin for next release (#24) ([822d9d5](https://github.com/yargs/yargs-parser/commit/822d9d5))
### Features
* **configuration:** Allow to pass configuration objects to yargs-parser ([0780900](https://github.com/yargs/yargs-parser/commit/0780900))
* **normalize:** allow normalize to work with arrays ([e0eaa1a](https://github.com/yargs/yargs-parser/commit/e0eaa1a))
+14
View File
@@ -0,0 +1,14 @@
Copyright (c) 2016, Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice
appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE
LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+449
View File
@@ -0,0 +1,449 @@
# yargs-parser
[![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser)
[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser)
[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version)
The mighty option parser used by [yargs](https://github.com/yargs/yargs).
visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions.
<img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png">
## Example
```sh
npm i yargs-parser --save
```
```js
var argv = require('yargs-parser')(process.argv.slice(2))
console.log(argv)
```
```sh
node example.js --foo=33 --bar hello
{ _: [], foo: 33, bar: 'hello' }
```
_or parse a string!_
```js
var argv = require('yargs-parser')('--foo=99 --bar=33')
console.log(argv)
```
```sh
{ _: [], foo: 99, bar: 33 }
```
Convert an array of mixed types before passing to `yargs-parser`:
```js
var parse = require('yargs-parser')
parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string
parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings
```
## API
### require('yargs-parser')(args, opts={})
Parses command line arguments returning a simple mapping of keys and values.
**expects:**
* `args`: a string or array of strings representing the options to parse.
* `opts`: provide a set of hints indicating how `args` should be parsed:
* `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`.
* `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br>
Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br>
`{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`.
* `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`.
* `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided
(or throws an error). For arrays the function is called only once for the entire array:<br>
`{coerce: {foo: function (arg) {return modifiedArg}}}`.
* `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed).
* `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br>
`{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`.
* `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)).
* `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`.
* `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`.
* `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed.
* `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`.
* `opts.normalize`: `path.normalize()` will be applied to values set to this key.
* `opts.number`: keys should be treated as numbers.
* `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`).
**returns:**
* `obj`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* [optional] `--`: an array with arguments after the end-of-options flag `--`.
### require('yargs-parser').detailed(args, opts={})
Parses a command line string, returning detailed information required by the
yargs engine.
**expects:**
* `args`: a string or array of strings representing options to parse.
* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`.
**returns:**
* `argv`: an object representing the parsed value of `args`
* `key/value`: key value pairs for each argument and their aliases.
* `_`: an array representing the positional arguments.
* [optional] `--`: an array with arguments after the end-of-options flag `--`.
* `error`: populated with an error object if an exception occurred during parsing.
* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`.
* `newAliases`: any new aliases added via camel-case expansion:
* `boolean`: `{ fooBar: true }`
* `defaulted`: any new argument created by `opts.default`, no aliases included.
* `boolean`: `{ foo: true }`
* `configuration`: given by default settings and `opts.configuration`.
<a name="configuration"></a>
### Configuration
The yargs-parser applies several automated transformations on the keys provided
in `args`. These features can be turned on and off using the `configuration` field
of `opts`.
```js
var parsed = parser(['--no-dice'], {
configuration: {
'boolean-negation': false
}
})
```
### short option groups
* default: `true`.
* key: `short-option-groups`.
Should a group of short-options be treated as boolean flags?
```sh
node example.js -abc
{ _: [], a: true, b: true, c: true }
```
_if disabled:_
```sh
node example.js -abc
{ _: [], abc: true }
```
### camel-case expansion
* default: `true`.
* key: `camel-case-expansion`.
Should hyphenated arguments be expanded into camel-case aliases?
```sh
node example.js --foo-bar
{ _: [], 'foo-bar': true, fooBar: true }
```
_if disabled:_
```sh
node example.js --foo-bar
{ _: [], 'foo-bar': true }
```
### dot-notation
* default: `true`
* key: `dot-notation`
Should keys that contain `.` be treated as objects?
```sh
node example.js --foo.bar
{ _: [], foo: { bar: true } }
```
_if disabled:_
```sh
node example.js --foo.bar
{ _: [], "foo.bar": true }
```
### parse numbers
* default: `true`
* key: `parse-numbers`
Should keys that look like numbers be treated as such?
```sh
node example.js --foo=99.3
{ _: [], foo: 99.3 }
```
_if disabled:_
```sh
node example.js --foo=99.3
{ _: [], foo: "99.3" }
```
### boolean negation
* default: `true`
* key: `boolean-negation`
Should variables prefixed with `--no` be treated as negations?
```sh
node example.js --no-foo
{ _: [], foo: false }
```
_if disabled:_
```sh
node example.js --no-foo
{ _: [], "no-foo": true }
```
### combine arrays
* default: `false`
* key: `combine-arrays`
Should arrays be combined when provided by both command line arguments and
a configuration file.
### duplicate arguments array
* default: `true`
* key: `duplicate-arguments-array`
Should arguments be coerced into an array when duplicated:
```sh
node example.js -x 1 -x 2
{ _: [], x: [1, 2] }
```
_if disabled:_
```sh
node example.js -x 1 -x 2
{ _: [], x: 2 }
```
### flatten duplicate arrays
* default: `true`
* key: `flatten-duplicate-arrays`
Should array arguments be coerced into a single array when duplicated:
```sh
node example.js -x 1 2 -x 3 4
{ _: [], x: [1, 2, 3, 4] }
```
_if disabled:_
```sh
node example.js -x 1 2 -x 3 4
{ _: [], x: [[1, 2], [3, 4]] }
```
### greedy arrays
* default: `true`
* key: `greedy-arrays`
Should arrays consume more than one positional argument following their flag.
```sh
node example --arr 1 2
{ _[], arr: [1, 2] }
```
_if disabled:_
```sh
node example --arr 1 2
{ _[2], arr: [1] }
```
**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.**
### nargs eats options
* default: `false`
* key: `nargs-eats-options`
Should nargs consume dash options as well as positional arguments.
### negation prefix
* default: `no-`
* key: `negation-prefix`
The prefix to use for negated boolean variables.
```sh
node example.js --no-foo
{ _: [], foo: false }
```
_if set to `quux`:_
```sh
node example.js --quuxfoo
{ _: [], foo: false }
```
### populate --
* default: `false`.
* key: `populate--`
Should unparsed flags be stored in `--` or `_`.
_If disabled:_
```sh
node example.js a -b -- x y
{ _: [ 'a', 'x', 'y' ], b: true }
```
_If enabled:_
```sh
node example.js a -b -- x y
{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true }
```
### set placeholder key
* default: `false`.
* key: `set-placeholder-key`.
Should a placeholder be added for keys not set via the corresponding CLI argument?
_If disabled:_
```sh
node example.js -a 1 -c 2
{ _: [], a: 1, c: 2 }
```
_If enabled:_
```sh
node example.js -a 1 -c 2
{ _: [], a: 1, b: undefined, c: 2 }
```
### halt at non-option
* default: `false`.
* key: `halt-at-non-option`.
Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line.
_If disabled:_
```sh
node example.js -a run b -x y
{ _: [ 'b' ], a: 'run', x: 'y' }
```
_If enabled:_
```sh
node example.js -a run b -x y
{ _: [ 'b', '-x', 'y' ], a: 'run' }
```
### strip aliased
* default: `false`
* key: `strip-aliased`
Should aliases be removed before returning results?
_If disabled:_
```sh
node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 }
```
_If enabled:_
```sh
node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```
### strip dashed
* default: `false`
* key: `strip-dashed`
Should dashed keys be removed before returning results? This option has no effect if
`camel-case-expansion` is disabled.
_If disabled:_
```sh
node example.js --test-field 1
{ _: [], 'test-field': 1, testField: 1 }
```
_If enabled:_
```sh
node example.js --test-field 1
{ _: [], testField: 1 }
```
### unknown options as args
* default: `false`
* key: `unknown-options-as-args`
Should unknown options be treated like regular arguments? An unknown option is one that is not
configured in `opts`.
_If disabled_
```sh
node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true }
```
_If enabled_
```sh
node example.js --unknown-option --known-option 2 --string-option --unknown-option2
{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' }
```
## Special Thanks
The yargs project evolves from optimist and minimist. It owes its
existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/
## License
ISC
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,40 @@
// take an un-split argv string and tokenize it.
module.exports = function (argString) {
if (Array.isArray(argString)) {
return argString.map(e => typeof e !== 'string' ? e + '' : e)
}
argString = argString.trim()
let i = 0
let prevC = null
let c = null
let opening = null
const args = []
for (let ii = 0; ii < argString.length; ii++) {
prevC = c
c = argString.charAt(ii)
// split on spaces unless we're in quotes.
if (c === ' ' && !opening) {
if (!(prevC === ' ')) {
i++
}
continue
}
// don't split the string if we're in matching
// opening or closing single and double quotes.
if (c === opening) {
opening = null
} else if ((c === "'" || c === '"') && !opening) {
opening = c
}
if (!args[i]) args[i] = ''
args[i] += c
}
return args
}
+55
View File
@@ -0,0 +1,55 @@
{
"author": {
"name": "Ben Coe",
"email": "ben@npmjs.com"
},
"bugs": {
"url": "https://github.com/yargs/yargs-parser/issues"
},
"bundleDependencies": false,
"dependencies": {
"camelcase": "^5.0.0",
"decamelize": "^1.2.0"
},
"deprecated": false,
"description": "the mighty option parser used by yargs",
"devDependencies": {
"c8": "^7.0.1",
"chai": "^4.2.0",
"mocha": "^7.0.0",
"standard": "^14.3.1"
},
"engines": {
"node": ">=6"
},
"files": [
"lib",
"index.js"
],
"homepage": "https://github.com/yargs/yargs-parser#readme",
"keywords": [
"argument",
"parser",
"yargs",
"command",
"cli",
"parsing",
"option",
"args",
"argument"
],
"license": "ISC",
"main": "index.js",
"name": "yargs-parser",
"repository": {
"type": "git",
"url": "git+https://github.com/yargs/yargs-parser.git"
},
"scripts": {
"coverage": "c8 report --check-coverage check-coverage --lines=100 --branches=97 --statements=100",
"fix": "standard --fix",
"posttest": "standard",
"test": "c8 --reporter=text --reporter=html mocha test/*.js"
},
"version": "18.1.2"
}
+159
View File
@@ -0,0 +1,159 @@
{
"author": {
"name": "Kulshekhar Kabra",
"email": "kulshekhar@users.noreply.github.com",
"url": "https://github.com/kulshekhar"
},
"bin": {
"ts-jest": "cli.js"
},
"bugs": {
"url": "https://github.com/kulshekhar/ts-jest/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Huafu Gandon",
"email": "huafu.gandon@gmail.com",
"url": "https://github.com/huafu"
},
{
"name": "Anh Pham",
"email": "anhpnnd@gmail.com",
"url": "https://github.com/ahnpnl"
},
{
"name": "Gustav Wengel",
"email": "gustavwengel@gmail.com",
"url": "https://github.com/GeeWee"
}
],
"dependencies": {
"bs-logger": "0.x",
"buffer-from": "1.x",
"fast-json-stable-stringify": "2.x",
"json5": "2.x",
"lodash.memoize": "4.x",
"make-error": "1.x",
"mkdirp": "1.x",
"resolve": "1.x",
"semver": "6.x",
"yargs-parser": "^18.1.1"
},
"deprecated": false,
"description": "A preprocessor with source maps support to help use TypeScript with Jest",
"devDependencies": {
"@commitlint/cli": "8.x",
"@commitlint/config-conventional": "7.x",
"@jest/transform": "25.x",
"@jest/types": "25.x",
"@types/babel__core": "7.x",
"@types/buffer-from": "latest",
"@types/cross-spawn": "latest",
"@types/fs-extra": "latest",
"@types/jest": "25.x",
"@types/js-yaml": "latest",
"@types/json5": "latest",
"@types/lodash.memoize": "4.x",
"@types/lodash.merge": "4.x",
"@types/lodash.set": "4.x",
"@types/mkdirp": "latest",
"@types/node": "10.x",
"@types/react": "^16.x",
"@types/resolve": "latest",
"@types/semver": "latest",
"@types/yargs": "latest",
"@types/yargs-parser": "^15.0.0",
"conventional-changelog-cli": "2.x",
"cross-spawn": "latest",
"eslint": "latest",
"fs-extra": "8.x",
"glob-gitignore": "latest",
"husky": "3.x",
"jest": "25.x",
"js-yaml": "latest",
"lint-staged": "latest",
"lodash.merge": "4.x",
"lodash.set": "4.x",
"npm-run-all": "latest",
"prettier": "1.x",
"source-map": "latest",
"tslint": "latest",
"tslint-config-prettier": "latest",
"tslint-plugin-prettier": "latest",
"typescript": "3.x"
},
"engines": {
"node": ">= 8"
},
"homepage": "https://kulshekhar.github.io/ts-jest",
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
"post-commit": "git reset"
}
},
"keywords": [
"jest",
"typescript",
"sourcemap",
"react",
"testing"
],
"license": "MIT",
"lint-staged": {
"*.{ts,tsx}": [
"tslint --fix",
"git add"
],
"*.{js,jsx}": [
"eslint --fix",
"git add"
]
},
"main": "dist/index.js",
"name": "ts-jest",
"peerDependencies": {
"jest": ">=25 <26"
},
"repository": {
"type": "git",
"url": "git+https://github.com/kulshekhar/ts-jest.git"
},
"scripts": {
"build": "tsc -p tsconfig.build.json",
"build:watch": "tsc -p tsconfig.build.json -w",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
"clean": "node scripts/clean.js",
"doc": "cd docs && bundle exec jekyll serve --livereload",
"doc:build": "cd docs && bundle exec jekyll build",
"doc:build-commit": "npm run doc:build && cd docs/_site && git add --all && git commit -m \"Updates github pages\"",
"doc:link": "git worktree add docs/_site gh-pages",
"doc:unlink": "git worktree prune",
"lint": "run-s lint:ts lint:js",
"lint:fix": "run-s lint:fix:ts lint:fix:js",
"lint:fix:js": "eslint . --fix",
"lint:fix:ts": "tslint --fix --project .",
"lint:js": "eslint . -f stylish",
"lint:ts": "tslint -t stylish --project .",
"postbuild": "node scripts/post-build.js",
"prebuild": "node scripts/clean-dist.js",
"prepare": "npm run build",
"prepublishOnly": "npm run test",
"pretest": "npm run lint",
"preversion": "npm run test",
"test": "run-s -s test:e2e \"test:unit -- {@}\" --",
"test:e2e": "node scripts/e2e.js",
"test:e2e:update-snaphots": "node scripts/e2e.js --updateSnapshot",
"test:external": "node scripts/test-external-project.js",
"test:monorepo": "npm run test:external monorepo",
"test:prepare": "npm run test:e2e -- --prepareOnly",
"test:unit": "jest",
"typecheck": "tsc -p .",
"update:e2e": "node scripts/update-e2e-templates.js",
"version": "npm run changelog && git add CHANGELOG.md"
},
"types": "dist/index.d.ts",
"version": "25.3.0"
}
+7
View File
@@ -0,0 +1,7 @@
console.warn(
'ts-jest[main] (WARN) Replace any occurrences of "ts-jest/dist/preprocessor.js" or ' +
' "<rootDir>/node_modules/ts-jest/preprocessor.js"' +
' in the \'transform\' section of your Jest config with just "ts-jest".'
)
module.exports = require('./dist')
+1
View File
@@ -0,0 +1 @@
module.exports = require('../dist/config/create-jest-preset').createJestPreset

Some files were not shown because too many files have changed in this diff Show More